1use std::collections::{BTreeMap, HashMap, HashSet};
2use std::sync::Arc;
3
4use anyhow::Result;
5use oxdock_func_macro::oxdock_func;
6use oxdock_parser::{
7 KEYWORD_INSPECT, SCRIPT_MODULE_NAME, STD_MODULE_NAME, Step, Value, base_name, qualify,
8 split_qualified,
9};
10use oxdock_process::{CommandStdin, DefaultProcessManager, ProcessManager};
11
12use super::io::StreamHandle;
13use super::state::ExecState;
14use super::steps::StepCtx;
15use super::typing::TypeDescriptor;
16
17#[derive(Debug, Clone, Copy, PartialEq, Eq)]
23pub enum FuncKind {
24 Script,
25 HostCtx,
26 HostPure,
27}
28
29impl FuncKind {
30 pub fn label(&self) -> &'static str {
31 match self {
32 FuncKind::Script => "script",
33 FuncKind::HostCtx | FuncKind::HostPure => "host",
34 }
35 }
36}
37
38#[derive(Debug, Clone)]
41pub struct FuncParam {
42 pub name: String,
43 pub param_type: Option<String>,
44}
45
46#[derive(Debug, Clone)]
52pub struct FuncMeta {
53 pub name: String,
54 pub module: String,
58 pub kind: FuncKind,
59 pub params: Option<Vec<FuncParam>>,
60 pub returns: Option<String>,
61 pub rpn: bool,
62 pub summary: &'static str,
63 pub docs: &'static str,
64}
65
66pub type PureFn = Arc<dyn Fn(Vec<Value>) -> Result<Value> + Send + Sync>;
69
70pub type NativeFn<P> = Arc<dyn Fn(&mut StepCtx<P>, Vec<Value>) -> Result<Value> + Send + Sync>;
72
73pub trait OxDockFn<P: ProcessManager> {
77 fn registration() -> HostRegistration<P>;
80}
81
82pub enum HostRegistration<P: ProcessManager> {
88 Stateful {
89 name: String,
90 meta: FuncMeta,
91 func: NativeFn<P>,
92 },
93 Pure {
94 name: String,
95 meta: FuncMeta,
96 func: PureFn,
97 },
98}
99
100impl<P: ProcessManager> Clone for HostRegistration<P> {
103 fn clone(&self) -> Self {
104 match self {
105 HostRegistration::Stateful { name, meta, func } => HostRegistration::Stateful {
106 name: name.clone(),
107 meta: meta.clone(),
108 func: Arc::clone(func),
109 },
110 HostRegistration::Pure { name, meta, func } => HostRegistration::Pure {
111 name: name.clone(),
112 meta: meta.clone(),
113 func: Arc::clone(func),
114 },
115 }
116 }
117}
118
119impl<P: ProcessManager> HostRegistration<P> {
120 pub fn meta(&self) -> &FuncMeta {
123 match self {
124 HostRegistration::Stateful { meta, .. } => meta,
125 HostRegistration::Pure { meta, .. } => meta,
126 }
127 }
128}
129
130#[derive(Debug, Clone)]
132pub(super) struct FuncDefData {
133 pub(super) params: Vec<(String, String)>,
134 pub(super) body: Vec<Step>,
135}
136
137pub(super) enum FuncBody<P: ProcessManager> {
140 Script(FuncDefData),
141 Pure(PureFn),
142 Ctx(NativeFn<P>),
143}
144
145impl<P: ProcessManager> Clone for FuncBody<P> {
147 fn clone(&self) -> Self {
148 match self {
149 FuncBody::Script(def) => FuncBody::Script(def.clone()),
150 FuncBody::Pure(func) => FuncBody::Pure(Arc::clone(func)),
151 FuncBody::Ctx(func) => FuncBody::Ctx(Arc::clone(func)),
152 }
153 }
154}
155
156pub(super) struct FuncEntry<P: ProcessManager> {
160 pub(super) meta: FuncMeta,
161 pub(super) body: FuncBody<P>,
162}
163
164impl<P: ProcessManager> Clone for FuncEntry<P> {
166 fn clone(&self) -> Self {
167 Self {
168 meta: self.meta.clone(),
169 body: self.body.clone(),
170 }
171 }
172}
173
174struct ScopeFrame<P: ProcessManager> {
177 defined: HashSet<String>,
178 shadowed: Vec<(String, FuncEntry<P>)>,
179}
180
181impl<P: ProcessManager> Clone for ScopeFrame<P> {
183 fn clone(&self) -> Self {
184 Self {
185 defined: self.defined.clone(),
186 shadowed: self.shadowed.clone(),
187 }
188 }
189}
190
191pub struct FunctionRegistry<P: ProcessManager> {
198 entries: HashMap<String, FuncEntry<P>>,
199 scopes: Vec<ScopeFrame<P>>,
200}
201
202impl<P: ProcessManager> FunctionRegistry<P> {
203 pub(super) fn with_builtins() -> Self {
204 let mut reg = Self {
205 entries: HashMap::new(),
206 scopes: vec![ScopeFrame {
207 defined: HashSet::new(),
208 shadowed: Vec::new(),
209 }],
210 };
211 for host in Self::builtin_registrations() {
215 match host {
216 HostRegistration::Stateful { name, meta, func } => {
217 reg.insert_qualified(STD_MODULE_NAME, name, meta, FuncBody::Ctx(func));
218 }
219 HostRegistration::Pure { name, meta, func } => {
220 reg.insert_qualified(STD_MODULE_NAME, name, meta, FuncBody::Pure(func));
221 }
222 }
223 }
224 reg
225 }
226
227 pub(super) fn builtin_registrations() -> Vec<HostRegistration<P>> {
232 vec![
233 Int::registration(),
234 Float::registration(),
235 Types::registration(),
236 TypeDescribe::registration(),
237 Glob::registration(),
238 LoadToml::registration(),
239 LoadJson::registration(),
240 PathType::registration(),
241 Functions::registration(),
242 Describe::registration(),
243 IsTerminal::registration(),
244 Eof::registration(),
245 SemaphoreNew::registration(),
246 SemaphoreTryAcquire::registration(),
247 SemaphoreAvailable::registration(),
248 ]
249 }
250
251 pub(super) fn keys(&self) -> HashSet<String> {
254 self.entries.keys().cloned().collect()
255 }
256
257 pub(super) fn get(&self, name: &str) -> Option<FuncEntry<P>> {
259 self.entries.get(name).cloned()
260 }
261
262 fn insert_native(&mut self, name: String, meta: FuncMeta, body: FuncBody<P>) {
263 self.entries.insert(name, FuncEntry { meta, body });
264 }
265
266 fn insert_qualified(
270 &mut self,
271 module: &str,
272 base: String,
273 mut meta: FuncMeta,
274 body: FuncBody<P>,
275 ) {
276 meta.name = qualify(module, &base);
277 meta.module = module.to_string();
278 if self.entries.contains_key(&meta.name) {
283 panic!("duplicate function registration `{}`", meta.name);
284 }
285 self.insert_native(meta.name.clone(), meta, body);
286 }
287
288 pub(super) fn register_host(
289 &mut self,
290 module: &str,
291 name: String,
292 mut meta: FuncMeta,
293 func: NativeFn<P>,
294 ) {
295 meta.kind = FuncKind::HostCtx;
296 self.insert_qualified(module, name, meta, FuncBody::Ctx(func));
297 }
298
299 pub(super) fn register_pure_host(
300 &mut self,
301 module: &str,
302 name: String,
303 mut meta: FuncMeta,
304 func: PureFn,
305 ) {
306 meta.kind = FuncKind::HostPure;
307 self.insert_qualified(module, name, meta, FuncBody::Pure(func));
308 }
309
310 pub(super) fn define_script(
315 &mut self,
316 name: &str,
317 params: &[(String, String)],
318 body: &[Step],
319 ) -> Result<()> {
320 let qualified = qualify(SCRIPT_MODULE_NAME, name);
321 let shadowable = matches!(
322 self.entries.get(&qualified).map(|entry| &entry.body),
323 Some(FuncBody::Script(_))
324 );
325 let reserved = self
328 .entries
329 .keys()
330 .any(|key| split_qualified(key).is_some_and(|(_, base)| base == name));
331 if reserved && !shadowable {
332 anyhow::bail!("cannot shadow reserved function `{name}`");
333 }
334 if self
335 .scopes
336 .last()
337 .is_some_and(|frame| frame.defined.contains(&qualified))
338 {
339 anyhow::bail!("duplicate function `{name}` in same scope");
340 }
341 let old = self.entries.insert(
342 qualified.clone(),
343 FuncEntry {
344 meta: FuncMeta {
345 name: qualified.clone(),
346 module: SCRIPT_MODULE_NAME.to_string(),
347 kind: FuncKind::Script,
348 params: Some(
349 params
350 .iter()
351 .map(|(name, param_type)| FuncParam {
352 name: name.clone(),
353 param_type: Some(param_type.clone()),
354 })
355 .collect(),
356 ),
357 returns: None,
358 rpn: false,
359 summary: "DSL-defined function.",
360 docs: "Defined via FUNC in script.",
361 },
362 body: FuncBody::Script(FuncDefData {
363 params: params.to_vec(),
364 body: body.to_vec(),
365 }),
366 },
367 );
368 if let Some(frame) = self.scopes.last_mut() {
369 frame.defined.insert(qualified.clone());
370 if let Some(old) = old {
371 frame.shadowed.push((qualified, old));
372 }
373 }
374 Ok(())
375 }
376
377 pub(super) fn push_scope(&mut self) {
380 self.scopes.push(ScopeFrame {
381 defined: HashSet::new(),
382 shadowed: Vec::new(),
383 });
384 }
385
386 pub(super) fn pop_scope(&mut self) {
389 let Some(frame) = self.scopes.pop() else {
390 return;
391 };
392 for name in frame.defined {
393 self.entries.remove(&name);
394 }
395 for (name, old) in frame.shadowed {
396 self.entries.insert(name, old);
397 }
398 }
399
400 pub(super) fn contains_script(&self, name: &str) -> bool {
404 matches!(
405 self.entries.get(name).map(|entry| &entry.body),
406 Some(FuncBody::Script(_))
407 )
408 }
409
410 fn clone_pure_fn(&self, name: &str) -> Option<PureFn> {
413 match self.entries.get(name)?.body {
414 FuncBody::Pure(ref func) => Some(Arc::clone(func)),
415 _ => None,
416 }
417 }
418
419 fn clone_ctx_fn(&self, name: &str) -> Option<NativeFn<P>> {
422 match self.entries.get(name)?.body {
423 FuncBody::Ctx(ref func) => Some(Arc::clone(func)),
424 _ => None,
425 }
426 }
427
428 fn meta(&self, name: &str) -> Option<FuncMeta> {
429 self.entries.get(name).map(|entry| entry.meta.clone())
430 }
431
432 fn native_metas(&self) -> Vec<FuncMeta> {
433 let mut out: Vec<FuncMeta> = Vec::new();
434 for entry in self.entries.values() {
435 if !matches!(entry.body, FuncBody::Script(_)) {
436 out.push(entry.meta.clone());
437 }
438 }
439 out.sort_by(|a, b| a.name.cmp(&b.name));
440 out
441 }
442
443 fn entries_metas(&self) -> Vec<FuncMeta> {
446 let mut out: Vec<FuncMeta> = self
447 .entries
448 .values()
449 .map(|entry| entry.meta.clone())
450 .collect();
451 out.sort_by(|a, b| a.name.cmp(&b.name));
452 out
453 }
454}
455
456impl<P: ProcessManager> Clone for FunctionRegistry<P> {
457 fn clone(&self) -> Self {
458 Self {
459 entries: self.entries.clone(),
460 scopes: self.scopes.clone(),
461 }
462 }
463}
464
465pub fn builtin_function_names() -> HashSet<String> {
472 let mut names = FunctionRegistry::<DefaultProcessManager>::with_builtins().keys();
473 names.insert(KEYWORD_INSPECT.to_string());
474 names
475}
476
477pub fn builtin_function_metas() -> Vec<FuncMeta> {
481 FunctionRegistry::<DefaultProcessManager>::with_builtins().native_metas()
482}
483
484pub fn std_module_table() -> oxdock_parser::ModuleTable {
489 let functions: HashSet<String> = builtin_function_metas()
491 .into_iter()
492 .map(|meta| base_name(&meta.name).to_string())
493 .collect();
494 oxdock_parser::ModuleTable {
495 modules: HashMap::from([(
496 STD_MODULE_NAME.to_string(),
497 Some(oxdock_parser::ModuleFuncs { functions }),
498 )]),
499 }
500}
501
502#[oxdock_func(pure, returns = "INT")]
514fn int(val: Value) -> Result<Value> {
515 super::args::int_from_value(val)
516}
517
518#[oxdock_func(pure, returns = "FLOAT")]
522fn float(val: Value) -> Result<Value> {
523 super::args::float_from_value(val)
524}
525
526#[oxdock_func(rpn, returns = "LIST")]
530fn glob<P: ProcessManager>(cx: &mut StepCtx<P>, pattern: String) -> Result<Value> {
531 super::args::glob_from_value(&[Value::string(pattern)], cx)
532}
533
534#[oxdock_func(rpn, returns = "MAP")]
538fn load_toml<P: ProcessManager>(cx: &mut StepCtx<P>, path: String) -> Result<Value> {
539 super::args::load_toml_from_value(&[Value::string(path)], cx)
540}
541
542#[oxdock_func(rpn, returns = "MAP")]
546fn load_json<P: ProcessManager>(cx: &mut StepCtx<P>, path: String) -> Result<Value> {
547 super::args::load_json_from_value(&[Value::string(path)], cx)
548}
549
550#[oxdock_func(returns = "STRING")]
555fn path_type<P: ProcessManager>(cx: &mut StepCtx<P>, path: String) -> Result<Value> {
556 super::args::path_type_from_value(&[Value::string(path)], cx)
557}
558
559#[oxdock_func(returns = "LIST")]
564fn functions<P: ProcessManager>(cx: &mut StepCtx<P>) -> Result<Value> {
565 let mut names: Vec<String> = cx
566 .state
567 .list_functions()
568 .into_iter()
569 .map(|meta| meta.name)
570 .collect();
571 names.sort();
572 names.dedup();
573 Ok(Value::list(names.into_iter().map(Value::string).collect()))
574}
575
576#[oxdock_func(returns = "MAP")]
583fn describe<P: ProcessManager>(cx: &mut StepCtx<P>, name: String) -> Result<Value> {
584 if split_qualified(&name).is_none() && name != KEYWORD_INSPECT {
585 anyhow::bail!(
586 "unknown function `{name}`: DESCRIBE requires a qualified name (e.g. `STD::{name}`)"
587 );
588 }
589 cx.state
590 .describe_function(&name)
591 .ok_or_else(|| anyhow::anyhow!("unknown function {name}"))
592}
593
594#[oxdock_func(returns = "LIST")]
600fn types<P: ProcessManager>(cx: &mut StepCtx<P>) -> Result<Value> {
601 Ok(Value::list(
602 cx.state
603 .type_names()
604 .into_iter()
605 .map(Value::string)
606 .collect(),
607 ))
608}
609
610#[oxdock_func(returns = "MAP")]
615fn type_describe<P: ProcessManager>(cx: &mut StepCtx<P>, name: String) -> Result<Value> {
616 cx.state
617 .describe_type(&name)
618 .map(|descriptor| {
619 let mut map = BTreeMap::new();
620 map.insert(
621 "name".to_string(),
622 Value::string(descriptor.name.to_string()),
623 );
624 map.insert(
625 "summary".to_string(),
626 Value::string(descriptor.summary.to_string()),
627 );
628 map.insert(
629 "docs".to_string(),
630 Value::string(descriptor.docs.to_string()),
631 );
632 Value::map(map)
633 })
634 .ok_or_else(|| anyhow::anyhow!("unknown type {name}"))
635}
636
637#[oxdock_func(returns = "BOOL")]
650fn is_terminal<P: ProcessManager>(cx: &mut StepCtx<P>, stream: String) -> Result<Value> {
651 use std::io::IsTerminal;
652 let terminal = match stream.as_str() {
653 "stdin" => {
654 if cx.stdin_pipe.is_some() {
659 false
660 } else {
661 match &cx.stdin {
662 CommandStdin::Null => false,
663 #[cfg(not(miri))]
664 CommandStdin::OsPipe(_) => false,
665 CommandStdin::Stream(_) => false,
666 CommandStdin::Inherit => std::io::stdin().is_terminal(),
667 }
668 }
669 }
670 "stdout" => {
671 if cx.out_pipe.is_some() {
672 false
674 } else if cx.state.io.stdout().is_some() {
675 false
678 } else {
679 match &cx.out {
680 None => std::io::stdout().is_terminal(),
682 #[cfg(not(miri))]
684 Some(StreamHandle::Os(_)) => false,
685 Some(StreamHandle::Stream(_)) => std::io::stdout().is_terminal(),
695 }
696 }
697 }
698 "stderr" => {
699 if cx.state.io.stderr().is_some() {
700 false
702 } else {
703 match &cx.err {
704 None => std::io::stderr().is_terminal(),
706 #[cfg(not(miri))]
708 Some(StreamHandle::Os(_)) => false,
709 Some(StreamHandle::Stream(_)) => false,
712 }
713 }
714 }
715 _ => anyhow::bail!(
716 "IS_TERMINAL expects \"stdin\", \"stdout\", or \"stderr\", got {stream:?}"
717 ),
718 };
719 Ok(Value::bool(terminal))
720}
721
722#[oxdock_func(returns = "SEMAPHORE")]
733fn semaphore_new<P: ProcessManager>(cx: &mut StepCtx<P>, max: i64) -> Result<Value> {
734 let _ = cx;
735 if max <= 0 {
736 return Err(anyhow::anyhow!(
737 "SEMAPHORE_NEW() requires a positive max, got {max}"
738 ));
739 }
740 Ok(Value::semaphore(max as usize))
741}
742
743#[oxdock_func(returns = "MAP")]
762fn semaphore_try_acquire<P: ProcessManager>(cx: &mut StepCtx<P>, sem: Value) -> Result<Value> {
763 let _ = cx;
764 let Some(sem) = sem.as_semaphore() else {
765 return Err(anyhow::anyhow!(
766 "SEMAPHORE_TRY_ACQUIRE() argument `$sem` must be a SEMAPHORE, got {}",
767 sem.type_name(),
768 ));
769 };
770 let mut map = BTreeMap::new();
771 if sem.try_acquire() {
772 map.insert("held".to_string(), Value::int(1));
773 map.insert("permit".to_string(), Value::permit(&sem));
774 } else {
775 map.insert("held".to_string(), Value::int(0));
776 }
777 Ok(Value::map(map))
778}
779
780#[oxdock_func(pure, returns = "INT")]
790fn semaphore_available(sem: Value) -> Result<Value> {
791 let Some(sem) = sem.as_semaphore() else {
792 return Err(anyhow::anyhow!(
793 "SEMAPHORE_AVAILABLE() argument `$sem` must be a SEMAPHORE, got {}",
794 sem.type_name(),
795 ));
796 };
797 Ok(Value::int(sem.available() as i64))
798}
799
800#[oxdock_func(returns = "BOOL")]
826fn eof<P: ProcessManager>(cx: &mut StepCtx<P>, pipe: Value) -> Result<Value> {
827 let Some(handle) = pipe.as_pipe_handle() else {
828 return Err(anyhow::anyhow!(
829 "EOF() argument `$pipe` must be a PIPE, got {}",
830 pipe.type_name(),
831 ));
832 };
833 let info = cx.state.io.inspect_pipe(&handle);
834 Ok(Value::bool(info.closed && info.buffered == 0))
835}
836
837fn meta_to_value(meta: &FuncMeta) -> Value {
838 let mut map = BTreeMap::new();
839 map.insert("name".to_string(), Value::string(meta.name.clone()));
840 map.insert("module".to_string(), Value::string(meta.module.clone()));
841 map.insert(
842 "kind".to_string(),
843 Value::string(meta.kind.label().to_string()),
844 );
845 let params = match &meta.params {
846 Some(params) => Value::list(
847 params
848 .iter()
849 .map(|p| {
850 let mut entry = BTreeMap::new();
851 entry.insert("name".to_string(), Value::string(p.name.clone()));
852 entry.insert(
853 "param_type".to_string(),
854 Value::string(p.param_type.clone().unwrap_or_default()),
855 );
856 Value::map(entry)
857 })
858 .collect(),
859 ),
860 None => Value::string(String::new()),
861 };
862 map.insert("params".to_string(), params);
863 map.insert(
864 "returns".to_string(),
865 Value::string(meta.returns.clone().unwrap_or_default()),
866 );
867 map.insert("rpn".to_string(), Value::bool(meta.rpn));
868 map.insert(
869 "summary".to_string(),
870 Value::string(meta.summary.to_string()),
871 );
872 Value::map(map)
873}
874
875#[derive(Clone)]
879pub struct HostModule<P: ProcessManager> {
880 pub name: String,
881 pub funcs: Vec<HostRegistration<P>>,
882 pub types: Vec<&'static TypeDescriptor>,
883}
884
885impl<P: ProcessManager> ExecState<P> {
886 pub fn register_module(&mut self, module: HostModule<P>) {
889 for registration in module.funcs {
890 match registration {
891 HostRegistration::Stateful { name, meta, func } => {
892 self.functions.register_host(&module.name, name, meta, func);
893 }
894 HostRegistration::Pure { name, meta, func } => {
895 self.functions
896 .register_pure_host(&module.name, name, meta, func);
897 }
898 }
899 }
900 for descriptor in module.types {
901 self.register_type(descriptor);
902 }
903 }
904
905 pub fn list_functions(&self) -> Vec<FuncMeta> {
907 let mut out: Vec<FuncMeta> = self.functions.entries_metas().into_iter().collect();
908 if !out.iter().any(|m| m.name == KEYWORD_INSPECT) {
910 out.push(FuncMeta {
911 name: KEYWORD_INSPECT.to_string(),
912 module: STD_MODULE_NAME.to_string(),
913 kind: FuncKind::HostCtx,
914 params: None,
915 returns: Some("MAP".to_string()),
916 rpn: false,
917 summary: "Inspect a variable binding.",
918 docs: "INSPECT($var): dedicated AST node taking a variable, not a value.",
919 });
920 }
921 out.sort_by(|a, b| a.name.cmp(&b.name));
922 out
923 }
924
925 pub fn describe_function(&self, name: &str) -> Option<Value> {
927 if let Some(meta) = self.functions.meta(name) {
928 return Some(meta_to_value(&meta));
929 }
930 if name == KEYWORD_INSPECT {
932 return Some(meta_to_value(&FuncMeta {
933 name: KEYWORD_INSPECT.to_string(),
934 module: STD_MODULE_NAME.to_string(),
935 kind: FuncKind::HostCtx,
936 params: None,
937 returns: Some("MAP".to_string()),
938 rpn: false,
939 summary: "Inspect a variable binding.",
940 docs: "INSPECT($var): dedicated AST node taking a variable, not a value.",
941 }));
942 }
943 None
944 }
945
946 pub(super) fn clone_native_pure(&self, name: &str) -> Option<PureFn> {
947 self.functions.clone_pure_fn(name)
948 }
949
950 pub(super) fn clone_native_ctx(&self, name: &str) -> Option<NativeFn<P>> {
951 self.functions.clone_ctx_fn(name)
952 }
953
954 pub(super) fn native_meta(&self, name: &str) -> Option<FuncMeta> {
955 self.functions.meta(name)
956 }
957}