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)]
227pub(super) struct FuncDefData {
228 pub(super) params: Vec<(String, TypeTag)>,
229 pub(super) return_type: TypeTag,
230 pub(super) return_spelling: String,
231 pub(super) is_async: bool,
232 pub(super) body: Vec<Step>,
233 pub(super) module: Option<String>,
238}
239
240pub(super) enum FuncBody<P: ProcessManager> {
245 Script(FuncDefData),
246 Pure(PureFn),
247 Ctx(NativeFn<P>),
248 Both { pure: PureFn, ctx: NativeFn<P> },
249}
250
251impl<P: ProcessManager> Clone for FuncBody<P> {
253 fn clone(&self) -> Self {
254 match self {
255 FuncBody::Script(def) => FuncBody::Script(def.clone()),
256 FuncBody::Pure(func) => FuncBody::Pure(Arc::clone(func)),
257 FuncBody::Ctx(func) => FuncBody::Ctx(Arc::clone(func)),
258 FuncBody::Both { pure, ctx } => FuncBody::Both {
259 pure: Arc::clone(pure),
260 ctx: Arc::clone(ctx),
261 },
262 }
263 }
264}
265
266pub(super) struct FuncEntry<P: ProcessManager> {
270 pub(super) meta: FuncMeta,
271 pub(super) body: FuncBody<P>,
272}
273
274impl<P: ProcessManager> Clone for FuncEntry<P> {
276 fn clone(&self) -> Self {
277 Self {
278 meta: self.meta.clone(),
279 body: self.body.clone(),
280 }
281 }
282}
283
284struct ScopeFrame<P: ProcessManager> {
287 defined: HashSet<String>,
288 shadowed: Vec<(String, FuncEntry<P>)>,
289}
290
291impl<P: ProcessManager> Clone for ScopeFrame<P> {
293 fn clone(&self) -> Self {
294 Self {
295 defined: self.defined.clone(),
296 shadowed: self.shadowed.clone(),
297 }
298 }
299}
300
301pub type PureTable = HashMap<String, HashMap<String, PureFn>>;
311
312pub fn placeholder_resolver(table: Arc<PureTable>) -> oxdock_process::PlaceholderCall {
321 Arc::new(move |module, func, args| {
322 let callee = table
323 .get(module)
324 .and_then(|entries| entries.get(func))
325 .ok_or_else(|| {
326 let mut known: Vec<String> = table
327 .iter()
328 .flat_map(|(m, entries)| entries.keys().map(move |f| format!("{m}::{f}")))
329 .collect();
330 known.sort();
331 anyhow::anyhow!(
332 "unknown placeholder function '{module}::{func}'; known functions: {}",
333 known.join(", ")
334 )
335 })?;
336 callee(args)
337 })
338}
339
340pub struct FunctionRegistry<P: ProcessManager> {
341 entries: HashMap<String, FuncEntry<P>>,
342 scopes: Vec<ScopeFrame<P>>,
343 pure_shared: Arc<PureTable>,
344 script_docs: HashMap<String, (String, String)>,
348}
349
350impl<P: ProcessManager> FunctionRegistry<P> {
351 pub(super) fn with_builtins() -> Self {
352 let mut reg = Self {
353 entries: HashMap::new(),
354 pure_shared: Arc::new(HashMap::new()),
355 script_docs: HashMap::new(),
356 scopes: vec![ScopeFrame {
357 defined: HashSet::new(),
358 shadowed: Vec::new(),
359 }],
360 };
361 for host in Self::builtin_registrations() {
365 match host {
366 HostRegistration::Stateful { name, meta, func } => {
367 reg.insert_qualified(STD_MODULE_NAME, name, meta, FuncBody::Ctx(func));
368 }
369 HostRegistration::Pure { name, meta, func } => {
370 reg.insert_qualified(STD_MODULE_NAME, name, meta, FuncBody::Pure(func));
371 }
372 HostRegistration::Both {
373 name,
374 meta,
375 func,
376 template,
377 } => {
378 reg.insert_qualified(
379 STD_MODULE_NAME,
380 name,
381 meta,
382 FuncBody::Both {
383 pure: template,
384 ctx: func,
385 },
386 );
387 }
388 }
389 }
390 reg
391 }
392
393 pub(super) fn builtin_registrations() -> Vec<HostRegistration<P>> {
398 vec![
399 Int::registration(),
400 Float::registration(),
401 BoolConvert::registration(),
402 BoolOr::registration(),
403 FormatByteCount::registration(),
404 ParseByteCount::registration(),
405 FormatDuration::registration(),
406 ParseDuration::registration(),
407 Types::registration(),
408 TypeDescribe::registration(),
409 Glob::registration(),
410 LoadToml::registration(),
411 LoadJson::registration(),
412 HashSha256::registration(),
413 Cwd::registration(),
414 ParseToml::registration(),
415 ParseJson::registration(),
416 PathType::registration(),
417 PathWritable::registration(),
418 IsExec::registration(),
419 HasKey::registration(),
420 MapSet::registration(),
421 MergeMaps::registration(),
422 Base64Encode::registration(),
423 Base64Decode::registration(),
424 Rand::registration(),
425 ToJson::registration(),
426 TypeOf::registration(),
427 Functions::registration(),
428 Describe::registration(),
429 IsMain::registration(),
430 IsTerminal::registration(),
431 Eof::registration(),
432 TaskPoll::registration(),
433 Version::registration(),
434 Interpreter::registration(),
435 TextTrim::registration(),
436 TextTrimPrefix::registration(),
437 TextTrimSuffix::registration(),
438 PathJoin::registration(),
439 TextToUpper::registration(),
440 TextToLower::registration(),
441 TextReplace::registration(),
442 TextReplaceRegex::registration(),
443 TextSplit::registration(),
444 TextJoin::registration(),
445 TextLines::registration(),
446 TextFields::registration(),
447 TextMatch::registration(),
448 TextExtract::registration(),
449 TextStartsWith::registration(),
450 TextEndsWith::registration(),
451 TextContains::registration(),
452 TextLength::registration(),
453 TextCount::registration(),
454 TextCountMatches::registration(),
455 TextGrep::registration(),
456 TextLinesRange::registration(),
457 SemaphoreNew::registration(),
458 SemaphoreTryAcquire::registration(),
459 SemaphoreAvailable::registration(),
460 ShellSplitArgs::registration(),
461 ShellJoinArgs::registration(),
462 ]
463 }
464
465 pub(super) fn keys(&self) -> HashSet<String> {
468 self.entries.keys().cloned().collect()
469 }
470
471 pub(super) fn get(&self, name: &str) -> Option<FuncEntry<P>> {
473 self.entries.get(name).cloned()
474 }
475
476 fn insert_native(&mut self, name: String, meta: FuncMeta, body: FuncBody<P>) {
477 self.entries.insert(name, FuncEntry { meta, body });
478 self.rebuild_pure_shared();
479 }
480
481 fn rebuild_pure_shared(&mut self) {
487 let mut table: PureTable = HashMap::new();
488 for (name, entry) in &self.entries {
489 let func = match &entry.body {
490 FuncBody::Pure(func) => func,
491 FuncBody::Both { pure, .. } => pure,
492 FuncBody::Script(_) | FuncBody::Ctx(_) => continue,
493 };
494 if let Some((module, base)) = split_qualified(name) {
495 table
496 .entry(module.to_string())
497 .or_default()
498 .insert(base.to_string(), Arc::clone(func));
499 }
500 }
501 self.pure_shared = Arc::new(table);
502 }
503
504 fn insert_qualified(
508 &mut self,
509 module: &str,
510 base: String,
511 mut meta: FuncMeta,
512 body: FuncBody<P>,
513 ) {
514 meta.name = qualify(module, &base);
515 meta.module = module.to_string();
516 if self.entries.contains_key(&meta.name) {
521 panic!("duplicate function registration `{}`", meta.name);
522 }
523 self.insert_native(meta.name.clone(), meta, body);
524 }
525
526 pub(super) fn register_host(
527 &mut self,
528 module: &str,
529 name: String,
530 mut meta: FuncMeta,
531 func: NativeFn<P>,
532 ) {
533 meta.kind = FuncKind::HostCtx;
534 self.insert_qualified(module, name, meta, FuncBody::Ctx(func));
535 }
536
537 pub(super) fn register_pure_host(
538 &mut self,
539 module: &str,
540 name: String,
541 mut meta: FuncMeta,
542 func: PureFn,
543 ) {
544 meta.kind = FuncKind::HostPure;
545 self.insert_qualified(module, name, meta, FuncBody::Pure(func));
546 }
547
548 pub(super) fn register_both_host(
549 &mut self,
550 module: &str,
551 name: String,
552 mut meta: FuncMeta,
553 func: NativeFn<P>,
554 template: PureFn,
555 ) {
556 meta.kind = FuncKind::HostCtx;
557 self.insert_qualified(
558 module,
559 name,
560 meta,
561 FuncBody::Both {
562 pure: template,
563 ctx: func,
564 },
565 );
566 }
567
568 #[allow(clippy::too_many_arguments)]
573 pub(super) fn define_script(
574 &mut self,
575 name: &str,
576 params: &[(String, TypeTag)],
577 return_type: TypeTag,
578 return_spelling: &str,
579 is_async: bool,
580 body: &[Step],
581 module: Option<&str>,
582 ) -> Result<()> {
583 let qualified = qualify(SCRIPT_MODULE_NAME, name);
584 let shadowable = matches!(
585 self.entries.get(&qualified).map(|entry| &entry.body),
586 Some(FuncBody::Script(_))
587 );
588 let reserved = self.entries.iter().any(|(key, entry)| {
593 split_qualified(key).is_some_and(|(_, base)| base == name)
594 && !matches!(entry.body, FuncBody::Script(_))
595 });
596 if reserved && !shadowable {
597 anyhow::bail!("cannot shadow reserved function `{name}`");
598 }
599 if self
600 .scopes
601 .last()
602 .is_some_and(|frame| frame.defined.contains(&qualified))
603 {
604 anyhow::bail!("duplicate function `{name}` in same scope");
605 }
606 let old = self.entries.insert(
607 qualified.clone(),
608 FuncEntry {
609 meta: FuncMeta {
610 name: qualified.clone(),
611 module: SCRIPT_MODULE_NAME.to_string(),
612 kind: FuncKind::Script,
613 params: Some(
614 params
615 .iter()
616 .map(|(name, param_type)| FuncParam {
617 name: name.clone(),
618 param_type: Some(param_type.clone()),
619 allowed: None,
620 docs: "",
623 options: None,
624 optional: false,
625 })
626 .collect(),
627 ),
628 returns: Some(return_type.clone()),
629 rpn: false,
630 summary: "DSL-defined function.",
631 docs: "Defined via FUNC in script.",
632 examples: &[],
633 },
634 body: FuncBody::Script(FuncDefData {
635 params: params.to_vec(),
636 return_type,
637 return_spelling: return_spelling.to_string(),
638 is_async,
639 body: body.to_vec(),
640 module: module.map(|m| m.to_string()),
641 }),
642 },
643 );
644 if let Some(frame) = self.scopes.last_mut() {
645 frame.defined.insert(qualified.clone());
646 if let Some(old) = old {
647 frame.shadowed.push((qualified, old));
648 }
649 }
650 Ok(())
651 }
652
653 #[allow(clippy::too_many_arguments)]
661 pub(super) fn define_aliased_in(
662 &mut self,
663 depth: usize,
664 alias: &str,
665 name: &str,
666 params: &[(String, TypeTag)],
667 return_type: TypeTag,
668 return_spelling: &str,
669 is_async: bool,
670 body: &[Step],
671 module: Option<&str>,
672 ) -> Result<()> {
673 let qualified = qualify(alias, name);
674 let shadowable = matches!(
675 self.entries.get(&qualified).map(|entry| &entry.body),
676 Some(FuncBody::Script(_))
677 );
678 let reserved = self.entries.iter().any(|(key, entry)| {
682 split_qualified(key).is_some_and(|(_, base)| base == name)
683 && !matches!(entry.body, FuncBody::Script(_))
684 });
685 if reserved && !shadowable {
686 anyhow::bail!("cannot shadow reserved function `{name}`");
687 }
688 let depth_in_range = depth < self.scopes.len();
692 let frame_idx = if depth_in_range {
693 depth
694 } else {
695 self.scopes.len().saturating_sub(1)
696 };
697 if self
698 .scopes
699 .get(frame_idx)
700 .is_some_and(|frame| frame.defined.contains(&qualified))
701 {
702 anyhow::bail!("duplicate function `{name}` in same scope");
703 }
704 let old = self.entries.insert(
705 qualified.clone(),
706 FuncEntry {
707 meta: FuncMeta {
708 name: qualified.clone(),
709 module: alias.to_string(),
710 kind: FuncKind::Script,
711 params: Some(
712 params
713 .iter()
714 .map(|(name, param_type)| FuncParam {
715 name: name.clone(),
716 param_type: Some(param_type.clone()),
717 allowed: None,
718 docs: "",
719 options: None,
720 optional: false,
721 })
722 .collect(),
723 ),
724 returns: Some(return_type.clone()),
725 rpn: false,
726 summary: "DSL-defined function.",
727 docs: "Defined via FUNC in an imported script.",
728 examples: &[],
729 },
730 body: FuncBody::Script(FuncDefData {
731 params: params.to_vec(),
732 return_type,
733 return_spelling: return_spelling.to_string(),
734 is_async,
735 body: body.to_vec(),
736 module: module.map(|m| m.to_string()),
737 }),
738 },
739 );
740 if let Some(frame) = self.scopes.get_mut(frame_idx) {
741 frame.defined.insert(qualified.clone());
742 if let Some(old) = old {
743 frame.shadowed.push((qualified, old));
744 }
745 }
746 Ok(())
747 }
748
749 pub(super) fn scope_depth(&self) -> usize {
752 self.scopes.len()
753 }
754
755 pub(super) fn push_scope(&mut self) {
758 self.scopes.push(ScopeFrame {
759 defined: HashSet::new(),
760 shadowed: Vec::new(),
761 });
762 }
763
764 pub(super) fn pop_scope(&mut self) {
767 let Some(frame) = self.scopes.pop() else {
768 return;
769 };
770 for name in frame.defined {
771 self.entries.remove(&name);
772 }
773 for (name, old) in frame.shadowed {
774 self.entries.insert(name, old);
775 }
776 }
777
778 pub(super) fn contains_script(&self, name: &str) -> bool {
782 matches!(
783 self.entries.get(name).map(|entry| &entry.body),
784 Some(FuncBody::Script(_))
785 )
786 }
787
788 fn clone_pure_fn(&self, name: &str) -> Option<PureFn> {
792 match self.entries.get(name)?.body {
793 FuncBody::Pure(ref func) => Some(Arc::clone(func)),
794 FuncBody::Both { ref pure, .. } => Some(Arc::clone(pure)),
795 _ => None,
796 }
797 }
798
799 pub(super) fn pure_shared(&self) -> Arc<PureTable> {
803 Arc::clone(&self.pure_shared)
804 }
805
806 pub(super) fn all_metas(&self) -> Vec<FuncMeta> {
809 self.entries_metas()
810 }
811
812 fn clone_ctx_fn(&self, name: &str) -> Option<NativeFn<P>> {
817 match self.entries.get(name)?.body {
818 FuncBody::Ctx(ref func) => Some(Arc::clone(func)),
819 FuncBody::Both { ref ctx, .. } => Some(Arc::clone(ctx)),
820 _ => None,
821 }
822 }
823
824 fn meta(&self, name: &str) -> Option<FuncMeta> {
825 self.entries.get(name).map(|entry| entry.meta.clone())
826 }
827
828 fn native_metas(&self) -> Vec<FuncMeta> {
829 let mut out: Vec<FuncMeta> = Vec::new();
830 for entry in self.entries.values() {
831 if !matches!(entry.body, FuncBody::Script(_)) {
832 out.push(entry.meta.clone());
833 }
834 }
835 out.sort_by(|a, b| a.name.cmp(&b.name));
836 out
837 }
838
839 fn entries_metas(&self) -> Vec<FuncMeta> {
842 let mut out: Vec<FuncMeta> = self
843 .entries
844 .values()
845 .map(|entry| entry.meta.clone())
846 .collect();
847 out.sort_by(|a, b| a.name.cmp(&b.name));
848 out
849 }
850
851 pub fn set_script_docs(&mut self, docs: &HashMap<String, (String, String)>) {
854 for (base, pair) in docs {
855 self.script_docs
856 .insert(qualify(SCRIPT_MODULE_NAME, base), pair.clone());
857 }
858 }
859
860 pub fn script_doc_for(&self, qualified: &str) -> Option<(String, String)> {
862 self.script_docs.get(qualified).cloned()
863 }
864
865 pub fn exported_metas(&self, func_exports: &[String]) -> anyhow::Result<Vec<FuncMeta>> {
868 let mut out = Vec::with_capacity(func_exports.len());
869 for name in func_exports {
870 let qualified = match name.split_once("::") {
874 None => qualify(SCRIPT_MODULE_NAME, name),
875 Some(_) => name.clone(),
876 };
877 match self.entries.get(&qualified) {
878 Some(entry) => out.push(entry.meta.clone()),
879 None => anyhow::bail!(
880 "EXPORT `{name}` matches no defined script function or known host function"
881 ),
882 }
883 }
884 Ok(out)
885 }
886}
887
888impl<P: ProcessManager> Clone for FunctionRegistry<P> {
889 fn clone(&self) -> Self {
890 Self {
891 entries: self.entries.clone(),
892 scopes: self.scopes.clone(),
893 pure_shared: Arc::clone(&self.pure_shared),
894 script_docs: self.script_docs.clone(),
895 }
896 }
897}
898
899pub fn builtin_function_names() -> HashSet<String> {
906 let mut names = FunctionRegistry::<DefaultProcessManager>::with_builtins().keys();
907 names.insert(KEYWORD_INSPECT.to_string());
908 names
909}
910
911pub fn builtin_function_metas() -> Vec<FuncMeta> {
915 FunctionRegistry::<DefaultProcessManager>::with_builtins().native_metas()
916}
917
918pub fn std_module_table() -> oxdock_parser::ModuleTable {
923 let func_names: HashSet<String> = builtin_function_metas()
925 .into_iter()
926 .map(|meta| base_name(&meta.name).to_string())
927 .collect();
928 oxdock_parser::ModuleTable {
929 modules: HashMap::from([(
930 STD_MODULE_NAME.to_string(),
931 Some(oxdock_parser::ModuleFuncs { func_names }),
932 )]),
933 }
934}
935
936#[oxdock_func(pure, returns = TypeTag::Int)]
949#[example(
950 name = "convert",
951 code = r###"
952 IMPORT [STD]
953 LET $n: INT = INT("42")
954 ASSERT_EQ $n 42
955 LET $flag: INT = INT(true)
956 ASSERT_EQ $flag 1
957 "###
958)]
959fn int(
960 #[union(Int, Float, String, Bool)]
962 val: Value,
963) -> Result<Value> {
964 super::args::int_from_value(val)
965}
966
967#[oxdock_func(pure, returns = TypeTag::Float)]
972#[example(
973 name = "convert",
974 code = r###"
975 IMPORT [STD]
976 LET $f: FLOAT = FLOAT("1.5")
977 ASSERT_EQ $f 1.5
978 LET $whole: FLOAT = FLOAT(2)
979 ASSERT_EQ $whole 2.0
980 "###
981)]
982fn float(
983 #[union(Float, Int, String)]
985 val: Value,
986) -> Result<Value> {
987 super::args::float_from_value(val)
988}
989
990#[oxdock_func(pure, returns = TypeTag::String)]
995#[example(
996 name = "format and round-trip",
997 code = r###"
998 # Byte counts render in the largest exact unit.
999 IMPORT [STD]
1000 LET $pretty: STRING = FORMAT_BYTE_COUNT(1_048_576)
1001 ASSERT_EQ $pretty "1MiB"
1002
1003 # The pair round-trips through the parser.
1004 LET $back: INT = PARSE_BYTE_COUNT($pretty)
1005 ASSERT_EQ $back 1_048_576
1006 "###
1007)]
1008fn format_byte_count(
1009 bytes: i64,
1011) -> Result<Value> {
1012 if bytes < 0 {
1013 return Err(anyhow::anyhow!(
1014 "FORMAT_BYTE_COUNT needs a non-negative byte count, got {bytes}"
1015 ));
1016 }
1017 Ok(Value::string(oxdock_parser::command::format_byte_count(
1018 bytes as u64,
1019 )))
1020}
1021
1022#[oxdock_func(pure, returns = TypeTag::Int)]
1057#[example(
1058 name = "parse",
1059 code = r###"
1060 IMPORT [STD]
1061 LET $n: INT = PARSE_BYTE_COUNT("10KB")
1062 ASSERT_EQ $n 10_000
1063 LET $identity: INT = PARSE_BYTE_COUNT(512)
1064 ASSERT_EQ $identity 512
1065 "###
1066)]
1067fn parse_byte_count(
1068 #[union(Int, Float, String)]
1070 text: Value,
1071) -> Result<Value> {
1072 if let Some(n) = text.as_i64() {
1073 if n < 0 {
1074 return Err(anyhow::anyhow!(
1075 "PARSE_BYTE_COUNT needs a non-negative byte count, got {n}"
1076 ));
1077 }
1078 return Ok(Value::int(n));
1079 }
1080 if let Some(f) = text.as_f64() {
1081 if f.is_finite() && f.fract() == 0.0 && f >= 0.0 && f <= i64::MAX as f64 {
1082 return Ok(Value::int(f as i64));
1083 }
1084 return Err(anyhow::anyhow!(
1085 "PARSE_BYTE_COUNT needs an integral byte count, got {f:?}"
1086 ));
1087 }
1088 let Some(s) = text.as_str() else {
1089 return Err(anyhow::anyhow!(
1090 "PARSE_BYTE_COUNT needs a token or number, found {text:?}"
1091 ));
1092 };
1093 let n = oxdock_parser::command::parse_byte_count(s)?;
1094 let n = i64::try_from(n)
1095 .map_err(|_| anyhow::anyhow!("PARSE_BYTE_COUNT out of INT range: {s:?}"))?;
1096 Ok(Value::int(n))
1097}
1098
1099#[oxdock_func(pure, returns = TypeTag::String)]
1104#[example(
1105 name = "format and round-trip",
1106 code = r###"
1107 # Durations render in the largest exact unit.
1108 IMPORT [STD]
1109 LET $pretty: STRING = FORMAT_DURATION(90_000)
1110 ASSERT_EQ $pretty "90s"
1111
1112 # The pair round-trips through the parser.
1113 LET $back: INT = PARSE_DURATION($pretty)
1114 ASSERT_EQ $back 90_000
1115 "###
1116)]
1117fn format_duration(
1118 millis: i64,
1120) -> Result<Value> {
1121 if millis < 0 {
1122 return Err(anyhow::anyhow!(
1123 "FORMAT_DURATION needs non-negative milliseconds, got {millis}"
1124 ));
1125 }
1126 Ok(Value::string(oxdock_parser::command::format_duration(
1127 &std::time::Duration::from_millis(millis as u64),
1128 )))
1129}
1130
1131#[oxdock_func(pure, returns = TypeTag::Int)]
1137#[example(
1138 name = "parse",
1139 code = r###"
1140 # A bare number means seconds, like TIMEOUT.
1141 IMPORT [STD]
1142 LET $ms: INT = PARSE_DURATION("2m")
1143 ASSERT_EQ $ms 120_000
1144
1145 # Milliseconds stay exact.
1146 LET $exact: INT = PARSE_DURATION("1500ms")
1147 ASSERT_EQ $exact 1_500
1148
1149 # One optional space separates number from unit.
1150 LET $spaced: INT = PARSE_DURATION("1 h")
1151 ASSERT_EQ $spaced 3_600_000
1152 "###
1153)]
1154fn parse_duration(
1155 text: String,
1157) -> Result<Value> {
1158 let duration = oxdock_parser::command::parse_duration(&text)?;
1159 let millis = i64::try_from(duration.as_millis())
1160 .map_err(|_| anyhow::anyhow!("PARSE_DURATION out of INT range: {text:?}"))?;
1161 Ok(Value::int(millis))
1162}
1163
1164#[oxdock_func(rpn, returns = TypeTag::ListOf(std::sync::Arc::new(TypeTag::String)))]
1169#[example(
1170 name = "match",
1171 code = r###"
1172 IMPORT [STD]
1173 WRITE "notes-a.md" "a"
1174 WRITE "notes-b.md" "b"
1175 WRITE "other.txt" "c"
1176 LET $found: LIST<STRING> = GLOB("notes-*.md")
1177 ASSERT_EQ $found.0 "notes-a.md"
1178 ASSERT_EQ $found.1 "notes-b.md"
1179 "###
1180)]
1181fn glob<P: ProcessManager>(
1182 cx: &mut StepCtx<P>,
1183 #[union(String, Path)]
1185 pattern: Value,
1186) -> Result<Value> {
1187 let text = super::args::string_or_path_text(&pattern)?;
1188 super::args::glob_from_value(&[Value::string(text)], cx)
1189}
1190
1191#[oxdock_func(rpn, returns = TypeTag::MapOf(std::sync::Arc::new(TypeTag::Any)))]
1196#[example(
1197 name = "load",
1198 code = r###"
1199 IMPORT [STD]
1200 WRITE "cfg.toml" "title = \"demo\""
1201 LET $cfg: MAP<ANY> = LOAD_TOML("cfg.toml")
1202 ASSERT_EQ $cfg.title "demo"
1203 "###
1204)]
1205fn load_toml<P: ProcessManager>(
1206 cx: &mut StepCtx<P>,
1207 #[union(String, Path)]
1209 path: Value,
1210) -> Result<Value> {
1211 let text = super::args::string_or_path_text(&path)?;
1212 super::args::load_toml_from_value(&[Value::string(text)], cx)
1213}
1214
1215#[oxdock_func(rpn, returns = TypeTag::Any)]
1223#[example(
1224 name = "load",
1225 code = r###"
1226 IMPORT [STD]
1227 WRITE "data.json" "{\"a\": 1}"
1228 LET $doc: MAP<ANY> = LOAD_JSON("data.json")
1229 ASSERT_EQ $doc.a 1
1230 "###
1231)]
1232fn load_json<P: ProcessManager>(
1233 cx: &mut StepCtx<P>,
1234 #[union(String, Path)]
1236 path: Value,
1237) -> Result<Value> {
1238 let text = super::args::string_or_path_text(&path)?;
1239 super::args::load_json_from_value(&[Value::string(text)], cx)
1240}
1241
1242#[oxdock_func(rpn, returns = TypeTag::String)]
1252#[example(
1253 name = "hash",
1254 code = r###"
1255 IMPORT [STD]
1256 WRITE payload.txt hello
1257 LET $digest: STRING = HASH_SHA256("payload.txt")
1258 ASSERT_EQ $digest "2cf24dba5fb0a30e26e83b2ac5b9e29e1b161e5c1fa7425e73043362938b9824"
1259 "###
1260)]
1261fn hash_sha256<P: ProcessManager>(
1262 cx: &mut StepCtx<P>,
1263 #[union(String, Path)]
1265 path: Value,
1266) -> Result<Value> {
1267 use sha2::Digest;
1268
1269 let text = super::args::string_or_path_text(&path)?;
1270 let target = cx.state.fs.resolve_read(&cx.state.cwd, &text)?;
1271 let mut hasher = sha2::Sha256::new();
1272 super::fs_ops::hash_path(cx.state.fs.as_ref(), &target, "", &mut hasher)?;
1273 let digest = hasher.finalize();
1274 let bytes: &[u8] = digest.as_ref();
1275 Ok(Value::string(oxdock_utils::hex_encode(bytes)))
1276}
1277
1278#[oxdock_func(rpn, returns = TypeTag::String)]
1289#[example(
1290 name = "cwd",
1291 code = r###"
1292 IMPORT [STD]
1293 WORKDIR sub
1294 LET $c: STRING = CWD()
1295 ASSERT_CONTAINS $c "sub"
1296 "###
1297)]
1298fn cwd<P: ProcessManager>(cx: &mut StepCtx<P>) -> Result<Value> {
1299 if cx.state.fs.is_snapshot_pending() {
1300 return Ok(Value::string(super::SNAPSHOT_PENDING_DISPLAY.to_string()));
1301 }
1302 let concrete = cx.state.fs.concretize_cwd(&cx.state.cwd);
1303 let real = super::fs_ops::canonical_cwd(cx.state.fs.as_ref(), &concrete)?;
1304 Ok(Value::string(real))
1305}
1306
1307#[oxdock_func(pure, returns = TypeTag::MapOf(std::sync::Arc::new(TypeTag::Any)))]
1313#[example(
1314 name = "parse",
1315 code = r###"
1316 IMPORT [STD]
1317 LET $doc: MAP<ANY> = PARSE_TOML("title = \"demo\"")
1318 ASSERT_EQ $doc.title "demo"
1319 "###
1320)]
1321fn parse_toml(
1322 text: String,
1324) -> Result<Value> {
1325 super::args::parse_toml_from_value(Value::string(text))
1326}
1327
1328#[oxdock_func(pure, returns = TypeTag::Any)]
1337#[example(
1338 name = "parse",
1339 code = r###"
1340 # Parse in-memory JSON text with the same conversion as file loading.
1341 IMPORT [STD]
1342 LET $body: STRING = "{\"a\": 1}"
1343 LET $doc: ANY = PARSE_JSON($body)
1344 ASSERT_EQ $doc.a 1
1345
1346 # Top-level arrays parse to LIST, which is why the return is ANY.
1347 LET $items: LIST<ANY> = PARSE_JSON("[1, 2]")
1348 ASSERT_EQ $items.0 1
1349 ASSERT_EQ $items.1 2
1350 "###
1351)]
1352fn parse_json(
1353 text: String,
1355) -> Result<Value> {
1356 super::args::parse_json_from_value(Value::string(text))
1357}
1358
1359#[oxdock_func(returns = TypeTag::String)]
1365#[example(
1366 name = "describe",
1367 code = r###"
1368 IMPORT [STD]
1369 WRITE "entry.txt" "words"
1370 LET $kind: STRING = PATH_TYPE("entry.txt")
1371 ASSERT_EQ $kind "file"
1372 LET $missing: STRING = PATH_TYPE("no-such-entry.txt")
1373 ASSERT_EQ $missing "absent"
1374 "###
1375)]
1376fn path_type<P: ProcessManager>(
1377 cx: &mut StepCtx<P>,
1378 #[union(String, Path)]
1380 path: Value,
1381) -> Result<Value> {
1382 let text = super::args::string_or_path_text(&path)?;
1383 super::args::path_type_from_value(&[Value::string(text)], cx)
1384}
1385
1386#[oxdock_func(returns = TypeTag::Bool)]
1395#[example(
1396 name = "probe",
1397 code = r###"
1398 # An absent nested path is writable when its ancestor is.
1399 IMPORT [STD]
1400 LET $fresh: BOOL = PATH_WRITABLE("probe-check/nested/file.txt")
1401 ASSERT_EQ $fresh true
1402
1403 # The empty string never aliases the working directory.
1404 LET $empty: BOOL = PATH_WRITABLE("")
1405 ASSERT_EQ $empty false
1406 "###
1407)]
1408fn path_writable<P: ProcessManager>(
1409 cx: &mut StepCtx<P>,
1410 #[union(String, Path)]
1412 path: Value,
1413) -> Result<Value> {
1414 let text = super::args::string_or_path_text(&path)?;
1415 super::args::path_writable_from_value(&[Value::string(text)], cx)
1416}
1417
1418#[oxdock_func(returns = TypeTag::Bool)]
1431#[example(
1432 name = "probe",
1433 code = r###"
1434 # Missing tools read false instead of failing the run.
1435 IMPORT [STD]
1436 LET $missing: BOOL = IS_EXEC("no-such-tool-xyz")
1437 ASSERT_EQ $missing false
1438
1439 # Plain files are not executable on any platform.
1440 WRITE tool.txt payload
1441 LET $plain: BOOL = IS_EXEC("tool.txt")
1442 ASSERT_EQ $plain false
1443 "###
1444)]
1445fn is_exec<P: ProcessManager>(
1446 cx: &mut StepCtx<P>,
1447 #[union(String, Path)]
1449 name: Value,
1450) -> Result<Value> {
1451 let text = super::args::string_or_path_text(&name)?;
1452 super::args::is_exec_from_value(&[Value::string(text)], cx)
1453}
1454
1455#[oxdock_func(pure, returns = TypeTag::Bool)]
1461#[example(
1462 name = "probe",
1463 code = r###"
1464 IMPORT [STD]
1465 LET $m: MAP<ANY> = PARSE_JSON("{\"a\": 1}")
1466 LET $hit: BOOL = HAS_KEY($m, "a")
1467 ASSERT_EQ $hit true
1468 LET $miss: BOOL = HAS_KEY($m, "b")
1469 ASSERT_EQ $miss false
1470 "###
1471)]
1472fn has_key(
1473 map: BTreeMap<String, Value>,
1475 key: String,
1477) -> Result<Value> {
1478 super::args::has_key_from_value(Value::map(map), &key)
1479}
1480
1481#[oxdock_func(pure, returns = TypeTag::MapOf(std::sync::Arc::new(TypeTag::Any)))]
1487#[example(
1488 name = "insert",
1489 code = r###"
1490 IMPORT [STD]
1491 LET $m: MAP<ANY> = MAP_SET({seed: 0}, "a", 1)
1492 ASSERT_EQ $m.a 1
1493 "###
1494)]
1495fn map_set(
1496 map: BTreeMap<String, Value>,
1498 key: String,
1500 value: Value,
1502) -> Result<Value> {
1503 super::args::map_set_from_value(Value::map(map), key, value)
1504}
1505
1506#[oxdock_func(returns = TypeTag::Float, summary = "Draw a random FLOAT uniformly from [0, 1), optionally seeded.")]
1514#[example(
1515 name = "seeded draw",
1516 code = r###"
1517 # A seed draws the same value on every run.
1518 IMPORT [STD]
1519 LET $one: FLOAT = RAND({seed: 7})
1520 LET $two: FLOAT = RAND({seed: 7})
1521 ASSERT_EQ $one $two
1522 "###
1523)]
1524#[example(
1525 name = "unseeded draw",
1526 code = r###"
1527 # Scale a unit draw into a backoff delay between 1 and 11 seconds.
1528 IMPORT [STD]
1529 LET $draw: FLOAT = RAND()
1530 LET $delay: FLOAT = 1.0 + $draw * 10.0
1531 IF $delay < 1.0 {
1532 EXIT 1
1533 }
1534 IF $delay >= 11.0 {
1535 EXIT 1
1536 }
1537 ECHO "retrying in {{ $delay }}s"
1538 "###
1539)]
1540fn rand<P: ProcessManager>(
1541 cx: &mut StepCtx<P>,
1542 #[options("seed?: INT")]
1544 #[optional]
1545 options: BTreeMap<String, Value>,
1546) -> Result<Value> {
1547 let _ = cx;
1548 let seed = options
1551 .get("seed")
1552 .map(|value| value.as_i64().expect("check_options verified INT"));
1553 super::args::rand_float_from_value(seed)
1554}
1555
1556#[oxdock_func(pure, returns = TypeTag::String)]
1562#[example(
1563 name = "encode",
1564 code = r###"
1565 # Encode text to standard base64.
1566 IMPORT [STD]
1567 LET $encoded: STRING = BASE64_ENCODE("hello")
1568 ASSERT_EQ $encoded "aGVsbG8="
1569 "###
1570)]
1571fn base64_encode(
1572 text: String,
1574) -> Result<Value> {
1575 super::args::base64_encode_from_value(Value::string(text))
1576}
1577
1578#[oxdock_func(pure, returns = TypeTag::String)]
1585#[example(
1586 name = "decode",
1587 code = r###"
1588 # Decode standard base64 back to text.
1589 IMPORT [STD]
1590 LET $decoded: STRING = BASE64_DECODE("aGVsbG8=")
1591 ASSERT_EQ $decoded "hello"
1592 "###
1593)]
1594fn base64_decode(
1595 text: String,
1597) -> Result<Value> {
1598 super::args::base64_decode_from_value(Value::string(text))
1599}
1600
1601#[oxdock_func(pure, returns = TypeTag::String)]
1608#[example(
1609 name = "encode",
1610 code = r###"
1611 IMPORT [STD]
1612 LET $json: STRING = TO_JSON({a: 1})
1613 ASSERT_EQ $json "{\"a\":1}\n"
1614 "###
1615)]
1616fn to_json(
1617 #[union(String, Int, Float, Bool, List, Map)]
1619 value: Value,
1620) -> Result<Value> {
1621 super::args::to_json_from_value(value)
1622}
1623
1624#[oxdock_func(pure, returns = TypeTag::String)]
1632#[example(
1633 name = "name the word",
1634 code = r###"
1635 IMPORT [STD]
1636 LET $word: STRING = TYPE_OF(42)
1637 ASSERT_EQ $word "INT"
1638 "###
1639)]
1640fn type_of(
1641 value: Value,
1643) -> Result<Value> {
1644 super::args::type_of_from_value(value)
1645}
1646
1647#[oxdock_func(pure, returns = TypeTag::MapOf(std::sync::Arc::new(TypeTag::Any)))]
1655#[example(
1656 name = "merge",
1657 code = r###"
1658 IMPORT [STD]
1659 LET $m: MAP<ANY> = MERGE_MAPS([{a: 1}, {b: 2}], "overwrite")
1660 ASSERT_EQ $m.a 1
1661 ASSERT_EQ $m.b 2
1662 "###
1663)]
1664fn merge_maps(
1665 maps: Vec<BTreeMap<String, Value>>,
1667 #[values("fail_on_duplicate", "overwrite")]
1669 policy: String,
1670) -> Result<Value> {
1671 super::args::merge_maps_from_value(
1672 Value::list(maps.into_iter().map(Value::map).collect()),
1673 policy,
1674 )
1675}
1676
1677#[oxdock_func(pure, returns = TypeTag::String)]
1682#[example(
1683 name = "report",
1684 code = r###"
1685 # The engine reports its own build version as a dotted string.
1686 IMPORT [STD]
1687 LET $v: STRING = VERSION()
1688 ASSERT_CONTAINS $v "."
1689 "###
1690)]
1691fn version() -> Result<Value> {
1692 Ok(Value::string(env!("CARGO_PKG_VERSION").to_string()))
1693}
1694
1695#[oxdock_func(returns = TypeTag::ListOf(std::sync::Arc::new(TypeTag::String)))]
1700#[example(
1701 name = "list",
1702 code = r###"
1703 IMPORT [STD]
1704 LET $names: LIST<STRING> = FUNCTIONS()
1705 ASSERT_CONTAINS $names "STD::INT"
1706 "###
1707)]
1708fn functions<P: ProcessManager>(cx: &mut StepCtx<P>) -> Result<Value> {
1709 let mut names: Vec<String> = cx
1710 .state
1711 .list_functions()
1712 .into_iter()
1713 .map(|meta| meta.name)
1714 .collect();
1715 names.sort();
1716 names.dedup();
1717 Ok(Value::list(names.into_iter().map(Value::string).collect()))
1718}
1719
1720#[oxdock_func(
1735 returns = TypeTag::Record(std::sync::Arc::from([Field {
1736 name: "name".to_string(),
1737 ty: TypeTag::String,
1738 docs: "Qualified function name.",
1739 optional: false,
1740 }, Field {
1741 name: "module".to_string(),
1742 ty: TypeTag::String,
1743 docs: "Owning module.",
1744 optional: false,
1745 }, Field {
1746 name: "kind".to_string(),
1747 ty: TypeTag::String,
1748 docs: "Origin label (`host` or `script`).",
1749 optional: false,
1750 }, Field {
1751 name: "params".to_string(),
1752 ty: TypeTag::ListOf(std::sync::Arc::new(TypeTag::MapOf(std::sync::Arc::new(
1753 TypeTag::Any,
1754 )))),
1755 docs: "Parameter entries (empty for parameterless functions).",
1756 optional: false,
1757 }, Field {
1758 name: "returns".to_string(),
1759 ty: TypeTag::String,
1760 docs: "Structural return shape (empty when untagged).",
1761 optional: false,
1762 }, Field {
1763 name: "rpn".to_string(),
1764 ty: TypeTag::Bool,
1765 docs: "True when callable in RPN position.",
1766 optional: false,
1767 }, Field {
1768 name: "summary".to_string(),
1769 ty: TypeTag::String,
1770 docs: "One-line description.",
1771 optional: false,
1772 }]))
1773 summary = "Describe one function by qualified name."
1774)]
1775#[example(
1776 name = "describe",
1777 code = r###"
1778 IMPORT [STD]
1779 LET $info: MAP<ANY> = DESCRIBE("STD::INT")
1780 ASSERT_EQ $info.name "STD::INT"
1781 ASSERT_EQ $info.returns "INT"
1782 "###
1783)]
1784fn describe<P: ProcessManager>(
1785 cx: &mut StepCtx<P>,
1786 name: String,
1788) -> Result<Value> {
1789 if split_qualified(&name).is_none() && name != KEYWORD_INSPECT {
1790 anyhow::bail!(
1791 "unknown function `{name}`: DESCRIBE requires a qualified name (e.g. `STD::{name}`)"
1792 );
1793 }
1794 cx.state
1795 .describe_function(&name)
1796 .ok_or_else(|| anyhow::anyhow!("unknown function {name}"))
1797}
1798
1799#[oxdock_func(returns = TypeTag::ListOf(std::sync::Arc::new(TypeTag::String)))]
1805#[example(
1806 name = "list",
1807 code = r###"
1808 IMPORT [STD]
1809 LET $names: LIST<STRING> = TYPES()
1810 ASSERT_CONTAINS $names "STRING"
1811 "###
1812)]
1813fn types<P: ProcessManager>(cx: &mut StepCtx<P>) -> Result<Value> {
1814 Ok(Value::list(
1815 cx.state
1816 .type_names()
1817 .into_iter()
1818 .map(Value::string)
1819 .collect(),
1820 ))
1821}
1822
1823#[oxdock_func(returns = TypeTag::Record(std::sync::Arc::from([Field {
1829 name: "name".to_string(),
1830 ty: TypeTag::String,
1831 docs: "Queried type name.",
1832 optional: false,
1833}, Field {
1834 name: "summary".to_string(),
1835 ty: TypeTag::String,
1836 docs: "One-line description.",
1837 optional: false,
1838}, Field {
1839 name: "docs".to_string(),
1840 ty: TypeTag::String,
1841 docs: "Full documentation text.",
1842 optional: false,
1843}])))]
1844#[example(
1845 name = "describe",
1846 code = r###"
1847 IMPORT [STD]
1848 LET $info: MAP<ANY> = TYPE_DESCRIBE("STRING")
1849 ASSERT_EQ $info.name "STRING"
1850 "###
1851)]
1852fn type_describe<P: ProcessManager>(
1853 cx: &mut StepCtx<P>,
1854 name: String,
1856) -> Result<Value> {
1857 if let Some(descriptor) = cx.state.describe_type(&name) {
1858 let mut map = BTreeMap::new();
1859 map.insert(
1860 "name".to_string(),
1861 Value::string(descriptor.name.to_string()),
1862 );
1863 map.insert(
1864 "summary".to_string(),
1865 Value::string(descriptor.summary.to_string()),
1866 );
1867 map.insert(
1868 "docs".to_string(),
1869 Value::string(descriptor.docs.to_string()),
1870 );
1871 return Ok(Value::map(map));
1872 }
1873 if let Some(target) = cx.state.alias_target(&name) {
1876 let mut map = BTreeMap::new();
1877 map.insert("name".to_string(), Value::string(name.clone()));
1878 map.insert(
1879 "summary".to_string(),
1880 Value::string(format!("Script type alias for {target}.")),
1881 );
1882 map.insert(
1883 "docs".to_string(),
1884 Value::string(format!(
1885 "Declared with TYPE {name} = {target}. The alias expands structurally at every declaration."
1886 )),
1887 );
1888 return Ok(Value::map(map));
1889 }
1890 Err(anyhow::anyhow!("unknown type {name}"))
1891}
1892
1893#[oxdock_func(returns = TypeTag::String)]
1907#[example(
1908 name = "self",
1909 code = r###"
1910 # The running interpreter resolves to a non-empty path.
1911 IMPORT [STD]
1912 LET $exe: STRING = INTERPRETER()
1913 LET $nonempty: BOOL = $exe != ""
1914 ASSERT_EQ $nonempty true
1915 "###
1916)]
1917#[example(
1918 name = "dynamic assembly",
1919 code = r###"
1920 # Assemble the child script dynamically: the parent interpolates
1921 # its own bindings into the pipe, then runs the interpreter on it.
1922 # Unescaped {{ }} bakes in at render time; \{{ }} stays literal
1923 # so the child expands it with its own bindings.
1924 # The pipe delivers EOF when the producer step ends, so the child
1925 # reads exactly one script.
1926 IMPORT [STD]
1927 LET $exe: STRING = INTERPRETER()
1928 LET $who: STRING = "Ada"
1929 LET $child: PIPE
1930 WITH_IO [stdout=$child] ECHO """
1931 ECHO "hello {{ $who }}!"
1932 LET $who: STRING = "Grace"
1933 ECHO "child sees \{{ $who }}!"
1934 """
1935 LET $out: STRING = WITH_IO [stdin=$child] RUN [$exe]
1936 ASSERT_CONTAINS $out "hello Ada!"
1937 ASSERT_CONTAINS $out "child sees Grace!"
1938 "###
1939)]
1940fn interpreter<P: ProcessManager>(cx: &mut StepCtx<P>) -> Result<Value> {
1941 if let Some(staged) = cx.state.io.interpreter_override() {
1942 return Ok(Value::string(staged));
1943 }
1944 Ok(Value::string(oxdock_process::interpreter_exe()?))
1945}
1946
1947#[oxdock_func(returns = TypeTag::Bool)]
1955#[example(
1956 name = "main",
1957 code = r###"
1958 # Entry top level runs as main.
1959 IMPORT [STD]
1960 LET $m: BOOL = IS_MAIN()
1961 ASSERT_EQ $m true
1962 "###
1963)]
1964#[example(
1965 name = "library doubles as demo",
1966 fence_meta = "roots:unified",
1967 code = r###"
1968 # A library doubles as a runnable demo: guard the demo with
1969 # IF IS_MAIN() so importing it stays side effect free. The
1970 # parent writes both files, then runs each in a fresh
1971 # interpreter: direct execution prints the demo, importing
1972 # it does not. Unified roots: the child inherits one
1973 # workspace, so parent and child see the same files. The
1974 # exact stdout match proves the demo line stays out of the
1975 # importing run.
1976 IMPORT [STD]
1977
1978 # The library under test: demo guarded by IS_MAIN.
1979 WRITE lib.oxfile """
1980 IMPORT [STD]
1981 FUNC GREET($x: STRING): STRING { RETURN "hi \{{ $x }}" }
1982 EXPORT GREET
1983 IF IS_MAIN() {
1984 ECHO "demo: hi Ada"
1985 }
1986 """
1987
1988 # The importer: calls the library, prints only its own line.
1989 WRITE main.oxfile """
1990 IMPORT ["lib.oxfile" AS LIB]
1991 LET $g: STRING = LIB::GREET("Bo")
1992 ECHO "imported: \{{ $g }}"
1993 """
1994
1995 # Direct run executes the demo.
1996 LET $exe: STRING = INTERPRETER()
1997 LET $direct: STRING = RUN [$exe, "lib.oxfile"]
1998 ASSERT_CONTAINS $direct "demo: hi Ada"
1999
2000 # Importing run stays silent apart from its own line.
2001 LET $via: STRING = RUN [$exe, "main.oxfile"]
2002 ASSERT_EQ $via "imported: hi Bo\n"
2003 "###
2004)]
2005fn is_main<P: ProcessManager>(cx: &mut StepCtx<P>) -> Result<Value> {
2006 let main = match cx.state.module_stack.last() {
2007 None | Some(None) => true,
2008 Some(Some(_)) => false,
2009 };
2010 Ok(Value::bool(main))
2011}
2012
2013#[oxdock_func(returns = TypeTag::Bool)]
2027#[example(
2028 name = "null stdin",
2029 code = r###"
2030 # A null stdin is never a terminal, in every harness.
2031 IMPORT [STD]
2032 LET $term: BOOL = IS_TERMINAL("stdin")
2033 ASSERT_EQ $term false
2034 "###
2035)]
2036fn is_terminal<P: ProcessManager>(
2037 cx: &mut StepCtx<P>,
2038 #[values("stdin", "stdout", "stderr")]
2040 stream_name: String,
2041) -> Result<Value> {
2042 use std::io::IsTerminal;
2043 let terminal = match stream_name.as_str() {
2044 "stdin" => {
2045 if cx.stdin_pipe.is_some() {
2050 false
2051 } else {
2052 match &cx.stdin {
2053 CommandStdin::Null => false,
2054 #[cfg(not(miri))]
2055 CommandStdin::OsPipe(_) => false,
2056 CommandStdin::Stream(_) => false,
2057 CommandStdin::Inherit => std::io::stdin().is_terminal(),
2058 }
2059 }
2060 }
2061 "stdout" => {
2062 if cx.out_pipe.is_some() {
2063 false
2065 } else if cx.state.io.stdout().is_some() {
2066 false
2069 } else {
2070 match &cx.out {
2071 None => std::io::stdout().is_terminal(),
2073 #[cfg(not(miri))]
2075 Some(StreamHandle::Os(_)) => false,
2076 Some(StreamHandle::Stream(_)) => std::io::stdout().is_terminal(),
2086 }
2087 }
2088 }
2089 "stderr" => {
2090 if cx.state.io.stderr().is_some() {
2091 false
2093 } else {
2094 match &cx.err {
2095 None => std::io::stderr().is_terminal(),
2097 #[cfg(not(miri))]
2099 Some(StreamHandle::Os(_)) => false,
2100 Some(StreamHandle::Stream(_)) => false,
2103 }
2104 }
2105 }
2106 _ => anyhow::bail!(
2107 "IS_TERMINAL expects \"stdin\", \"stdout\", or \"stderr\", got {stream_name:?}"
2112 ),
2113 };
2114 Ok(Value::bool(terminal))
2115}
2116
2117#[oxdock_func(returns = TypeTag::Semaphore)]
2125#[example(
2126 name = "mint",
2127 code = r###"
2128 # Mint a semaphore admitting at most two holders.
2129 IMPORT [STD]
2130 LET $sem: SEMAPHORE = SEMAPHORE_NEW(2)
2131
2132 # A fresh semaphore reports its full cap as available.
2133 LET $free: INT = SEMAPHORE_AVAILABLE($sem)
2134 ASSERT_EQ $free 2
2135 "###
2136)]
2137fn semaphore_new<P: ProcessManager>(
2138 cx: &mut StepCtx<P>,
2139 max: i64,
2141) -> Result<Value> {
2142 let _ = cx;
2143 if max <= 0 {
2144 return Err(anyhow::anyhow!(
2145 "SEMAPHORE_NEW() requires a positive max, got {max}"
2146 ));
2147 }
2148 Ok(Value::semaphore(max as usize))
2149}
2150
2151#[oxdock_func(returns = TypeTag::Record(std::sync::Arc::from([Field {
2160 name: "held".to_string(),
2161 ty: TypeTag::Bool,
2162 docs: "`true` with the permit under `permit`, `false` with no `permit` key.",
2163 optional: false,
2164}, Field {
2165 name: "permit".to_string(),
2166 ty: TypeTag::Permit,
2167 docs: "Permit handle; read only when `held`.",
2168 optional: true,
2169}])))]
2170#[example(
2171 name = "acquire",
2172 code = r###"
2173 # First acquire holds with a permit to bind.
2174 IMPORT [STD]
2175 LET $sem: SEMAPHORE = SEMAPHORE_NEW(1)
2176 LET $first: MAP<held: BOOL, permit?: PERMIT> = SEMAPHORE_TRY_ACQUIRE($sem)
2177 ASSERT_EQ $first.held true
2178 LET $permit: PERMIT = $first.permit
2179
2180 # A capped semaphore answers held false with no permit key.
2181 LET $second: MAP<held: BOOL, permit?: PERMIT> = SEMAPHORE_TRY_ACQUIRE($sem)
2182 ASSERT_EQ $second.held false
2183 LET $has_permit: BOOL = HAS_KEY($second, "permit")
2184 ASSERT_EQ $has_permit false
2185 "###
2186)]
2187fn semaphore_try_acquire<P: ProcessManager>(
2188 cx: &mut StepCtx<P>,
2189 sem: Arc<SemaphoreState>,
2191) -> Result<Value> {
2192 let _ = cx;
2193 let mut map = BTreeMap::new();
2194 if sem.try_acquire() {
2195 map.insert("held".to_string(), Value::bool(true));
2196 map.insert("permit".to_string(), Value::permit(&sem));
2197 } else {
2198 map.insert("held".to_string(), Value::bool(false));
2199 }
2200 Ok(Value::map(map))
2201}
2202
2203#[oxdock_func(pure, returns = TypeTag::Int)]
2210#[example(
2211 name = "readout",
2212 code = r###"
2213 # Hold one permit on a cap of two.
2214 IMPORT [STD]
2215 LET $sem: SEMAPHORE = SEMAPHORE_NEW(2)
2216 LET $acq: MAP<held: BOOL, permit?: PERMIT> = SEMAPHORE_TRY_ACQUIRE($sem)
2217 ASSERT_EQ $acq.held true
2218
2219 # One held permit leaves exactly one free.
2220 LET $free: INT = SEMAPHORE_AVAILABLE($sem)
2221 ASSERT_EQ $free 1
2222 "###
2223)]
2224fn semaphore_available(
2225 sem: Arc<SemaphoreState>,
2227) -> Result<Value> {
2228 Ok(Value::int(sem.available() as i64))
2229}
2230
2231#[oxdock_func(
2240 rpn,
2241 returns = TypeTag::union(vec![TypeTag::String, TypeTag::Pipe]),
2242 template = text_trim_string
2243)]
2244#[example(
2245 name = "trim",
2246 code = r###"
2247 # Leading and trailing whitespace falls away.
2248 IMPORT [STD]
2249 LET $clean: STRING = TEXT_TRIM(" hello ")
2250 ASSERT_EQ $clean "hello"
2251 "###
2252)]
2253#[example(
2254 name = "trim pipe mirrors",
2255 code = r###"
2256 # Pipe input mints pipe output with the same transform.
2257 IMPORT [STD]
2258 LET $cap: PIPE
2259 WITH_IO [stdout=$cap] {
2260 ECHO " hello "
2261 }
2262 LET $out: PIPE = TEXT_TRIM($cap)
2263 WITH_IO [stdin=$out] READ_LINE $line
2264 ASSERT_EQ $line "hello"
2265 "###
2266)]
2267#[example(
2268 name = "trim template",
2269 code = r###"
2270 # String inputs run inside placeholders too.
2271 IMPORT [STD]
2272 LET $msg: STRING = 'clean:{{ STD::TEXT_TRIM(" hello ") }}'
2273 ASSERT_EQ $msg "clean:hello"
2274 "###
2275)]
2276#[example(
2277 name = "trim file template",
2278 code = r###"
2279 # EXPAND templates resolve the same registry.
2280 IMPORT [STD]
2281 WRITE "tpl.txt" "clean:\{{ STD::TEXT_TRIM(\" hello \") }}"
2282 LET $out: STRING = EXPAND "tpl.txt"
2283 ASSERT_EQ $out "clean:hello"
2284 "###
2285)]
2286fn text_trim<P: ProcessManager>(
2287 cx: &mut StepCtx<P>,
2288 #[union(String, Pipe)]
2290 text: Value,
2291) -> Result<Value> {
2292 super::args::mirror_stream(cx, "TEXT_TRIM", &text, super::args::TextPump::Trim)
2293}
2294
2295fn text_trim_string(text: Value) -> Result<Value> {
2298 super::args::mirror_string("TEXT_TRIM", &text, super::args::TextPump::Trim)
2299}
2300
2301#[oxdock_func(
2310 rpn,
2311 returns = TypeTag::union(vec![TypeTag::String, TypeTag::Pipe]),
2312 template = text_trim_prefix_string
2313)]
2314#[example(
2315 name = "strip prefix",
2316 code = r###"
2317 # A present prefix falls away; absence returns the input unchanged.
2318 IMPORT [STD]
2319 LET $bare: STRING = TEXT_TRIM_PREFIX("v1.2.3", "v")
2320 ASSERT_EQ $bare "1.2.3"
2321
2322 # Missing prefixes pass through untouched.
2323 LET $same: STRING = TEXT_TRIM_PREFIX("1.2.3", "v")
2324 ASSERT_EQ $same "1.2.3"
2325 "###
2326)]
2327#[example(
2328 name = "strip prefix pipe mirrors",
2329 code = r###"
2330 # Pipe input mints pipe output with the same strip.
2331 IMPORT [STD]
2332 LET $cap: PIPE
2333 WITH_IO [stdout=$cap] {
2334 ECHO "v1.2.3"
2335 }
2336 LET $trimmed: PIPE = TEXT_TRIM($cap)
2337 LET $out: PIPE = TEXT_TRIM_PREFIX($trimmed, "v")
2338 WITH_IO [stdin=$out] READ_LINE $line
2339 ASSERT_EQ $line "1.2.3"
2340 "###
2341)]
2342#[example(
2343 name = "strip prefix template",
2344 code = r###"
2345 # String inputs run inside placeholders too.
2346 IMPORT [STD]
2347 LET $msg: STRING = 'bare:{{ STD::TEXT_TRIM_PREFIX("v1.2.3", "v") }}'
2348 ASSERT_EQ $msg "bare:1.2.3"
2349 "###
2350)]
2351fn text_trim_prefix<P: ProcessManager>(
2352 cx: &mut StepCtx<P>,
2353 #[union(String, Pipe)]
2355 text: Value,
2356 prefix: String,
2358) -> Result<Value> {
2359 super::args::mirror_stream(
2360 cx,
2361 "TEXT_TRIM_PREFIX",
2362 &text,
2363 super::args::TextPump::TrimPrefix(prefix),
2364 )
2365}
2366
2367fn text_trim_prefix_string(text: Value, prefix: String) -> Result<Value> {
2370 super::args::mirror_string(
2371 "TEXT_TRIM_PREFIX",
2372 &text,
2373 super::args::TextPump::TrimPrefix(prefix),
2374 )
2375}
2376
2377#[oxdock_func(
2384 rpn,
2385 returns = TypeTag::union(vec![TypeTag::String, TypeTag::Pipe]),
2386 template = text_trim_suffix_string
2387)]
2388#[example(
2389 name = "strip suffix",
2390 code = r###"
2391 # A present suffix falls away; absence returns the input unchanged.
2392 IMPORT [STD]
2393 LET $bare: STRING = TEXT_TRIM_SUFFIX("archive.tar.gz", ".gz")
2394 ASSERT_EQ $bare "archive.tar"
2395
2396 # Missing suffixes pass through untouched.
2397 LET $same: STRING = TEXT_TRIM_SUFFIX("archive.tar", ".gz")
2398 ASSERT_EQ $same "archive.tar"
2399 "###
2400)]
2401#[example(
2402 name = "strip suffix pipe mirrors",
2403 code = r###"
2404 # Pipe input mints pipe output with the same strip.
2405 IMPORT [STD]
2406 LET $cap: PIPE
2407 WITH_IO [stdout=$cap] {
2408 ECHO "archive.tar.gz"
2409 }
2410 LET $trimmed: PIPE = TEXT_TRIM($cap)
2411 LET $out: PIPE = TEXT_TRIM_SUFFIX($trimmed, ".gz")
2412 WITH_IO [stdin=$out] READ_LINE $line
2413 ASSERT_EQ $line "archive.tar"
2414 "###
2415)]
2416#[example(
2417 name = "strip suffix template",
2418 code = r###"
2419 # String inputs run inside placeholders too.
2420 IMPORT [STD]
2421 LET $msg: STRING = 'bare:{{ STD::TEXT_TRIM_SUFFIX("archive.tar.gz", ".gz") }}'
2422 ASSERT_EQ $msg "bare:archive.tar"
2423 "###
2424)]
2425fn text_trim_suffix<P: ProcessManager>(
2426 cx: &mut StepCtx<P>,
2427 #[union(String, Pipe)]
2429 text: Value,
2430 suffix: String,
2432) -> Result<Value> {
2433 super::args::mirror_stream(
2434 cx,
2435 "TEXT_TRIM_SUFFIX",
2436 &text,
2437 super::args::TextPump::TrimSuffix(suffix),
2438 )
2439}
2440
2441fn text_trim_suffix_string(text: Value, suffix: String) -> Result<Value> {
2444 super::args::mirror_string(
2445 "TEXT_TRIM_SUFFIX",
2446 &text,
2447 super::args::TextPump::TrimSuffix(suffix),
2448 )
2449}
2450
2451#[oxdock_func(returns = TypeTag::String)]
2462#[example(
2463 name = "join path",
2464 code = r###"
2465 # Directory and file stem join with the native separator.
2466 # Source `\\` is one backslash at runtime; `/` works on Windows
2467 # too, native just reads better there.
2468 IMPORT [STD]
2469 LET $p: STRING = PATH_JOIN("some-dir", "some-file")
2470 [family:unix] ASSERT_EQ $p "some-dir/some-file"
2471 [family:windows] ASSERT_EQ $p "some-dir\\some-file"
2472 "###
2473)]
2474fn path_join<P: ProcessManager>(
2475 _cx: &mut StepCtx<P>,
2476 #[union(String, Path)]
2478 dir: Value,
2479 #[union(String, Path)]
2481 name: Value,
2482) -> Result<Value> {
2483 let d = super::args::string_or_path_text(&dir)?;
2484 let n = super::args::string_or_path_text(&name)?;
2485 Ok(Value::string(oxdock_fs::join_native(&d, &n)))
2486}
2487
2488#[oxdock_func(
2495 rpn,
2496 returns = TypeTag::union(vec![TypeTag::String, TypeTag::Pipe]),
2497 template = text_to_upper_string
2498)]
2499#[example(
2500 name = "uppercase",
2501 code = r###"
2502 # Text folds to uppercase.
2503 IMPORT [STD]
2504 LET $loud: STRING = TEXT_TO_UPPER("hello")
2505 ASSERT_EQ $loud "HELLO"
2506 "###
2507)]
2508#[example(
2509 name = "uppercase pipe mirrors",
2510 code = r###"
2511 # Pipe input mints pipe output with the same fold.
2512 IMPORT [STD]
2513 LET $cap: PIPE
2514 WITH_IO [stdout=$cap] {
2515 ECHO "hello"
2516 }
2517 LET $out: PIPE = TEXT_TO_UPPER($cap)
2518 WITH_IO [stdin=$out] READ_LINE $line
2519 ASSERT_EQ $line "HELLO"
2520 "###
2521)]
2522#[example(
2523 name = "uppercase template",
2524 code = r###"
2525 # String inputs run inside placeholders too.
2526 IMPORT [STD]
2527 LET $msg: STRING = 'loud:{{ STD::TEXT_TO_UPPER("hello") }}'
2528 ASSERT_EQ $msg "loud:HELLO"
2529 "###
2530)]
2531fn text_to_upper<P: ProcessManager>(
2532 cx: &mut StepCtx<P>,
2533 #[union(String, Pipe)]
2535 text: Value,
2536) -> Result<Value> {
2537 super::args::mirror_stream(cx, "TEXT_TO_UPPER", &text, super::args::TextPump::ToUpper)
2538}
2539
2540fn text_to_upper_string(text: Value) -> Result<Value> {
2543 super::args::mirror_string("TEXT_TO_UPPER", &text, super::args::TextPump::ToUpper)
2544}
2545
2546#[oxdock_func(
2553 rpn,
2554 returns = TypeTag::union(vec![TypeTag::String, TypeTag::Pipe]),
2555 template = text_to_lower_string
2556)]
2557#[example(
2558 name = "lowercase",
2559 code = r###"
2560 # Text folds to lowercase.
2561 IMPORT [STD]
2562 LET $quiet: STRING = TEXT_TO_LOWER("HELLO")
2563 ASSERT_EQ $quiet "hello"
2564 "###
2565)]
2566#[example(
2567 name = "lowercase pipe mirrors",
2568 code = r###"
2569 # Pipe input mints pipe output with the same fold.
2570 IMPORT [STD]
2571 LET $cap: PIPE
2572 WITH_IO [stdout=$cap] {
2573 ECHO "HELLO"
2574 }
2575 LET $out: PIPE = TEXT_TO_LOWER($cap)
2576 WITH_IO [stdin=$out] READ_LINE $line
2577 ASSERT_EQ $line "hello"
2578 "###
2579)]
2580#[example(
2581 name = "lowercase template",
2582 code = r###"
2583 # String inputs run inside placeholders too.
2584 IMPORT [STD]
2585 LET $msg: STRING = 'quiet:{{ STD::TEXT_TO_LOWER("HELLO") }}'
2586 ASSERT_EQ $msg "quiet:hello"
2587 "###
2588)]
2589fn text_to_lower<P: ProcessManager>(
2590 cx: &mut StepCtx<P>,
2591 #[union(String, Pipe)]
2593 text: Value,
2594) -> Result<Value> {
2595 super::args::mirror_stream(cx, "TEXT_TO_LOWER", &text, super::args::TextPump::ToLower)
2596}
2597
2598fn text_to_lower_string(text: Value) -> Result<Value> {
2601 super::args::mirror_string("TEXT_TO_LOWER", &text, super::args::TextPump::ToLower)
2602}
2603
2604#[oxdock_func(
2615 rpn,
2616 returns = TypeTag::union(vec![TypeTag::String, TypeTag::Pipe]),
2617 template = text_replace_string
2618)]
2619#[example(
2620 name = "replace",
2621 code = r###"
2622 # Every literal occurrence rewrites in place.
2623 IMPORT [STD]
2624 LET $fixed: STRING = TEXT_REPLACE("hello world", "world", "there")
2625 ASSERT_EQ $fixed "hello there"
2626 "###
2627)]
2628#[example(
2629 name = "replace pipe mirrors",
2630 code = r###"
2631 # Pipe input mints pipe output with the same rewrite.
2632 IMPORT [STD]
2633 LET $cap: PIPE
2634 WITH_IO [stdout=$cap] {
2635 ECHO "hello world"
2636 }
2637 LET $trimmed: PIPE = TEXT_TRIM($cap)
2638 LET $out: PIPE = TEXT_REPLACE($trimmed, "world", "there")
2639 WITH_IO [stdin=$out] READ_LINE $line
2640 ASSERT_EQ $line "hello there"
2641 "###
2642)]
2643#[example(
2644 name = "replace template",
2645 code = r###"
2646 # String inputs run inside placeholders too.
2647 IMPORT [STD]
2648 LET $msg: STRING = 'fixed:{{ STD::TEXT_REPLACE("hello world", "world", "there") }}'
2649 ASSERT_EQ $msg "fixed:hello there"
2650 "###
2651)]
2652fn text_replace<P: ProcessManager>(
2653 cx: &mut StepCtx<P>,
2654 #[union(String, Pipe)]
2656 text: Value,
2657 from: String,
2659 to: String,
2661) -> Result<Value> {
2662 super::args::mirror_stream(
2663 cx,
2664 "TEXT_REPLACE",
2665 &text,
2666 super::args::TextPump::ReplaceLiteral { from, to },
2667 )
2668}
2669
2670fn text_replace_string(text: Value, from: String, to: String) -> Result<Value> {
2673 super::args::mirror_string(
2674 "TEXT_REPLACE",
2675 &text,
2676 super::args::TextPump::ReplaceLiteral { from, to },
2677 )
2678}
2679
2680#[oxdock_func(
2692 rpn,
2693 returns = TypeTag::union(vec![TypeTag::String, TypeTag::Pipe]),
2694 template = text_replace_regex_string
2695)]
2696#[example(
2697 name = "replace with captures",
2698 code = r###"
2699 # Capture groups expand in the replacement.
2700 IMPORT [STD]
2701 LET $swapped: STRING = TEXT_REPLACE_REGEX("2026-10-13", "(\\d+)-(\\d+)-(\\d+)", "$3/$2/$1")
2702 ASSERT_EQ $swapped "13/10/2026"
2703 "###
2704)]
2705#[example(
2706 name = "replace regex pipe mirrors",
2707 code = r###"
2708 # Pipe input mints pipe output with the same rewrite.
2709 IMPORT [STD]
2710 LET $cap: PIPE
2711 WITH_IO [stdout=$cap] {
2712 ECHO "2026-10-13"
2713 }
2714 LET $trimmed: PIPE = TEXT_TRIM($cap)
2715 LET $out: PIPE = TEXT_REPLACE_REGEX($trimmed, "(\\d+)-(\\d+)-(\\d+)", "$3/$2/$1")
2716 WITH_IO [stdin=$out] READ_LINE $line
2717 ASSERT_EQ $line "13/10/2026"
2718 "###
2719)]
2720#[example(
2721 name = "replace regex template",
2722 code = r###"
2723 # String inputs run inside placeholders too.
2724 IMPORT [STD]
2725 LET $msg: STRING = 'swapped:{{ STD::TEXT_REPLACE_REGEX("2026-10-13", "(\\d+)-(\\d+)-(\\d+)", "$3/$2/$1") }}'
2726 ASSERT_EQ $msg "swapped:13/10/2026"
2727 "###
2728)]
2729fn text_replace_regex<P: ProcessManager>(
2730 cx: &mut StepCtx<P>,
2731 #[union(String, Pipe)]
2733 text: Value,
2734 pattern: String,
2736 replacement: String,
2738) -> Result<Value> {
2739 if let Some(s) = text.as_str() {
2740 let out =
2741 super::args::text_replace_regex_str(s, &pattern, &replacement, "TEXT_REPLACE_REGEX")?;
2742 return Ok(Value::string(out));
2743 }
2744 let content = super::args::read_pipe_eager(cx, "TEXT_REPLACE_REGEX", &text)?;
2745 let out = super::args::text_replace_regex_str(
2746 &content,
2747 &pattern,
2748 &replacement,
2749 "TEXT_REPLACE_REGEX",
2750 )?;
2751 super::args::write_completed_pipe(cx, "TEXT_REPLACE_REGEX", out)
2752}
2753
2754fn text_replace_regex_string(text: Value, pattern: String, replacement: String) -> Result<Value> {
2757 let Some(s) = text.as_str() else {
2758 return Err(super::args::pipe_needs_step_io("TEXT_REPLACE_REGEX"));
2759 };
2760 let out = super::args::text_replace_regex_str(s, &pattern, &replacement, "TEXT_REPLACE_REGEX")?;
2761 Ok(Value::string(out))
2762}
2763
2764#[oxdock_func(pure, returns = TypeTag::ListOf(std::sync::Arc::new(TypeTag::String)))]
2772#[example(
2773 name = "split",
2774 code = r###"
2775 # Delimiters split into list items.
2776 IMPORT [STD]
2777 LET $parts: LIST<STRING> = TEXT_SPLIT("a,b,c", ",")
2778 ASSERT_EQ $parts.0 "a"
2779 ASSERT_EQ $parts.1 "b"
2780 ASSERT_EQ $parts.2 "c"
2781 "###
2782)]
2783fn text_split(
2784 text: String,
2786 delimiter: String,
2788) -> Result<Value> {
2789 Ok(super::args::text_list_value(super::args::text_split_str(
2790 &text, &delimiter,
2791 )))
2792}
2793
2794#[oxdock_func(pure, returns = TypeTag::String)]
2797#[example(
2798 name = "join",
2799 code = r###"
2800 # List items join with the separator between them.
2801 IMPORT [STD]
2802 LET $joined: STRING = TEXT_JOIN(["a", "b", "c"], ",")
2803 ASSERT_EQ $joined "a,b,c"
2804 "###
2805)]
2806fn text_join(
2807 elements: Vec<String>,
2809 delimiter: String,
2811) -> Result<Value> {
2812 Ok(Value::string(elements.join(delimiter.as_str())))
2813}
2814
2815#[oxdock_func(pure, returns = TypeTag::ListOf(std::sync::Arc::new(TypeTag::String)))]
2827#[example(
2828 name = "split args",
2829 code = r###"
2830 # Quoted segments stay one word.
2831 IMPORT [STD]
2832 LET $argv: LIST<STRING> = SHELL_SPLIT_ARGS("gh issue comment 153 --body-file notes.md")
2833 ASSERT_EQ $argv.0 "gh"
2834 ASSERT_EQ $argv.3 "153"
2835 ASSERT_EQ $argv.5 "notes.md"
2836
2837 # Quotes and escapes parse the shell way.
2838 LET $quoted: LIST<STRING> = SHELL_SPLIT_ARGS("say \"hi there\" 'a b'")
2839 ASSERT_EQ $quoted.0 "say"
2840 ASSERT_EQ $quoted.1 "hi there"
2841 ASSERT_EQ $quoted.2 "a b"
2842 "###
2843)]
2844fn shell_split_args(
2845 command: String,
2847) -> Result<Value> {
2848 match shell_words::split(&command) {
2849 Ok(words) => Ok(super::args::text_list_value(words)),
2850 Err(err) => anyhow::bail!("SHELL_SPLIT_ARGS: {err}"),
2851 }
2852}
2853
2854#[oxdock_func(pure, returns = TypeTag::String)]
2862#[example(
2863 name = "join args",
2864 code = r###"
2865 # Plain words join with spaces and no quoting.
2866 IMPORT [STD]
2867 LET $plain: STRING = SHELL_JOIN_ARGS(["gh", "issue", "list"])
2868 ASSERT_EQ $plain "gh issue list"
2869
2870 # Words with spaces quote, and the round trip is exact.
2871 LET $words: LIST<STRING> = ["say", "hi there", "a'b"]
2872 LET $joined: STRING = SHELL_JOIN_ARGS($words)
2873 LET $back: LIST<STRING> = SHELL_SPLIT_ARGS($joined)
2874 ASSERT_EQ $back.0 "say"
2875 ASSERT_EQ $back.1 "hi there"
2876 ASSERT_EQ $back.2 "a'b"
2877 "###
2878)]
2879fn shell_join_args(
2880 words: Vec<String>,
2882) -> Result<Value> {
2883 Ok(Value::string(shell_words::join(&words)))
2884}
2885
2886#[oxdock_func(pure, returns = TypeTag::ListOf(std::sync::Arc::new(TypeTag::String)))]
2894#[example(
2895 name = "lines",
2896 code = r###"
2897 # Newlines split into line items.
2898 IMPORT [STD]
2899 LET $lines: LIST<STRING> = TEXT_LINES("one\ntwo\nthree")
2900 ASSERT_EQ $lines.0 "one"
2901 ASSERT_EQ $lines.1 "two"
2902 ASSERT_EQ $lines.2 "three"
2903
2904 # Windows endings split the same way after normalization.
2905 LET $crlf: LIST<STRING> = TEXT_LINES("one\r\ntwo\r\nthree")
2906 ASSERT_EQ $crlf.0 "one"
2907 ASSERT_EQ $crlf.1 "two"
2908 ASSERT_EQ $crlf.2 "three"
2909
2910 # Old Mac endings split too, and mixed endings split together because the input normalizes to LF before splitting.
2911 LET $mixed: LIST<STRING> = TEXT_LINES("a\r\nb\nc\rd")
2912 ASSERT_EQ $mixed.0 "a"
2913 ASSERT_EQ $mixed.1 "b"
2914 ASSERT_EQ $mixed.2 "c"
2915 ASSERT_EQ $mixed.3 "d"
2916 "###
2917)]
2918fn text_lines(
2919 text: String,
2921) -> Result<Value> {
2922 Ok(super::args::text_list_value(super::args::text_lines_str(
2923 &text,
2924 )))
2925}
2926
2927#[oxdock_func(pure, returns = TypeTag::ListOf(std::sync::Arc::new(TypeTag::String)))]
2933#[example(
2934 name = "fields",
2935 code = r###"
2936 # Runs of whitespace separate fields; empties never appear.
2937 IMPORT [STD]
2938 LET $fields: LIST<STRING> = TEXT_FIELDS(" abc def ")
2939 ASSERT_EQ $fields.0 "abc"
2940 ASSERT_EQ $fields.1 "def"
2941 "###
2942)]
2943fn text_fields(
2944 text: String,
2946) -> Result<Value> {
2947 Ok(super::args::text_list_value(super::args::text_fields_str(
2948 &text,
2949 )))
2950}
2951
2952#[oxdock_func(pure, returns = TypeTag::ListOf(std::sync::Arc::new(TypeTag::String)))]
2961#[example(
2962 name = "line range",
2963 code = r###"
2964 # Lines 2 through 3 come back as a list, 1-based inclusive.
2965 IMPORT [STD]
2966 LET $window: LIST<STRING> = TEXT_LINES_RANGE("one\ntwo\nthree\nfour", 2, 3)
2967 ASSERT_EQ $window.0 "two"
2968 ASSERT_EQ $window.1 "three"
2969
2970 # Ranges past the end clamp instead of failing.
2971 LET $tail: LIST<STRING> = TEXT_LINES_RANGE("one\ntwo", 2, 9)
2972 ASSERT_EQ $tail.0 "two"
2973 "###
2974)]
2975fn text_lines_range(
2976 text: String,
2978 from: i64,
2980 to: i64,
2982) -> Result<Value> {
2983 Ok(super::args::text_list_value(
2984 super::args::text_lines_range_str(&text, from, to, "TEXT_LINES_RANGE")?,
2985 ))
2986}
2987
2988#[oxdock_func(pure, returns = TypeTag::Bool)]
2996#[example(
2997 name = "match",
2998 code = r###"
2999 # Regex matches report true; misses report false.
3000 IMPORT [STD]
3001 LET $hit: BOOL = TEXT_MATCH("abc123", "\\d+")
3002 ASSERT_EQ $hit true
3003
3004 # A miss is false, not a failure.
3005 LET $miss: BOOL = TEXT_MATCH("abc", "^\\d+$")
3006 ASSERT_EQ $miss false
3007 "###
3008)]
3009fn text_match(
3010 text: String,
3012 pattern: String,
3014) -> Result<Value> {
3015 let re = super::args::text_compile_pattern("TEXT_MATCH", &pattern)?;
3016 Ok(Value::bool(re.is_match(&text)))
3017}
3018
3019#[oxdock_func(pure, name = "BOOL", returns = TypeTag::Bool)]
3028#[example(
3029 name = "convert",
3030 code = r###"
3031 IMPORT [STD]
3032 LET $n: BOOL = BOOL("yes")
3033 ASSERT_EQ $n true
3034 LET $f: BOOL = BOOL("0")
3035 ASSERT_EQ $f false
3036 "###
3037)]
3038fn bool_convert(
3039 #[union(Bool, String)]
3041 val: Value,
3042) -> Result<Value> {
3043 if let Some(b) = val.as_bool() {
3044 return Ok(Value::bool(b));
3045 }
3046 let Some(s) = val.as_str() else {
3047 return Err(anyhow::anyhow!(
3048 "BOOL needs a Bool or String, found {val:?}"
3049 ));
3050 };
3051 match super::args::parse_bool_str(s) {
3052 Some(b) => Ok(Value::bool(b)),
3053 None => anyhow::bail!("BOOL cannot coerce {s:?} to BOOL"),
3054 }
3055}
3056
3057#[oxdock_func(pure, returns = TypeTag::Bool)]
3067#[example(
3068 name = "absent-default",
3069 code = r###"
3070 # Absent names read empty; the default settles the polarity.
3071 IMPORT [STD]
3072 INHERIT_ENV [OXDOCK_TEST_ABSENT_FLAG]
3073 LET $dry: BOOL = BOOL_OR("{{ env:OXDOCK_TEST_ABSENT_FLAG }}", true)
3074 ASSERT_EQ $dry true
3075
3076 # Present values coerce strictly, ignoring the default.
3077 LET $off: BOOL = BOOL_OR("false", true)
3078 ASSERT_EQ $off false
3079 "###
3080)]
3081fn bool_or(
3082 text: String,
3084 default: bool,
3086) -> Result<Value> {
3087 if text.trim().is_empty() {
3088 return Ok(Value::bool(default));
3089 }
3090 match super::args::parse_bool_str(&text) {
3091 Some(b) => Ok(Value::bool(b)),
3092 None => anyhow::bail!("BOOL_OR cannot coerce {text:?} to BOOL"),
3093 }
3094}
3095
3096#[oxdock_func(pure, returns = TypeTag::ListOf(std::sync::Arc::new(TypeTag::String)))]
3105#[example(
3106 name = "extract",
3107 code = r###"
3108 # Index zero is the full match; groups follow in order.
3109 IMPORT [STD]
3110 LET $caps: LIST<STRING> = TEXT_EXTRACT("abc123", "([a-z]+)(\\d+)")
3111 ASSERT_EQ $caps.0 "abc123"
3112 ASSERT_EQ $caps.1 "abc"
3113 ASSERT_EQ $caps.2 "123"
3114 "###
3115)]
3116fn text_extract(
3117 text: String,
3119 pattern: String,
3121) -> Result<Value> {
3122 let groups = super::args::text_extract_str(&text, &pattern, "TEXT_EXTRACT")?;
3123 Ok(super::args::text_list_value(groups))
3124}
3125
3126#[oxdock_func(pure, returns = TypeTag::Bool)]
3133#[example(
3134 name = "starts with",
3135 code = r###"
3136 # Present prefixes report true; misses report false.
3137 IMPORT [STD]
3138 LET $hit: BOOL = TEXT_STARTS_WITH("linux-musl-x64", "linux")
3139 ASSERT_EQ $hit true
3140
3141 # A miss is false, not a failure.
3142 LET $miss: BOOL = TEXT_STARTS_WITH("macos-arm", "linux")
3143 ASSERT_EQ $miss false
3144 "###
3145)]
3146fn text_starts_with(
3147 text: String,
3149 prefix: String,
3151) -> Result<Value> {
3152 Ok(Value::bool(text.starts_with(prefix.as_str())))
3153}
3154
3155#[oxdock_func(pure, returns = TypeTag::Bool)]
3162#[example(
3163 name = "ends with",
3164 code = r###"
3165 # Present suffixes report true; misses report false.
3166 IMPORT [STD]
3167 LET $hit: BOOL = TEXT_ENDS_WITH("x86_64-linux-musl", "linux-musl")
3168 ASSERT_EQ $hit true
3169
3170 # A miss is false, not a failure.
3171 LET $miss: BOOL = TEXT_ENDS_WITH("x86_64-linux-gnu", "linux-musl")
3172 ASSERT_EQ $miss false
3173 "###
3174)]
3175fn text_ends_with(
3176 text: String,
3178 suffix: String,
3180) -> Result<Value> {
3181 Ok(Value::bool(text.ends_with(suffix.as_str())))
3182}
3183
3184#[oxdock_func(pure, returns = TypeTag::Bool)]
3191#[example(
3192 name = "contains",
3193 code = r###"
3194 # Present needles report true; misses report false.
3195 IMPORT [STD]
3196 LET $hit: BOOL = TEXT_CONTAINS("x86_64-linux-musl", "musl")
3197 ASSERT_EQ $hit true
3198
3199 # A miss is false, not a failure.
3200 LET $miss: BOOL = TEXT_CONTAINS("x86_64-linux-gnu", "musl")
3201 ASSERT_EQ $miss false
3202 "###
3203)]
3204fn text_contains(
3205 text: String,
3207 needle: String,
3209) -> Result<Value> {
3210 Ok(Value::bool(text.contains(needle.as_str())))
3211}
3212
3213#[oxdock_func(pure, returns = TypeTag::Int)]
3220#[example(
3221 name = "length",
3222 code = r###"
3223 # Plain text counts one per character.
3224 IMPORT [STD]
3225 LET $n: INT = TEXT_LENGTH("hello")
3226 ASSERT_EQ $n 5
3227
3228 # Multibyte characters count once each, not per byte.
3229 LET $wide: INT = TEXT_LENGTH("héllo")
3230 ASSERT_EQ $wide 5
3231 "###
3232)]
3233fn text_length(
3234 text: String,
3236) -> Result<Value> {
3237 Ok(Value::int(text.chars().count() as i64))
3238}
3239
3240#[oxdock_func(pure, returns = TypeTag::Int)]
3248#[example(
3249 name = "count",
3250 code = r###"
3251 # Every non-overlapping occurrence counts once.
3252 IMPORT [STD]
3253 LET $n: INT = TEXT_COUNT("hello world", "o")
3254 ASSERT_EQ $n 2
3255
3256 # Overlapping candidates never double count.
3257 LET $once: INT = TEXT_COUNT("aaa", "aa")
3258 ASSERT_EQ $once 1
3259 "###
3260)]
3261fn text_count(
3262 text: String,
3264 needle: String,
3266) -> Result<Value> {
3267 let n = super::args::text_count_str(&text, &needle, "TEXT_COUNT")?;
3268 Ok(Value::int(n))
3269}
3270
3271#[oxdock_func(pure, returns = TypeTag::Int)]
3281#[example(
3282 name = "count matches",
3283 code = r###"
3284 # One line matches once no matter how many times it hits.
3285 IMPORT [STD]
3286 LET $n: INT = TEXT_COUNT_MATCHES("test a: test\ntest b: nope\ntest c: test", ": test")
3287 ASSERT_EQ $n 2
3288
3289 # A miss binds zero, never an error.
3290 LET $none: INT = TEXT_COUNT_MATCHES("test b: nope", ": test$")
3291 ASSERT_EQ $none 0
3292 "###
3293)]
3294fn text_count_matches(
3295 text: String,
3297 pattern: String,
3299) -> Result<Value> {
3300 let n = super::args::text_count_matches_str(&text, &pattern, "TEXT_COUNT_MATCHES")?;
3301 Ok(Value::int(n))
3302}
3303
3304#[oxdock_func(pure, returns = TypeTag::ListOf(std::sync::Arc::new(TypeTag::String)))]
3317#[example(
3318 name = "grep",
3319 code = r###"
3320 # Matching lines come back as a list, in order.
3321 IMPORT [STD]
3322 LET $hits: LIST<STRING> = TEXT_GREP("one\ntwo\none more", "^one")
3323 ASSERT_EQ $hits.0 "one"
3324 ASSERT_EQ $hits.1 "one more"
3325
3326 # A miss binds an empty list, never an error.
3327 LET $miss: LIST<STRING> = TEXT_GREP("one\ntwo", "^z")
3328 LET $joined: STRING = TEXT_JOIN($miss, ",")
3329 ASSERT_EQ $joined ""
3330
3331 # The (?i) flag ignores case, so uppercase lines match too.
3332 LET $folded: LIST<STRING> = TEXT_GREP("One\ntwo\nONE more", "(?i)^one")
3333 ASSERT_EQ $folded.0 "One"
3334 ASSERT_EQ $folded.1 "ONE more"
3335 "###
3336)]
3337#[example(
3338 name = "grep invert",
3339 code = r###"
3340 # The invert option keeps every non-matching line instead.
3341 IMPORT [STD]
3342 LET $kept: LIST<STRING> = TEXT_GREP("one\ntwo\none more", "^one", {invert: true})
3343 ASSERT_EQ $kept.0 "two"
3344
3345 # A pattern matching every line binds an empty list, never an error.
3346 LET $none: LIST<STRING> = TEXT_GREP("one\ntwo", "^", {invert: true})
3347 LET $joined: STRING = TEXT_JOIN($none, ",")
3348 ASSERT_EQ $joined ""
3349
3350 # Options ride into placeholders as MAP literals. Placeholder
3351 # strings unescape only backslash and quote, so multiline text
3352 # arrives through a variable.
3353 LET $two_lines: STRING = "one\ntwo"
3354 LET $msg: STRING = 'kept:{{ STD::TEXT_GREP($two_lines, "^one", {invert: true}) }}'
3355 ASSERT_EQ $msg "kept:two"
3356 "###
3357)]
3358fn text_grep(
3359 text: String,
3361 pattern: String,
3363 #[options("invert?: BOOL")]
3365 #[optional]
3366 options: BTreeMap<String, Value>,
3367) -> Result<Value> {
3368 let invert = super::args::text_invert_flag(&options);
3371 Ok(super::args::text_list_value(super::args::text_grep_str(
3372 &text,
3373 &pattern,
3374 invert,
3375 "TEXT_GREP",
3376 )?))
3377}
3378
3379#[oxdock_func(returns = TypeTag::Bool)]
3390#[example(
3391 name = "drain to end",
3392 code = r###"
3393 # Capture two lines, then drain to end of stream with no sentinel line.
3394 IMPORT [STD]
3395 LET $cap: PIPE
3396 WITH_IO [stdout=$cap] {
3397 ECHO "one"
3398 ECHO "two"
3399 }
3400
3401 # The loop exits on close, and the count proves both lines drained.
3402 LET $n: INT = 0
3403 WHILE !EOF($cap) {
3404 WITH_IO [stdin=$cap] READ_LINE $line
3405 $n = $n + 1
3406 }
3407 ASSERT_EQ $n 2
3408 "###
3409)]
3410fn eof<P: ProcessManager>(
3411 cx: &mut StepCtx<P>,
3412 pipe: PipeHandle,
3414) -> Result<Value> {
3415 let info = cx.state.io.inspect_pipe(&pipe);
3416 Ok(Value::bool(info.closed && info.buffered == 0))
3417}
3418
3419fn task_poll_result_fields() -> Arc<[Field]> {
3423 Arc::from(vec![
3424 Field {
3425 name: "state".to_string(),
3426 ty: TypeTag::String,
3427 docs: "Task phase: `running` or `finished`.",
3428 optional: false,
3429 },
3430 Field {
3431 name: "ok".to_string(),
3432 ty: TypeTag::Bool,
3433 docs: "True unless the task failed.",
3434 optional: false,
3435 },
3436 Field {
3437 name: "stdout_tail".to_string(),
3438 ty: TypeTag::String,
3439 docs: "Bounded stdout tail, live while running.",
3440 optional: false,
3441 },
3442 Field {
3443 name: "stderr_tail".to_string(),
3444 ty: TypeTag::String,
3445 docs: "Bounded stderr tail, live while running.",
3446 optional: false,
3447 },
3448 Field {
3449 name: "truncated_bytes".to_string(),
3450 ty: TypeTag::Int,
3451 docs: "Dropped head bytes past the per-stream cap.",
3452 optional: false,
3453 },
3454 Field {
3455 name: "exit_code".to_string(),
3456 ty: TypeTag::Int,
3457 docs: "Process exit code, present once finished.",
3458 optional: true,
3459 },
3460 Field {
3461 name: "result".to_string(),
3462 ty: TypeTag::Any,
3463 docs: "Task `RETURN` value, present on clean finish.",
3464 optional: true,
3465 },
3466 Field {
3467 name: "error".to_string(),
3468 ty: TypeTag::String,
3469 docs: "Failure text, present on failed finish.",
3470 optional: true,
3471 },
3472 ])
3473}
3474
3475#[oxdock_func(returns = TypeTag::Record(task_poll_result_fields()))]
3488#[example(
3489 name = "running poll",
3490 code = r###"
3491 # A sleeping task is still running on the first poll.
3492 IMPORT [STD]
3493 LET $t: HANDLE<STRING> = ASYNC { SLEEP 30s; RETURN "done" }
3494 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)
3495 ASSERT_EQ $m.state "running"
3496 ASSERT_EQ $m.ok true
3497 # Clean up the sleeper so the run ends promptly.
3498 CANCEL $t
3499 "###
3500)]
3501#[example(
3502 name = "finished poll",
3503 code = r###"
3504 # A finished task reports its value and final tails, then still awaits.
3505 IMPORT [STD]
3506 LET $t: HANDLE<STRING> = ASYNC { ECHO "hi"; SLEEP 1s; RETURN "done" }
3507 # Do other work while the task runs; poll once it should be done.
3508 SLEEP 2s
3509 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)
3510 ASSERT_EQ $m.state "finished"
3511 ASSERT_EQ $m.result "done"
3512 LET $o: STRING = AWAIT $t
3513 ASSERT_EQ $o "done"
3514 "###
3515)]
3516fn task_poll<P: ProcessManager>(
3517 cx: &mut StepCtx<P>,
3518 task: HandleValue,
3520) -> Result<Value> {
3521 let entry =
3522 super::handlers::resolve_task_entry_by_id(task.0, &format!("TASK_POLL({})", task.0), cx)?;
3523 let obs = entry.observe_completion();
3524 let (stdout_tail, stderr_tail, dropped) = entry.snapshot_tails();
3525 let mut out = BTreeMap::new();
3526 out.insert(
3527 "state".to_string(),
3528 Value::string(if obs.running { "running" } else { "finished" }.to_string()),
3529 );
3530 out.insert("ok".to_string(), Value::bool(obs.ok));
3531 if !obs.running {
3532 out.insert("exit_code".to_string(), Value::int(obs.exit_code));
3533 }
3534 if let Some(result) = obs.result {
3535 out.insert("result".to_string(), result);
3536 }
3537 if !obs.error.is_empty() {
3538 out.insert("error".to_string(), Value::string(obs.error));
3539 }
3540 out.insert("stdout_tail".to_string(), Value::string(stdout_tail));
3541 out.insert("stderr_tail".to_string(), Value::string(stderr_tail));
3542 out.insert(
3543 "truncated_bytes".to_string(),
3544 Value::int(dropped.min(i64::MAX as u64) as i64),
3545 );
3546 Ok(Value::map(out))
3547}
3548
3549fn meta_to_value(meta: &FuncMeta) -> Value {
3550 let mut map = BTreeMap::new();
3551 map.insert("name".to_string(), Value::string(meta.name.clone()));
3552 map.insert("module".to_string(), Value::string(meta.module.clone()));
3553 map.insert(
3554 "kind".to_string(),
3555 Value::string(meta.kind.label().to_string()),
3556 );
3557 let params = match &meta.params {
3558 Some(params) => Value::list(
3559 params
3560 .iter()
3561 .map(|p| {
3562 let mut entry = BTreeMap::new();
3563 entry.insert("name".to_string(), Value::string(p.name.clone()));
3564 entry.insert(
3565 "param_type".to_string(),
3566 Value::string(
3567 p.param_type
3568 .as_ref()
3569 .map(render_structural)
3570 .unwrap_or_default(),
3571 ),
3572 );
3573 entry.insert(
3574 "allowed".to_string(),
3575 Value::string(
3576 p.allowed
3577 .map(|values| values.join(", "))
3578 .unwrap_or_default(),
3579 ),
3580 );
3581 entry.insert("docs".to_string(), Value::string(String::new()));
3582 entry.insert("optional".to_string(), Value::bool(p.optional));
3583 entry.insert(
3584 "options".to_string(),
3585 match p.options {
3586 Some(keys) => Value::list(
3587 keys.iter()
3588 .map(|key| {
3589 let mut option = BTreeMap::new();
3590 option.insert(
3591 "name".to_string(),
3592 Value::string(key.name.to_string()),
3593 );
3594 option.insert(
3595 "value_type".to_string(),
3596 Value::string(render_structural(&key.value)),
3597 );
3598 option.insert(
3599 "required".to_string(),
3600 Value::bool(key.required),
3601 );
3602 option.insert(
3603 "default".to_string(),
3604 Value::string(
3605 key.default.unwrap_or_default().to_string(),
3606 ),
3607 );
3608 Value::map(option)
3609 })
3610 .collect(),
3611 ),
3612 None => Value::string(String::new()),
3613 },
3614 );
3615 Value::map(entry)
3616 })
3617 .collect(),
3618 ),
3619 None => Value::list(Vec::new()),
3623 };
3624 map.insert("params".to_string(), params);
3625 map.insert(
3626 "returns".to_string(),
3627 Value::string(
3628 meta.returns
3629 .as_ref()
3630 .map(render_structural)
3631 .unwrap_or_default(),
3632 ),
3633 );
3634 map.insert("rpn".to_string(), Value::bool(meta.rpn));
3635 map.insert(
3636 "summary".to_string(),
3637 Value::string(meta.summary.to_string()),
3638 );
3639 Value::map(map)
3640}
3641
3642#[derive(Debug, Clone)]
3646pub struct RecordSchema {
3647 pub name: &'static str,
3648 pub fields: std::sync::Arc<[Field]>,
3649}
3650
3651#[derive(Clone)]
3655pub struct HostModule<P: ProcessManager> {
3656 pub name: String,
3657 pub funcs: Vec<HostRegistration<P>>,
3658 pub types: Vec<&'static TypeDescriptor>,
3659 pub record_schemas: Vec<RecordSchema>,
3660 pub states: Vec<ModuleState>,
3667}
3668
3669#[derive(Clone)]
3673pub struct ModuleState {
3674 id: std::any::TypeId,
3675 state: std::sync::Arc<dyn std::any::Any + Send + Sync>,
3676}
3677
3678pub type PreRunInspector = dyn Fn(&[Step]) -> Result<()> + Send + Sync;
3682
3683#[derive(Clone)]
3689pub struct PreRunCheck {
3690 check: Arc<PreRunInspector>,
3691}
3692
3693impl PreRunCheck {
3694 pub fn new(check: impl Fn(&[Step]) -> Result<()> + Send + Sync + 'static) -> Self {
3696 Self {
3697 check: Arc::new(check),
3698 }
3699 }
3700
3701 pub fn run(&self, steps: &[Step]) -> Result<()> {
3703 (self.check)(steps)
3704 }
3705}
3706
3707impl<P: ProcessManager> HostModule<P> {
3708 pub fn with_state<T: Send + Sync + 'static>(mut self, state: std::sync::Arc<T>) -> Self {
3711 self.states.push(ModuleState {
3712 id: std::any::TypeId::of::<T>(),
3713 state,
3714 });
3715 self
3716 }
3717
3718 pub fn check_pre_run(&self, steps: &[Step]) -> Result<()> {
3722 for state in &self.states {
3723 if let Some(check) = state.state.downcast_ref::<PreRunCheck>() {
3724 check.run(steps)?;
3725 }
3726 }
3727 Ok(())
3728 }
3729}
3730
3731impl<P: ProcessManager> ExecState<P> {
3732 pub fn register_module(&mut self, module: HostModule<P>) {
3735 for registration in module.funcs {
3736 match registration {
3737 HostRegistration::Stateful { name, meta, func } => {
3738 self.functions.register_host(&module.name, name, meta, func);
3739 }
3740 HostRegistration::Pure { name, meta, func } => {
3741 self.functions
3742 .register_pure_host(&module.name, name, meta, func);
3743 }
3744 HostRegistration::Both {
3745 name,
3746 meta,
3747 func,
3748 template,
3749 } => {
3750 self.functions
3751 .register_both_host(&module.name, name, meta, func, template);
3752 }
3753 }
3754 }
3755 for descriptor in module.types {
3756 self.register_type(descriptor);
3757 }
3758 for schema in module.record_schemas {
3759 self.register_record_schema(schema.name, schema.fields);
3760 }
3761 for state in module.states {
3762 self.module_states
3763 .insert((module.name.clone(), state.id), state.state);
3764 }
3765 }
3766
3767 pub fn list_functions(&self) -> Vec<FuncMeta> {
3769 let mut out: Vec<FuncMeta> = self.functions.entries_metas().into_iter().collect();
3770 if !out.iter().any(|m| m.name == KEYWORD_INSPECT) {
3772 out.push(FuncMeta {
3773 name: KEYWORD_INSPECT.to_string(),
3774 module: STD_MODULE_NAME.to_string(),
3775 kind: FuncKind::HostCtx,
3776 params: None,
3777 returns: Some(TypeTag::Map),
3778 rpn: false,
3779 summary: "Inspect a variable binding.",
3780 docs: "INSPECT($var): dedicated AST node taking a variable, not a value.",
3781 examples: &[],
3782 });
3783 }
3784 out.sort_by(|a, b| a.name.cmp(&b.name));
3785 out
3786 }
3787
3788 pub fn describe_function(&self, name: &str) -> Option<Value> {
3790 if let Some(meta) = self.functions.meta(name) {
3791 return Some(meta_to_value(&meta));
3792 }
3793 if name == KEYWORD_INSPECT {
3795 return Some(meta_to_value(&FuncMeta {
3796 name: KEYWORD_INSPECT.to_string(),
3797 module: STD_MODULE_NAME.to_string(),
3798 kind: FuncKind::HostCtx,
3799 params: None,
3800 returns: Some(TypeTag::Map),
3801 rpn: false,
3802 summary: "Inspect a variable binding.",
3803 docs: "INSPECT($var): dedicated AST node taking a variable, not a value.",
3804 examples: &[],
3805 }));
3806 }
3807 None
3808 }
3809
3810 pub(super) fn clone_native_pure(&self, name: &str) -> Option<PureFn> {
3811 self.functions.clone_pure_fn(name)
3812 }
3813
3814 pub fn pure_function_table(&self) -> Arc<PureTable> {
3819 self.functions.pure_shared()
3820 }
3821
3822 pub(super) fn clone_native_ctx(&self, name: &str) -> Option<NativeFn<P>> {
3823 self.functions.clone_ctx_fn(name)
3824 }
3825
3826 pub(super) fn native_meta(&self, name: &str) -> Option<FuncMeta> {
3827 self.functions.meta(name)
3828 }
3829}
3830
3831#[cfg(test)]
3832mod tests {
3833 use super::*;
3834
3835 #[test]
3836 fn placeholder_resolver_dispatches_table_entries() {
3837 let echo: PureFn = Arc::new(|args| {
3841 args.into_iter()
3842 .next()
3843 .ok_or_else(|| anyhow::anyhow!("ECHO needs 1 arg"))
3844 });
3845 let mut entries = HashMap::new();
3846 entries.insert("ECHO".to_string(), echo);
3847 let mut table = PureTable::new();
3848 table.insert("T".to_string(), entries);
3849 let resolve = placeholder_resolver(Arc::new(table));
3850 let out = resolve("T", "ECHO", vec![Value::string("hi".to_string())]).expect("dispatch");
3851 assert_eq!(out.as_str().expect("string"), "hi");
3852 let err = format!(
3853 "{:#}",
3854 resolve("T", "NOPE", vec![]).expect_err("unknown must fail")
3855 );
3856 assert!(
3857 err.contains("unknown placeholder function 'T::NOPE'"),
3858 "names the call: {err}"
3859 );
3860 assert!(
3861 err.contains("known functions: T::ECHO"),
3862 "lists known names: {err}"
3863 );
3864 }
3865
3866 #[test]
3867 fn describe_entry_renders_union_spellings() {
3868 let union = oxdock_parser::union_tag!(String, Pipe);
3874 let meta = FuncMeta {
3875 name: "T::F".to_string(),
3876 module: "T".to_string(),
3877 kind: FuncKind::HostPure,
3878 params: Some(vec![FuncParam {
3879 name: "text".to_string(),
3880 param_type: Some(union.clone()),
3881 allowed: None,
3882 docs: "",
3883 options: None,
3884 optional: false,
3885 }]),
3886 returns: Some(union),
3887 rpn: false,
3888 summary: "test-only",
3889 docs: "test-only",
3890 examples: &[],
3891 };
3892 let value = meta_to_value(&meta);
3893 let map = value.as_map().expect("describe value is a map");
3894 let params = map
3895 .get("params")
3896 .expect("params key")
3897 .as_list()
3898 .expect("params is a list");
3899 let first = params[0].as_map().expect("entry is a map");
3900 assert_eq!(
3901 first.get("param_type").and_then(Value::as_str),
3902 Some("STRING|PIPE"),
3903 "param renders the set"
3904 );
3905 assert_eq!(
3906 map.get("returns").and_then(Value::as_str),
3907 Some("STRING|PIPE"),
3908 "returns render the set"
3909 );
3910 }
3911
3912 #[test]
3913 fn describe_entry_renders_handle_payload() {
3914 let meta = FuncMeta {
3918 name: "SCRIPT::FETCH".to_string(),
3919 module: "SCRIPT".to_string(),
3920 kind: FuncKind::Script,
3921 params: Some(vec![]),
3922 returns: Some(TypeTag::HandleOf(std::sync::Arc::new(TypeTag::String))),
3923 rpn: false,
3924 summary: "test-only",
3925 docs: "test-only",
3926 examples: &[],
3927 };
3928 let value = meta_to_value(&meta);
3929 let map = value.as_map().expect("describe value is a map");
3930 assert_eq!(
3931 map.get("returns").and_then(Value::as_str),
3932 Some("HANDLE<STRING>"),
3933 "returns render the payload"
3934 );
3935 }
3936
3937 #[test]
3938 fn describe_entry_carries_optional_flag() {
3939 let meta = FuncMeta {
3943 name: "T::F".to_string(),
3944 module: "T".to_string(),
3945 kind: FuncKind::HostPure,
3946 params: Some(vec![
3947 FuncParam {
3948 name: "url".to_string(),
3949 param_type: Some(TypeTag::String),
3950 allowed: None,
3951 docs: "",
3952 options: None,
3953 optional: false,
3954 },
3955 FuncParam {
3956 name: "options".to_string(),
3957 param_type: Some(TypeTag::Map),
3958 allowed: None,
3959 docs: "",
3960 options: None,
3961 optional: true,
3962 },
3963 ]),
3964 returns: Some(TypeTag::String),
3965 rpn: false,
3966 summary: "test-only",
3967 docs: "test-only",
3968 examples: &[],
3969 };
3970 let value = meta_to_value(&meta);
3971 let map = value.as_map().expect("describe value is a map");
3972 let params = map
3973 .get("params")
3974 .expect("params key")
3975 .as_list()
3976 .expect("params is a list");
3977 assert_eq!(params.len(), 2);
3978 let first = params[0].as_map().expect("entry is a map");
3979 let second = params[1].as_map().expect("entry is a map");
3980 assert_eq!(
3981 first.get("optional").and_then(Value::as_bool),
3982 Some(false),
3983 "required param must read false"
3984 );
3985 assert_eq!(
3986 second.get("optional").and_then(Value::as_bool),
3987 Some(true),
3988 "omittable param must read true"
3989 );
3990 }
3991
3992 #[test]
3993 fn template_twins_mirror_string_paths_and_refuse_pipes() {
3994 let pipe = Value::pipe_fresh();
4000 type TwinCase = (&'static str, Box<dyn Fn() -> Result<Value>>);
4001 let cases: Vec<TwinCase> = vec![
4002 (
4003 "TEXT_TRIM",
4004 Box::new(|| text_trim_string(Value::string(" hello ".to_string()))),
4005 ),
4006 (
4007 "TEXT_TRIM_PREFIX",
4008 Box::new(|| {
4009 text_trim_prefix_string(Value::string("v1".to_string()), "v".to_string())
4010 }),
4011 ),
4012 (
4013 "TEXT_TRIM_SUFFIX",
4014 Box::new(|| {
4015 text_trim_suffix_string(Value::string("a.gz".to_string()), "x".to_string())
4016 }),
4017 ),
4018 (
4019 "TEXT_TO_UPPER",
4020 Box::new(|| text_to_upper_string(Value::string("hi".to_string()))),
4021 ),
4022 (
4023 "TEXT_TO_LOWER",
4024 Box::new(|| text_to_lower_string(Value::string("HI".to_string()))),
4025 ),
4026 (
4027 "TEXT_REPLACE",
4028 Box::new(|| {
4029 text_replace_string(
4030 Value::string("ab".to_string()),
4031 "b".to_string(),
4032 "c".to_string(),
4033 )
4034 }),
4035 ),
4036 (
4037 "TEXT_REPLACE_REGEX",
4038 Box::new(|| {
4039 text_replace_regex_string(
4040 Value::string("ab".to_string()),
4041 "b".to_string(),
4042 "c".to_string(),
4043 )
4044 }),
4045 ),
4046 ];
4047 assert_eq!(cases.len(), 7, "every mirror op needs a twin row");
4048 for (name, run) in &cases {
4049 let value = run().unwrap_or_else(|e| panic!("{name} twin must answer strings: {e:#}"));
4050 assert!(
4051 value.as_str().is_some(),
4052 "{name} twin must answer STRING, got {}",
4053 value.type_name()
4054 );
4055 }
4056 assert_eq!(
4057 text_trim_string(Value::string(" hello ".to_string()))
4058 .expect("trim twin")
4059 .as_str(),
4060 Some("hello")
4061 );
4062 let pipe_cases: Vec<(&str, Result<Value>)> = vec![
4064 ("TEXT_TRIM", text_trim_string(pipe.clone())),
4065 (
4066 "TEXT_TRIM_PREFIX",
4067 text_trim_prefix_string(pipe.clone(), "v".to_string()),
4068 ),
4069 (
4070 "TEXT_TRIM_SUFFIX",
4071 text_trim_suffix_string(pipe.clone(), ".gz".to_string()),
4072 ),
4073 ("TEXT_TO_UPPER", text_to_upper_string(pipe.clone())),
4074 ("TEXT_TO_LOWER", text_to_lower_string(pipe.clone())),
4075 (
4076 "TEXT_REPLACE",
4077 text_replace_string(pipe.clone(), "a".to_string(), "b".to_string()),
4078 ),
4079 (
4080 "TEXT_REPLACE_REGEX",
4081 text_replace_regex_string(pipe.clone(), "a".to_string(), "b".to_string()),
4082 ),
4083 ];
4084 for (name, result) in pipe_cases {
4085 let err = result.expect_err(&format!("{name} twin must refuse PIPE"));
4086 assert!(
4087 format!("{err:#}").contains("step IO"),
4088 "{name} refusal names the missing context: {err:#}"
4089 );
4090 }
4091 }
4092
4093 #[test]
4094 fn shell_words_join_split_round_trip() {
4095 let words = vec![
4099 "gh".to_string(),
4100 "issue".to_string(),
4101 "comment".to_string(),
4102 "with spaces".to_string(),
4103 "it's".to_string(),
4104 "say \"hi\"".to_string(),
4105 "$HOME".to_string(),
4106 "$(whoami)".to_string(),
4107 "C:\\path\\to".to_string(),
4108 "naïve café".to_string(),
4109 "".to_string(),
4110 ];
4111 let joined = shell_words::join(&words);
4112 let back = shell_words::split(&joined).expect("join output must parse");
4113 assert_eq!(back, words);
4114 assert!(shell_words::split("unbalanced \"quote").is_err());
4115 }
4116}