1use std::collections::{BTreeMap, HashMap, HashSet};
2use std::sync::Arc;
3
4use anyhow::Result;
5use oxdock_func_macro::oxdock_func;
6use oxdock_parser::value::HandleValue;
7use oxdock_parser::{
8 Field, KEYWORD_INSPECT, SCRIPT_MODULE_NAME, STD_MODULE_NAME, SemaphoreState, Step, TypeTag,
9 Value, base_name, qualify, render_structural, split_qualified,
10};
11use oxdock_pipe::PipeHandle;
12use oxdock_process::{CommandStdin, DefaultProcessManager, ProcessManager};
13
14use super::io::StreamHandle;
15use super::state::ExecState;
16use super::steps::StepCtx;
17use super::typing::TypeDescriptor;
18
19#[derive(Debug, Clone, Copy, PartialEq, Eq)]
25pub enum FuncKind {
26 Script,
27 HostCtx,
28 HostPure,
29}
30
31impl FuncKind {
32 pub fn label(&self) -> &'static str {
33 match self {
34 FuncKind::Script => "script",
35 FuncKind::HostCtx | FuncKind::HostPure => "host",
36 }
37 }
38}
39
40#[derive(Debug, Clone)]
58pub struct FuncParam {
59 pub name: String,
60 pub param_type: Option<TypeTag>,
61 pub allowed: Option<&'static [&'static str]>,
62 pub docs: &'static str,
63 pub options: Option<&'static [ParamOption]>,
64 pub optional: bool,
65}
66
67pub fn required_arity(params: &[FuncParam]) -> usize {
72 params
73 .iter()
74 .rev()
75 .take_while(|param| param.optional)
76 .fold(params.len(), |count, _| count - 1)
77}
78
79pub fn fill_optional_args(params: &[FuncParam], mut values: Vec<Value>) -> Vec<Value> {
84 assert!(
85 values.len() <= params.len(),
86 "arity gate must run before fill_optional_args"
87 );
88 assert!(
89 values.len() >= required_arity(params),
90 "arity gate must run before fill_optional_args"
91 );
92 while values.len() < params.len() {
93 values.push(Value::map(BTreeMap::new()));
94 }
95 values
96}
97
98#[derive(Debug, Clone)]
105pub struct ParamOption {
106 pub name: &'static str,
107 pub value: TypeTag,
108 pub required: bool,
109 pub default: Option<&'static str>,
110}
111
112#[derive(Debug, Clone)]
118pub struct FuncMeta {
119 pub name: String,
120 pub module: String,
124 pub kind: FuncKind,
125 pub params: Option<Vec<FuncParam>>,
126 pub returns: Option<TypeTag>,
127 pub rpn: bool,
128 pub summary: &'static str,
129 pub docs: &'static str,
130 pub examples: &'static [crate::Example],
136}
137
138pub type PureFn = Arc<dyn Fn(Vec<Value>) -> Result<Value> + Send + Sync>;
141
142pub type NativeFn<P> = Arc<dyn Fn(&mut StepCtx<P>, Vec<Value>) -> Result<Value> + Send + Sync>;
144
145pub trait OxDockFn<P: ProcessManager> {
149 fn registration() -> HostRegistration<P>;
152}
153
154pub enum HostRegistration<P: ProcessManager> {
163 Stateful {
164 name: String,
165 meta: FuncMeta,
166 func: NativeFn<P>,
167 },
168 Pure {
169 name: String,
170 meta: FuncMeta,
171 func: PureFn,
172 },
173 Both {
174 name: String,
175 meta: FuncMeta,
176 func: NativeFn<P>,
177 template: PureFn,
178 },
179}
180
181impl<P: ProcessManager> Clone for HostRegistration<P> {
184 fn clone(&self) -> Self {
185 match self {
186 HostRegistration::Stateful { name, meta, func } => HostRegistration::Stateful {
187 name: name.clone(),
188 meta: meta.clone(),
189 func: Arc::clone(func),
190 },
191 HostRegistration::Pure { name, meta, func } => HostRegistration::Pure {
192 name: name.clone(),
193 meta: meta.clone(),
194 func: Arc::clone(func),
195 },
196 HostRegistration::Both {
197 name,
198 meta,
199 func,
200 template,
201 } => HostRegistration::Both {
202 name: name.clone(),
203 meta: meta.clone(),
204 func: Arc::clone(func),
205 template: Arc::clone(template),
206 },
207 }
208 }
209}
210
211impl<P: ProcessManager> HostRegistration<P> {
212 pub fn meta(&self) -> &FuncMeta {
215 match self {
216 HostRegistration::Stateful { meta, .. } => meta,
217 HostRegistration::Pure { meta, .. } => meta,
218 HostRegistration::Both { meta, .. } => meta,
219 }
220 }
221}
222
223#[derive(Debug, Clone)]
229pub(super) struct FuncDefData {
230 pub(super) params: Vec<(String, TypeTag, bool)>,
231 pub(super) return_type: TypeTag,
232 pub(super) return_spelling: String,
233 pub(super) is_async: bool,
234 pub(super) body: Vec<Step>,
235 pub(super) module: Option<String>,
240}
241
242pub fn optional_zero_value(tag: &TypeTag) -> Result<Value> {
249 match tag {
250 TypeTag::Bool => Ok(Value::bool(false)),
251 TypeTag::String | TypeTag::Any => Ok(Value::string(String::new())),
252 TypeTag::Int => Ok(Value::int(0)),
253 TypeTag::Float => Ok(Value::float(0.0)),
254 TypeTag::List | TypeTag::ListOf(_) => Ok(Value::list(Vec::new())),
255 TypeTag::Map | TypeTag::MapOf(_) => Ok(Value::map(BTreeMap::new())),
256 TypeTag::Record(fields) if fields.iter().all(|field| field.optional) => {
257 Ok(Value::map(BTreeMap::new()))
258 }
259 other => anyhow::bail!(
260 "no zero value for {}; omit the `?` or pass the argument explicitly",
261 oxdock_parser::render_structural(other)
262 ),
263 }
264}
265
266pub fn resolve_script_params<P: ProcessManager>(
272 state: &ExecState<P>,
273 func_name: &str,
274 params: &[(String, String, bool)],
275) -> Result<Vec<(String, TypeTag, bool)>> {
276 let mut resolved = Vec::with_capacity(params.len());
277 for (pname, ptype, optional) in params {
278 let clean = pname.trim_start_matches('$').to_string();
279 let tag = state
280 .resolve_tag(ptype)
281 .map_err(|err| anyhow::anyhow!("function `{func_name}`: {err:#}"))?;
282 state.check_declaration_tag(&format!("function `{func_name}` param `${clean}`"), &tag)?;
283 if *optional {
284 optional_zero_value(&tag).map(|_| ()).map_err(|err| {
285 anyhow::anyhow!("function `{func_name}` optional param `${clean}`: {err:#}")
286 })?;
287 }
288 resolved.push((clean, tag, *optional));
289 }
290 Ok(resolved)
291}
292
293pub fn check_script_param_tags(func_name: &str, params: &[(String, TypeTag, bool)]) -> Result<()> {
296 for (pname, tag, optional) in params {
297 if *optional {
298 optional_zero_value(tag).map(|_| ()).map_err(|err| {
299 anyhow::anyhow!("function `{func_name}` optional param `${pname}`: {err:#}")
300 })?;
301 }
302 }
303 Ok(())
304}
305
306pub(super) enum FuncBody<P: ProcessManager> {
311 Script(FuncDefData),
312 Pure(PureFn),
313 Ctx(NativeFn<P>),
314 Both { pure: PureFn, ctx: NativeFn<P> },
315}
316
317impl<P: ProcessManager> Clone for FuncBody<P> {
319 fn clone(&self) -> Self {
320 match self {
321 FuncBody::Script(def) => FuncBody::Script(def.clone()),
322 FuncBody::Pure(func) => FuncBody::Pure(Arc::clone(func)),
323 FuncBody::Ctx(func) => FuncBody::Ctx(Arc::clone(func)),
324 FuncBody::Both { pure, ctx } => FuncBody::Both {
325 pure: Arc::clone(pure),
326 ctx: Arc::clone(ctx),
327 },
328 }
329 }
330}
331
332pub(super) struct FuncEntry<P: ProcessManager> {
336 pub(super) meta: FuncMeta,
337 pub(super) body: FuncBody<P>,
338}
339
340impl<P: ProcessManager> Clone for FuncEntry<P> {
342 fn clone(&self) -> Self {
343 Self {
344 meta: self.meta.clone(),
345 body: self.body.clone(),
346 }
347 }
348}
349
350struct ScopeFrame<P: ProcessManager> {
353 defined: HashSet<String>,
354 shadowed: Vec<(String, FuncEntry<P>)>,
355}
356
357impl<P: ProcessManager> Clone for ScopeFrame<P> {
359 fn clone(&self) -> Self {
360 Self {
361 defined: self.defined.clone(),
362 shadowed: self.shadowed.clone(),
363 }
364 }
365}
366
367pub type PureTable = HashMap<String, HashMap<String, PureFn>>;
377
378pub fn placeholder_resolver(table: Arc<PureTable>) -> oxdock_process::PlaceholderCall {
387 Arc::new(move |module, func, args| {
388 let callee = table
389 .get(module)
390 .and_then(|entries| entries.get(func))
391 .ok_or_else(|| {
392 let mut known: Vec<String> = table
393 .iter()
394 .flat_map(|(m, entries)| entries.keys().map(move |f| format!("{m}::{f}")))
395 .collect();
396 known.sort();
397 anyhow::anyhow!(
398 "unknown placeholder function '{module}::{func}'; known functions: {}",
399 known.join(", ")
400 )
401 })?;
402 callee(args)
403 })
404}
405
406pub struct FunctionRegistry<P: ProcessManager> {
407 entries: HashMap<String, FuncEntry<P>>,
408 scopes: Vec<ScopeFrame<P>>,
409 pure_shared: Arc<PureTable>,
410 script_docs: HashMap<String, (String, String)>,
414}
415
416impl<P: ProcessManager> FunctionRegistry<P> {
417 pub(super) fn with_builtins() -> Self {
418 let mut reg = Self {
419 entries: HashMap::new(),
420 pure_shared: Arc::new(HashMap::new()),
421 script_docs: HashMap::new(),
422 scopes: vec![ScopeFrame {
423 defined: HashSet::new(),
424 shadowed: Vec::new(),
425 }],
426 };
427 for host in Self::builtin_registrations() {
431 match host {
432 HostRegistration::Stateful { name, meta, func } => {
433 reg.insert_qualified(STD_MODULE_NAME, name, meta, FuncBody::Ctx(func));
434 }
435 HostRegistration::Pure { name, meta, func } => {
436 reg.insert_qualified(STD_MODULE_NAME, name, meta, FuncBody::Pure(func));
437 }
438 HostRegistration::Both {
439 name,
440 meta,
441 func,
442 template,
443 } => {
444 reg.insert_qualified(
445 STD_MODULE_NAME,
446 name,
447 meta,
448 FuncBody::Both {
449 pure: template,
450 ctx: func,
451 },
452 );
453 }
454 }
455 }
456 reg
457 }
458
459 pub(super) fn builtin_registrations() -> Vec<HostRegistration<P>> {
464 vec![
465 Int::registration(),
466 Float::registration(),
467 BoolConvert::registration(),
468 BoolOr::registration(),
469 FormatByteCount::registration(),
470 ParseByteCount::registration(),
471 FormatDuration::registration(),
472 ParseDuration::registration(),
473 Types::registration(),
474 TypeDescribe::registration(),
475 Glob::registration(),
476 LoadToml::registration(),
477 LoadJson::registration(),
478 HashSha256::registration(),
479 Cwd::registration(),
480 ParseToml::registration(),
481 ParseJson::registration(),
482 PathType::registration(),
483 PathWritable::registration(),
484 IsExec::registration(),
485 HasKey::registration(),
486 MapSet::registration(),
487 MergeMaps::registration(),
488 Base64Encode::registration(),
489 Base64Decode::registration(),
490 Rand::registration(),
491 ToJson::registration(),
492 TypeOf::registration(),
493 Functions::registration(),
494 Describe::registration(),
495 IsMain::registration(),
496 IsTerminal::registration(),
497 Eof::registration(),
498 TaskPoll::registration(),
499 Version::registration(),
500 Interpreter::registration(),
501 TextTrim::registration(),
502 TextTrimPrefix::registration(),
503 TextTrimSuffix::registration(),
504 PathJoin::registration(),
505 TextToUpper::registration(),
506 TextToLower::registration(),
507 TextReplace::registration(),
508 TextReplaceRegex::registration(),
509 TextSplit::registration(),
510 TextJoin::registration(),
511 TextLines::registration(),
512 TextFields::registration(),
513 TextMatch::registration(),
514 TextExtract::registration(),
515 TextStartsWith::registration(),
516 TextEndsWith::registration(),
517 TextContains::registration(),
518 Len::registration(),
519 TextCount::registration(),
520 TextCountMatches::registration(),
521 TextGrep::registration(),
522 TextLinesRange::registration(),
523 SemaphoreNew::registration(),
524 SemaphoreTryAcquire::registration(),
525 SemaphoreAvailable::registration(),
526 ShellSplitArgs::registration(),
527 ShellJoinArgs::registration(),
528 ]
529 }
530
531 pub(super) fn keys(&self) -> HashSet<String> {
534 self.entries.keys().cloned().collect()
535 }
536
537 pub(super) fn get(&self, name: &str) -> Option<FuncEntry<P>> {
539 self.entries.get(name).cloned()
540 }
541
542 fn insert_native(&mut self, name: String, meta: FuncMeta, body: FuncBody<P>) {
543 self.entries.insert(name, FuncEntry { meta, body });
544 self.rebuild_pure_shared();
545 }
546
547 fn rebuild_pure_shared(&mut self) {
553 let mut table: PureTable = HashMap::new();
554 for (name, entry) in &self.entries {
555 let func = match &entry.body {
556 FuncBody::Pure(func) => func,
557 FuncBody::Both { pure, .. } => pure,
558 FuncBody::Script(_) | FuncBody::Ctx(_) => continue,
559 };
560 if let Some((module, base)) = split_qualified(name) {
561 table
562 .entry(module.to_string())
563 .or_default()
564 .insert(base.to_string(), Arc::clone(func));
565 }
566 }
567 self.pure_shared = Arc::new(table);
568 }
569
570 fn insert_qualified(
574 &mut self,
575 module: &str,
576 base: String,
577 mut meta: FuncMeta,
578 body: FuncBody<P>,
579 ) {
580 meta.name = qualify(module, &base);
581 meta.module = module.to_string();
582 if self.entries.contains_key(&meta.name) {
587 panic!("duplicate function registration `{}`", meta.name);
588 }
589 self.insert_native(meta.name.clone(), meta, body);
590 }
591
592 pub(super) fn register_host(
593 &mut self,
594 module: &str,
595 name: String,
596 mut meta: FuncMeta,
597 func: NativeFn<P>,
598 ) {
599 meta.kind = FuncKind::HostCtx;
600 self.insert_qualified(module, name, meta, FuncBody::Ctx(func));
601 }
602
603 pub(super) fn register_pure_host(
604 &mut self,
605 module: &str,
606 name: String,
607 mut meta: FuncMeta,
608 func: PureFn,
609 ) {
610 meta.kind = FuncKind::HostPure;
611 self.insert_qualified(module, name, meta, FuncBody::Pure(func));
612 }
613
614 pub(super) fn register_both_host(
615 &mut self,
616 module: &str,
617 name: String,
618 mut meta: FuncMeta,
619 func: NativeFn<P>,
620 template: PureFn,
621 ) {
622 meta.kind = FuncKind::HostCtx;
623 self.insert_qualified(
624 module,
625 name,
626 meta,
627 FuncBody::Both {
628 pure: template,
629 ctx: func,
630 },
631 );
632 }
633
634 #[allow(clippy::too_many_arguments)]
639 pub(super) fn define_script(
640 &mut self,
641 name: &str,
642 params: &[(String, TypeTag, bool)],
643 return_type: TypeTag,
644 return_spelling: &str,
645 is_async: bool,
646 body: &[Step],
647 module: Option<&str>,
648 ) -> Result<()> {
649 let qualified = qualify(SCRIPT_MODULE_NAME, name);
650 let shadowable = matches!(
651 self.entries.get(&qualified).map(|entry| &entry.body),
652 Some(FuncBody::Script(_))
653 );
654 let reserved = self.entries.iter().any(|(key, entry)| {
659 split_qualified(key).is_some_and(|(_, base)| base == name)
660 && !matches!(entry.body, FuncBody::Script(_))
661 });
662 if reserved && !shadowable {
663 anyhow::bail!("cannot shadow reserved function `{name}`");
664 }
665 if self
666 .scopes
667 .last()
668 .is_some_and(|frame| frame.defined.contains(&qualified))
669 {
670 anyhow::bail!("duplicate function `{name}` in same scope");
671 }
672 check_script_param_tags(name, params)?;
673 let old = self.entries.insert(
674 qualified.clone(),
675 FuncEntry {
676 meta: FuncMeta {
677 name: qualified.clone(),
678 module: SCRIPT_MODULE_NAME.to_string(),
679 kind: FuncKind::Script,
680 params: Some(
681 params
682 .iter()
683 .map(|(pname, param_type, optional)| {
684 Ok(FuncParam {
685 name: pname.clone(),
686 param_type: Some(param_type.clone()),
687 allowed: None,
688 docs: "",
691 options: None,
692 optional: *optional,
693 })
694 })
695 .collect::<Result<_>>()?,
696 ),
697 returns: Some(return_type.clone()),
698 rpn: false,
699 summary: "DSL-defined function.",
700 docs: "Defined via FUNC in script.",
701 examples: &[],
702 },
703 body: FuncBody::Script(FuncDefData {
704 params: params.to_vec(),
705 return_type,
706 return_spelling: return_spelling.to_string(),
707 is_async,
708 body: body.to_vec(),
709 module: module.map(|m| m.to_string()),
710 }),
711 },
712 );
713 if let Some(frame) = self.scopes.last_mut() {
714 frame.defined.insert(qualified.clone());
715 if let Some(old) = old {
716 frame.shadowed.push((qualified, old));
717 }
718 }
719 Ok(())
720 }
721
722 #[allow(clippy::too_many_arguments)]
730 pub(super) fn define_aliased_in(
731 &mut self,
732 depth: usize,
733 alias: &str,
734 name: &str,
735 params: &[(String, TypeTag, bool)],
736 return_type: TypeTag,
737 return_spelling: &str,
738 is_async: bool,
739 body: &[Step],
740 module: Option<&str>,
741 ) -> Result<()> {
742 let qualified = qualify(alias, name);
743 let shadowable = matches!(
744 self.entries.get(&qualified).map(|entry| &entry.body),
745 Some(FuncBody::Script(_))
746 );
747 let reserved = self.entries.iter().any(|(key, entry)| {
751 split_qualified(key).is_some_and(|(_, base)| base == name)
752 && !matches!(entry.body, FuncBody::Script(_))
753 });
754 if reserved && !shadowable {
755 anyhow::bail!("cannot shadow reserved function `{name}`");
756 }
757 let depth_in_range = depth < self.scopes.len();
761 let frame_idx = if depth_in_range {
762 depth
763 } else {
764 self.scopes.len().saturating_sub(1)
765 };
766 if self
767 .scopes
768 .get(frame_idx)
769 .is_some_and(|frame| frame.defined.contains(&qualified))
770 {
771 anyhow::bail!("duplicate function `{name}` in same scope");
772 }
773 check_script_param_tags(name, params)?;
774 let old = self.entries.insert(
775 qualified.clone(),
776 FuncEntry {
777 meta: FuncMeta {
778 name: qualified.clone(),
779 module: alias.to_string(),
780 kind: FuncKind::Script,
781 params: Some(
782 params
783 .iter()
784 .map(|(pname, param_type, optional)| {
785 Ok(FuncParam {
786 name: pname.clone(),
787 param_type: Some(param_type.clone()),
788 allowed: None,
789 docs: "",
790 options: None,
791 optional: *optional,
792 })
793 })
794 .collect::<Result<_>>()?,
795 ),
796 returns: Some(return_type.clone()),
797 rpn: false,
798 summary: "DSL-defined function.",
799 docs: "Defined via FUNC in an imported script.",
800 examples: &[],
801 },
802 body: FuncBody::Script(FuncDefData {
803 params: params.to_vec(),
804 return_type,
805 return_spelling: return_spelling.to_string(),
806 is_async,
807 body: body.to_vec(),
808 module: module.map(|m| m.to_string()),
809 }),
810 },
811 );
812 if let Some(frame) = self.scopes.get_mut(frame_idx) {
813 frame.defined.insert(qualified.clone());
814 if let Some(old) = old {
815 frame.shadowed.push((qualified, old));
816 }
817 }
818 Ok(())
819 }
820
821 pub(super) fn scope_depth(&self) -> usize {
824 self.scopes.len()
825 }
826
827 pub(super) fn push_scope(&mut self) {
830 self.scopes.push(ScopeFrame {
831 defined: HashSet::new(),
832 shadowed: Vec::new(),
833 });
834 }
835
836 pub(super) fn pop_scope(&mut self) {
839 let Some(frame) = self.scopes.pop() else {
840 return;
841 };
842 for name in frame.defined {
843 self.entries.remove(&name);
844 }
845 for (name, old) in frame.shadowed {
846 self.entries.insert(name, old);
847 }
848 }
849
850 pub(super) fn contains_script(&self, name: &str) -> bool {
854 matches!(
855 self.entries.get(name).map(|entry| &entry.body),
856 Some(FuncBody::Script(_))
857 )
858 }
859
860 fn clone_pure_fn(&self, name: &str) -> Option<PureFn> {
864 match self.entries.get(name)?.body {
865 FuncBody::Pure(ref func) => Some(Arc::clone(func)),
866 FuncBody::Both { ref pure, .. } => Some(Arc::clone(pure)),
867 _ => None,
868 }
869 }
870
871 pub(super) fn pure_shared(&self) -> Arc<PureTable> {
875 Arc::clone(&self.pure_shared)
876 }
877
878 pub(super) fn all_metas(&self) -> Vec<FuncMeta> {
881 self.entries_metas()
882 }
883
884 fn clone_ctx_fn(&self, name: &str) -> Option<NativeFn<P>> {
889 match self.entries.get(name)?.body {
890 FuncBody::Ctx(ref func) => Some(Arc::clone(func)),
891 FuncBody::Both { ref ctx, .. } => Some(Arc::clone(ctx)),
892 _ => None,
893 }
894 }
895
896 fn meta(&self, name: &str) -> Option<FuncMeta> {
897 self.entries.get(name).map(|entry| entry.meta.clone())
898 }
899
900 fn native_metas(&self) -> Vec<FuncMeta> {
901 let mut out: Vec<FuncMeta> = Vec::new();
902 for entry in self.entries.values() {
903 if !matches!(entry.body, FuncBody::Script(_)) {
904 out.push(entry.meta.clone());
905 }
906 }
907 out.sort_by(|a, b| a.name.cmp(&b.name));
908 out
909 }
910
911 fn entries_metas(&self) -> Vec<FuncMeta> {
914 let mut out: Vec<FuncMeta> = self
915 .entries
916 .values()
917 .map(|entry| entry.meta.clone())
918 .collect();
919 out.sort_by(|a, b| a.name.cmp(&b.name));
920 out
921 }
922
923 pub fn set_script_docs(&mut self, docs: &HashMap<String, (String, String)>) {
926 for (base, pair) in docs {
927 self.script_docs
928 .insert(qualify(SCRIPT_MODULE_NAME, base), pair.clone());
929 }
930 }
931
932 pub fn script_doc_for(&self, qualified: &str) -> Option<(String, String)> {
934 self.script_docs.get(qualified).cloned()
935 }
936
937 pub fn exported_metas(&self, func_exports: &[String]) -> anyhow::Result<Vec<FuncMeta>> {
940 let mut out = Vec::with_capacity(func_exports.len());
941 for name in func_exports {
942 let qualified = match name.split_once("::") {
946 None => qualify(SCRIPT_MODULE_NAME, name),
947 Some(_) => name.clone(),
948 };
949 match self.entries.get(&qualified) {
950 Some(entry) => out.push(entry.meta.clone()),
951 None => anyhow::bail!(
952 "EXPORT `{name}` matches no defined script function or known host function"
953 ),
954 }
955 }
956 Ok(out)
957 }
958}
959
960impl<P: ProcessManager> Clone for FunctionRegistry<P> {
961 fn clone(&self) -> Self {
962 Self {
963 entries: self.entries.clone(),
964 scopes: self.scopes.clone(),
965 pure_shared: Arc::clone(&self.pure_shared),
966 script_docs: self.script_docs.clone(),
967 }
968 }
969}
970
971pub fn builtin_function_names() -> HashSet<String> {
978 let mut names = FunctionRegistry::<DefaultProcessManager>::with_builtins().keys();
979 names.insert(KEYWORD_INSPECT.to_string());
980 names
981}
982
983pub fn builtin_function_metas() -> Vec<FuncMeta> {
987 FunctionRegistry::<DefaultProcessManager>::with_builtins().native_metas()
988}
989
990pub fn std_module_table() -> oxdock_parser::ModuleTable {
995 let func_names: HashSet<String> = builtin_function_metas()
997 .into_iter()
998 .map(|meta| base_name(&meta.name).to_string())
999 .collect();
1000 oxdock_parser::ModuleTable {
1001 modules: HashMap::from([(
1002 STD_MODULE_NAME.to_string(),
1003 Some(oxdock_parser::ModuleFuncs { func_names }),
1004 )]),
1005 }
1006}
1007
1008#[oxdock_func(pure, returns = TypeTag::Int)]
1021#[example(
1022 name = "convert",
1023 code = r###"
1024 IMPORT [STD]
1025 LET $n: INT = INT("42")
1026 ASSERT_EQ $n 42
1027 LET $flag: INT = INT(true)
1028 ASSERT_EQ $flag 1
1029 "###
1030)]
1031fn int(
1032 #[union(Int, Float, String, Bool)]
1034 val: Value,
1035) -> Result<Value> {
1036 super::args::int_from_value(val)
1037}
1038
1039#[oxdock_func(pure, returns = TypeTag::Float)]
1044#[example(
1045 name = "convert",
1046 code = r###"
1047 IMPORT [STD]
1048 LET $f: FLOAT = FLOAT("1.5")
1049 ASSERT_EQ $f 1.5
1050 LET $whole: FLOAT = FLOAT(2)
1051 ASSERT_EQ $whole 2.0
1052 "###
1053)]
1054fn float(
1055 #[union(Float, Int, String)]
1057 val: Value,
1058) -> Result<Value> {
1059 super::args::float_from_value(val)
1060}
1061
1062#[oxdock_func(pure, returns = TypeTag::String)]
1067#[example(
1068 name = "format and round-trip",
1069 code = r###"
1070 # Byte counts render in the largest exact unit.
1071 IMPORT [STD]
1072 LET $pretty: STRING = FORMAT_BYTE_COUNT(1_048_576)
1073 ASSERT_EQ $pretty "1MiB"
1074
1075 # The pair round-trips through the parser.
1076 LET $back: INT = PARSE_BYTE_COUNT($pretty)
1077 ASSERT_EQ $back 1_048_576
1078 "###
1079)]
1080fn format_byte_count(
1081 bytes: i64,
1083) -> Result<Value> {
1084 if bytes < 0 {
1085 return Err(anyhow::anyhow!(
1086 "FORMAT_BYTE_COUNT needs a non-negative byte count, got {bytes}"
1087 ));
1088 }
1089 Ok(Value::string(oxdock_parser::command::format_byte_count(
1090 bytes as u64,
1091 )))
1092}
1093
1094#[oxdock_func(pure, returns = TypeTag::Int)]
1129#[example(
1130 name = "parse",
1131 code = r###"
1132 IMPORT [STD]
1133 LET $n: INT = PARSE_BYTE_COUNT("10KB")
1134 ASSERT_EQ $n 10_000
1135 LET $identity: INT = PARSE_BYTE_COUNT(512)
1136 ASSERT_EQ $identity 512
1137 "###
1138)]
1139fn parse_byte_count(
1140 #[union(Int, Float, String)]
1142 text: Value,
1143) -> Result<Value> {
1144 if let Some(n) = text.as_i64() {
1145 if n < 0 {
1146 return Err(anyhow::anyhow!(
1147 "PARSE_BYTE_COUNT needs a non-negative byte count, got {n}"
1148 ));
1149 }
1150 return Ok(Value::int(n));
1151 }
1152 if let Some(f) = text.as_f64() {
1153 if f.is_finite() && f.fract() == 0.0 && f >= 0.0 && f <= i64::MAX as f64 {
1154 return Ok(Value::int(f as i64));
1155 }
1156 return Err(anyhow::anyhow!(
1157 "PARSE_BYTE_COUNT needs an integral byte count, got {f:?}"
1158 ));
1159 }
1160 let Some(s) = text.as_str() else {
1161 return Err(anyhow::anyhow!(
1162 "PARSE_BYTE_COUNT needs a token or number, found {text:?}"
1163 ));
1164 };
1165 let n = oxdock_parser::command::parse_byte_count(s)?;
1166 let n = i64::try_from(n)
1167 .map_err(|_| anyhow::anyhow!("PARSE_BYTE_COUNT out of INT range: {s:?}"))?;
1168 Ok(Value::int(n))
1169}
1170
1171#[oxdock_func(pure, returns = TypeTag::String)]
1176#[example(
1177 name = "format and round-trip",
1178 code = r###"
1179 # Durations render in the largest exact unit.
1180 IMPORT [STD]
1181 LET $pretty: STRING = FORMAT_DURATION(90_000)
1182 ASSERT_EQ $pretty "90s"
1183
1184 # The pair round-trips through the parser.
1185 LET $back: INT = PARSE_DURATION($pretty)
1186 ASSERT_EQ $back 90_000
1187 "###
1188)]
1189fn format_duration(
1190 millis: i64,
1192) -> Result<Value> {
1193 if millis < 0 {
1194 return Err(anyhow::anyhow!(
1195 "FORMAT_DURATION needs non-negative milliseconds, got {millis}"
1196 ));
1197 }
1198 Ok(Value::string(oxdock_parser::command::format_duration(
1199 &std::time::Duration::from_millis(millis as u64),
1200 )))
1201}
1202
1203#[oxdock_func(pure, returns = TypeTag::Int)]
1209#[example(
1210 name = "parse",
1211 code = r###"
1212 # A bare number means seconds, like TIMEOUT.
1213 IMPORT [STD]
1214 LET $ms: INT = PARSE_DURATION("2m")
1215 ASSERT_EQ $ms 120_000
1216
1217 # Milliseconds stay exact.
1218 LET $exact: INT = PARSE_DURATION("1500ms")
1219 ASSERT_EQ $exact 1_500
1220
1221 # One optional space separates number from unit.
1222 LET $spaced: INT = PARSE_DURATION("1 h")
1223 ASSERT_EQ $spaced 3_600_000
1224 "###
1225)]
1226fn parse_duration(
1227 text: String,
1229) -> Result<Value> {
1230 let duration = oxdock_parser::command::parse_duration(&text)?;
1231 let millis = i64::try_from(duration.as_millis())
1232 .map_err(|_| anyhow::anyhow!("PARSE_DURATION out of INT range: {text:?}"))?;
1233 Ok(Value::int(millis))
1234}
1235
1236#[oxdock_func(rpn, returns = TypeTag::ListOf(std::sync::Arc::new(TypeTag::String)))]
1241#[example(
1242 name = "match",
1243 code = r###"
1244 IMPORT [STD]
1245 WRITE "notes-a.md" "a"
1246 WRITE "notes-b.md" "b"
1247 WRITE "other.txt" "c"
1248 LET $found: LIST<STRING> = GLOB("notes-*.md")
1249 ASSERT_EQ $found.0 "notes-a.md"
1250 ASSERT_EQ $found.1 "notes-b.md"
1251 "###
1252)]
1253fn glob<P: ProcessManager>(
1254 cx: &mut StepCtx<P>,
1255 #[union(String, Path)]
1257 pattern: Value,
1258) -> Result<Value> {
1259 let text = super::args::string_or_path_text(&pattern)?;
1260 super::args::glob_from_value(&[Value::string(text)], cx)
1261}
1262
1263#[oxdock_func(rpn, returns = TypeTag::MapOf(std::sync::Arc::new(TypeTag::Any)))]
1268#[example(
1269 name = "load",
1270 code = r###"
1271 IMPORT [STD]
1272 WRITE "cfg.toml" "title = \"demo\""
1273 LET $cfg: MAP<ANY> = LOAD_TOML("cfg.toml")
1274 ASSERT_EQ $cfg.title "demo"
1275 "###
1276)]
1277fn load_toml<P: ProcessManager>(
1278 cx: &mut StepCtx<P>,
1279 #[union(String, Path)]
1281 path: Value,
1282) -> Result<Value> {
1283 let text = super::args::string_or_path_text(&path)?;
1284 super::args::load_toml_from_value(&[Value::string(text)], cx)
1285}
1286
1287#[oxdock_func(rpn, returns = TypeTag::Any)]
1295#[example(
1296 name = "load",
1297 code = r###"
1298 IMPORT [STD]
1299 WRITE "data.json" "{\"a\": 1}"
1300 LET $doc: MAP<ANY> = LOAD_JSON("data.json")
1301 ASSERT_EQ $doc.a 1
1302 "###
1303)]
1304fn load_json<P: ProcessManager>(
1305 cx: &mut StepCtx<P>,
1306 #[union(String, Path)]
1308 path: Value,
1309) -> Result<Value> {
1310 let text = super::args::string_or_path_text(&path)?;
1311 super::args::load_json_from_value(&[Value::string(text)], cx)
1312}
1313
1314#[oxdock_func(rpn, returns = TypeTag::String)]
1324#[example(
1325 name = "hash",
1326 code = r###"
1327 IMPORT [STD]
1328 WRITE payload.txt hello
1329 LET $digest: STRING = HASH_SHA256("payload.txt")
1330 ASSERT_EQ $digest "2cf24dba5fb0a30e26e83b2ac5b9e29e1b161e5c1fa7425e73043362938b9824"
1331 "###
1332)]
1333fn hash_sha256<P: ProcessManager>(
1334 cx: &mut StepCtx<P>,
1335 #[union(String, Path)]
1337 path: Value,
1338) -> Result<Value> {
1339 use sha2::Digest;
1340
1341 let text = super::args::string_or_path_text(&path)?;
1342 let target = cx.state.fs.resolve_read(&cx.state.cwd, &text)?;
1343 let mut hasher = sha2::Sha256::new();
1344 super::fs_ops::hash_path(cx.state.fs.as_ref(), &target, "", &mut hasher)?;
1345 let digest = hasher.finalize();
1346 let bytes: &[u8] = digest.as_ref();
1347 Ok(Value::string(oxdock_utils::hex_encode(bytes)))
1348}
1349
1350#[oxdock_func(rpn, returns = TypeTag::String)]
1361#[example(
1362 name = "cwd",
1363 code = r###"
1364 IMPORT [STD]
1365 WORKDIR sub
1366 LET $c: STRING = CWD()
1367 ASSERT_CONTAINS $c "sub"
1368 "###
1369)]
1370fn cwd<P: ProcessManager>(cx: &mut StepCtx<P>) -> Result<Value> {
1371 if cx.state.fs.is_snapshot_pending() {
1372 return Ok(Value::string(super::SNAPSHOT_PENDING_DISPLAY.to_string()));
1373 }
1374 let concrete = cx.state.fs.concretize_cwd(&cx.state.cwd);
1375 let real = super::fs_ops::canonical_cwd(cx.state.fs.as_ref(), &concrete)?;
1376 Ok(Value::string(real))
1377}
1378
1379#[oxdock_func(pure, returns = TypeTag::MapOf(std::sync::Arc::new(TypeTag::Any)))]
1385#[example(
1386 name = "parse",
1387 code = r###"
1388 IMPORT [STD]
1389 LET $doc: MAP<ANY> = PARSE_TOML("title = \"demo\"")
1390 ASSERT_EQ $doc.title "demo"
1391 "###
1392)]
1393fn parse_toml(
1394 text: String,
1396) -> Result<Value> {
1397 super::args::parse_toml_from_value(Value::string(text))
1398}
1399
1400#[oxdock_func(pure, returns = TypeTag::Any)]
1409#[example(
1410 name = "parse",
1411 code = r###"
1412 # Parse in-memory JSON text with the same conversion as file loading.
1413 IMPORT [STD]
1414 LET $body: STRING = "{\"a\": 1}"
1415 LET $doc: ANY = PARSE_JSON($body)
1416 ASSERT_EQ $doc.a 1
1417
1418 # Top-level arrays parse to LIST, which is why the return is ANY.
1419 LET $items: LIST<ANY> = PARSE_JSON("[1, 2]")
1420 ASSERT_EQ $items.0 1
1421 ASSERT_EQ $items.1 2
1422 "###
1423)]
1424fn parse_json(
1425 text: String,
1427) -> Result<Value> {
1428 super::args::parse_json_from_value(Value::string(text))
1429}
1430
1431#[oxdock_func(returns = TypeTag::String)]
1437#[example(
1438 name = "describe",
1439 code = r###"
1440 IMPORT [STD]
1441 WRITE "entry.txt" "words"
1442 LET $kind: STRING = PATH_TYPE("entry.txt")
1443 ASSERT_EQ $kind "file"
1444 LET $missing: STRING = PATH_TYPE("no-such-entry.txt")
1445 ASSERT_EQ $missing "absent"
1446 "###
1447)]
1448fn path_type<P: ProcessManager>(
1449 cx: &mut StepCtx<P>,
1450 #[union(String, Path)]
1452 path: Value,
1453) -> Result<Value> {
1454 let text = super::args::string_or_path_text(&path)?;
1455 super::args::path_type_from_value(&[Value::string(text)], cx)
1456}
1457
1458#[oxdock_func(returns = TypeTag::Bool)]
1467#[example(
1468 name = "probe",
1469 code = r###"
1470 # An absent nested path is writable when its ancestor is.
1471 IMPORT [STD]
1472 LET $fresh: BOOL = PATH_WRITABLE("probe-check/nested/file.txt")
1473 ASSERT_EQ $fresh true
1474
1475 # The empty string never aliases the working directory.
1476 LET $empty: BOOL = PATH_WRITABLE("")
1477 ASSERT_EQ $empty false
1478 "###
1479)]
1480fn path_writable<P: ProcessManager>(
1481 cx: &mut StepCtx<P>,
1482 #[union(String, Path)]
1484 path: Value,
1485) -> Result<Value> {
1486 let text = super::args::string_or_path_text(&path)?;
1487 super::args::path_writable_from_value(&[Value::string(text)], cx)
1488}
1489
1490#[oxdock_func(returns = TypeTag::Bool)]
1503#[example(
1504 name = "probe",
1505 code = r###"
1506 # Missing tools read false instead of failing the run.
1507 IMPORT [STD]
1508 LET $missing: BOOL = IS_EXEC("no-such-tool-xyz")
1509 ASSERT_EQ $missing false
1510
1511 # Plain files are not executable on any platform.
1512 WRITE tool.txt payload
1513 LET $plain: BOOL = IS_EXEC("tool.txt")
1514 ASSERT_EQ $plain false
1515 "###
1516)]
1517fn is_exec<P: ProcessManager>(
1518 cx: &mut StepCtx<P>,
1519 #[union(String, Path)]
1521 name: Value,
1522) -> Result<Value> {
1523 let text = super::args::string_or_path_text(&name)?;
1524 super::args::is_exec_from_value(&[Value::string(text)], cx)
1525}
1526
1527#[oxdock_func(pure, returns = TypeTag::Bool)]
1533#[example(
1534 name = "probe",
1535 code = r###"
1536 IMPORT [STD]
1537 LET $m: MAP<ANY> = PARSE_JSON("{\"a\": 1}")
1538 LET $hit: BOOL = HAS_KEY($m, "a")
1539 ASSERT_EQ $hit true
1540 LET $miss: BOOL = HAS_KEY($m, "b")
1541 ASSERT_EQ $miss false
1542 "###
1543)]
1544fn has_key(
1545 map: BTreeMap<String, Value>,
1547 key: String,
1549) -> Result<Value> {
1550 super::args::has_key_from_value(Value::map(map), &key)
1551}
1552
1553#[oxdock_func(pure, returns = TypeTag::MapOf(std::sync::Arc::new(TypeTag::Any)))]
1559#[example(
1560 name = "insert",
1561 code = r###"
1562 IMPORT [STD]
1563 LET $m: MAP<ANY> = MAP_SET({seed: 0}, "a", 1)
1564 ASSERT_EQ $m.a 1
1565 "###
1566)]
1567fn map_set(
1568 map: BTreeMap<String, Value>,
1570 key: String,
1572 value: Value,
1574) -> Result<Value> {
1575 super::args::map_set_from_value(Value::map(map), key, value)
1576}
1577
1578#[oxdock_func(returns = TypeTag::Float, summary = "Draw a random FLOAT uniformly from [0, 1), optionally seeded.")]
1586#[example(
1587 name = "seeded draw",
1588 code = r###"
1589 # A seed draws the same value on every run.
1590 IMPORT [STD]
1591 LET $one: FLOAT = RAND({seed: 7})
1592 LET $two: FLOAT = RAND({seed: 7})
1593 ASSERT_EQ $one $two
1594 "###
1595)]
1596#[example(
1597 name = "unseeded draw",
1598 code = r###"
1599 # Scale a unit draw into a backoff delay between 1 and 11 seconds.
1600 IMPORT [STD]
1601 LET $draw: FLOAT = RAND()
1602 LET $delay: FLOAT = 1.0 + $draw * 10.0
1603 IF $delay < 1.0 {
1604 EXIT 1
1605 }
1606 IF $delay >= 11.0 {
1607 EXIT 1
1608 }
1609 ECHO "retrying in {{ $delay }}s"
1610 "###
1611)]
1612fn rand<P: ProcessManager>(
1613 cx: &mut StepCtx<P>,
1614 #[options("seed?: INT")]
1616 #[optional]
1617 options: BTreeMap<String, Value>,
1618) -> Result<Value> {
1619 let _ = cx;
1620 let seed = options
1623 .get("seed")
1624 .map(|value| value.as_i64().expect("check_options verified INT"));
1625 super::args::rand_float_from_value(seed)
1626}
1627
1628#[oxdock_func(pure, returns = TypeTag::String)]
1634#[example(
1635 name = "encode",
1636 code = r###"
1637 # Encode text to standard base64.
1638 IMPORT [STD]
1639 LET $encoded: STRING = BASE64_ENCODE("hello")
1640 ASSERT_EQ $encoded "aGVsbG8="
1641 "###
1642)]
1643fn base64_encode(
1644 text: String,
1646) -> Result<Value> {
1647 super::args::base64_encode_from_value(Value::string(text))
1648}
1649
1650#[oxdock_func(pure, returns = TypeTag::String)]
1657#[example(
1658 name = "decode",
1659 code = r###"
1660 # Decode standard base64 back to text.
1661 IMPORT [STD]
1662 LET $decoded: STRING = BASE64_DECODE("aGVsbG8=")
1663 ASSERT_EQ $decoded "hello"
1664 "###
1665)]
1666fn base64_decode(
1667 text: String,
1669) -> Result<Value> {
1670 super::args::base64_decode_from_value(Value::string(text))
1671}
1672
1673#[oxdock_func(pure, returns = TypeTag::String)]
1680#[example(
1681 name = "encode",
1682 code = r###"
1683 IMPORT [STD]
1684 LET $json: STRING = TO_JSON({a: 1})
1685 ASSERT_EQ $json "{\"a\":1}\n"
1686 "###
1687)]
1688fn to_json(
1689 #[union(String, Int, Float, Bool, List, Map)]
1691 value: Value,
1692) -> Result<Value> {
1693 super::args::to_json_from_value(value)
1694}
1695
1696#[oxdock_func(pure, returns = TypeTag::String)]
1704#[example(
1705 name = "name the word",
1706 code = r###"
1707 IMPORT [STD]
1708 LET $word: STRING = TYPE_OF(42)
1709 ASSERT_EQ $word "INT"
1710 "###
1711)]
1712fn type_of(
1713 value: Value,
1715) -> Result<Value> {
1716 super::args::type_of_from_value(value)
1717}
1718
1719#[oxdock_func(pure, returns = TypeTag::MapOf(std::sync::Arc::new(TypeTag::Any)))]
1727#[example(
1728 name = "merge",
1729 code = r###"
1730 IMPORT [STD]
1731 LET $m: MAP<ANY> = MERGE_MAPS([{a: 1}, {b: 2}], "overwrite")
1732 ASSERT_EQ $m.a 1
1733 ASSERT_EQ $m.b 2
1734 "###
1735)]
1736fn merge_maps(
1737 maps: Vec<BTreeMap<String, Value>>,
1739 #[values("fail_on_duplicate", "overwrite")]
1741 policy: String,
1742) -> Result<Value> {
1743 super::args::merge_maps_from_value(
1744 Value::list(maps.into_iter().map(Value::map).collect()),
1745 policy,
1746 )
1747}
1748
1749#[oxdock_func(pure, returns = TypeTag::String)]
1754#[example(
1755 name = "report",
1756 code = r###"
1757 # The engine reports its own build version as a dotted string.
1758 IMPORT [STD]
1759 LET $v: STRING = VERSION()
1760 ASSERT_CONTAINS $v "."
1761 "###
1762)]
1763fn version() -> Result<Value> {
1764 Ok(Value::string(env!("CARGO_PKG_VERSION").to_string()))
1765}
1766
1767#[oxdock_func(returns = TypeTag::ListOf(std::sync::Arc::new(TypeTag::String)))]
1772#[example(
1773 name = "list",
1774 code = r###"
1775 IMPORT [STD]
1776 LET $names: LIST<STRING> = FUNCTIONS()
1777 ASSERT_CONTAINS $names "STD::INT"
1778 "###
1779)]
1780fn functions<P: ProcessManager>(cx: &mut StepCtx<P>) -> Result<Value> {
1781 let mut names: Vec<String> = cx
1782 .state
1783 .list_functions()
1784 .into_iter()
1785 .map(|meta| meta.name)
1786 .collect();
1787 names.sort();
1788 names.dedup();
1789 Ok(Value::list(names.into_iter().map(Value::string).collect()))
1790}
1791
1792#[oxdock_func(
1807 returns = TypeTag::Record(std::sync::Arc::from([Field {
1808 name: "name".to_string(),
1809 ty: TypeTag::String,
1810 docs: "Qualified function name.",
1811 optional: false,
1812 }, Field {
1813 name: "module".to_string(),
1814 ty: TypeTag::String,
1815 docs: "Owning module.",
1816 optional: false,
1817 }, Field {
1818 name: "kind".to_string(),
1819 ty: TypeTag::String,
1820 docs: "Origin label (`host` or `script`).",
1821 optional: false,
1822 }, Field {
1823 name: "params".to_string(),
1824 ty: TypeTag::ListOf(std::sync::Arc::new(TypeTag::MapOf(std::sync::Arc::new(
1825 TypeTag::Any,
1826 )))),
1827 docs: "Parameter entries (empty for parameterless functions).",
1828 optional: false,
1829 }, Field {
1830 name: "returns".to_string(),
1831 ty: TypeTag::String,
1832 docs: "Structural return shape (empty when untagged).",
1833 optional: false,
1834 }, Field {
1835 name: "rpn".to_string(),
1836 ty: TypeTag::Bool,
1837 docs: "True when callable in RPN position.",
1838 optional: false,
1839 }, Field {
1840 name: "summary".to_string(),
1841 ty: TypeTag::String,
1842 docs: "One-line description.",
1843 optional: false,
1844 }]))
1845 summary = "Describe one function by qualified name."
1846)]
1847#[example(
1848 name = "describe",
1849 code = r###"
1850 IMPORT [STD]
1851 LET $info: MAP<ANY> = DESCRIBE("STD::INT")
1852 ASSERT_EQ $info.name "STD::INT"
1853 ASSERT_EQ $info.returns "INT"
1854 "###
1855)]
1856fn describe<P: ProcessManager>(
1857 cx: &mut StepCtx<P>,
1858 name: String,
1860) -> Result<Value> {
1861 if split_qualified(&name).is_none() && name != KEYWORD_INSPECT {
1862 anyhow::bail!(
1863 "unknown function `{name}`: DESCRIBE requires a qualified name (e.g. `STD::{name}`)"
1864 );
1865 }
1866 cx.state
1867 .describe_function(&name)
1868 .ok_or_else(|| anyhow::anyhow!("unknown function {name}"))
1869}
1870
1871#[oxdock_func(returns = TypeTag::ListOf(std::sync::Arc::new(TypeTag::String)))]
1877#[example(
1878 name = "list",
1879 code = r###"
1880 IMPORT [STD]
1881 LET $names: LIST<STRING> = TYPES()
1882 ASSERT_CONTAINS $names "STRING"
1883 "###
1884)]
1885fn types<P: ProcessManager>(cx: &mut StepCtx<P>) -> Result<Value> {
1886 Ok(Value::list(
1887 cx.state
1888 .type_names()
1889 .into_iter()
1890 .map(Value::string)
1891 .collect(),
1892 ))
1893}
1894
1895#[oxdock_func(returns = TypeTag::Record(std::sync::Arc::from([Field {
1901 name: "name".to_string(),
1902 ty: TypeTag::String,
1903 docs: "Queried type name.",
1904 optional: false,
1905}, Field {
1906 name: "summary".to_string(),
1907 ty: TypeTag::String,
1908 docs: "One-line description.",
1909 optional: false,
1910}, Field {
1911 name: "docs".to_string(),
1912 ty: TypeTag::String,
1913 docs: "Full documentation text.",
1914 optional: false,
1915}])))]
1916#[example(
1917 name = "describe",
1918 code = r###"
1919 IMPORT [STD]
1920 LET $info: MAP<ANY> = TYPE_DESCRIBE("STRING")
1921 ASSERT_EQ $info.name "STRING"
1922 "###
1923)]
1924fn type_describe<P: ProcessManager>(
1925 cx: &mut StepCtx<P>,
1926 name: String,
1928) -> Result<Value> {
1929 if let Some(descriptor) = cx.state.describe_type(&name) {
1930 let mut map = BTreeMap::new();
1931 map.insert(
1932 "name".to_string(),
1933 Value::string(descriptor.name.to_string()),
1934 );
1935 map.insert(
1936 "summary".to_string(),
1937 Value::string(descriptor.summary.to_string()),
1938 );
1939 map.insert(
1940 "docs".to_string(),
1941 Value::string(descriptor.docs.to_string()),
1942 );
1943 return Ok(Value::map(map));
1944 }
1945 if let Some(target) = cx.state.alias_target(&name) {
1948 let mut map = BTreeMap::new();
1949 map.insert("name".to_string(), Value::string(name.clone()));
1950 map.insert(
1951 "summary".to_string(),
1952 Value::string(format!("Script type alias for {target}.")),
1953 );
1954 map.insert(
1955 "docs".to_string(),
1956 Value::string(format!(
1957 "Declared with TYPE {name} = {target}. The alias expands structurally at every declaration."
1958 )),
1959 );
1960 return Ok(Value::map(map));
1961 }
1962 Err(anyhow::anyhow!("unknown type {name}"))
1963}
1964
1965#[oxdock_func(returns = TypeTag::String)]
1979#[example(
1980 name = "self",
1981 code = r###"
1982 # The running interpreter resolves to a non-empty path.
1983 IMPORT [STD]
1984 LET $exe: STRING = INTERPRETER()
1985 LET $nonempty: BOOL = $exe != ""
1986 ASSERT_EQ $nonempty true
1987 "###
1988)]
1989#[example(
1990 name = "dynamic assembly",
1991 code = r###"
1992 # Assemble the child script dynamically: the parent interpolates
1993 # its own bindings into the pipe, then runs the interpreter on it.
1994 # Unescaped {{ }} bakes in at render time; \{{ }} stays literal
1995 # so the child expands it with its own bindings.
1996 # The pipe delivers EOF when the producer step ends, so the child
1997 # reads exactly one script.
1998 IMPORT [STD]
1999 LET $exe: STRING = INTERPRETER()
2000 LET $who: STRING = "Ada"
2001 LET $child: PIPE
2002 WITH_IO [stdout=$child] ECHO """
2003 ECHO "hello {{ $who }}!"
2004 LET $who: STRING = "Grace"
2005 ECHO "child sees \{{ $who }}!"
2006 """
2007 LET $out: STRING = WITH_IO [stdin=$child] RUN [$exe]
2008 ASSERT_CONTAINS $out "hello Ada!"
2009 ASSERT_CONTAINS $out "child sees Grace!"
2010 "###
2011)]
2012fn interpreter<P: ProcessManager>(cx: &mut StepCtx<P>) -> Result<Value> {
2013 if let Some(staged) = cx.state.io.interpreter_override() {
2014 return Ok(Value::string(staged));
2015 }
2016 Ok(Value::string(oxdock_process::interpreter_exe()?))
2017}
2018
2019#[oxdock_func(returns = TypeTag::Bool)]
2027#[example(
2028 name = "main",
2029 code = r###"
2030 # Entry top level runs as main.
2031 IMPORT [STD]
2032 LET $m: BOOL = IS_MAIN()
2033 ASSERT_EQ $m true
2034 "###
2035)]
2036#[example(
2037 name = "library doubles as demo",
2038 fence_meta = "roots:unified",
2039 code = r###"
2040 # A library doubles as a runnable demo: guard the demo with
2041 # IF IS_MAIN() so importing it stays side effect free. The
2042 # parent writes both files, then runs each in a fresh
2043 # interpreter: direct execution prints the demo, importing
2044 # it does not. Unified roots: the child inherits one
2045 # workspace, so parent and child see the same files. The
2046 # exact stdout match proves the demo line stays out of the
2047 # importing run.
2048 IMPORT [STD]
2049
2050 # The library under test: demo guarded by IS_MAIN.
2051 WRITE lib.oxfile """
2052 IMPORT [STD]
2053 FUNC GREET($x: STRING): STRING { RETURN "hi \{{ $x }}" }
2054 EXPORT GREET
2055 IF IS_MAIN() {
2056 ECHO "demo: hi Ada"
2057 }
2058 """
2059
2060 # The importer: calls the library, prints only its own line.
2061 WRITE main.oxfile """
2062 IMPORT ["lib.oxfile" AS LIB]
2063 LET $g: STRING = LIB::GREET("Bo")
2064 ECHO "imported: \{{ $g }}"
2065 """
2066
2067 # Direct run executes the demo.
2068 LET $exe: STRING = INTERPRETER()
2069 LET $direct: STRING = RUN [$exe, "lib.oxfile"]
2070 ASSERT_CONTAINS $direct "demo: hi Ada"
2071
2072 # Importing run stays silent apart from its own line.
2073 LET $via: STRING = RUN [$exe, "main.oxfile"]
2074 ASSERT_EQ $via "imported: hi Bo\n"
2075 "###
2076)]
2077fn is_main<P: ProcessManager>(cx: &mut StepCtx<P>) -> Result<Value> {
2078 let main = match cx.state.module_stack.last() {
2079 None | Some(None) => true,
2080 Some(Some(_)) => false,
2081 };
2082 Ok(Value::bool(main))
2083}
2084
2085#[oxdock_func(returns = TypeTag::Bool)]
2099#[example(
2100 name = "null stdin",
2101 code = r###"
2102 # A null stdin is never a terminal, in every harness.
2103 IMPORT [STD]
2104 LET $term: BOOL = IS_TERMINAL("stdin")
2105 ASSERT_EQ $term false
2106 "###
2107)]
2108fn is_terminal<P: ProcessManager>(
2109 cx: &mut StepCtx<P>,
2110 #[values("stdin", "stdout", "stderr")]
2112 stream_name: String,
2113) -> Result<Value> {
2114 use std::io::IsTerminal;
2115 let terminal = match stream_name.as_str() {
2116 "stdin" => {
2117 if cx.stdin_pipe.is_some() {
2122 false
2123 } else {
2124 match &cx.stdin {
2125 CommandStdin::Null => false,
2126 #[cfg(not(miri))]
2127 CommandStdin::OsPipe(_) => false,
2128 CommandStdin::Stream(_) => false,
2129 CommandStdin::Inherit => std::io::stdin().is_terminal(),
2130 }
2131 }
2132 }
2133 "stdout" => {
2134 if cx.out_pipe.is_some() {
2135 false
2137 } else if cx.state.io.stdout().is_some() {
2138 false
2141 } else {
2142 match &cx.out {
2143 None => std::io::stdout().is_terminal(),
2145 #[cfg(not(miri))]
2147 Some(StreamHandle::Os(_)) => false,
2148 Some(StreamHandle::Stream(_)) => std::io::stdout().is_terminal(),
2158 }
2159 }
2160 }
2161 "stderr" => {
2162 if cx.state.io.stderr().is_some() {
2163 false
2165 } else {
2166 match &cx.err {
2167 None => std::io::stderr().is_terminal(),
2169 #[cfg(not(miri))]
2171 Some(StreamHandle::Os(_)) => false,
2172 Some(StreamHandle::Stream(_)) => false,
2175 }
2176 }
2177 }
2178 _ => anyhow::bail!(
2179 "IS_TERMINAL expects \"stdin\", \"stdout\", or \"stderr\", got {stream_name:?}"
2184 ),
2185 };
2186 Ok(Value::bool(terminal))
2187}
2188
2189#[oxdock_func(returns = TypeTag::Semaphore)]
2197#[example(
2198 name = "mint",
2199 code = r###"
2200 # Mint a semaphore admitting at most two holders.
2201 IMPORT [STD]
2202 LET $sem: SEMAPHORE = SEMAPHORE_NEW(2)
2203
2204 # A fresh semaphore reports its full cap as available.
2205 LET $free: INT = SEMAPHORE_AVAILABLE($sem)
2206 ASSERT_EQ $free 2
2207 "###
2208)]
2209fn semaphore_new<P: ProcessManager>(
2210 cx: &mut StepCtx<P>,
2211 max: i64,
2213) -> Result<Value> {
2214 let _ = cx;
2215 if max <= 0 {
2216 return Err(anyhow::anyhow!(
2217 "SEMAPHORE_NEW() requires a positive max, got {max}"
2218 ));
2219 }
2220 Ok(Value::semaphore(max as usize))
2221}
2222
2223#[oxdock_func(returns = TypeTag::Record(std::sync::Arc::from([Field {
2232 name: "held".to_string(),
2233 ty: TypeTag::Bool,
2234 docs: "`true` with the permit under `permit`, `false` with no `permit` key.",
2235 optional: false,
2236}, Field {
2237 name: "permit".to_string(),
2238 ty: TypeTag::Permit,
2239 docs: "Permit handle; read only when `held`.",
2240 optional: true,
2241}])))]
2242#[example(
2243 name = "acquire",
2244 code = r###"
2245 # First acquire holds with a permit to bind.
2246 IMPORT [STD]
2247 LET $sem: SEMAPHORE = SEMAPHORE_NEW(1)
2248 LET $first: MAP<held: BOOL, permit?: PERMIT> = SEMAPHORE_TRY_ACQUIRE($sem)
2249 ASSERT_EQ $first.held true
2250 LET $permit: PERMIT = $first.permit
2251
2252 # A capped semaphore answers held false with no permit key.
2253 LET $second: MAP<held: BOOL, permit?: PERMIT> = SEMAPHORE_TRY_ACQUIRE($sem)
2254 ASSERT_EQ $second.held false
2255 LET $has_permit: BOOL = HAS_KEY($second, "permit")
2256 ASSERT_EQ $has_permit false
2257 "###
2258)]
2259fn semaphore_try_acquire<P: ProcessManager>(
2260 cx: &mut StepCtx<P>,
2261 sem: Arc<SemaphoreState>,
2263) -> Result<Value> {
2264 let _ = cx;
2265 let mut map = BTreeMap::new();
2266 if sem.try_acquire() {
2267 map.insert("held".to_string(), Value::bool(true));
2268 map.insert("permit".to_string(), Value::permit(&sem));
2269 } else {
2270 map.insert("held".to_string(), Value::bool(false));
2271 }
2272 Ok(Value::map(map))
2273}
2274
2275#[oxdock_func(pure, returns = TypeTag::Int)]
2282#[example(
2283 name = "readout",
2284 code = r###"
2285 # Hold one permit on a cap of two.
2286 IMPORT [STD]
2287 LET $sem: SEMAPHORE = SEMAPHORE_NEW(2)
2288 LET $acq: MAP<held: BOOL, permit?: PERMIT> = SEMAPHORE_TRY_ACQUIRE($sem)
2289 ASSERT_EQ $acq.held true
2290
2291 # One held permit leaves exactly one free.
2292 LET $free: INT = SEMAPHORE_AVAILABLE($sem)
2293 ASSERT_EQ $free 1
2294 "###
2295)]
2296fn semaphore_available(
2297 sem: Arc<SemaphoreState>,
2299) -> Result<Value> {
2300 Ok(Value::int(sem.available() as i64))
2301}
2302
2303#[oxdock_func(
2312 rpn,
2313 returns = TypeTag::union(vec![TypeTag::String, TypeTag::Pipe]),
2314 template = text_trim_string
2315)]
2316#[example(
2317 name = "trim",
2318 code = r###"
2319 # Leading and trailing whitespace falls away.
2320 IMPORT [STD]
2321 LET $clean: STRING = TEXT_TRIM(" hello ")
2322 ASSERT_EQ $clean "hello"
2323 "###
2324)]
2325#[example(
2326 name = "trim pipe mirrors",
2327 code = r###"
2328 # Pipe input mints pipe output with the same transform.
2329 IMPORT [STD]
2330 LET $cap: PIPE
2331 WITH_IO [stdout=$cap] {
2332 ECHO " hello "
2333 }
2334 LET $out: PIPE = TEXT_TRIM($cap)
2335 WITH_IO [stdin=$out] READ_LINE $line
2336 ASSERT_EQ $line "hello"
2337 "###
2338)]
2339#[example(
2340 name = "trim template",
2341 code = r###"
2342 # String inputs run inside placeholders too.
2343 IMPORT [STD]
2344 LET $msg: STRING = 'clean:{{ STD::TEXT_TRIM(" hello ") }}'
2345 ASSERT_EQ $msg "clean:hello"
2346 "###
2347)]
2348#[example(
2349 name = "trim file template",
2350 code = r###"
2351 # EXPAND templates resolve the same registry.
2352 IMPORT [STD]
2353 WRITE "tpl.txt" "clean:\{{ STD::TEXT_TRIM(\" hello \") }}"
2354 LET $out: STRING = EXPAND "tpl.txt"
2355 ASSERT_EQ $out "clean:hello"
2356 "###
2357)]
2358fn text_trim<P: ProcessManager>(
2359 cx: &mut StepCtx<P>,
2360 #[union(String, Pipe)]
2362 text: Value,
2363) -> Result<Value> {
2364 super::args::mirror_stream(cx, "TEXT_TRIM", &text, super::args::TextPump::Trim)
2365}
2366
2367fn text_trim_string(text: Value) -> Result<Value> {
2370 super::args::mirror_string("TEXT_TRIM", &text, super::args::TextPump::Trim)
2371}
2372
2373#[oxdock_func(
2382 rpn,
2383 returns = TypeTag::union(vec![TypeTag::String, TypeTag::Pipe]),
2384 template = text_trim_prefix_string
2385)]
2386#[example(
2387 name = "strip prefix",
2388 code = r###"
2389 # A present prefix falls away; absence returns the input unchanged.
2390 IMPORT [STD]
2391 LET $bare: STRING = TEXT_TRIM_PREFIX("v1.2.3", "v")
2392 ASSERT_EQ $bare "1.2.3"
2393
2394 # Missing prefixes pass through untouched.
2395 LET $same: STRING = TEXT_TRIM_PREFIX("1.2.3", "v")
2396 ASSERT_EQ $same "1.2.3"
2397 "###
2398)]
2399#[example(
2400 name = "strip prefix pipe mirrors",
2401 code = r###"
2402 # Pipe input mints pipe output with the same strip.
2403 IMPORT [STD]
2404 LET $cap: PIPE
2405 WITH_IO [stdout=$cap] {
2406 ECHO "v1.2.3"
2407 }
2408 LET $trimmed: PIPE = TEXT_TRIM($cap)
2409 LET $out: PIPE = TEXT_TRIM_PREFIX($trimmed, "v")
2410 WITH_IO [stdin=$out] READ_LINE $line
2411 ASSERT_EQ $line "1.2.3"
2412 "###
2413)]
2414#[example(
2415 name = "strip prefix template",
2416 code = r###"
2417 # String inputs run inside placeholders too.
2418 IMPORT [STD]
2419 LET $msg: STRING = 'bare:{{ STD::TEXT_TRIM_PREFIX("v1.2.3", "v") }}'
2420 ASSERT_EQ $msg "bare:1.2.3"
2421 "###
2422)]
2423fn text_trim_prefix<P: ProcessManager>(
2424 cx: &mut StepCtx<P>,
2425 #[union(String, Pipe)]
2427 text: Value,
2428 prefix: String,
2430) -> Result<Value> {
2431 super::args::mirror_stream(
2432 cx,
2433 "TEXT_TRIM_PREFIX",
2434 &text,
2435 super::args::TextPump::TrimPrefix(prefix),
2436 )
2437}
2438
2439fn text_trim_prefix_string(text: Value, prefix: String) -> Result<Value> {
2442 super::args::mirror_string(
2443 "TEXT_TRIM_PREFIX",
2444 &text,
2445 super::args::TextPump::TrimPrefix(prefix),
2446 )
2447}
2448
2449#[oxdock_func(
2456 rpn,
2457 returns = TypeTag::union(vec![TypeTag::String, TypeTag::Pipe]),
2458 template = text_trim_suffix_string
2459)]
2460#[example(
2461 name = "strip suffix",
2462 code = r###"
2463 # A present suffix falls away; absence returns the input unchanged.
2464 IMPORT [STD]
2465 LET $bare: STRING = TEXT_TRIM_SUFFIX("archive.tar.gz", ".gz")
2466 ASSERT_EQ $bare "archive.tar"
2467
2468 # Missing suffixes pass through untouched.
2469 LET $same: STRING = TEXT_TRIM_SUFFIX("archive.tar", ".gz")
2470 ASSERT_EQ $same "archive.tar"
2471 "###
2472)]
2473#[example(
2474 name = "strip suffix pipe mirrors",
2475 code = r###"
2476 # Pipe input mints pipe output with the same strip.
2477 IMPORT [STD]
2478 LET $cap: PIPE
2479 WITH_IO [stdout=$cap] {
2480 ECHO "archive.tar.gz"
2481 }
2482 LET $trimmed: PIPE = TEXT_TRIM($cap)
2483 LET $out: PIPE = TEXT_TRIM_SUFFIX($trimmed, ".gz")
2484 WITH_IO [stdin=$out] READ_LINE $line
2485 ASSERT_EQ $line "archive.tar"
2486 "###
2487)]
2488#[example(
2489 name = "strip suffix template",
2490 code = r###"
2491 # String inputs run inside placeholders too.
2492 IMPORT [STD]
2493 LET $msg: STRING = 'bare:{{ STD::TEXT_TRIM_SUFFIX("archive.tar.gz", ".gz") }}'
2494 ASSERT_EQ $msg "bare:archive.tar"
2495 "###
2496)]
2497fn text_trim_suffix<P: ProcessManager>(
2498 cx: &mut StepCtx<P>,
2499 #[union(String, Pipe)]
2501 text: Value,
2502 suffix: String,
2504) -> Result<Value> {
2505 super::args::mirror_stream(
2506 cx,
2507 "TEXT_TRIM_SUFFIX",
2508 &text,
2509 super::args::TextPump::TrimSuffix(suffix),
2510 )
2511}
2512
2513fn text_trim_suffix_string(text: Value, suffix: String) -> Result<Value> {
2516 super::args::mirror_string(
2517 "TEXT_TRIM_SUFFIX",
2518 &text,
2519 super::args::TextPump::TrimSuffix(suffix),
2520 )
2521}
2522
2523#[oxdock_func(returns = TypeTag::String)]
2534#[example(
2535 name = "join path",
2536 code = r###"
2537 # Directory and file stem join with the native separator.
2538 # Source `\\` is one backslash at runtime; `/` works on Windows
2539 # too, native just reads better there.
2540 IMPORT [STD]
2541 LET $p: STRING = PATH_JOIN("some-dir", "some-file")
2542 [family:unix] ASSERT_EQ $p "some-dir/some-file"
2543 [family:windows] ASSERT_EQ $p "some-dir\\some-file"
2544 "###
2545)]
2546fn path_join<P: ProcessManager>(
2547 _cx: &mut StepCtx<P>,
2548 #[union(String, Path)]
2550 dir: Value,
2551 #[union(String, Path)]
2553 name: Value,
2554) -> Result<Value> {
2555 let d = super::args::string_or_path_text(&dir)?;
2556 let n = super::args::string_or_path_text(&name)?;
2557 Ok(Value::string(oxdock_fs::join_native(&d, &n)))
2558}
2559
2560#[oxdock_func(
2567 rpn,
2568 returns = TypeTag::union(vec![TypeTag::String, TypeTag::Pipe]),
2569 template = text_to_upper_string
2570)]
2571#[example(
2572 name = "uppercase",
2573 code = r###"
2574 # Text folds to uppercase.
2575 IMPORT [STD]
2576 LET $loud: STRING = TEXT_TO_UPPER("hello")
2577 ASSERT_EQ $loud "HELLO"
2578 "###
2579)]
2580#[example(
2581 name = "uppercase pipe mirrors",
2582 code = r###"
2583 # Pipe input mints pipe output with the same fold.
2584 IMPORT [STD]
2585 LET $cap: PIPE
2586 WITH_IO [stdout=$cap] {
2587 ECHO "hello"
2588 }
2589 LET $out: PIPE = TEXT_TO_UPPER($cap)
2590 WITH_IO [stdin=$out] READ_LINE $line
2591 ASSERT_EQ $line "HELLO"
2592 "###
2593)]
2594#[example(
2595 name = "uppercase template",
2596 code = r###"
2597 # String inputs run inside placeholders too.
2598 IMPORT [STD]
2599 LET $msg: STRING = 'loud:{{ STD::TEXT_TO_UPPER("hello") }}'
2600 ASSERT_EQ $msg "loud:HELLO"
2601 "###
2602)]
2603fn text_to_upper<P: ProcessManager>(
2604 cx: &mut StepCtx<P>,
2605 #[union(String, Pipe)]
2607 text: Value,
2608) -> Result<Value> {
2609 super::args::mirror_stream(cx, "TEXT_TO_UPPER", &text, super::args::TextPump::ToUpper)
2610}
2611
2612fn text_to_upper_string(text: Value) -> Result<Value> {
2615 super::args::mirror_string("TEXT_TO_UPPER", &text, super::args::TextPump::ToUpper)
2616}
2617
2618#[oxdock_func(
2625 rpn,
2626 returns = TypeTag::union(vec![TypeTag::String, TypeTag::Pipe]),
2627 template = text_to_lower_string
2628)]
2629#[example(
2630 name = "lowercase",
2631 code = r###"
2632 # Text folds to lowercase.
2633 IMPORT [STD]
2634 LET $quiet: STRING = TEXT_TO_LOWER("HELLO")
2635 ASSERT_EQ $quiet "hello"
2636 "###
2637)]
2638#[example(
2639 name = "lowercase pipe mirrors",
2640 code = r###"
2641 # Pipe input mints pipe output with the same fold.
2642 IMPORT [STD]
2643 LET $cap: PIPE
2644 WITH_IO [stdout=$cap] {
2645 ECHO "HELLO"
2646 }
2647 LET $out: PIPE = TEXT_TO_LOWER($cap)
2648 WITH_IO [stdin=$out] READ_LINE $line
2649 ASSERT_EQ $line "hello"
2650 "###
2651)]
2652#[example(
2653 name = "lowercase template",
2654 code = r###"
2655 # String inputs run inside placeholders too.
2656 IMPORT [STD]
2657 LET $msg: STRING = 'quiet:{{ STD::TEXT_TO_LOWER("HELLO") }}'
2658 ASSERT_EQ $msg "quiet:hello"
2659 "###
2660)]
2661fn text_to_lower<P: ProcessManager>(
2662 cx: &mut StepCtx<P>,
2663 #[union(String, Pipe)]
2665 text: Value,
2666) -> Result<Value> {
2667 super::args::mirror_stream(cx, "TEXT_TO_LOWER", &text, super::args::TextPump::ToLower)
2668}
2669
2670fn text_to_lower_string(text: Value) -> Result<Value> {
2673 super::args::mirror_string("TEXT_TO_LOWER", &text, super::args::TextPump::ToLower)
2674}
2675
2676#[oxdock_func(
2687 rpn,
2688 returns = TypeTag::union(vec![TypeTag::String, TypeTag::Pipe]),
2689 template = text_replace_string
2690)]
2691#[example(
2692 name = "replace",
2693 code = r###"
2694 # Every literal occurrence rewrites in place.
2695 IMPORT [STD]
2696 LET $fixed: STRING = TEXT_REPLACE("hello world", "world", "there")
2697 ASSERT_EQ $fixed "hello there"
2698 "###
2699)]
2700#[example(
2701 name = "replace pipe mirrors",
2702 code = r###"
2703 # Pipe input mints pipe output with the same rewrite.
2704 IMPORT [STD]
2705 LET $cap: PIPE
2706 WITH_IO [stdout=$cap] {
2707 ECHO "hello world"
2708 }
2709 LET $trimmed: PIPE = TEXT_TRIM($cap)
2710 LET $out: PIPE = TEXT_REPLACE($trimmed, "world", "there")
2711 WITH_IO [stdin=$out] READ_LINE $line
2712 ASSERT_EQ $line "hello there"
2713 "###
2714)]
2715#[example(
2716 name = "replace template",
2717 code = r###"
2718 # String inputs run inside placeholders too.
2719 IMPORT [STD]
2720 LET $msg: STRING = 'fixed:{{ STD::TEXT_REPLACE("hello world", "world", "there") }}'
2721 ASSERT_EQ $msg "fixed:hello there"
2722 "###
2723)]
2724fn text_replace<P: ProcessManager>(
2725 cx: &mut StepCtx<P>,
2726 #[union(String, Pipe)]
2728 text: Value,
2729 from: String,
2731 to: String,
2733) -> Result<Value> {
2734 super::args::mirror_stream(
2735 cx,
2736 "TEXT_REPLACE",
2737 &text,
2738 super::args::TextPump::ReplaceLiteral { from, to },
2739 )
2740}
2741
2742fn text_replace_string(text: Value, from: String, to: String) -> Result<Value> {
2745 super::args::mirror_string(
2746 "TEXT_REPLACE",
2747 &text,
2748 super::args::TextPump::ReplaceLiteral { from, to },
2749 )
2750}
2751
2752#[oxdock_func(
2764 rpn,
2765 returns = TypeTag::union(vec![TypeTag::String, TypeTag::Pipe]),
2766 template = text_replace_regex_string
2767)]
2768#[example(
2769 name = "replace with captures",
2770 code = r###"
2771 # Capture groups expand in the replacement.
2772 IMPORT [STD]
2773 LET $swapped: STRING = TEXT_REPLACE_REGEX("2026-10-13", "(\\d+)-(\\d+)-(\\d+)", "$3/$2/$1")
2774 ASSERT_EQ $swapped "13/10/2026"
2775 "###
2776)]
2777#[example(
2778 name = "replace regex pipe mirrors",
2779 code = r###"
2780 # Pipe input mints pipe output with the same rewrite.
2781 IMPORT [STD]
2782 LET $cap: PIPE
2783 WITH_IO [stdout=$cap] {
2784 ECHO "2026-10-13"
2785 }
2786 LET $trimmed: PIPE = TEXT_TRIM($cap)
2787 LET $out: PIPE = TEXT_REPLACE_REGEX($trimmed, "(\\d+)-(\\d+)-(\\d+)", "$3/$2/$1")
2788 WITH_IO [stdin=$out] READ_LINE $line
2789 ASSERT_EQ $line "13/10/2026"
2790 "###
2791)]
2792#[example(
2793 name = "replace regex template",
2794 code = r###"
2795 # String inputs run inside placeholders too.
2796 IMPORT [STD]
2797 LET $msg: STRING = 'swapped:{{ STD::TEXT_REPLACE_REGEX("2026-10-13", "(\\d+)-(\\d+)-(\\d+)", "$3/$2/$1") }}'
2798 ASSERT_EQ $msg "swapped:13/10/2026"
2799 "###
2800)]
2801fn text_replace_regex<P: ProcessManager>(
2802 cx: &mut StepCtx<P>,
2803 #[union(String, Pipe)]
2805 text: Value,
2806 pattern: String,
2808 replacement: String,
2810) -> Result<Value> {
2811 if let Some(s) = text.as_str() {
2812 let out =
2813 super::args::text_replace_regex_str(s, &pattern, &replacement, "TEXT_REPLACE_REGEX")?;
2814 return Ok(Value::string(out));
2815 }
2816 let content = super::args::read_pipe_eager(cx, "TEXT_REPLACE_REGEX", &text)?;
2817 let out = super::args::text_replace_regex_str(
2818 &content,
2819 &pattern,
2820 &replacement,
2821 "TEXT_REPLACE_REGEX",
2822 )?;
2823 super::args::write_completed_pipe(cx, "TEXT_REPLACE_REGEX", out)
2824}
2825
2826fn text_replace_regex_string(text: Value, pattern: String, replacement: String) -> Result<Value> {
2829 let Some(s) = text.as_str() else {
2830 return Err(super::args::pipe_needs_step_io("TEXT_REPLACE_REGEX"));
2831 };
2832 let out = super::args::text_replace_regex_str(s, &pattern, &replacement, "TEXT_REPLACE_REGEX")?;
2833 Ok(Value::string(out))
2834}
2835
2836#[oxdock_func(pure, returns = TypeTag::ListOf(std::sync::Arc::new(TypeTag::String)))]
2844#[example(
2845 name = "split",
2846 code = r###"
2847 # Delimiters split into list items.
2848 IMPORT [STD]
2849 LET $parts: LIST<STRING> = TEXT_SPLIT("a,b,c", ",")
2850 ASSERT_EQ $parts.0 "a"
2851 ASSERT_EQ $parts.1 "b"
2852 ASSERT_EQ $parts.2 "c"
2853 "###
2854)]
2855fn text_split(
2856 text: String,
2858 delimiter: String,
2860) -> Result<Value> {
2861 Ok(super::args::text_list_value(super::args::text_split_str(
2862 &text, &delimiter,
2863 )))
2864}
2865
2866#[oxdock_func(pure, returns = TypeTag::String)]
2869#[example(
2870 name = "join",
2871 code = r###"
2872 # List items join with the separator between them.
2873 IMPORT [STD]
2874 LET $joined: STRING = TEXT_JOIN(["a", "b", "c"], ",")
2875 ASSERT_EQ $joined "a,b,c"
2876 "###
2877)]
2878fn text_join(
2879 elements: Vec<String>,
2881 delimiter: String,
2883) -> Result<Value> {
2884 Ok(Value::string(elements.join(delimiter.as_str())))
2885}
2886
2887#[oxdock_func(pure, returns = TypeTag::ListOf(std::sync::Arc::new(TypeTag::String)))]
2899#[example(
2900 name = "split args",
2901 code = r###"
2902 # Quoted segments stay one word.
2903 IMPORT [STD]
2904 LET $argv: LIST<STRING> = SHELL_SPLIT_ARGS("gh issue comment 153 --body-file notes.md")
2905 ASSERT_EQ $argv.0 "gh"
2906 ASSERT_EQ $argv.3 "153"
2907 ASSERT_EQ $argv.5 "notes.md"
2908
2909 # Quotes and escapes parse the shell way.
2910 LET $quoted: LIST<STRING> = SHELL_SPLIT_ARGS("say \"hi there\" 'a b'")
2911 ASSERT_EQ $quoted.0 "say"
2912 ASSERT_EQ $quoted.1 "hi there"
2913 ASSERT_EQ $quoted.2 "a b"
2914 "###
2915)]
2916fn shell_split_args(
2917 command: String,
2919) -> Result<Value> {
2920 match shell_words::split(&command) {
2921 Ok(words) => Ok(super::args::text_list_value(words)),
2922 Err(err) => anyhow::bail!("SHELL_SPLIT_ARGS: {err}"),
2923 }
2924}
2925
2926#[oxdock_func(pure, returns = TypeTag::String)]
2934#[example(
2935 name = "join args",
2936 code = r###"
2937 # Plain words join with spaces and no quoting.
2938 IMPORT [STD]
2939 LET $plain: STRING = SHELL_JOIN_ARGS(["gh", "issue", "list"])
2940 ASSERT_EQ $plain "gh issue list"
2941
2942 # Words with spaces quote, and the round trip is exact.
2943 LET $words: LIST<STRING> = ["say", "hi there", "a'b"]
2944 LET $joined: STRING = SHELL_JOIN_ARGS($words)
2945 LET $back: LIST<STRING> = SHELL_SPLIT_ARGS($joined)
2946 ASSERT_EQ $back.0 "say"
2947 ASSERT_EQ $back.1 "hi there"
2948 ASSERT_EQ $back.2 "a'b"
2949 "###
2950)]
2951fn shell_join_args(
2952 words: Vec<String>,
2954) -> Result<Value> {
2955 Ok(Value::string(shell_words::join(&words)))
2956}
2957
2958#[oxdock_func(pure, returns = TypeTag::ListOf(std::sync::Arc::new(TypeTag::String)))]
2966#[example(
2967 name = "lines",
2968 code = r###"
2969 # Newlines split into line items.
2970 IMPORT [STD]
2971 LET $lines: LIST<STRING> = TEXT_LINES("one\ntwo\nthree")
2972 ASSERT_EQ $lines.0 "one"
2973 ASSERT_EQ $lines.1 "two"
2974 ASSERT_EQ $lines.2 "three"
2975
2976 # Windows endings split the same way after normalization.
2977 LET $crlf: LIST<STRING> = TEXT_LINES("one\r\ntwo\r\nthree")
2978 ASSERT_EQ $crlf.0 "one"
2979 ASSERT_EQ $crlf.1 "two"
2980 ASSERT_EQ $crlf.2 "three"
2981
2982 # Old Mac endings split too, and mixed endings split together because the input normalizes to LF before splitting.
2983 LET $mixed: LIST<STRING> = TEXT_LINES("a\r\nb\nc\rd")
2984 ASSERT_EQ $mixed.0 "a"
2985 ASSERT_EQ $mixed.1 "b"
2986 ASSERT_EQ $mixed.2 "c"
2987 ASSERT_EQ $mixed.3 "d"
2988 "###
2989)]
2990fn text_lines(
2991 text: String,
2993) -> Result<Value> {
2994 Ok(super::args::text_list_value(super::args::text_lines_str(
2995 &text,
2996 )))
2997}
2998
2999#[oxdock_func(pure, returns = TypeTag::ListOf(std::sync::Arc::new(TypeTag::String)))]
3005#[example(
3006 name = "fields",
3007 code = r###"
3008 # Runs of whitespace separate fields; empties never appear.
3009 IMPORT [STD]
3010 LET $fields: LIST<STRING> = TEXT_FIELDS(" abc def ")
3011 ASSERT_EQ $fields.0 "abc"
3012 ASSERT_EQ $fields.1 "def"
3013 "###
3014)]
3015fn text_fields(
3016 text: String,
3018) -> Result<Value> {
3019 Ok(super::args::text_list_value(super::args::text_fields_str(
3020 &text,
3021 )))
3022}
3023
3024#[oxdock_func(pure, returns = TypeTag::ListOf(std::sync::Arc::new(TypeTag::String)))]
3033#[example(
3034 name = "line range",
3035 code = r###"
3036 # Lines 2 through 3 come back as a list, 1-based inclusive.
3037 IMPORT [STD]
3038 LET $window: LIST<STRING> = TEXT_LINES_RANGE("one\ntwo\nthree\nfour", 2, 3)
3039 ASSERT_EQ $window.0 "two"
3040 ASSERT_EQ $window.1 "three"
3041
3042 # Ranges past the end clamp instead of failing.
3043 LET $tail: LIST<STRING> = TEXT_LINES_RANGE("one\ntwo", 2, 9)
3044 ASSERT_EQ $tail.0 "two"
3045 "###
3046)]
3047fn text_lines_range(
3048 text: String,
3050 from: i64,
3052 to: i64,
3054) -> Result<Value> {
3055 Ok(super::args::text_list_value(
3056 super::args::text_lines_range_str(&text, from, to, "TEXT_LINES_RANGE")?,
3057 ))
3058}
3059
3060#[oxdock_func(pure, returns = TypeTag::Bool)]
3068#[example(
3069 name = "match",
3070 code = r###"
3071 # Regex matches report true; misses report false.
3072 IMPORT [STD]
3073 LET $hit: BOOL = TEXT_MATCH("abc123", "\\d+")
3074 ASSERT_EQ $hit true
3075
3076 # A miss is false, not a failure.
3077 LET $miss: BOOL = TEXT_MATCH("abc", "^\\d+$")
3078 ASSERT_EQ $miss false
3079 "###
3080)]
3081fn text_match(
3082 text: String,
3084 pattern: String,
3086) -> Result<Value> {
3087 let re = super::args::text_compile_pattern("TEXT_MATCH", &pattern)?;
3088 Ok(Value::bool(re.is_match(&text)))
3089}
3090
3091#[oxdock_func(pure, name = "BOOL", returns = TypeTag::Bool)]
3100#[example(
3101 name = "convert",
3102 code = r###"
3103 IMPORT [STD]
3104 LET $n: BOOL = BOOL("yes")
3105 ASSERT_EQ $n true
3106 LET $f: BOOL = BOOL("0")
3107 ASSERT_EQ $f false
3108 "###
3109)]
3110fn bool_convert(
3111 #[union(Bool, String)]
3113 val: Value,
3114) -> Result<Value> {
3115 if let Some(b) = val.as_bool() {
3116 return Ok(Value::bool(b));
3117 }
3118 let Some(s) = val.as_str() else {
3119 return Err(anyhow::anyhow!(
3120 "BOOL needs a Bool or String, found {val:?}"
3121 ));
3122 };
3123 match super::args::parse_bool_str(s) {
3124 Some(b) => Ok(Value::bool(b)),
3125 None => anyhow::bail!("BOOL cannot coerce {s:?} to BOOL"),
3126 }
3127}
3128
3129#[oxdock_func(pure, returns = TypeTag::Bool)]
3139#[example(
3140 name = "absent-default",
3141 code = r###"
3142 # Absent names read empty; the default settles the polarity.
3143 IMPORT [STD]
3144 INHERIT_ENV [OXDOCK_TEST_ABSENT_FLAG]
3145 LET $dry: BOOL = BOOL_OR("{{ env:OXDOCK_TEST_ABSENT_FLAG }}", true)
3146 ASSERT_EQ $dry true
3147
3148 # Present values coerce strictly, ignoring the default.
3149 LET $off: BOOL = BOOL_OR("false", true)
3150 ASSERT_EQ $off false
3151 "###
3152)]
3153fn bool_or(
3154 text: String,
3156 default: bool,
3158) -> Result<Value> {
3159 if text.trim().is_empty() {
3160 return Ok(Value::bool(default));
3161 }
3162 match super::args::parse_bool_str(&text) {
3163 Some(b) => Ok(Value::bool(b)),
3164 None => anyhow::bail!("BOOL_OR cannot coerce {text:?} to BOOL"),
3165 }
3166}
3167
3168#[oxdock_func(pure, returns = TypeTag::ListOf(std::sync::Arc::new(TypeTag::String)))]
3177#[example(
3178 name = "extract",
3179 code = r###"
3180 # Index zero is the full match; groups follow in order.
3181 IMPORT [STD]
3182 LET $caps: LIST<STRING> = TEXT_EXTRACT("abc123", "([a-z]+)(\\d+)")
3183 ASSERT_EQ $caps.0 "abc123"
3184 ASSERT_EQ $caps.1 "abc"
3185 ASSERT_EQ $caps.2 "123"
3186 "###
3187)]
3188fn text_extract(
3189 text: String,
3191 pattern: String,
3193) -> Result<Value> {
3194 let groups = super::args::text_extract_str(&text, &pattern, "TEXT_EXTRACT")?;
3195 Ok(super::args::text_list_value(groups))
3196}
3197
3198#[oxdock_func(pure, returns = TypeTag::Bool)]
3205#[example(
3206 name = "starts with",
3207 code = r###"
3208 # Present prefixes report true; misses report false.
3209 IMPORT [STD]
3210 LET $hit: BOOL = TEXT_STARTS_WITH("linux-musl-x64", "linux")
3211 ASSERT_EQ $hit true
3212
3213 # A miss is false, not a failure.
3214 LET $miss: BOOL = TEXT_STARTS_WITH("macos-arm", "linux")
3215 ASSERT_EQ $miss false
3216 "###
3217)]
3218fn text_starts_with(
3219 text: String,
3221 prefix: String,
3223) -> Result<Value> {
3224 Ok(Value::bool(text.starts_with(prefix.as_str())))
3225}
3226
3227#[oxdock_func(pure, returns = TypeTag::Bool)]
3234#[example(
3235 name = "ends with",
3236 code = r###"
3237 # Present suffixes report true; misses report false.
3238 IMPORT [STD]
3239 LET $hit: BOOL = TEXT_ENDS_WITH("x86_64-linux-musl", "linux-musl")
3240 ASSERT_EQ $hit true
3241
3242 # A miss is false, not a failure.
3243 LET $miss: BOOL = TEXT_ENDS_WITH("x86_64-linux-gnu", "linux-musl")
3244 ASSERT_EQ $miss false
3245 "###
3246)]
3247fn text_ends_with(
3248 text: String,
3250 suffix: String,
3252) -> Result<Value> {
3253 Ok(Value::bool(text.ends_with(suffix.as_str())))
3254}
3255
3256#[oxdock_func(pure, returns = TypeTag::Bool)]
3263#[example(
3264 name = "contains",
3265 code = r###"
3266 # Present needles report true; misses report false.
3267 IMPORT [STD]
3268 LET $hit: BOOL = TEXT_CONTAINS("x86_64-linux-musl", "musl")
3269 ASSERT_EQ $hit true
3270
3271 # A miss is false, not a failure.
3272 LET $miss: BOOL = TEXT_CONTAINS("x86_64-linux-gnu", "musl")
3273 ASSERT_EQ $miss false
3274 "###
3275)]
3276fn text_contains(
3277 text: String,
3279 needle: String,
3281) -> Result<Value> {
3282 Ok(Value::bool(text.contains(needle.as_str())))
3283}
3284
3285#[oxdock_func(pure, returns = TypeTag::Int)]
3294#[example(
3295 name = "length",
3296 code = r###"
3297 # Plain text counts one per character.
3298 IMPORT [STD]
3299 LET $n: INT = LEN("hello")
3300 ASSERT_EQ $n 5
3301
3302 # Multibyte characters count once each, not per byte.
3303 LET $wide: INT = LEN("héllo")
3304 ASSERT_EQ $wide 5
3305
3306 # Lists count elements, maps count entries.
3307 LET $items: LIST<STRING> = ["a", "b", "c"]
3308 LET $nitems: INT = LEN($items)
3309 ASSERT_EQ $nitems 3
3310 LET $row: MAP<name: STRING> = {name: "ada"}
3311 LET $nkeys: INT = LEN($row)
3312 ASSERT_EQ $nkeys 1
3313 LET $empty: INT = LEN([])
3314 ASSERT_EQ $empty 0
3315 "###
3316)]
3317fn len(
3318 #[union(String, List, Map)]
3320 value: Value,
3321) -> Result<Value> {
3322 if let Some(text) = value.as_str() {
3323 return Ok(Value::int(text.chars().count() as i64));
3324 }
3325 if let Some(items) = value.as_list() {
3326 return Ok(Value::int(items.len() as i64));
3327 }
3328 if let Some(entries) = value.as_map() {
3329 return Ok(Value::int(entries.len() as i64));
3330 }
3331 Err(anyhow::anyhow!(
3332 "LEN needs a STRING, LIST, or MAP value, got {}",
3333 value.type_name()
3334 ))
3335}
3336
3337#[oxdock_func(pure, returns = TypeTag::Int)]
3345#[example(
3346 name = "count",
3347 code = r###"
3348 # Every non-overlapping occurrence counts once.
3349 IMPORT [STD]
3350 LET $n: INT = TEXT_COUNT("hello world", "o")
3351 ASSERT_EQ $n 2
3352
3353 # Overlapping candidates never double count.
3354 LET $once: INT = TEXT_COUNT("aaa", "aa")
3355 ASSERT_EQ $once 1
3356 "###
3357)]
3358fn text_count(
3359 text: String,
3361 needle: String,
3363) -> Result<Value> {
3364 let n = super::args::text_count_str(&text, &needle, "TEXT_COUNT")?;
3365 Ok(Value::int(n))
3366}
3367
3368#[oxdock_func(pure, returns = TypeTag::Int)]
3378#[example(
3379 name = "count matches",
3380 code = r###"
3381 # One line matches once no matter how many times it hits.
3382 IMPORT [STD]
3383 LET $n: INT = TEXT_COUNT_MATCHES("test a: test\ntest b: nope\ntest c: test", ": test")
3384 ASSERT_EQ $n 2
3385
3386 # A miss binds zero, never an error.
3387 LET $none: INT = TEXT_COUNT_MATCHES("test b: nope", ": test$")
3388 ASSERT_EQ $none 0
3389 "###
3390)]
3391fn text_count_matches(
3392 text: String,
3394 pattern: String,
3396) -> Result<Value> {
3397 let n = super::args::text_count_matches_str(&text, &pattern, "TEXT_COUNT_MATCHES")?;
3398 Ok(Value::int(n))
3399}
3400
3401#[oxdock_func(pure, returns = TypeTag::ListOf(std::sync::Arc::new(TypeTag::String)))]
3414#[example(
3415 name = "grep",
3416 code = r###"
3417 # Matching lines come back as a list, in order.
3418 IMPORT [STD]
3419 LET $hits: LIST<STRING> = TEXT_GREP("one\ntwo\none more", "^one")
3420 ASSERT_EQ $hits.0 "one"
3421 ASSERT_EQ $hits.1 "one more"
3422
3423 # A miss binds an empty list, never an error.
3424 LET $miss: LIST<STRING> = TEXT_GREP("one\ntwo", "^z")
3425 LET $joined: STRING = TEXT_JOIN($miss, ",")
3426 ASSERT_EQ $joined ""
3427
3428 # The (?i) flag ignores case, so uppercase lines match too.
3429 LET $folded: LIST<STRING> = TEXT_GREP("One\ntwo\nONE more", "(?i)^one")
3430 ASSERT_EQ $folded.0 "One"
3431 ASSERT_EQ $folded.1 "ONE more"
3432 "###
3433)]
3434#[example(
3435 name = "grep invert",
3436 code = r###"
3437 # The invert option keeps every non-matching line instead.
3438 IMPORT [STD]
3439 LET $kept: LIST<STRING> = TEXT_GREP("one\ntwo\none more", "^one", {invert: true})
3440 ASSERT_EQ $kept.0 "two"
3441
3442 # A pattern matching every line binds an empty list, never an error.
3443 LET $none: LIST<STRING> = TEXT_GREP("one\ntwo", "^", {invert: true})
3444 LET $joined: STRING = TEXT_JOIN($none, ",")
3445 ASSERT_EQ $joined ""
3446
3447 # Options ride into placeholders as MAP literals. Placeholder
3448 # strings unescape only backslash and quote, so multiline text
3449 # arrives through a variable.
3450 LET $two_lines: STRING = "one\ntwo"
3451 LET $msg: STRING = 'kept:{{ STD::TEXT_GREP($two_lines, "^one", {invert: true}) }}'
3452 ASSERT_EQ $msg "kept:two"
3453 "###
3454)]
3455fn text_grep(
3456 text: String,
3458 pattern: String,
3460 #[options("invert?: BOOL")]
3462 #[optional]
3463 options: BTreeMap<String, Value>,
3464) -> Result<Value> {
3465 let invert = super::args::text_invert_flag(&options);
3468 Ok(super::args::text_list_value(super::args::text_grep_str(
3469 &text,
3470 &pattern,
3471 invert,
3472 "TEXT_GREP",
3473 )?))
3474}
3475
3476#[oxdock_func(returns = TypeTag::Bool)]
3487#[example(
3488 name = "drain to end",
3489 code = r###"
3490 # Capture two lines, then drain to end of stream with no sentinel line.
3491 IMPORT [STD]
3492 LET $cap: PIPE
3493 WITH_IO [stdout=$cap] {
3494 ECHO "one"
3495 ECHO "two"
3496 }
3497
3498 # The loop exits on close, and the count proves both lines drained.
3499 LET $n: INT = 0
3500 WHILE !EOF($cap) {
3501 WITH_IO [stdin=$cap] READ_LINE $line
3502 $n = $n + 1
3503 }
3504 ASSERT_EQ $n 2
3505 "###
3506)]
3507fn eof<P: ProcessManager>(
3508 cx: &mut StepCtx<P>,
3509 pipe: PipeHandle,
3511) -> Result<Value> {
3512 let info = cx.state.io.inspect_pipe(&pipe);
3513 Ok(Value::bool(info.closed && info.buffered == 0))
3514}
3515
3516fn task_poll_result_fields() -> Arc<[Field]> {
3520 Arc::from(vec![
3521 Field {
3522 name: "state".to_string(),
3523 ty: TypeTag::String,
3524 docs: "Task phase: `running` or `finished`.",
3525 optional: false,
3526 },
3527 Field {
3528 name: "ok".to_string(),
3529 ty: TypeTag::Bool,
3530 docs: "True unless the task failed.",
3531 optional: false,
3532 },
3533 Field {
3534 name: "stdout_tail".to_string(),
3535 ty: TypeTag::String,
3536 docs: "Bounded stdout tail, live while running.",
3537 optional: false,
3538 },
3539 Field {
3540 name: "stderr_tail".to_string(),
3541 ty: TypeTag::String,
3542 docs: "Bounded stderr tail, live while running.",
3543 optional: false,
3544 },
3545 Field {
3546 name: "truncated_bytes".to_string(),
3547 ty: TypeTag::Int,
3548 docs: "Dropped head bytes past the per-stream cap.",
3549 optional: false,
3550 },
3551 Field {
3552 name: "exit_code".to_string(),
3553 ty: TypeTag::Int,
3554 docs: "Process exit code, present once finished.",
3555 optional: true,
3556 },
3557 Field {
3558 name: "result".to_string(),
3559 ty: TypeTag::Any,
3560 docs: "Task `RETURN` value, present on clean finish.",
3561 optional: true,
3562 },
3563 Field {
3564 name: "error".to_string(),
3565 ty: TypeTag::String,
3566 docs: "Failure text, present on failed finish.",
3567 optional: true,
3568 },
3569 ])
3570}
3571
3572#[oxdock_func(returns = TypeTag::Record(task_poll_result_fields()))]
3585#[example(
3586 name = "running poll",
3587 code = r###"
3588 # A sleeping task is still running on the first poll.
3589 IMPORT [STD]
3590 LET $t: HANDLE<STRING> = ASYNC { SLEEP 30s; RETURN "done" }
3591 LET $m: MAP<state: STRING, ok: BOOL, stdout_tail: STRING, stderr_tail: STRING, truncated_bytes: INT, exit_code?: INT, result?: ANY, error?: STRING> = TASK_POLL($t)
3592 ASSERT_EQ $m.state "running"
3593 ASSERT_EQ $m.ok true
3594 # Clean up the sleeper so the run ends promptly.
3595 CANCEL $t
3596 "###
3597)]
3598#[example(
3599 name = "finished poll",
3600 code = r###"
3601 # A finished task reports its value and final tails, then still awaits.
3602 IMPORT [STD]
3603 LET $t: HANDLE<STRING> = ASYNC { ECHO "hi"; SLEEP 1s; RETURN "done" }
3604 # Do other work while the task runs; poll once it should be done.
3605 SLEEP 2s
3606 LET $m: MAP<state: STRING, ok: BOOL, stdout_tail: STRING, stderr_tail: STRING, truncated_bytes: INT, exit_code?: INT, result?: ANY, error?: STRING> = TASK_POLL($t)
3607 ASSERT_EQ $m.state "finished"
3608 ASSERT_EQ $m.result "done"
3609 LET $o: STRING = AWAIT $t
3610 ASSERT_EQ $o "done"
3611 "###
3612)]
3613fn task_poll<P: ProcessManager>(
3614 cx: &mut StepCtx<P>,
3615 task: HandleValue,
3617) -> Result<Value> {
3618 let entry =
3619 super::handlers::resolve_task_entry_by_id(task.0, &format!("TASK_POLL({})", task.0), cx)?;
3620 let obs = entry.observe_completion();
3621 let (stdout_tail, stderr_tail, dropped) = entry.snapshot_tails();
3622 let mut out = BTreeMap::new();
3623 out.insert(
3624 "state".to_string(),
3625 Value::string(if obs.running { "running" } else { "finished" }.to_string()),
3626 );
3627 out.insert("ok".to_string(), Value::bool(obs.ok));
3628 if !obs.running {
3629 out.insert("exit_code".to_string(), Value::int(obs.exit_code));
3630 }
3631 if let Some(result) = obs.result {
3632 out.insert("result".to_string(), result);
3633 }
3634 if !obs.error.is_empty() {
3635 out.insert("error".to_string(), Value::string(obs.error));
3636 }
3637 out.insert("stdout_tail".to_string(), Value::string(stdout_tail));
3638 out.insert("stderr_tail".to_string(), Value::string(stderr_tail));
3639 out.insert(
3640 "truncated_bytes".to_string(),
3641 Value::int(dropped.min(i64::MAX as u64) as i64),
3642 );
3643 Ok(Value::map(out))
3644}
3645
3646fn meta_to_value(meta: &FuncMeta) -> Value {
3647 let mut map = BTreeMap::new();
3648 map.insert("name".to_string(), Value::string(meta.name.clone()));
3649 map.insert("module".to_string(), Value::string(meta.module.clone()));
3650 map.insert(
3651 "kind".to_string(),
3652 Value::string(meta.kind.label().to_string()),
3653 );
3654 let params = match &meta.params {
3655 Some(params) => Value::list(
3656 params
3657 .iter()
3658 .map(|p| {
3659 let mut entry = BTreeMap::new();
3660 entry.insert("name".to_string(), Value::string(p.name.clone()));
3661 entry.insert(
3662 "param_type".to_string(),
3663 Value::string(
3664 p.param_type
3665 .as_ref()
3666 .map(render_structural)
3667 .unwrap_or_default(),
3668 ),
3669 );
3670 entry.insert(
3671 "allowed".to_string(),
3672 Value::string(
3673 p.allowed
3674 .map(|values| values.join(", "))
3675 .unwrap_or_default(),
3676 ),
3677 );
3678 entry.insert("docs".to_string(), Value::string(String::new()));
3679 entry.insert("optional".to_string(), Value::bool(p.optional));
3680 entry.insert(
3681 "options".to_string(),
3682 match p.options {
3683 Some(keys) => Value::list(
3684 keys.iter()
3685 .map(|key| {
3686 let mut option = BTreeMap::new();
3687 option.insert(
3688 "name".to_string(),
3689 Value::string(key.name.to_string()),
3690 );
3691 option.insert(
3692 "value_type".to_string(),
3693 Value::string(render_structural(&key.value)),
3694 );
3695 option.insert(
3696 "required".to_string(),
3697 Value::bool(key.required),
3698 );
3699 option.insert(
3700 "default".to_string(),
3701 Value::string(
3702 key.default.unwrap_or_default().to_string(),
3703 ),
3704 );
3705 Value::map(option)
3706 })
3707 .collect(),
3708 ),
3709 None => Value::string(String::new()),
3710 },
3711 );
3712 Value::map(entry)
3713 })
3714 .collect(),
3715 ),
3716 None => Value::list(Vec::new()),
3720 };
3721 map.insert("params".to_string(), params);
3722 map.insert(
3723 "returns".to_string(),
3724 Value::string(
3725 meta.returns
3726 .as_ref()
3727 .map(render_structural)
3728 .unwrap_or_default(),
3729 ),
3730 );
3731 map.insert("rpn".to_string(), Value::bool(meta.rpn));
3732 map.insert(
3733 "summary".to_string(),
3734 Value::string(meta.summary.to_string()),
3735 );
3736 Value::map(map)
3737}
3738
3739#[derive(Debug, Clone)]
3743pub struct RecordSchema {
3744 pub name: &'static str,
3745 pub fields: std::sync::Arc<[Field]>,
3746}
3747
3748#[derive(Clone)]
3752pub struct HostModule<P: ProcessManager> {
3753 pub name: String,
3754 pub funcs: Vec<HostRegistration<P>>,
3755 pub types: Vec<&'static TypeDescriptor>,
3756 pub record_schemas: Vec<RecordSchema>,
3757 pub states: Vec<ModuleState>,
3764}
3765
3766#[derive(Clone)]
3770pub struct ModuleState {
3771 id: std::any::TypeId,
3772 state: std::sync::Arc<dyn std::any::Any + Send + Sync>,
3773}
3774
3775pub type PreRunInspector = dyn Fn(&[Step]) -> Result<()> + Send + Sync;
3779
3780#[derive(Clone)]
3786pub struct PreRunCheck {
3787 check: Arc<PreRunInspector>,
3788}
3789
3790impl PreRunCheck {
3791 pub fn new(check: impl Fn(&[Step]) -> Result<()> + Send + Sync + 'static) -> Self {
3793 Self {
3794 check: Arc::new(check),
3795 }
3796 }
3797
3798 pub fn run(&self, steps: &[Step]) -> Result<()> {
3800 (self.check)(steps)
3801 }
3802}
3803
3804impl<P: ProcessManager> HostModule<P> {
3805 pub fn with_state<T: Send + Sync + 'static>(mut self, state: std::sync::Arc<T>) -> Self {
3808 self.states.push(ModuleState {
3809 id: std::any::TypeId::of::<T>(),
3810 state,
3811 });
3812 self
3813 }
3814
3815 pub fn check_pre_run(&self, steps: &[Step]) -> Result<()> {
3819 for state in &self.states {
3820 if let Some(check) = state.state.downcast_ref::<PreRunCheck>() {
3821 check.run(steps)?;
3822 }
3823 }
3824 Ok(())
3825 }
3826}
3827
3828impl<P: ProcessManager> ExecState<P> {
3829 pub fn register_module(&mut self, module: HostModule<P>) {
3832 for registration in module.funcs {
3833 match registration {
3834 HostRegistration::Stateful { name, meta, func } => {
3835 self.functions.register_host(&module.name, name, meta, func);
3836 }
3837 HostRegistration::Pure { name, meta, func } => {
3838 self.functions
3839 .register_pure_host(&module.name, name, meta, func);
3840 }
3841 HostRegistration::Both {
3842 name,
3843 meta,
3844 func,
3845 template,
3846 } => {
3847 self.functions
3848 .register_both_host(&module.name, name, meta, func, template);
3849 }
3850 }
3851 }
3852 for descriptor in module.types {
3853 self.register_type(descriptor);
3854 }
3855 for schema in module.record_schemas {
3856 self.register_record_schema(schema.name, schema.fields);
3857 }
3858 for state in module.states {
3859 self.module_states
3860 .insert((module.name.clone(), state.id), state.state);
3861 }
3862 }
3863
3864 pub fn list_functions(&self) -> Vec<FuncMeta> {
3866 let mut out: Vec<FuncMeta> = self.functions.entries_metas().into_iter().collect();
3867 if !out.iter().any(|m| m.name == KEYWORD_INSPECT) {
3869 out.push(FuncMeta {
3870 name: KEYWORD_INSPECT.to_string(),
3871 module: STD_MODULE_NAME.to_string(),
3872 kind: FuncKind::HostCtx,
3873 params: None,
3874 returns: Some(TypeTag::Map),
3875 rpn: false,
3876 summary: "Inspect a variable binding.",
3877 docs: "INSPECT($var): dedicated AST node taking a variable, not a value.",
3878 examples: &[],
3879 });
3880 }
3881 out.sort_by(|a, b| a.name.cmp(&b.name));
3882 out
3883 }
3884
3885 pub fn describe_function(&self, name: &str) -> Option<Value> {
3887 if let Some(meta) = self.functions.meta(name) {
3888 return Some(meta_to_value(&meta));
3889 }
3890 if name == KEYWORD_INSPECT {
3892 return Some(meta_to_value(&FuncMeta {
3893 name: KEYWORD_INSPECT.to_string(),
3894 module: STD_MODULE_NAME.to_string(),
3895 kind: FuncKind::HostCtx,
3896 params: None,
3897 returns: Some(TypeTag::Map),
3898 rpn: false,
3899 summary: "Inspect a variable binding.",
3900 docs: "INSPECT($var): dedicated AST node taking a variable, not a value.",
3901 examples: &[],
3902 }));
3903 }
3904 None
3905 }
3906
3907 pub(super) fn clone_native_pure(&self, name: &str) -> Option<PureFn> {
3908 self.functions.clone_pure_fn(name)
3909 }
3910
3911 pub fn pure_function_table(&self) -> Arc<PureTable> {
3916 self.functions.pure_shared()
3917 }
3918
3919 pub(super) fn clone_native_ctx(&self, name: &str) -> Option<NativeFn<P>> {
3920 self.functions.clone_ctx_fn(name)
3921 }
3922
3923 pub(super) fn native_meta(&self, name: &str) -> Option<FuncMeta> {
3924 self.functions.meta(name)
3925 }
3926}
3927
3928#[cfg(test)]
3929mod tests {
3930 use super::*;
3931
3932 #[test]
3933 fn placeholder_resolver_dispatches_table_entries() {
3934 let echo: PureFn = Arc::new(|args| {
3938 args.into_iter()
3939 .next()
3940 .ok_or_else(|| anyhow::anyhow!("ECHO needs 1 arg"))
3941 });
3942 let mut entries = HashMap::new();
3943 entries.insert("ECHO".to_string(), echo);
3944 let mut table = PureTable::new();
3945 table.insert("T".to_string(), entries);
3946 let resolve = placeholder_resolver(Arc::new(table));
3947 let out = resolve("T", "ECHO", vec![Value::string("hi".to_string())]).expect("dispatch");
3948 assert_eq!(out.as_str().expect("string"), "hi");
3949 let err = format!(
3950 "{:#}",
3951 resolve("T", "NOPE", vec![]).expect_err("unknown must fail")
3952 );
3953 assert!(
3954 err.contains("unknown placeholder function 'T::NOPE'"),
3955 "names the call: {err}"
3956 );
3957 assert!(
3958 err.contains("known functions: T::ECHO"),
3959 "lists known names: {err}"
3960 );
3961 }
3962
3963 #[test]
3964 fn describe_entry_renders_union_spellings() {
3965 let union = oxdock_parser::union_tag!(String, Pipe);
3971 let meta = FuncMeta {
3972 name: "T::F".to_string(),
3973 module: "T".to_string(),
3974 kind: FuncKind::HostPure,
3975 params: Some(vec![FuncParam {
3976 name: "text".to_string(),
3977 param_type: Some(union.clone()),
3978 allowed: None,
3979 docs: "",
3980 options: None,
3981 optional: false,
3982 }]),
3983 returns: Some(union),
3984 rpn: false,
3985 summary: "test-only",
3986 docs: "test-only",
3987 examples: &[],
3988 };
3989 let value = meta_to_value(&meta);
3990 let map = value.as_map().expect("describe value is a map");
3991 let params = map
3992 .get("params")
3993 .expect("params key")
3994 .as_list()
3995 .expect("params is a list");
3996 let first = params[0].as_map().expect("entry is a map");
3997 assert_eq!(
3998 first.get("param_type").and_then(Value::as_str),
3999 Some("STRING|PIPE"),
4000 "param renders the set"
4001 );
4002 assert_eq!(
4003 map.get("returns").and_then(Value::as_str),
4004 Some("STRING|PIPE"),
4005 "returns render the set"
4006 );
4007 }
4008
4009 #[test]
4010 fn describe_entry_renders_handle_payload() {
4011 let meta = FuncMeta {
4015 name: "SCRIPT::FETCH".to_string(),
4016 module: "SCRIPT".to_string(),
4017 kind: FuncKind::Script,
4018 params: Some(vec![]),
4019 returns: Some(TypeTag::HandleOf(std::sync::Arc::new(TypeTag::String))),
4020 rpn: false,
4021 summary: "test-only",
4022 docs: "test-only",
4023 examples: &[],
4024 };
4025 let value = meta_to_value(&meta);
4026 let map = value.as_map().expect("describe value is a map");
4027 assert_eq!(
4028 map.get("returns").and_then(Value::as_str),
4029 Some("HANDLE<STRING>"),
4030 "returns render the payload"
4031 );
4032 }
4033
4034 #[test]
4035 fn describe_entry_carries_optional_flag() {
4036 let meta = FuncMeta {
4040 name: "T::F".to_string(),
4041 module: "T".to_string(),
4042 kind: FuncKind::HostPure,
4043 params: Some(vec![
4044 FuncParam {
4045 name: "url".to_string(),
4046 param_type: Some(TypeTag::String),
4047 allowed: None,
4048 docs: "",
4049 options: None,
4050 optional: false,
4051 },
4052 FuncParam {
4053 name: "options".to_string(),
4054 param_type: Some(TypeTag::Map),
4055 allowed: None,
4056 docs: "",
4057 options: None,
4058 optional: true,
4059 },
4060 ]),
4061 returns: Some(TypeTag::String),
4062 rpn: false,
4063 summary: "test-only",
4064 docs: "test-only",
4065 examples: &[],
4066 };
4067 let value = meta_to_value(&meta);
4068 let map = value.as_map().expect("describe value is a map");
4069 let params = map
4070 .get("params")
4071 .expect("params key")
4072 .as_list()
4073 .expect("params is a list");
4074 assert_eq!(params.len(), 2);
4075 let first = params[0].as_map().expect("entry is a map");
4076 let second = params[1].as_map().expect("entry is a map");
4077 assert_eq!(
4078 first.get("optional").and_then(Value::as_bool),
4079 Some(false),
4080 "required param must read false"
4081 );
4082 assert_eq!(
4083 second.get("optional").and_then(Value::as_bool),
4084 Some(true),
4085 "omittable param must read true"
4086 );
4087 }
4088
4089 #[test]
4090 fn template_twins_mirror_string_paths_and_refuse_pipes() {
4091 let pipe = Value::pipe_fresh();
4097 type TwinCase = (&'static str, Box<dyn Fn() -> Result<Value>>);
4098 let cases: Vec<TwinCase> = vec![
4099 (
4100 "TEXT_TRIM",
4101 Box::new(|| text_trim_string(Value::string(" hello ".to_string()))),
4102 ),
4103 (
4104 "TEXT_TRIM_PREFIX",
4105 Box::new(|| {
4106 text_trim_prefix_string(Value::string("v1".to_string()), "v".to_string())
4107 }),
4108 ),
4109 (
4110 "TEXT_TRIM_SUFFIX",
4111 Box::new(|| {
4112 text_trim_suffix_string(Value::string("a.gz".to_string()), "x".to_string())
4113 }),
4114 ),
4115 (
4116 "TEXT_TO_UPPER",
4117 Box::new(|| text_to_upper_string(Value::string("hi".to_string()))),
4118 ),
4119 (
4120 "TEXT_TO_LOWER",
4121 Box::new(|| text_to_lower_string(Value::string("HI".to_string()))),
4122 ),
4123 (
4124 "TEXT_REPLACE",
4125 Box::new(|| {
4126 text_replace_string(
4127 Value::string("ab".to_string()),
4128 "b".to_string(),
4129 "c".to_string(),
4130 )
4131 }),
4132 ),
4133 (
4134 "TEXT_REPLACE_REGEX",
4135 Box::new(|| {
4136 text_replace_regex_string(
4137 Value::string("ab".to_string()),
4138 "b".to_string(),
4139 "c".to_string(),
4140 )
4141 }),
4142 ),
4143 ];
4144 assert_eq!(cases.len(), 7, "every mirror op needs a twin row");
4145 for (name, run) in &cases {
4146 let value = run().unwrap_or_else(|e| panic!("{name} twin must answer strings: {e:#}"));
4147 assert!(
4148 value.as_str().is_some(),
4149 "{name} twin must answer STRING, got {}",
4150 value.type_name()
4151 );
4152 }
4153 assert_eq!(
4154 text_trim_string(Value::string(" hello ".to_string()))
4155 .expect("trim twin")
4156 .as_str(),
4157 Some("hello")
4158 );
4159 let pipe_cases: Vec<(&str, Result<Value>)> = vec![
4161 ("TEXT_TRIM", text_trim_string(pipe.clone())),
4162 (
4163 "TEXT_TRIM_PREFIX",
4164 text_trim_prefix_string(pipe.clone(), "v".to_string()),
4165 ),
4166 (
4167 "TEXT_TRIM_SUFFIX",
4168 text_trim_suffix_string(pipe.clone(), ".gz".to_string()),
4169 ),
4170 ("TEXT_TO_UPPER", text_to_upper_string(pipe.clone())),
4171 ("TEXT_TO_LOWER", text_to_lower_string(pipe.clone())),
4172 (
4173 "TEXT_REPLACE",
4174 text_replace_string(pipe.clone(), "a".to_string(), "b".to_string()),
4175 ),
4176 (
4177 "TEXT_REPLACE_REGEX",
4178 text_replace_regex_string(pipe.clone(), "a".to_string(), "b".to_string()),
4179 ),
4180 ];
4181 for (name, result) in pipe_cases {
4182 let err = result.expect_err(&format!("{name} twin must refuse PIPE"));
4183 assert!(
4184 format!("{err:#}").contains("step IO"),
4185 "{name} refusal names the missing context: {err:#}"
4186 );
4187 }
4188 }
4189
4190 #[test]
4191 fn shell_words_join_split_round_trip() {
4192 let words = vec![
4196 "gh".to_string(),
4197 "issue".to_string(),
4198 "comment".to_string(),
4199 "with spaces".to_string(),
4200 "it's".to_string(),
4201 "say \"hi\"".to_string(),
4202 "$HOME".to_string(),
4203 "$(whoami)".to_string(),
4204 "C:\\path\\to".to_string(),
4205 "naïve café".to_string(),
4206 "".to_string(),
4207 ];
4208 let joined = shell_words::join(&words);
4209 let back = shell_words::split(&joined).expect("join output must parse");
4210 assert_eq!(back, words);
4211 assert!(shell_words::split("unbalanced \"quote").is_err());
4212 }
4213}