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) body: Vec<Step>,
230 pub(super) module: Option<String>,
235}
236
237pub(super) enum FuncBody<P: ProcessManager> {
242 Script(FuncDefData),
243 Pure(PureFn),
244 Ctx(NativeFn<P>),
245 Both { pure: PureFn, ctx: NativeFn<P> },
246}
247
248impl<P: ProcessManager> Clone for FuncBody<P> {
250 fn clone(&self) -> Self {
251 match self {
252 FuncBody::Script(def) => FuncBody::Script(def.clone()),
253 FuncBody::Pure(func) => FuncBody::Pure(Arc::clone(func)),
254 FuncBody::Ctx(func) => FuncBody::Ctx(Arc::clone(func)),
255 FuncBody::Both { pure, ctx } => FuncBody::Both {
256 pure: Arc::clone(pure),
257 ctx: Arc::clone(ctx),
258 },
259 }
260 }
261}
262
263pub(super) struct FuncEntry<P: ProcessManager> {
267 pub(super) meta: FuncMeta,
268 pub(super) body: FuncBody<P>,
269}
270
271impl<P: ProcessManager> Clone for FuncEntry<P> {
273 fn clone(&self) -> Self {
274 Self {
275 meta: self.meta.clone(),
276 body: self.body.clone(),
277 }
278 }
279}
280
281struct ScopeFrame<P: ProcessManager> {
284 defined: HashSet<String>,
285 shadowed: Vec<(String, FuncEntry<P>)>,
286}
287
288impl<P: ProcessManager> Clone for ScopeFrame<P> {
290 fn clone(&self) -> Self {
291 Self {
292 defined: self.defined.clone(),
293 shadowed: self.shadowed.clone(),
294 }
295 }
296}
297
298pub type PureTable = HashMap<String, HashMap<String, PureFn>>;
308
309pub fn placeholder_resolver(table: Arc<PureTable>) -> oxdock_process::PlaceholderCall {
318 Arc::new(move |module, func, args| {
319 let callee = table
320 .get(module)
321 .and_then(|entries| entries.get(func))
322 .ok_or_else(|| {
323 let mut known: Vec<String> = table
324 .iter()
325 .flat_map(|(m, entries)| entries.keys().map(move |f| format!("{m}::{f}")))
326 .collect();
327 known.sort();
328 anyhow::anyhow!(
329 "unknown placeholder function '{module}::{func}'; known functions: {}",
330 known.join(", ")
331 )
332 })?;
333 callee(args)
334 })
335}
336
337pub struct FunctionRegistry<P: ProcessManager> {
338 entries: HashMap<String, FuncEntry<P>>,
339 scopes: Vec<ScopeFrame<P>>,
340 pure_shared: Arc<PureTable>,
341 script_docs: HashMap<String, (String, String)>,
345}
346
347impl<P: ProcessManager> FunctionRegistry<P> {
348 pub(super) fn with_builtins() -> Self {
349 let mut reg = Self {
350 entries: HashMap::new(),
351 pure_shared: Arc::new(HashMap::new()),
352 script_docs: HashMap::new(),
353 scopes: vec![ScopeFrame {
354 defined: HashSet::new(),
355 shadowed: Vec::new(),
356 }],
357 };
358 for host in Self::builtin_registrations() {
362 match host {
363 HostRegistration::Stateful { name, meta, func } => {
364 reg.insert_qualified(STD_MODULE_NAME, name, meta, FuncBody::Ctx(func));
365 }
366 HostRegistration::Pure { name, meta, func } => {
367 reg.insert_qualified(STD_MODULE_NAME, name, meta, FuncBody::Pure(func));
368 }
369 HostRegistration::Both {
370 name,
371 meta,
372 func,
373 template,
374 } => {
375 reg.insert_qualified(
376 STD_MODULE_NAME,
377 name,
378 meta,
379 FuncBody::Both {
380 pure: template,
381 ctx: func,
382 },
383 );
384 }
385 }
386 }
387 reg
388 }
389
390 pub(super) fn builtin_registrations() -> Vec<HostRegistration<P>> {
395 vec![
396 Int::registration(),
397 Float::registration(),
398 BoolConvert::registration(),
399 BoolOr::registration(),
400 FormatByteCount::registration(),
401 ParseByteCount::registration(),
402 FormatDuration::registration(),
403 ParseDuration::registration(),
404 Types::registration(),
405 TypeDescribe::registration(),
406 Glob::registration(),
407 LoadToml::registration(),
408 LoadJson::registration(),
409 HashSha256::registration(),
410 Cwd::registration(),
411 ParseToml::registration(),
412 ParseJson::registration(),
413 PathType::registration(),
414 PathWritable::registration(),
415 IsExec::registration(),
416 HasKey::registration(),
417 MapSet::registration(),
418 MergeMaps::registration(),
419 Base64Encode::registration(),
420 Base64Decode::registration(),
421 Rand::registration(),
422 ToJson::registration(),
423 TypeOf::registration(),
424 Functions::registration(),
425 Describe::registration(),
426 IsMain::registration(),
427 IsTerminal::registration(),
428 Eof::registration(),
429 TaskPoll::registration(),
430 Version::registration(),
431 Interpreter::registration(),
432 TextTrim::registration(),
433 TextTrimPrefix::registration(),
434 TextTrimSuffix::registration(),
435 PathJoin::registration(),
436 TextToUpper::registration(),
437 TextToLower::registration(),
438 TextReplace::registration(),
439 TextReplaceRegex::registration(),
440 TextSplit::registration(),
441 TextJoin::registration(),
442 TextLines::registration(),
443 TextFields::registration(),
444 TextMatch::registration(),
445 TextExtract::registration(),
446 TextStartsWith::registration(),
447 TextEndsWith::registration(),
448 TextContains::registration(),
449 TextLength::registration(),
450 TextCount::registration(),
451 TextCountMatches::registration(),
452 TextGrep::registration(),
453 TextLinesRange::registration(),
454 SemaphoreNew::registration(),
455 SemaphoreTryAcquire::registration(),
456 SemaphoreAvailable::registration(),
457 ShellSplitArgs::registration(),
458 ShellJoinArgs::registration(),
459 ]
460 }
461
462 pub(super) fn keys(&self) -> HashSet<String> {
465 self.entries.keys().cloned().collect()
466 }
467
468 pub(super) fn get(&self, name: &str) -> Option<FuncEntry<P>> {
470 self.entries.get(name).cloned()
471 }
472
473 fn insert_native(&mut self, name: String, meta: FuncMeta, body: FuncBody<P>) {
474 self.entries.insert(name, FuncEntry { meta, body });
475 self.rebuild_pure_shared();
476 }
477
478 fn rebuild_pure_shared(&mut self) {
484 let mut table: PureTable = HashMap::new();
485 for (name, entry) in &self.entries {
486 let func = match &entry.body {
487 FuncBody::Pure(func) => func,
488 FuncBody::Both { pure, .. } => pure,
489 FuncBody::Script(_) | FuncBody::Ctx(_) => continue,
490 };
491 if let Some((module, base)) = split_qualified(name) {
492 table
493 .entry(module.to_string())
494 .or_default()
495 .insert(base.to_string(), Arc::clone(func));
496 }
497 }
498 self.pure_shared = Arc::new(table);
499 }
500
501 fn insert_qualified(
505 &mut self,
506 module: &str,
507 base: String,
508 mut meta: FuncMeta,
509 body: FuncBody<P>,
510 ) {
511 meta.name = qualify(module, &base);
512 meta.module = module.to_string();
513 if self.entries.contains_key(&meta.name) {
518 panic!("duplicate function registration `{}`", meta.name);
519 }
520 self.insert_native(meta.name.clone(), meta, body);
521 }
522
523 pub(super) fn register_host(
524 &mut self,
525 module: &str,
526 name: String,
527 mut meta: FuncMeta,
528 func: NativeFn<P>,
529 ) {
530 meta.kind = FuncKind::HostCtx;
531 self.insert_qualified(module, name, meta, FuncBody::Ctx(func));
532 }
533
534 pub(super) fn register_pure_host(
535 &mut self,
536 module: &str,
537 name: String,
538 mut meta: FuncMeta,
539 func: PureFn,
540 ) {
541 meta.kind = FuncKind::HostPure;
542 self.insert_qualified(module, name, meta, FuncBody::Pure(func));
543 }
544
545 pub(super) fn register_both_host(
546 &mut self,
547 module: &str,
548 name: String,
549 mut meta: FuncMeta,
550 func: NativeFn<P>,
551 template: PureFn,
552 ) {
553 meta.kind = FuncKind::HostCtx;
554 self.insert_qualified(
555 module,
556 name,
557 meta,
558 FuncBody::Both {
559 pure: template,
560 ctx: func,
561 },
562 );
563 }
564
565 pub(super) fn define_script(
570 &mut self,
571 name: &str,
572 params: &[(String, TypeTag)],
573 body: &[Step],
574 module: Option<&str>,
575 ) -> Result<()> {
576 let qualified = qualify(SCRIPT_MODULE_NAME, name);
577 let shadowable = matches!(
578 self.entries.get(&qualified).map(|entry| &entry.body),
579 Some(FuncBody::Script(_))
580 );
581 let reserved = self.entries.iter().any(|(key, entry)| {
586 split_qualified(key).is_some_and(|(_, base)| base == name)
587 && !matches!(entry.body, FuncBody::Script(_))
588 });
589 if reserved && !shadowable {
590 anyhow::bail!("cannot shadow reserved function `{name}`");
591 }
592 if self
593 .scopes
594 .last()
595 .is_some_and(|frame| frame.defined.contains(&qualified))
596 {
597 anyhow::bail!("duplicate function `{name}` in same scope");
598 }
599 let old = self.entries.insert(
600 qualified.clone(),
601 FuncEntry {
602 meta: FuncMeta {
603 name: qualified.clone(),
604 module: SCRIPT_MODULE_NAME.to_string(),
605 kind: FuncKind::Script,
606 params: Some(
607 params
608 .iter()
609 .map(|(name, param_type)| FuncParam {
610 name: name.clone(),
611 param_type: Some(param_type.clone()),
612 allowed: None,
613 docs: "",
616 options: None,
617 optional: false,
618 })
619 .collect(),
620 ),
621 returns: None,
622 rpn: false,
623 summary: "DSL-defined function.",
624 docs: "Defined via FUNC in script.",
625 examples: &[],
626 },
627 body: FuncBody::Script(FuncDefData {
628 params: params.to_vec(),
629 body: body.to_vec(),
630 module: module.map(|m| m.to_string()),
631 }),
632 },
633 );
634 if let Some(frame) = self.scopes.last_mut() {
635 frame.defined.insert(qualified.clone());
636 if let Some(old) = old {
637 frame.shadowed.push((qualified, old));
638 }
639 }
640 Ok(())
641 }
642
643 pub(super) fn define_aliased_in(
651 &mut self,
652 depth: usize,
653 alias: &str,
654 name: &str,
655 params: &[(String, TypeTag)],
656 body: &[Step],
657 module: Option<&str>,
658 ) -> Result<()> {
659 let qualified = qualify(alias, name);
660 let shadowable = matches!(
661 self.entries.get(&qualified).map(|entry| &entry.body),
662 Some(FuncBody::Script(_))
663 );
664 let reserved = self.entries.iter().any(|(key, entry)| {
668 split_qualified(key).is_some_and(|(_, base)| base == name)
669 && !matches!(entry.body, FuncBody::Script(_))
670 });
671 if reserved && !shadowable {
672 anyhow::bail!("cannot shadow reserved function `{name}`");
673 }
674 let depth_in_range = depth < self.scopes.len();
678 let frame_idx = if depth_in_range {
679 depth
680 } else {
681 self.scopes.len().saturating_sub(1)
682 };
683 if self
684 .scopes
685 .get(frame_idx)
686 .is_some_and(|frame| frame.defined.contains(&qualified))
687 {
688 anyhow::bail!("duplicate function `{name}` in same scope");
689 }
690 let old = self.entries.insert(
691 qualified.clone(),
692 FuncEntry {
693 meta: FuncMeta {
694 name: qualified.clone(),
695 module: alias.to_string(),
696 kind: FuncKind::Script,
697 params: Some(
698 params
699 .iter()
700 .map(|(name, param_type)| FuncParam {
701 name: name.clone(),
702 param_type: Some(param_type.clone()),
703 allowed: None,
704 docs: "",
705 options: None,
706 optional: false,
707 })
708 .collect(),
709 ),
710 returns: None,
711 rpn: false,
712 summary: "DSL-defined function.",
713 docs: "Defined via FUNC in an imported script.",
714 examples: &[],
715 },
716 body: FuncBody::Script(FuncDefData {
717 params: params.to_vec(),
718 body: body.to_vec(),
719 module: module.map(|m| m.to_string()),
720 }),
721 },
722 );
723 if let Some(frame) = self.scopes.get_mut(frame_idx) {
724 frame.defined.insert(qualified.clone());
725 if let Some(old) = old {
726 frame.shadowed.push((qualified, old));
727 }
728 }
729 Ok(())
730 }
731
732 pub(super) fn scope_depth(&self) -> usize {
735 self.scopes.len()
736 }
737
738 pub(super) fn push_scope(&mut self) {
741 self.scopes.push(ScopeFrame {
742 defined: HashSet::new(),
743 shadowed: Vec::new(),
744 });
745 }
746
747 pub(super) fn pop_scope(&mut self) {
750 let Some(frame) = self.scopes.pop() else {
751 return;
752 };
753 for name in frame.defined {
754 self.entries.remove(&name);
755 }
756 for (name, old) in frame.shadowed {
757 self.entries.insert(name, old);
758 }
759 }
760
761 pub(super) fn contains_script(&self, name: &str) -> bool {
765 matches!(
766 self.entries.get(name).map(|entry| &entry.body),
767 Some(FuncBody::Script(_))
768 )
769 }
770
771 fn clone_pure_fn(&self, name: &str) -> Option<PureFn> {
775 match self.entries.get(name)?.body {
776 FuncBody::Pure(ref func) => Some(Arc::clone(func)),
777 FuncBody::Both { ref pure, .. } => Some(Arc::clone(pure)),
778 _ => None,
779 }
780 }
781
782 pub(super) fn pure_shared(&self) -> Arc<PureTable> {
786 Arc::clone(&self.pure_shared)
787 }
788
789 pub(super) fn all_metas(&self) -> Vec<FuncMeta> {
792 self.entries_metas()
793 }
794
795 fn clone_ctx_fn(&self, name: &str) -> Option<NativeFn<P>> {
800 match self.entries.get(name)?.body {
801 FuncBody::Ctx(ref func) => Some(Arc::clone(func)),
802 FuncBody::Both { ref ctx, .. } => Some(Arc::clone(ctx)),
803 _ => None,
804 }
805 }
806
807 fn meta(&self, name: &str) -> Option<FuncMeta> {
808 self.entries.get(name).map(|entry| entry.meta.clone())
809 }
810
811 fn native_metas(&self) -> Vec<FuncMeta> {
812 let mut out: Vec<FuncMeta> = Vec::new();
813 for entry in self.entries.values() {
814 if !matches!(entry.body, FuncBody::Script(_)) {
815 out.push(entry.meta.clone());
816 }
817 }
818 out.sort_by(|a, b| a.name.cmp(&b.name));
819 out
820 }
821
822 fn entries_metas(&self) -> Vec<FuncMeta> {
825 let mut out: Vec<FuncMeta> = self
826 .entries
827 .values()
828 .map(|entry| entry.meta.clone())
829 .collect();
830 out.sort_by(|a, b| a.name.cmp(&b.name));
831 out
832 }
833
834 pub fn set_script_docs(&mut self, docs: &HashMap<String, (String, String)>) {
837 for (base, pair) in docs {
838 self.script_docs
839 .insert(qualify(SCRIPT_MODULE_NAME, base), pair.clone());
840 }
841 }
842
843 pub fn script_doc_for(&self, qualified: &str) -> Option<(String, String)> {
845 self.script_docs.get(qualified).cloned()
846 }
847
848 pub fn exported_metas(&self, func_exports: &[String]) -> anyhow::Result<Vec<FuncMeta>> {
851 let mut out = Vec::with_capacity(func_exports.len());
852 for name in func_exports {
853 let qualified = match name.split_once("::") {
857 None => qualify(SCRIPT_MODULE_NAME, name),
858 Some(_) => name.clone(),
859 };
860 match self.entries.get(&qualified) {
861 Some(entry) => out.push(entry.meta.clone()),
862 None => anyhow::bail!(
863 "EXPORT `{name}` matches no defined script function or known host function"
864 ),
865 }
866 }
867 Ok(out)
868 }
869}
870
871impl<P: ProcessManager> Clone for FunctionRegistry<P> {
872 fn clone(&self) -> Self {
873 Self {
874 entries: self.entries.clone(),
875 scopes: self.scopes.clone(),
876 pure_shared: Arc::clone(&self.pure_shared),
877 script_docs: self.script_docs.clone(),
878 }
879 }
880}
881
882pub fn builtin_function_names() -> HashSet<String> {
889 let mut names = FunctionRegistry::<DefaultProcessManager>::with_builtins().keys();
890 names.insert(KEYWORD_INSPECT.to_string());
891 names
892}
893
894pub fn builtin_function_metas() -> Vec<FuncMeta> {
898 FunctionRegistry::<DefaultProcessManager>::with_builtins().native_metas()
899}
900
901pub fn std_module_table() -> oxdock_parser::ModuleTable {
906 let func_names: HashSet<String> = builtin_function_metas()
908 .into_iter()
909 .map(|meta| base_name(&meta.name).to_string())
910 .collect();
911 oxdock_parser::ModuleTable {
912 modules: HashMap::from([(
913 STD_MODULE_NAME.to_string(),
914 Some(oxdock_parser::ModuleFuncs { func_names }),
915 )]),
916 }
917}
918
919#[oxdock_func(pure, returns = TypeTag::Int)]
932#[example(
933 name = "convert",
934 code = r###"
935 IMPORT [STD]
936 LET $n: INT = INT("42")
937 ASSERT_EQ $n 42
938 LET $flag: INT = INT(true)
939 ASSERT_EQ $flag 1
940 "###
941)]
942fn int(
943 #[union(Int, Float, String, Bool)]
945 val: Value,
946) -> Result<Value> {
947 super::args::int_from_value(val)
948}
949
950#[oxdock_func(pure, returns = TypeTag::Float)]
955#[example(
956 name = "convert",
957 code = r###"
958 IMPORT [STD]
959 LET $f: FLOAT = FLOAT("1.5")
960 ASSERT_EQ $f 1.5
961 LET $whole: FLOAT = FLOAT(2)
962 ASSERT_EQ $whole 2.0
963 "###
964)]
965fn float(
966 #[union(Float, Int, String)]
968 val: Value,
969) -> Result<Value> {
970 super::args::float_from_value(val)
971}
972
973#[oxdock_func(pure, returns = TypeTag::String)]
978#[example(
979 name = "format and round-trip",
980 code = r###"
981 # Byte counts render in the largest exact unit.
982 IMPORT [STD]
983 LET $pretty: STRING = FORMAT_BYTE_COUNT(1_048_576)
984 ASSERT_EQ $pretty "1MiB"
985
986 # The pair round-trips through the parser.
987 LET $back: INT = PARSE_BYTE_COUNT($pretty)
988 ASSERT_EQ $back 1_048_576
989 "###
990)]
991fn format_byte_count(
992 bytes: i64,
994) -> Result<Value> {
995 if bytes < 0 {
996 return Err(anyhow::anyhow!(
997 "FORMAT_BYTE_COUNT needs a non-negative byte count, got {bytes}"
998 ));
999 }
1000 Ok(Value::string(oxdock_parser::command::format_byte_count(
1001 bytes as u64,
1002 )))
1003}
1004
1005#[oxdock_func(pure, returns = TypeTag::Int)]
1040#[example(
1041 name = "parse",
1042 code = r###"
1043 IMPORT [STD]
1044 LET $n: INT = PARSE_BYTE_COUNT("10KB")
1045 ASSERT_EQ $n 10_000
1046 LET $identity: INT = PARSE_BYTE_COUNT(512)
1047 ASSERT_EQ $identity 512
1048 "###
1049)]
1050fn parse_byte_count(
1051 #[union(Int, Float, String)]
1053 text: Value,
1054) -> Result<Value> {
1055 if let Some(n) = text.as_i64() {
1056 if n < 0 {
1057 return Err(anyhow::anyhow!(
1058 "PARSE_BYTE_COUNT needs a non-negative byte count, got {n}"
1059 ));
1060 }
1061 return Ok(Value::int(n));
1062 }
1063 if let Some(f) = text.as_f64() {
1064 if f.is_finite() && f.fract() == 0.0 && f >= 0.0 && f <= i64::MAX as f64 {
1065 return Ok(Value::int(f as i64));
1066 }
1067 return Err(anyhow::anyhow!(
1068 "PARSE_BYTE_COUNT needs an integral byte count, got {f:?}"
1069 ));
1070 }
1071 let Some(s) = text.as_str() else {
1072 return Err(anyhow::anyhow!(
1073 "PARSE_BYTE_COUNT needs a token or number, found {text:?}"
1074 ));
1075 };
1076 let n = oxdock_parser::command::parse_byte_count(s)?;
1077 let n = i64::try_from(n)
1078 .map_err(|_| anyhow::anyhow!("PARSE_BYTE_COUNT out of INT range: {s:?}"))?;
1079 Ok(Value::int(n))
1080}
1081
1082#[oxdock_func(pure, returns = TypeTag::String)]
1087#[example(
1088 name = "format and round-trip",
1089 code = r###"
1090 # Durations render in the largest exact unit.
1091 IMPORT [STD]
1092 LET $pretty: STRING = FORMAT_DURATION(90_000)
1093 ASSERT_EQ $pretty "90s"
1094
1095 # The pair round-trips through the parser.
1096 LET $back: INT = PARSE_DURATION($pretty)
1097 ASSERT_EQ $back 90_000
1098 "###
1099)]
1100fn format_duration(
1101 millis: i64,
1103) -> Result<Value> {
1104 if millis < 0 {
1105 return Err(anyhow::anyhow!(
1106 "FORMAT_DURATION needs non-negative milliseconds, got {millis}"
1107 ));
1108 }
1109 Ok(Value::string(oxdock_parser::command::format_duration(
1110 &std::time::Duration::from_millis(millis as u64),
1111 )))
1112}
1113
1114#[oxdock_func(pure, returns = TypeTag::Int)]
1120#[example(
1121 name = "parse",
1122 code = r###"
1123 # A bare number means seconds, like TIMEOUT.
1124 IMPORT [STD]
1125 LET $ms: INT = PARSE_DURATION("2m")
1126 ASSERT_EQ $ms 120_000
1127
1128 # Milliseconds stay exact.
1129 LET $exact: INT = PARSE_DURATION("1500ms")
1130 ASSERT_EQ $exact 1_500
1131
1132 # One optional space separates number from unit.
1133 LET $spaced: INT = PARSE_DURATION("1 h")
1134 ASSERT_EQ $spaced 3_600_000
1135 "###
1136)]
1137fn parse_duration(
1138 text: String,
1140) -> Result<Value> {
1141 let duration = oxdock_parser::command::parse_duration(&text)?;
1142 let millis = i64::try_from(duration.as_millis())
1143 .map_err(|_| anyhow::anyhow!("PARSE_DURATION out of INT range: {text:?}"))?;
1144 Ok(Value::int(millis))
1145}
1146
1147#[oxdock_func(rpn, returns = TypeTag::ListOf(std::sync::Arc::new(TypeTag::String)))]
1152#[example(
1153 name = "match",
1154 code = r###"
1155 IMPORT [STD]
1156 WRITE "notes-a.md" "a"
1157 WRITE "notes-b.md" "b"
1158 WRITE "other.txt" "c"
1159 LET $found: LIST<STRING> = GLOB("notes-*.md")
1160 ASSERT_EQ $found.0 "notes-a.md"
1161 ASSERT_EQ $found.1 "notes-b.md"
1162 "###
1163)]
1164fn glob<P: ProcessManager>(
1165 cx: &mut StepCtx<P>,
1166 #[union(String, Path)]
1168 pattern: Value,
1169) -> Result<Value> {
1170 let text = super::args::string_or_path_text(&pattern)?;
1171 super::args::glob_from_value(&[Value::string(text)], cx)
1172}
1173
1174#[oxdock_func(rpn, returns = TypeTag::MapOf(std::sync::Arc::new(TypeTag::Any)))]
1179#[example(
1180 name = "load",
1181 code = r###"
1182 IMPORT [STD]
1183 WRITE "cfg.toml" "title = \"demo\""
1184 LET $cfg: MAP<ANY> = LOAD_TOML("cfg.toml")
1185 ASSERT_EQ $cfg.title "demo"
1186 "###
1187)]
1188fn load_toml<P: ProcessManager>(
1189 cx: &mut StepCtx<P>,
1190 #[union(String, Path)]
1192 path: Value,
1193) -> Result<Value> {
1194 let text = super::args::string_or_path_text(&path)?;
1195 super::args::load_toml_from_value(&[Value::string(text)], cx)
1196}
1197
1198#[oxdock_func(rpn, returns = TypeTag::Any)]
1206#[example(
1207 name = "load",
1208 code = r###"
1209 IMPORT [STD]
1210 WRITE "data.json" "{\"a\": 1}"
1211 LET $doc: MAP<ANY> = LOAD_JSON("data.json")
1212 ASSERT_EQ $doc.a 1
1213 "###
1214)]
1215fn load_json<P: ProcessManager>(
1216 cx: &mut StepCtx<P>,
1217 #[union(String, Path)]
1219 path: Value,
1220) -> Result<Value> {
1221 let text = super::args::string_or_path_text(&path)?;
1222 super::args::load_json_from_value(&[Value::string(text)], cx)
1223}
1224
1225#[oxdock_func(rpn, returns = TypeTag::String)]
1235#[example(
1236 name = "hash",
1237 code = r###"
1238 IMPORT [STD]
1239 WRITE payload.txt hello
1240 LET $digest: STRING = HASH_SHA256("payload.txt")
1241 ASSERT_EQ $digest "2cf24dba5fb0a30e26e83b2ac5b9e29e1b161e5c1fa7425e73043362938b9824"
1242 "###
1243)]
1244fn hash_sha256<P: ProcessManager>(
1245 cx: &mut StepCtx<P>,
1246 #[union(String, Path)]
1248 path: Value,
1249) -> Result<Value> {
1250 use sha2::Digest;
1251
1252 let text = super::args::string_or_path_text(&path)?;
1253 let target = cx.state.fs.resolve_read(&cx.state.cwd, &text)?;
1254 let mut hasher = sha2::Sha256::new();
1255 super::fs_ops::hash_path(cx.state.fs.as_ref(), &target, "", &mut hasher)?;
1256 let digest = hasher.finalize();
1257 let bytes: &[u8] = digest.as_ref();
1258 Ok(Value::string(oxdock_utils::hex_encode(bytes)))
1259}
1260
1261#[oxdock_func(rpn, returns = TypeTag::String)]
1272#[example(
1273 name = "cwd",
1274 code = r###"
1275 IMPORT [STD]
1276 WORKDIR sub
1277 LET $c: STRING = CWD()
1278 ASSERT_CONTAINS $c "sub"
1279 "###
1280)]
1281fn cwd<P: ProcessManager>(cx: &mut StepCtx<P>) -> Result<Value> {
1282 if cx.state.fs.is_snapshot_pending() {
1283 return Ok(Value::string(super::SNAPSHOT_PENDING_DISPLAY.to_string()));
1284 }
1285 let concrete = cx.state.fs.concretize_cwd(&cx.state.cwd);
1286 let real = super::fs_ops::canonical_cwd(cx.state.fs.as_ref(), &concrete)?;
1287 Ok(Value::string(real))
1288}
1289
1290#[oxdock_func(pure, returns = TypeTag::MapOf(std::sync::Arc::new(TypeTag::Any)))]
1296#[example(
1297 name = "parse",
1298 code = r###"
1299 IMPORT [STD]
1300 LET $doc: MAP<ANY> = PARSE_TOML("title = \"demo\"")
1301 ASSERT_EQ $doc.title "demo"
1302 "###
1303)]
1304fn parse_toml(
1305 text: String,
1307) -> Result<Value> {
1308 super::args::parse_toml_from_value(Value::string(text))
1309}
1310
1311#[oxdock_func(pure, returns = TypeTag::Any)]
1320#[example(
1321 name = "parse",
1322 code = r###"
1323 # Parse in-memory JSON text with the same conversion as file loading.
1324 IMPORT [STD]
1325 LET $body: STRING = "{\"a\": 1}"
1326 LET $doc: ANY = PARSE_JSON($body)
1327 ASSERT_EQ $doc.a 1
1328
1329 # Top-level arrays parse to LIST, which is why the return is ANY.
1330 LET $items: LIST<ANY> = PARSE_JSON("[1, 2]")
1331 ASSERT_EQ $items.0 1
1332 ASSERT_EQ $items.1 2
1333 "###
1334)]
1335fn parse_json(
1336 text: String,
1338) -> Result<Value> {
1339 super::args::parse_json_from_value(Value::string(text))
1340}
1341
1342#[oxdock_func(returns = TypeTag::String)]
1348#[example(
1349 name = "describe",
1350 code = r###"
1351 IMPORT [STD]
1352 WRITE "entry.txt" "words"
1353 LET $kind: STRING = PATH_TYPE("entry.txt")
1354 ASSERT_EQ $kind "file"
1355 LET $missing: STRING = PATH_TYPE("no-such-entry.txt")
1356 ASSERT_EQ $missing "absent"
1357 "###
1358)]
1359fn path_type<P: ProcessManager>(
1360 cx: &mut StepCtx<P>,
1361 #[union(String, Path)]
1363 path: Value,
1364) -> Result<Value> {
1365 let text = super::args::string_or_path_text(&path)?;
1366 super::args::path_type_from_value(&[Value::string(text)], cx)
1367}
1368
1369#[oxdock_func(returns = TypeTag::Bool)]
1378#[example(
1379 name = "probe",
1380 code = r###"
1381 # An absent nested path is writable when its ancestor is.
1382 IMPORT [STD]
1383 LET $fresh: BOOL = PATH_WRITABLE("probe-check/nested/file.txt")
1384 ASSERT_EQ $fresh true
1385
1386 # The empty string never aliases the working directory.
1387 LET $empty: BOOL = PATH_WRITABLE("")
1388 ASSERT_EQ $empty false
1389 "###
1390)]
1391fn path_writable<P: ProcessManager>(
1392 cx: &mut StepCtx<P>,
1393 #[union(String, Path)]
1395 path: Value,
1396) -> Result<Value> {
1397 let text = super::args::string_or_path_text(&path)?;
1398 super::args::path_writable_from_value(&[Value::string(text)], cx)
1399}
1400
1401#[oxdock_func(returns = TypeTag::Bool)]
1414#[example(
1415 name = "probe",
1416 code = r###"
1417 # Missing tools read false instead of failing the run.
1418 IMPORT [STD]
1419 LET $missing: BOOL = IS_EXEC("no-such-tool-xyz")
1420 ASSERT_EQ $missing false
1421
1422 # Plain files are not executable on any platform.
1423 WRITE tool.txt payload
1424 LET $plain: BOOL = IS_EXEC("tool.txt")
1425 ASSERT_EQ $plain false
1426 "###
1427)]
1428fn is_exec<P: ProcessManager>(
1429 cx: &mut StepCtx<P>,
1430 #[union(String, Path)]
1432 name: Value,
1433) -> Result<Value> {
1434 let text = super::args::string_or_path_text(&name)?;
1435 super::args::is_exec_from_value(&[Value::string(text)], cx)
1436}
1437
1438#[oxdock_func(pure, returns = TypeTag::Bool)]
1444#[example(
1445 name = "probe",
1446 code = r###"
1447 IMPORT [STD]
1448 LET $m: MAP<ANY> = PARSE_JSON("{\"a\": 1}")
1449 LET $hit: BOOL = HAS_KEY($m, "a")
1450 ASSERT_EQ $hit true
1451 LET $miss: BOOL = HAS_KEY($m, "b")
1452 ASSERT_EQ $miss false
1453 "###
1454)]
1455fn has_key(
1456 map: BTreeMap<String, Value>,
1458 key: String,
1460) -> Result<Value> {
1461 super::args::has_key_from_value(Value::map(map), &key)
1462}
1463
1464#[oxdock_func(pure, returns = TypeTag::MapOf(std::sync::Arc::new(TypeTag::Any)))]
1470#[example(
1471 name = "insert",
1472 code = r###"
1473 IMPORT [STD]
1474 LET $m: MAP<ANY> = MAP_SET({seed: 0}, "a", 1)
1475 ASSERT_EQ $m.a 1
1476 "###
1477)]
1478fn map_set(
1479 map: BTreeMap<String, Value>,
1481 key: String,
1483 value: Value,
1485) -> Result<Value> {
1486 super::args::map_set_from_value(Value::map(map), key, value)
1487}
1488
1489#[oxdock_func(returns = TypeTag::Float, summary = "Draw a random FLOAT uniformly from [0, 1), optionally seeded.")]
1497#[example(
1498 name = "seeded draw",
1499 code = r###"
1500 # A seed draws the same value on every run.
1501 IMPORT [STD]
1502 LET $one: FLOAT = RAND({seed: 7})
1503 LET $two: FLOAT = RAND({seed: 7})
1504 ASSERT_EQ $one $two
1505 "###
1506)]
1507#[example(
1508 name = "unseeded draw",
1509 code = r###"
1510 # Scale a unit draw into a backoff delay between 1 and 11 seconds.
1511 IMPORT [STD]
1512 LET $draw: FLOAT = RAND()
1513 LET $delay: FLOAT = 1.0 + $draw * 10.0
1514 IF $delay < 1.0 {
1515 EXIT 1
1516 }
1517 IF $delay >= 11.0 {
1518 EXIT 1
1519 }
1520 ECHO "retrying in {{ $delay }}s"
1521 "###
1522)]
1523fn rand<P: ProcessManager>(
1524 cx: &mut StepCtx<P>,
1525 #[options("seed?: INT")]
1527 #[optional]
1528 options: BTreeMap<String, Value>,
1529) -> Result<Value> {
1530 let _ = cx;
1531 let seed = options
1534 .get("seed")
1535 .map(|value| value.as_i64().expect("check_options verified INT"));
1536 super::args::rand_float_from_value(seed)
1537}
1538
1539#[oxdock_func(pure, returns = TypeTag::String)]
1545#[example(
1546 name = "encode",
1547 code = r###"
1548 # Encode text to standard base64.
1549 IMPORT [STD]
1550 LET $encoded: STRING = BASE64_ENCODE("hello")
1551 ASSERT_EQ $encoded "aGVsbG8="
1552 "###
1553)]
1554fn base64_encode(
1555 text: String,
1557) -> Result<Value> {
1558 super::args::base64_encode_from_value(Value::string(text))
1559}
1560
1561#[oxdock_func(pure, returns = TypeTag::String)]
1568#[example(
1569 name = "decode",
1570 code = r###"
1571 # Decode standard base64 back to text.
1572 IMPORT [STD]
1573 LET $decoded: STRING = BASE64_DECODE("aGVsbG8=")
1574 ASSERT_EQ $decoded "hello"
1575 "###
1576)]
1577fn base64_decode(
1578 text: String,
1580) -> Result<Value> {
1581 super::args::base64_decode_from_value(Value::string(text))
1582}
1583
1584#[oxdock_func(pure, returns = TypeTag::String)]
1591#[example(
1592 name = "encode",
1593 code = r###"
1594 IMPORT [STD]
1595 LET $json: STRING = TO_JSON({a: 1})
1596 ASSERT_EQ $json "{\"a\":1}\n"
1597 "###
1598)]
1599fn to_json(
1600 #[union(String, Int, Float, Bool, List, Map)]
1602 value: Value,
1603) -> Result<Value> {
1604 super::args::to_json_from_value(value)
1605}
1606
1607#[oxdock_func(pure, returns = TypeTag::String)]
1615#[example(
1616 name = "name the word",
1617 code = r###"
1618 IMPORT [STD]
1619 LET $word: STRING = TYPE_OF(42)
1620 ASSERT_EQ $word "INT"
1621 "###
1622)]
1623fn type_of(
1624 value: Value,
1626) -> Result<Value> {
1627 super::args::type_of_from_value(value)
1628}
1629
1630#[oxdock_func(pure, returns = TypeTag::MapOf(std::sync::Arc::new(TypeTag::Any)))]
1638#[example(
1639 name = "merge",
1640 code = r###"
1641 IMPORT [STD]
1642 LET $m: MAP<ANY> = MERGE_MAPS([{a: 1}, {b: 2}], "overwrite")
1643 ASSERT_EQ $m.a 1
1644 ASSERT_EQ $m.b 2
1645 "###
1646)]
1647fn merge_maps(
1648 maps: Vec<BTreeMap<String, Value>>,
1650 #[values("fail_on_duplicate", "overwrite")]
1652 policy: String,
1653) -> Result<Value> {
1654 super::args::merge_maps_from_value(
1655 Value::list(maps.into_iter().map(Value::map).collect()),
1656 policy,
1657 )
1658}
1659
1660#[oxdock_func(pure, returns = TypeTag::String)]
1665#[example(
1666 name = "report",
1667 code = r###"
1668 # The engine reports its own build version as a dotted string.
1669 IMPORT [STD]
1670 LET $v: STRING = VERSION()
1671 ASSERT_CONTAINS $v "."
1672 "###
1673)]
1674fn version() -> Result<Value> {
1675 Ok(Value::string(env!("CARGO_PKG_VERSION").to_string()))
1676}
1677
1678#[oxdock_func(returns = TypeTag::ListOf(std::sync::Arc::new(TypeTag::String)))]
1683#[example(
1684 name = "list",
1685 code = r###"
1686 IMPORT [STD]
1687 LET $names: LIST<STRING> = FUNCTIONS()
1688 ASSERT_CONTAINS $names "STD::INT"
1689 "###
1690)]
1691fn functions<P: ProcessManager>(cx: &mut StepCtx<P>) -> Result<Value> {
1692 let mut names: Vec<String> = cx
1693 .state
1694 .list_functions()
1695 .into_iter()
1696 .map(|meta| meta.name)
1697 .collect();
1698 names.sort();
1699 names.dedup();
1700 Ok(Value::list(names.into_iter().map(Value::string).collect()))
1701}
1702
1703#[oxdock_func(
1718 returns = TypeTag::Record(std::sync::Arc::from([Field {
1719 name: "name".to_string(),
1720 ty: TypeTag::String,
1721 docs: "Qualified function name.",
1722 optional: false,
1723 }, Field {
1724 name: "module".to_string(),
1725 ty: TypeTag::String,
1726 docs: "Owning module.",
1727 optional: false,
1728 }, Field {
1729 name: "kind".to_string(),
1730 ty: TypeTag::String,
1731 docs: "Origin label (`host` or `script`).",
1732 optional: false,
1733 }, Field {
1734 name: "params".to_string(),
1735 ty: TypeTag::ListOf(std::sync::Arc::new(TypeTag::MapOf(std::sync::Arc::new(
1736 TypeTag::Any,
1737 )))),
1738 docs: "Parameter entries (empty for parameterless functions).",
1739 optional: false,
1740 }, Field {
1741 name: "returns".to_string(),
1742 ty: TypeTag::String,
1743 docs: "Structural return shape (empty when untagged).",
1744 optional: false,
1745 }, Field {
1746 name: "rpn".to_string(),
1747 ty: TypeTag::Bool,
1748 docs: "True when callable in RPN position.",
1749 optional: false,
1750 }, Field {
1751 name: "summary".to_string(),
1752 ty: TypeTag::String,
1753 docs: "One-line description.",
1754 optional: false,
1755 }]))
1756 summary = "Describe one function by qualified name."
1757)]
1758#[example(
1759 name = "describe",
1760 code = r###"
1761 IMPORT [STD]
1762 LET $info: MAP<ANY> = DESCRIBE("STD::INT")
1763 ASSERT_EQ $info.name "STD::INT"
1764 ASSERT_EQ $info.returns "INT"
1765 "###
1766)]
1767fn describe<P: ProcessManager>(
1768 cx: &mut StepCtx<P>,
1769 name: String,
1771) -> Result<Value> {
1772 if split_qualified(&name).is_none() && name != KEYWORD_INSPECT {
1773 anyhow::bail!(
1774 "unknown function `{name}`: DESCRIBE requires a qualified name (e.g. `STD::{name}`)"
1775 );
1776 }
1777 cx.state
1778 .describe_function(&name)
1779 .ok_or_else(|| anyhow::anyhow!("unknown function {name}"))
1780}
1781
1782#[oxdock_func(returns = TypeTag::ListOf(std::sync::Arc::new(TypeTag::String)))]
1788#[example(
1789 name = "list",
1790 code = r###"
1791 IMPORT [STD]
1792 LET $names: LIST<STRING> = TYPES()
1793 ASSERT_CONTAINS $names "STRING"
1794 "###
1795)]
1796fn types<P: ProcessManager>(cx: &mut StepCtx<P>) -> Result<Value> {
1797 Ok(Value::list(
1798 cx.state
1799 .type_names()
1800 .into_iter()
1801 .map(Value::string)
1802 .collect(),
1803 ))
1804}
1805
1806#[oxdock_func(returns = TypeTag::Record(std::sync::Arc::from([Field {
1812 name: "name".to_string(),
1813 ty: TypeTag::String,
1814 docs: "Queried type name.",
1815 optional: false,
1816}, Field {
1817 name: "summary".to_string(),
1818 ty: TypeTag::String,
1819 docs: "One-line description.",
1820 optional: false,
1821}, Field {
1822 name: "docs".to_string(),
1823 ty: TypeTag::String,
1824 docs: "Full documentation text.",
1825 optional: false,
1826}])))]
1827#[example(
1828 name = "describe",
1829 code = r###"
1830 IMPORT [STD]
1831 LET $info: MAP<ANY> = TYPE_DESCRIBE("STRING")
1832 ASSERT_EQ $info.name "STRING"
1833 "###
1834)]
1835fn type_describe<P: ProcessManager>(
1836 cx: &mut StepCtx<P>,
1837 name: String,
1839) -> Result<Value> {
1840 if let Some(descriptor) = cx.state.describe_type(&name) {
1841 let mut map = BTreeMap::new();
1842 map.insert(
1843 "name".to_string(),
1844 Value::string(descriptor.name.to_string()),
1845 );
1846 map.insert(
1847 "summary".to_string(),
1848 Value::string(descriptor.summary.to_string()),
1849 );
1850 map.insert(
1851 "docs".to_string(),
1852 Value::string(descriptor.docs.to_string()),
1853 );
1854 return Ok(Value::map(map));
1855 }
1856 if let Some(target) = cx.state.alias_target(&name) {
1859 let mut map = BTreeMap::new();
1860 map.insert("name".to_string(), Value::string(name.clone()));
1861 map.insert(
1862 "summary".to_string(),
1863 Value::string(format!("Script type alias for {target}.")),
1864 );
1865 map.insert(
1866 "docs".to_string(),
1867 Value::string(format!(
1868 "Declared with TYPE {name} = {target}. The alias expands structurally at every declaration."
1869 )),
1870 );
1871 return Ok(Value::map(map));
1872 }
1873 Err(anyhow::anyhow!("unknown type {name}"))
1874}
1875
1876#[oxdock_func(returns = TypeTag::String)]
1890#[example(
1891 name = "self",
1892 code = r###"
1893 # The running interpreter resolves to a non-empty path.
1894 IMPORT [STD]
1895 LET $exe: STRING = INTERPRETER()
1896 LET $nonempty: BOOL = $exe != ""
1897 ASSERT_EQ $nonempty true
1898 "###
1899)]
1900#[example(
1901 name = "dynamic assembly",
1902 code = r###"
1903 # Assemble the child script dynamically: the parent interpolates
1904 # its own bindings into the pipe, then runs the interpreter on it.
1905 # Unescaped {{ }} bakes in at render time; \{{ }} stays literal
1906 # so the child expands it with its own bindings.
1907 # The pipe delivers EOF when the producer step ends, so the child
1908 # reads exactly one script.
1909 IMPORT [STD]
1910 LET $exe: STRING = INTERPRETER()
1911 LET $who: STRING = "Ada"
1912 LET $child: PIPE
1913 WITH_IO [stdout=$child] ECHO """
1914 ECHO "hello {{ $who }}!"
1915 LET $who: STRING = "Grace"
1916 ECHO "child sees \{{ $who }}!"
1917 """
1918 LET $out: STRING = WITH_IO [stdin=$child] RUN [$exe]
1919 ASSERT_CONTAINS $out "hello Ada!"
1920 ASSERT_CONTAINS $out "child sees Grace!"
1921 "###
1922)]
1923fn interpreter<P: ProcessManager>(cx: &mut StepCtx<P>) -> Result<Value> {
1924 if let Some(staged) = cx.state.io.interpreter_override() {
1925 return Ok(Value::string(staged));
1926 }
1927 Ok(Value::string(oxdock_process::interpreter_exe()?))
1928}
1929
1930#[oxdock_func(returns = TypeTag::Bool)]
1938#[example(
1939 name = "main",
1940 code = r###"
1941 # Entry top level runs as main.
1942 IMPORT [STD]
1943 LET $m: BOOL = IS_MAIN()
1944 ASSERT_EQ $m true
1945 "###
1946)]
1947#[example(
1948 name = "library doubles as demo",
1949 fence_meta = "roots:unified",
1950 code = r###"
1951 # A library doubles as a runnable demo: guard the demo with
1952 # IF IS_MAIN() so importing it stays side effect free. The
1953 # parent writes both files, then runs each in a fresh
1954 # interpreter: direct execution prints the demo, importing
1955 # it does not. Unified roots: the child inherits one
1956 # workspace, so parent and child see the same files. The
1957 # exact stdout match proves the demo line stays out of the
1958 # importing run.
1959 IMPORT [STD]
1960
1961 # The library under test: demo guarded by IS_MAIN.
1962 WRITE lib.oxfile """
1963 IMPORT [STD]
1964 FUNC GREET($x: STRING) { RETURN "hi \{{ $x }}" }
1965 EXPORT GREET
1966 IF IS_MAIN() {
1967 ECHO "demo: hi Ada"
1968 }
1969 """
1970
1971 # The importer: calls the library, prints only its own line.
1972 WRITE main.oxfile """
1973 IMPORT ["lib.oxfile" AS LIB]
1974 LET $g: STRING = LIB::GREET("Bo")
1975 ECHO "imported: \{{ $g }}"
1976 """
1977
1978 # Direct run executes the demo.
1979 LET $exe: STRING = INTERPRETER()
1980 LET $direct: STRING = RUN [$exe, "lib.oxfile"]
1981 ASSERT_CONTAINS $direct "demo: hi Ada"
1982
1983 # Importing run stays silent apart from its own line.
1984 LET $via: STRING = RUN [$exe, "main.oxfile"]
1985 ASSERT_EQ $via "imported: hi Bo\n"
1986 "###
1987)]
1988fn is_main<P: ProcessManager>(cx: &mut StepCtx<P>) -> Result<Value> {
1989 let main = match cx.state.module_stack.last() {
1990 None | Some(None) => true,
1991 Some(Some(_)) => false,
1992 };
1993 Ok(Value::bool(main))
1994}
1995
1996#[oxdock_func(returns = TypeTag::Bool)]
2010#[example(
2011 name = "null stdin",
2012 code = r###"
2013 # A null stdin is never a terminal, in every harness.
2014 IMPORT [STD]
2015 LET $term: BOOL = IS_TERMINAL("stdin")
2016 ASSERT_EQ $term false
2017 "###
2018)]
2019fn is_terminal<P: ProcessManager>(
2020 cx: &mut StepCtx<P>,
2021 #[values("stdin", "stdout", "stderr")]
2023 stream_name: String,
2024) -> Result<Value> {
2025 use std::io::IsTerminal;
2026 let terminal = match stream_name.as_str() {
2027 "stdin" => {
2028 if cx.stdin_pipe.is_some() {
2033 false
2034 } else {
2035 match &cx.stdin {
2036 CommandStdin::Null => false,
2037 #[cfg(not(miri))]
2038 CommandStdin::OsPipe(_) => false,
2039 CommandStdin::Stream(_) => false,
2040 CommandStdin::Inherit => std::io::stdin().is_terminal(),
2041 }
2042 }
2043 }
2044 "stdout" => {
2045 if cx.out_pipe.is_some() {
2046 false
2048 } else if cx.state.io.stdout().is_some() {
2049 false
2052 } else {
2053 match &cx.out {
2054 None => std::io::stdout().is_terminal(),
2056 #[cfg(not(miri))]
2058 Some(StreamHandle::Os(_)) => false,
2059 Some(StreamHandle::Stream(_)) => std::io::stdout().is_terminal(),
2069 }
2070 }
2071 }
2072 "stderr" => {
2073 if cx.state.io.stderr().is_some() {
2074 false
2076 } else {
2077 match &cx.err {
2078 None => std::io::stderr().is_terminal(),
2080 #[cfg(not(miri))]
2082 Some(StreamHandle::Os(_)) => false,
2083 Some(StreamHandle::Stream(_)) => false,
2086 }
2087 }
2088 }
2089 _ => anyhow::bail!(
2090 "IS_TERMINAL expects \"stdin\", \"stdout\", or \"stderr\", got {stream_name:?}"
2095 ),
2096 };
2097 Ok(Value::bool(terminal))
2098}
2099
2100#[oxdock_func(returns = TypeTag::Semaphore)]
2108#[example(
2109 name = "mint",
2110 code = r###"
2111 # Mint a semaphore admitting at most two holders.
2112 IMPORT [STD]
2113 LET $sem: SEMAPHORE = SEMAPHORE_NEW(2)
2114
2115 # A fresh semaphore reports its full cap as available.
2116 LET $free: INT = SEMAPHORE_AVAILABLE($sem)
2117 ASSERT_EQ $free 2
2118 "###
2119)]
2120fn semaphore_new<P: ProcessManager>(
2121 cx: &mut StepCtx<P>,
2122 max: i64,
2124) -> Result<Value> {
2125 let _ = cx;
2126 if max <= 0 {
2127 return Err(anyhow::anyhow!(
2128 "SEMAPHORE_NEW() requires a positive max, got {max}"
2129 ));
2130 }
2131 Ok(Value::semaphore(max as usize))
2132}
2133
2134#[oxdock_func(returns = TypeTag::Record(std::sync::Arc::from([Field {
2143 name: "held".to_string(),
2144 ty: TypeTag::Bool,
2145 docs: "`true` with the permit under `permit`, `false` with no `permit` key.",
2146 optional: false,
2147}, Field {
2148 name: "permit".to_string(),
2149 ty: TypeTag::Permit,
2150 docs: "Permit handle; read only when `held`.",
2151 optional: true,
2152}])))]
2153#[example(
2154 name = "acquire",
2155 code = r###"
2156 # First acquire holds with a permit to bind.
2157 IMPORT [STD]
2158 LET $sem: SEMAPHORE = SEMAPHORE_NEW(1)
2159 LET $first: MAP<held: BOOL, permit?: PERMIT> = SEMAPHORE_TRY_ACQUIRE($sem)
2160 ASSERT_EQ $first.held true
2161 LET $permit: PERMIT = $first.permit
2162
2163 # A capped semaphore answers held false with no permit key.
2164 LET $second: MAP<held: BOOL, permit?: PERMIT> = SEMAPHORE_TRY_ACQUIRE($sem)
2165 ASSERT_EQ $second.held false
2166 LET $has_permit: BOOL = HAS_KEY($second, "permit")
2167 ASSERT_EQ $has_permit false
2168 "###
2169)]
2170fn semaphore_try_acquire<P: ProcessManager>(
2171 cx: &mut StepCtx<P>,
2172 sem: Arc<SemaphoreState>,
2174) -> Result<Value> {
2175 let _ = cx;
2176 let mut map = BTreeMap::new();
2177 if sem.try_acquire() {
2178 map.insert("held".to_string(), Value::bool(true));
2179 map.insert("permit".to_string(), Value::permit(&sem));
2180 } else {
2181 map.insert("held".to_string(), Value::bool(false));
2182 }
2183 Ok(Value::map(map))
2184}
2185
2186#[oxdock_func(pure, returns = TypeTag::Int)]
2193#[example(
2194 name = "readout",
2195 code = r###"
2196 # Hold one permit on a cap of two.
2197 IMPORT [STD]
2198 LET $sem: SEMAPHORE = SEMAPHORE_NEW(2)
2199 LET $acq: MAP<held: BOOL, permit?: PERMIT> = SEMAPHORE_TRY_ACQUIRE($sem)
2200 ASSERT_EQ $acq.held true
2201
2202 # One held permit leaves exactly one free.
2203 LET $free: INT = SEMAPHORE_AVAILABLE($sem)
2204 ASSERT_EQ $free 1
2205 "###
2206)]
2207fn semaphore_available(
2208 sem: Arc<SemaphoreState>,
2210) -> Result<Value> {
2211 Ok(Value::int(sem.available() as i64))
2212}
2213
2214#[oxdock_func(
2223 rpn,
2224 returns = TypeTag::union(vec![TypeTag::String, TypeTag::Pipe]),
2225 template = text_trim_string
2226)]
2227#[example(
2228 name = "trim",
2229 code = r###"
2230 # Leading and trailing whitespace falls away.
2231 IMPORT [STD]
2232 LET $clean: STRING = TEXT_TRIM(" hello ")
2233 ASSERT_EQ $clean "hello"
2234 "###
2235)]
2236#[example(
2237 name = "trim pipe mirrors",
2238 code = r###"
2239 # Pipe input mints pipe output with the same transform.
2240 IMPORT [STD]
2241 LET $cap: PIPE
2242 WITH_IO [stdout=$cap] {
2243 ECHO " hello "
2244 }
2245 LET $out: PIPE = TEXT_TRIM($cap)
2246 WITH_IO [stdin=$out] READ_LINE $line
2247 ASSERT_EQ $line "hello"
2248 "###
2249)]
2250#[example(
2251 name = "trim template",
2252 code = r###"
2253 # String inputs run inside placeholders too.
2254 IMPORT [STD]
2255 LET $msg: STRING = 'clean:{{ STD::TEXT_TRIM(" hello ") }}'
2256 ASSERT_EQ $msg "clean:hello"
2257 "###
2258)]
2259#[example(
2260 name = "trim file template",
2261 code = r###"
2262 # EXPAND templates resolve the same registry.
2263 IMPORT [STD]
2264 WRITE "tpl.txt" "clean:\{{ STD::TEXT_TRIM(\" hello \") }}"
2265 LET $out: STRING = EXPAND "tpl.txt"
2266 ASSERT_EQ $out "clean:hello"
2267 "###
2268)]
2269fn text_trim<P: ProcessManager>(
2270 cx: &mut StepCtx<P>,
2271 #[union(String, Pipe)]
2273 text: Value,
2274) -> Result<Value> {
2275 super::args::mirror_stream(cx, "TEXT_TRIM", &text, super::args::TextPump::Trim)
2276}
2277
2278fn text_trim_string(text: Value) -> Result<Value> {
2281 super::args::mirror_string("TEXT_TRIM", &text, super::args::TextPump::Trim)
2282}
2283
2284#[oxdock_func(
2293 rpn,
2294 returns = TypeTag::union(vec![TypeTag::String, TypeTag::Pipe]),
2295 template = text_trim_prefix_string
2296)]
2297#[example(
2298 name = "strip prefix",
2299 code = r###"
2300 # A present prefix falls away; absence returns the input unchanged.
2301 IMPORT [STD]
2302 LET $bare: STRING = TEXT_TRIM_PREFIX("v1.2.3", "v")
2303 ASSERT_EQ $bare "1.2.3"
2304
2305 # Missing prefixes pass through untouched.
2306 LET $same: STRING = TEXT_TRIM_PREFIX("1.2.3", "v")
2307 ASSERT_EQ $same "1.2.3"
2308 "###
2309)]
2310#[example(
2311 name = "strip prefix pipe mirrors",
2312 code = r###"
2313 # Pipe input mints pipe output with the same strip.
2314 IMPORT [STD]
2315 LET $cap: PIPE
2316 WITH_IO [stdout=$cap] {
2317 ECHO "v1.2.3"
2318 }
2319 LET $trimmed: PIPE = TEXT_TRIM($cap)
2320 LET $out: PIPE = TEXT_TRIM_PREFIX($trimmed, "v")
2321 WITH_IO [stdin=$out] READ_LINE $line
2322 ASSERT_EQ $line "1.2.3"
2323 "###
2324)]
2325#[example(
2326 name = "strip prefix template",
2327 code = r###"
2328 # String inputs run inside placeholders too.
2329 IMPORT [STD]
2330 LET $msg: STRING = 'bare:{{ STD::TEXT_TRIM_PREFIX("v1.2.3", "v") }}'
2331 ASSERT_EQ $msg "bare:1.2.3"
2332 "###
2333)]
2334fn text_trim_prefix<P: ProcessManager>(
2335 cx: &mut StepCtx<P>,
2336 #[union(String, Pipe)]
2338 text: Value,
2339 prefix: String,
2341) -> Result<Value> {
2342 super::args::mirror_stream(
2343 cx,
2344 "TEXT_TRIM_PREFIX",
2345 &text,
2346 super::args::TextPump::TrimPrefix(prefix),
2347 )
2348}
2349
2350fn text_trim_prefix_string(text: Value, prefix: String) -> Result<Value> {
2353 super::args::mirror_string(
2354 "TEXT_TRIM_PREFIX",
2355 &text,
2356 super::args::TextPump::TrimPrefix(prefix),
2357 )
2358}
2359
2360#[oxdock_func(
2367 rpn,
2368 returns = TypeTag::union(vec![TypeTag::String, TypeTag::Pipe]),
2369 template = text_trim_suffix_string
2370)]
2371#[example(
2372 name = "strip suffix",
2373 code = r###"
2374 # A present suffix falls away; absence returns the input unchanged.
2375 IMPORT [STD]
2376 LET $bare: STRING = TEXT_TRIM_SUFFIX("archive.tar.gz", ".gz")
2377 ASSERT_EQ $bare "archive.tar"
2378
2379 # Missing suffixes pass through untouched.
2380 LET $same: STRING = TEXT_TRIM_SUFFIX("archive.tar", ".gz")
2381 ASSERT_EQ $same "archive.tar"
2382 "###
2383)]
2384#[example(
2385 name = "strip suffix pipe mirrors",
2386 code = r###"
2387 # Pipe input mints pipe output with the same strip.
2388 IMPORT [STD]
2389 LET $cap: PIPE
2390 WITH_IO [stdout=$cap] {
2391 ECHO "archive.tar.gz"
2392 }
2393 LET $trimmed: PIPE = TEXT_TRIM($cap)
2394 LET $out: PIPE = TEXT_TRIM_SUFFIX($trimmed, ".gz")
2395 WITH_IO [stdin=$out] READ_LINE $line
2396 ASSERT_EQ $line "archive.tar"
2397 "###
2398)]
2399#[example(
2400 name = "strip suffix template",
2401 code = r###"
2402 # String inputs run inside placeholders too.
2403 IMPORT [STD]
2404 LET $msg: STRING = 'bare:{{ STD::TEXT_TRIM_SUFFIX("archive.tar.gz", ".gz") }}'
2405 ASSERT_EQ $msg "bare:archive.tar"
2406 "###
2407)]
2408fn text_trim_suffix<P: ProcessManager>(
2409 cx: &mut StepCtx<P>,
2410 #[union(String, Pipe)]
2412 text: Value,
2413 suffix: String,
2415) -> Result<Value> {
2416 super::args::mirror_stream(
2417 cx,
2418 "TEXT_TRIM_SUFFIX",
2419 &text,
2420 super::args::TextPump::TrimSuffix(suffix),
2421 )
2422}
2423
2424fn text_trim_suffix_string(text: Value, suffix: String) -> Result<Value> {
2427 super::args::mirror_string(
2428 "TEXT_TRIM_SUFFIX",
2429 &text,
2430 super::args::TextPump::TrimSuffix(suffix),
2431 )
2432}
2433
2434#[oxdock_func(returns = TypeTag::String)]
2445#[example(
2446 name = "join path",
2447 code = r###"
2448 # Directory and file stem join with the native separator.
2449 # Source `\\` is one backslash at runtime; `/` works on Windows
2450 # too, native just reads better there.
2451 IMPORT [STD]
2452 LET $p: STRING = PATH_JOIN("some-dir", "some-file")
2453 [family:unix] ASSERT_EQ $p "some-dir/some-file"
2454 [family:windows] ASSERT_EQ $p "some-dir\\some-file"
2455 "###
2456)]
2457fn path_join<P: ProcessManager>(
2458 _cx: &mut StepCtx<P>,
2459 #[union(String, Path)]
2461 dir: Value,
2462 #[union(String, Path)]
2464 name: Value,
2465) -> Result<Value> {
2466 let d = super::args::string_or_path_text(&dir)?;
2467 let n = super::args::string_or_path_text(&name)?;
2468 Ok(Value::string(oxdock_fs::join_native(&d, &n)))
2469}
2470
2471#[oxdock_func(
2478 rpn,
2479 returns = TypeTag::union(vec![TypeTag::String, TypeTag::Pipe]),
2480 template = text_to_upper_string
2481)]
2482#[example(
2483 name = "uppercase",
2484 code = r###"
2485 # Text folds to uppercase.
2486 IMPORT [STD]
2487 LET $loud: STRING = TEXT_TO_UPPER("hello")
2488 ASSERT_EQ $loud "HELLO"
2489 "###
2490)]
2491#[example(
2492 name = "uppercase pipe mirrors",
2493 code = r###"
2494 # Pipe input mints pipe output with the same fold.
2495 IMPORT [STD]
2496 LET $cap: PIPE
2497 WITH_IO [stdout=$cap] {
2498 ECHO "hello"
2499 }
2500 LET $out: PIPE = TEXT_TO_UPPER($cap)
2501 WITH_IO [stdin=$out] READ_LINE $line
2502 ASSERT_EQ $line "HELLO"
2503 "###
2504)]
2505#[example(
2506 name = "uppercase template",
2507 code = r###"
2508 # String inputs run inside placeholders too.
2509 IMPORT [STD]
2510 LET $msg: STRING = 'loud:{{ STD::TEXT_TO_UPPER("hello") }}'
2511 ASSERT_EQ $msg "loud:HELLO"
2512 "###
2513)]
2514fn text_to_upper<P: ProcessManager>(
2515 cx: &mut StepCtx<P>,
2516 #[union(String, Pipe)]
2518 text: Value,
2519) -> Result<Value> {
2520 super::args::mirror_stream(cx, "TEXT_TO_UPPER", &text, super::args::TextPump::ToUpper)
2521}
2522
2523fn text_to_upper_string(text: Value) -> Result<Value> {
2526 super::args::mirror_string("TEXT_TO_UPPER", &text, super::args::TextPump::ToUpper)
2527}
2528
2529#[oxdock_func(
2536 rpn,
2537 returns = TypeTag::union(vec![TypeTag::String, TypeTag::Pipe]),
2538 template = text_to_lower_string
2539)]
2540#[example(
2541 name = "lowercase",
2542 code = r###"
2543 # Text folds to lowercase.
2544 IMPORT [STD]
2545 LET $quiet: STRING = TEXT_TO_LOWER("HELLO")
2546 ASSERT_EQ $quiet "hello"
2547 "###
2548)]
2549#[example(
2550 name = "lowercase pipe mirrors",
2551 code = r###"
2552 # Pipe input mints pipe output with the same fold.
2553 IMPORT [STD]
2554 LET $cap: PIPE
2555 WITH_IO [stdout=$cap] {
2556 ECHO "HELLO"
2557 }
2558 LET $out: PIPE = TEXT_TO_LOWER($cap)
2559 WITH_IO [stdin=$out] READ_LINE $line
2560 ASSERT_EQ $line "hello"
2561 "###
2562)]
2563#[example(
2564 name = "lowercase template",
2565 code = r###"
2566 # String inputs run inside placeholders too.
2567 IMPORT [STD]
2568 LET $msg: STRING = 'quiet:{{ STD::TEXT_TO_LOWER("HELLO") }}'
2569 ASSERT_EQ $msg "quiet:hello"
2570 "###
2571)]
2572fn text_to_lower<P: ProcessManager>(
2573 cx: &mut StepCtx<P>,
2574 #[union(String, Pipe)]
2576 text: Value,
2577) -> Result<Value> {
2578 super::args::mirror_stream(cx, "TEXT_TO_LOWER", &text, super::args::TextPump::ToLower)
2579}
2580
2581fn text_to_lower_string(text: Value) -> Result<Value> {
2584 super::args::mirror_string("TEXT_TO_LOWER", &text, super::args::TextPump::ToLower)
2585}
2586
2587#[oxdock_func(
2598 rpn,
2599 returns = TypeTag::union(vec![TypeTag::String, TypeTag::Pipe]),
2600 template = text_replace_string
2601)]
2602#[example(
2603 name = "replace",
2604 code = r###"
2605 # Every literal occurrence rewrites in place.
2606 IMPORT [STD]
2607 LET $fixed: STRING = TEXT_REPLACE("hello world", "world", "there")
2608 ASSERT_EQ $fixed "hello there"
2609 "###
2610)]
2611#[example(
2612 name = "replace pipe mirrors",
2613 code = r###"
2614 # Pipe input mints pipe output with the same rewrite.
2615 IMPORT [STD]
2616 LET $cap: PIPE
2617 WITH_IO [stdout=$cap] {
2618 ECHO "hello world"
2619 }
2620 LET $trimmed: PIPE = TEXT_TRIM($cap)
2621 LET $out: PIPE = TEXT_REPLACE($trimmed, "world", "there")
2622 WITH_IO [stdin=$out] READ_LINE $line
2623 ASSERT_EQ $line "hello there"
2624 "###
2625)]
2626#[example(
2627 name = "replace template",
2628 code = r###"
2629 # String inputs run inside placeholders too.
2630 IMPORT [STD]
2631 LET $msg: STRING = 'fixed:{{ STD::TEXT_REPLACE("hello world", "world", "there") }}'
2632 ASSERT_EQ $msg "fixed:hello there"
2633 "###
2634)]
2635fn text_replace<P: ProcessManager>(
2636 cx: &mut StepCtx<P>,
2637 #[union(String, Pipe)]
2639 text: Value,
2640 from: String,
2642 to: String,
2644) -> Result<Value> {
2645 super::args::mirror_stream(
2646 cx,
2647 "TEXT_REPLACE",
2648 &text,
2649 super::args::TextPump::ReplaceLiteral { from, to },
2650 )
2651}
2652
2653fn text_replace_string(text: Value, from: String, to: String) -> Result<Value> {
2656 super::args::mirror_string(
2657 "TEXT_REPLACE",
2658 &text,
2659 super::args::TextPump::ReplaceLiteral { from, to },
2660 )
2661}
2662
2663#[oxdock_func(
2675 rpn,
2676 returns = TypeTag::union(vec![TypeTag::String, TypeTag::Pipe]),
2677 template = text_replace_regex_string
2678)]
2679#[example(
2680 name = "replace with captures",
2681 code = r###"
2682 # Capture groups expand in the replacement.
2683 IMPORT [STD]
2684 LET $swapped: STRING = TEXT_REPLACE_REGEX("2026-10-13", "(\\d+)-(\\d+)-(\\d+)", "$3/$2/$1")
2685 ASSERT_EQ $swapped "13/10/2026"
2686 "###
2687)]
2688#[example(
2689 name = "replace regex pipe mirrors",
2690 code = r###"
2691 # Pipe input mints pipe output with the same rewrite.
2692 IMPORT [STD]
2693 LET $cap: PIPE
2694 WITH_IO [stdout=$cap] {
2695 ECHO "2026-10-13"
2696 }
2697 LET $trimmed: PIPE = TEXT_TRIM($cap)
2698 LET $out: PIPE = TEXT_REPLACE_REGEX($trimmed, "(\\d+)-(\\d+)-(\\d+)", "$3/$2/$1")
2699 WITH_IO [stdin=$out] READ_LINE $line
2700 ASSERT_EQ $line "13/10/2026"
2701 "###
2702)]
2703#[example(
2704 name = "replace regex template",
2705 code = r###"
2706 # String inputs run inside placeholders too.
2707 IMPORT [STD]
2708 LET $msg: STRING = 'swapped:{{ STD::TEXT_REPLACE_REGEX("2026-10-13", "(\\d+)-(\\d+)-(\\d+)", "$3/$2/$1") }}'
2709 ASSERT_EQ $msg "swapped:13/10/2026"
2710 "###
2711)]
2712fn text_replace_regex<P: ProcessManager>(
2713 cx: &mut StepCtx<P>,
2714 #[union(String, Pipe)]
2716 text: Value,
2717 pattern: String,
2719 replacement: String,
2721) -> Result<Value> {
2722 if let Some(s) = text.as_str() {
2723 let out =
2724 super::args::text_replace_regex_str(s, &pattern, &replacement, "TEXT_REPLACE_REGEX")?;
2725 return Ok(Value::string(out));
2726 }
2727 let content = super::args::read_pipe_eager(cx, "TEXT_REPLACE_REGEX", &text)?;
2728 let out = super::args::text_replace_regex_str(
2729 &content,
2730 &pattern,
2731 &replacement,
2732 "TEXT_REPLACE_REGEX",
2733 )?;
2734 super::args::write_completed_pipe(cx, "TEXT_REPLACE_REGEX", out)
2735}
2736
2737fn text_replace_regex_string(text: Value, pattern: String, replacement: String) -> Result<Value> {
2740 let Some(s) = text.as_str() else {
2741 return Err(super::args::pipe_needs_step_io("TEXT_REPLACE_REGEX"));
2742 };
2743 let out = super::args::text_replace_regex_str(s, &pattern, &replacement, "TEXT_REPLACE_REGEX")?;
2744 Ok(Value::string(out))
2745}
2746
2747#[oxdock_func(pure, returns = TypeTag::ListOf(std::sync::Arc::new(TypeTag::String)))]
2755#[example(
2756 name = "split",
2757 code = r###"
2758 # Delimiters split into list items.
2759 IMPORT [STD]
2760 LET $parts: LIST<STRING> = TEXT_SPLIT("a,b,c", ",")
2761 ASSERT_EQ $parts.0 "a"
2762 ASSERT_EQ $parts.1 "b"
2763 ASSERT_EQ $parts.2 "c"
2764 "###
2765)]
2766fn text_split(
2767 text: String,
2769 delimiter: String,
2771) -> Result<Value> {
2772 Ok(super::args::text_list_value(super::args::text_split_str(
2773 &text, &delimiter,
2774 )))
2775}
2776
2777#[oxdock_func(pure, returns = TypeTag::String)]
2780#[example(
2781 name = "join",
2782 code = r###"
2783 # List items join with the separator between them.
2784 IMPORT [STD]
2785 LET $joined: STRING = TEXT_JOIN(["a", "b", "c"], ",")
2786 ASSERT_EQ $joined "a,b,c"
2787 "###
2788)]
2789fn text_join(
2790 elements: Vec<String>,
2792 delimiter: String,
2794) -> Result<Value> {
2795 Ok(Value::string(elements.join(delimiter.as_str())))
2796}
2797
2798#[oxdock_func(pure, returns = TypeTag::ListOf(std::sync::Arc::new(TypeTag::String)))]
2810#[example(
2811 name = "split args",
2812 code = r###"
2813 # Quoted segments stay one word.
2814 IMPORT [STD]
2815 LET $argv: LIST<STRING> = SHELL_SPLIT_ARGS("gh issue comment 153 --body-file notes.md")
2816 ASSERT_EQ $argv.0 "gh"
2817 ASSERT_EQ $argv.3 "153"
2818 ASSERT_EQ $argv.5 "notes.md"
2819
2820 # Quotes and escapes parse the shell way.
2821 LET $quoted: LIST<STRING> = SHELL_SPLIT_ARGS("say \"hi there\" 'a b'")
2822 ASSERT_EQ $quoted.0 "say"
2823 ASSERT_EQ $quoted.1 "hi there"
2824 ASSERT_EQ $quoted.2 "a b"
2825 "###
2826)]
2827fn shell_split_args(
2828 command: String,
2830) -> Result<Value> {
2831 match shell_words::split(&command) {
2832 Ok(words) => Ok(super::args::text_list_value(words)),
2833 Err(err) => anyhow::bail!("SHELL_SPLIT_ARGS: {err}"),
2834 }
2835}
2836
2837#[oxdock_func(pure, returns = TypeTag::String)]
2845#[example(
2846 name = "join args",
2847 code = r###"
2848 # Plain words join with spaces and no quoting.
2849 IMPORT [STD]
2850 LET $plain: STRING = SHELL_JOIN_ARGS(["gh", "issue", "list"])
2851 ASSERT_EQ $plain "gh issue list"
2852
2853 # Words with spaces quote, and the round trip is exact.
2854 LET $words: LIST<STRING> = ["say", "hi there", "a'b"]
2855 LET $joined: STRING = SHELL_JOIN_ARGS($words)
2856 LET $back: LIST<STRING> = SHELL_SPLIT_ARGS($joined)
2857 ASSERT_EQ $back.0 "say"
2858 ASSERT_EQ $back.1 "hi there"
2859 ASSERT_EQ $back.2 "a'b"
2860 "###
2861)]
2862fn shell_join_args(
2863 words: Vec<String>,
2865) -> Result<Value> {
2866 Ok(Value::string(shell_words::join(&words)))
2867}
2868
2869#[oxdock_func(pure, returns = TypeTag::ListOf(std::sync::Arc::new(TypeTag::String)))]
2877#[example(
2878 name = "lines",
2879 code = r###"
2880 # Newlines split into line items.
2881 IMPORT [STD]
2882 LET $lines: LIST<STRING> = TEXT_LINES("one\ntwo\nthree")
2883 ASSERT_EQ $lines.0 "one"
2884 ASSERT_EQ $lines.1 "two"
2885 ASSERT_EQ $lines.2 "three"
2886
2887 # Windows endings split the same way after normalization.
2888 LET $crlf: LIST<STRING> = TEXT_LINES("one\r\ntwo\r\nthree")
2889 ASSERT_EQ $crlf.0 "one"
2890 ASSERT_EQ $crlf.1 "two"
2891 ASSERT_EQ $crlf.2 "three"
2892
2893 # Old Mac endings split too, and mixed endings split together because the input normalizes to LF before splitting.
2894 LET $mixed: LIST<STRING> = TEXT_LINES("a\r\nb\nc\rd")
2895 ASSERT_EQ $mixed.0 "a"
2896 ASSERT_EQ $mixed.1 "b"
2897 ASSERT_EQ $mixed.2 "c"
2898 ASSERT_EQ $mixed.3 "d"
2899 "###
2900)]
2901fn text_lines(
2902 text: String,
2904) -> Result<Value> {
2905 Ok(super::args::text_list_value(super::args::text_lines_str(
2906 &text,
2907 )))
2908}
2909
2910#[oxdock_func(pure, returns = TypeTag::ListOf(std::sync::Arc::new(TypeTag::String)))]
2916#[example(
2917 name = "fields",
2918 code = r###"
2919 # Runs of whitespace separate fields; empties never appear.
2920 IMPORT [STD]
2921 LET $fields: LIST<STRING> = TEXT_FIELDS(" abc def ")
2922 ASSERT_EQ $fields.0 "abc"
2923 ASSERT_EQ $fields.1 "def"
2924 "###
2925)]
2926fn text_fields(
2927 text: String,
2929) -> Result<Value> {
2930 Ok(super::args::text_list_value(super::args::text_fields_str(
2931 &text,
2932 )))
2933}
2934
2935#[oxdock_func(pure, returns = TypeTag::ListOf(std::sync::Arc::new(TypeTag::String)))]
2944#[example(
2945 name = "line range",
2946 code = r###"
2947 # Lines 2 through 3 come back as a list, 1-based inclusive.
2948 IMPORT [STD]
2949 LET $window: LIST<STRING> = TEXT_LINES_RANGE("one\ntwo\nthree\nfour", 2, 3)
2950 ASSERT_EQ $window.0 "two"
2951 ASSERT_EQ $window.1 "three"
2952
2953 # Ranges past the end clamp instead of failing.
2954 LET $tail: LIST<STRING> = TEXT_LINES_RANGE("one\ntwo", 2, 9)
2955 ASSERT_EQ $tail.0 "two"
2956 "###
2957)]
2958fn text_lines_range(
2959 text: String,
2961 from: i64,
2963 to: i64,
2965) -> Result<Value> {
2966 Ok(super::args::text_list_value(
2967 super::args::text_lines_range_str(&text, from, to, "TEXT_LINES_RANGE")?,
2968 ))
2969}
2970
2971#[oxdock_func(pure, returns = TypeTag::Bool)]
2979#[example(
2980 name = "match",
2981 code = r###"
2982 # Regex matches report true; misses report false.
2983 IMPORT [STD]
2984 LET $hit: BOOL = TEXT_MATCH("abc123", "\\d+")
2985 ASSERT_EQ $hit true
2986
2987 # A miss is false, not a failure.
2988 LET $miss: BOOL = TEXT_MATCH("abc", "^\\d+$")
2989 ASSERT_EQ $miss false
2990 "###
2991)]
2992fn text_match(
2993 text: String,
2995 pattern: String,
2997) -> Result<Value> {
2998 let re = super::args::text_compile_pattern("TEXT_MATCH", &pattern)?;
2999 Ok(Value::bool(re.is_match(&text)))
3000}
3001
3002#[oxdock_func(pure, name = "BOOL", returns = TypeTag::Bool)]
3011#[example(
3012 name = "convert",
3013 code = r###"
3014 IMPORT [STD]
3015 LET $n: BOOL = BOOL("yes")
3016 ASSERT_EQ $n true
3017 LET $f: BOOL = BOOL("0")
3018 ASSERT_EQ $f false
3019 "###
3020)]
3021fn bool_convert(
3022 #[union(Bool, String)]
3024 val: Value,
3025) -> Result<Value> {
3026 if let Some(b) = val.as_bool() {
3027 return Ok(Value::bool(b));
3028 }
3029 let Some(s) = val.as_str() else {
3030 return Err(anyhow::anyhow!(
3031 "BOOL needs a Bool or String, found {val:?}"
3032 ));
3033 };
3034 match super::args::parse_bool_str(s) {
3035 Some(b) => Ok(Value::bool(b)),
3036 None => anyhow::bail!("BOOL cannot coerce {s:?} to BOOL"),
3037 }
3038}
3039
3040#[oxdock_func(pure, returns = TypeTag::Bool)]
3050#[example(
3051 name = "absent-default",
3052 code = r###"
3053 # Absent names read empty; the default settles the polarity.
3054 IMPORT [STD]
3055 INHERIT_ENV [OXDOCK_TEST_ABSENT_FLAG]
3056 LET $dry: BOOL = BOOL_OR("{{ env:OXDOCK_TEST_ABSENT_FLAG }}", true)
3057 ASSERT_EQ $dry true
3058
3059 # Present values coerce strictly, ignoring the default.
3060 LET $off: BOOL = BOOL_OR("false", true)
3061 ASSERT_EQ $off false
3062 "###
3063)]
3064fn bool_or(
3065 text: String,
3067 default: bool,
3069) -> Result<Value> {
3070 if text.trim().is_empty() {
3071 return Ok(Value::bool(default));
3072 }
3073 match super::args::parse_bool_str(&text) {
3074 Some(b) => Ok(Value::bool(b)),
3075 None => anyhow::bail!("BOOL_OR cannot coerce {text:?} to BOOL"),
3076 }
3077}
3078
3079#[oxdock_func(pure, returns = TypeTag::ListOf(std::sync::Arc::new(TypeTag::String)))]
3088#[example(
3089 name = "extract",
3090 code = r###"
3091 # Index zero is the full match; groups follow in order.
3092 IMPORT [STD]
3093 LET $caps: LIST<STRING> = TEXT_EXTRACT("abc123", "([a-z]+)(\\d+)")
3094 ASSERT_EQ $caps.0 "abc123"
3095 ASSERT_EQ $caps.1 "abc"
3096 ASSERT_EQ $caps.2 "123"
3097 "###
3098)]
3099fn text_extract(
3100 text: String,
3102 pattern: String,
3104) -> Result<Value> {
3105 let groups = super::args::text_extract_str(&text, &pattern, "TEXT_EXTRACT")?;
3106 Ok(super::args::text_list_value(groups))
3107}
3108
3109#[oxdock_func(pure, returns = TypeTag::Bool)]
3116#[example(
3117 name = "starts with",
3118 code = r###"
3119 # Present prefixes report true; misses report false.
3120 IMPORT [STD]
3121 LET $hit: BOOL = TEXT_STARTS_WITH("linux-musl-x64", "linux")
3122 ASSERT_EQ $hit true
3123
3124 # A miss is false, not a failure.
3125 LET $miss: BOOL = TEXT_STARTS_WITH("macos-arm", "linux")
3126 ASSERT_EQ $miss false
3127 "###
3128)]
3129fn text_starts_with(
3130 text: String,
3132 prefix: String,
3134) -> Result<Value> {
3135 Ok(Value::bool(text.starts_with(prefix.as_str())))
3136}
3137
3138#[oxdock_func(pure, returns = TypeTag::Bool)]
3145#[example(
3146 name = "ends with",
3147 code = r###"
3148 # Present suffixes report true; misses report false.
3149 IMPORT [STD]
3150 LET $hit: BOOL = TEXT_ENDS_WITH("x86_64-linux-musl", "linux-musl")
3151 ASSERT_EQ $hit true
3152
3153 # A miss is false, not a failure.
3154 LET $miss: BOOL = TEXT_ENDS_WITH("x86_64-linux-gnu", "linux-musl")
3155 ASSERT_EQ $miss false
3156 "###
3157)]
3158fn text_ends_with(
3159 text: String,
3161 suffix: String,
3163) -> Result<Value> {
3164 Ok(Value::bool(text.ends_with(suffix.as_str())))
3165}
3166
3167#[oxdock_func(pure, returns = TypeTag::Bool)]
3174#[example(
3175 name = "contains",
3176 code = r###"
3177 # Present needles report true; misses report false.
3178 IMPORT [STD]
3179 LET $hit: BOOL = TEXT_CONTAINS("x86_64-linux-musl", "musl")
3180 ASSERT_EQ $hit true
3181
3182 # A miss is false, not a failure.
3183 LET $miss: BOOL = TEXT_CONTAINS("x86_64-linux-gnu", "musl")
3184 ASSERT_EQ $miss false
3185 "###
3186)]
3187fn text_contains(
3188 text: String,
3190 needle: String,
3192) -> Result<Value> {
3193 Ok(Value::bool(text.contains(needle.as_str())))
3194}
3195
3196#[oxdock_func(pure, returns = TypeTag::Int)]
3203#[example(
3204 name = "length",
3205 code = r###"
3206 # Plain text counts one per character.
3207 IMPORT [STD]
3208 LET $n: INT = TEXT_LENGTH("hello")
3209 ASSERT_EQ $n 5
3210
3211 # Multibyte characters count once each, not per byte.
3212 LET $wide: INT = TEXT_LENGTH("héllo")
3213 ASSERT_EQ $wide 5
3214 "###
3215)]
3216fn text_length(
3217 text: String,
3219) -> Result<Value> {
3220 Ok(Value::int(text.chars().count() as i64))
3221}
3222
3223#[oxdock_func(pure, returns = TypeTag::Int)]
3231#[example(
3232 name = "count",
3233 code = r###"
3234 # Every non-overlapping occurrence counts once.
3235 IMPORT [STD]
3236 LET $n: INT = TEXT_COUNT("hello world", "o")
3237 ASSERT_EQ $n 2
3238
3239 # Overlapping candidates never double count.
3240 LET $once: INT = TEXT_COUNT("aaa", "aa")
3241 ASSERT_EQ $once 1
3242 "###
3243)]
3244fn text_count(
3245 text: String,
3247 needle: String,
3249) -> Result<Value> {
3250 let n = super::args::text_count_str(&text, &needle, "TEXT_COUNT")?;
3251 Ok(Value::int(n))
3252}
3253
3254#[oxdock_func(pure, returns = TypeTag::Int)]
3264#[example(
3265 name = "count matches",
3266 code = r###"
3267 # One line matches once no matter how many times it hits.
3268 IMPORT [STD]
3269 LET $n: INT = TEXT_COUNT_MATCHES("test a: test\ntest b: nope\ntest c: test", ": test")
3270 ASSERT_EQ $n 2
3271
3272 # A miss binds zero, never an error.
3273 LET $none: INT = TEXT_COUNT_MATCHES("test b: nope", ": test$")
3274 ASSERT_EQ $none 0
3275 "###
3276)]
3277fn text_count_matches(
3278 text: String,
3280 pattern: String,
3282) -> Result<Value> {
3283 let n = super::args::text_count_matches_str(&text, &pattern, "TEXT_COUNT_MATCHES")?;
3284 Ok(Value::int(n))
3285}
3286
3287#[oxdock_func(pure, returns = TypeTag::ListOf(std::sync::Arc::new(TypeTag::String)))]
3300#[example(
3301 name = "grep",
3302 code = r###"
3303 # Matching lines come back as a list, in order.
3304 IMPORT [STD]
3305 LET $hits: LIST<STRING> = TEXT_GREP("one\ntwo\none more", "^one")
3306 ASSERT_EQ $hits.0 "one"
3307 ASSERT_EQ $hits.1 "one more"
3308
3309 # A miss binds an empty list, never an error.
3310 LET $miss: LIST<STRING> = TEXT_GREP("one\ntwo", "^z")
3311 LET $joined: STRING = TEXT_JOIN($miss, ",")
3312 ASSERT_EQ $joined ""
3313
3314 # The (?i) flag ignores case, so uppercase lines match too.
3315 LET $folded: LIST<STRING> = TEXT_GREP("One\ntwo\nONE more", "(?i)^one")
3316 ASSERT_EQ $folded.0 "One"
3317 ASSERT_EQ $folded.1 "ONE more"
3318 "###
3319)]
3320#[example(
3321 name = "grep invert",
3322 code = r###"
3323 # The invert option keeps every non-matching line instead.
3324 IMPORT [STD]
3325 LET $kept: LIST<STRING> = TEXT_GREP("one\ntwo\none more", "^one", {invert: true})
3326 ASSERT_EQ $kept.0 "two"
3327
3328 # A pattern matching every line binds an empty list, never an error.
3329 LET $none: LIST<STRING> = TEXT_GREP("one\ntwo", "^", {invert: true})
3330 LET $joined: STRING = TEXT_JOIN($none, ",")
3331 ASSERT_EQ $joined ""
3332
3333 # Options ride into placeholders as MAP literals. Placeholder
3334 # strings unescape only backslash and quote, so multiline text
3335 # arrives through a variable.
3336 LET $two_lines: STRING = "one\ntwo"
3337 LET $msg: STRING = 'kept:{{ STD::TEXT_GREP($two_lines, "^one", {invert: true}) }}'
3338 ASSERT_EQ $msg "kept:two"
3339 "###
3340)]
3341fn text_grep(
3342 text: String,
3344 pattern: String,
3346 #[options("invert?: BOOL")]
3348 #[optional]
3349 options: BTreeMap<String, Value>,
3350) -> Result<Value> {
3351 let invert = super::args::text_invert_flag(&options);
3354 Ok(super::args::text_list_value(super::args::text_grep_str(
3355 &text,
3356 &pattern,
3357 invert,
3358 "TEXT_GREP",
3359 )?))
3360}
3361
3362#[oxdock_func(returns = TypeTag::Bool)]
3373#[example(
3374 name = "drain to end",
3375 code = r###"
3376 # Capture two lines, then drain to end of stream with no sentinel line.
3377 IMPORT [STD]
3378 LET $cap: PIPE
3379 WITH_IO [stdout=$cap] {
3380 ECHO "one"
3381 ECHO "two"
3382 }
3383
3384 # The loop exits on close, and the count proves both lines drained.
3385 LET $n: INT = 0
3386 WHILE !EOF($cap) {
3387 WITH_IO [stdin=$cap] READ_LINE $line
3388 $n = $n + 1
3389 }
3390 ASSERT_EQ $n 2
3391 "###
3392)]
3393fn eof<P: ProcessManager>(
3394 cx: &mut StepCtx<P>,
3395 pipe: PipeHandle,
3397) -> Result<Value> {
3398 let info = cx.state.io.inspect_pipe(&pipe);
3399 Ok(Value::bool(info.closed && info.buffered == 0))
3400}
3401
3402fn task_poll_result_fields() -> Arc<[Field]> {
3406 Arc::from(vec![
3407 Field {
3408 name: "state".to_string(),
3409 ty: TypeTag::String,
3410 docs: "Task phase: `running` or `finished`.",
3411 optional: false,
3412 },
3413 Field {
3414 name: "ok".to_string(),
3415 ty: TypeTag::Bool,
3416 docs: "True unless the task failed.",
3417 optional: false,
3418 },
3419 Field {
3420 name: "stdout_tail".to_string(),
3421 ty: TypeTag::String,
3422 docs: "Bounded stdout tail, live while running.",
3423 optional: false,
3424 },
3425 Field {
3426 name: "stderr_tail".to_string(),
3427 ty: TypeTag::String,
3428 docs: "Bounded stderr tail, live while running.",
3429 optional: false,
3430 },
3431 Field {
3432 name: "truncated_bytes".to_string(),
3433 ty: TypeTag::Int,
3434 docs: "Dropped head bytes past the per-stream cap.",
3435 optional: false,
3436 },
3437 Field {
3438 name: "exit_code".to_string(),
3439 ty: TypeTag::Int,
3440 docs: "Process exit code, present once finished.",
3441 optional: true,
3442 },
3443 Field {
3444 name: "result".to_string(),
3445 ty: TypeTag::Any,
3446 docs: "Task `RETURN` value, present on clean finish.",
3447 optional: true,
3448 },
3449 Field {
3450 name: "error".to_string(),
3451 ty: TypeTag::String,
3452 docs: "Failure text, present on failed finish.",
3453 optional: true,
3454 },
3455 ])
3456}
3457
3458#[oxdock_func(returns = TypeTag::Record(task_poll_result_fields()))]
3471#[example(
3472 name = "running poll",
3473 code = r###"
3474 # A sleeping task is still running on the first poll.
3475 IMPORT [STD]
3476 LET $t: HANDLE = ASYNC { SLEEP 30s }
3477 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)
3478 ASSERT_EQ $m.state "running"
3479 ASSERT_EQ $m.ok true
3480 # Clean up the sleeper so the run ends promptly.
3481 CANCEL $t
3482 "###
3483)]
3484#[example(
3485 name = "finished poll",
3486 code = r###"
3487 # A finished task reports its value and final tails, then still awaits.
3488 IMPORT [STD]
3489 LET $t: HANDLE = ASYNC { ECHO "hi"; SLEEP 1s; RETURN "done" }
3490 # Do other work while the task runs; poll once it should be done.
3491 SLEEP 2s
3492 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)
3493 ASSERT_EQ $m.state "finished"
3494 ASSERT_EQ $m.result "done"
3495 LET $o: STRING = AWAIT $t
3496 ASSERT_EQ $o "done"
3497 "###
3498)]
3499fn task_poll<P: ProcessManager>(
3500 cx: &mut StepCtx<P>,
3501 task: HandleValue,
3503) -> Result<Value> {
3504 let entry =
3505 super::handlers::resolve_task_entry_by_id(task.0, &format!("TASK_POLL({})", task.0), cx)?;
3506 let obs = entry.observe_completion();
3507 let (stdout_tail, stderr_tail, dropped) = entry.snapshot_tails();
3508 let mut out = BTreeMap::new();
3509 out.insert(
3510 "state".to_string(),
3511 Value::string(if obs.running { "running" } else { "finished" }.to_string()),
3512 );
3513 out.insert("ok".to_string(), Value::bool(obs.ok));
3514 if !obs.running {
3515 out.insert("exit_code".to_string(), Value::int(obs.exit_code));
3516 }
3517 if let Some(result) = obs.result {
3518 out.insert("result".to_string(), result);
3519 }
3520 if !obs.error.is_empty() {
3521 out.insert("error".to_string(), Value::string(obs.error));
3522 }
3523 out.insert("stdout_tail".to_string(), Value::string(stdout_tail));
3524 out.insert("stderr_tail".to_string(), Value::string(stderr_tail));
3525 out.insert(
3526 "truncated_bytes".to_string(),
3527 Value::int(dropped.min(i64::MAX as u64) as i64),
3528 );
3529 Ok(Value::map(out))
3530}
3531
3532fn meta_to_value(meta: &FuncMeta) -> Value {
3533 let mut map = BTreeMap::new();
3534 map.insert("name".to_string(), Value::string(meta.name.clone()));
3535 map.insert("module".to_string(), Value::string(meta.module.clone()));
3536 map.insert(
3537 "kind".to_string(),
3538 Value::string(meta.kind.label().to_string()),
3539 );
3540 let params = match &meta.params {
3541 Some(params) => Value::list(
3542 params
3543 .iter()
3544 .map(|p| {
3545 let mut entry = BTreeMap::new();
3546 entry.insert("name".to_string(), Value::string(p.name.clone()));
3547 entry.insert(
3548 "param_type".to_string(),
3549 Value::string(
3550 p.param_type
3551 .as_ref()
3552 .map(render_structural)
3553 .unwrap_or_default(),
3554 ),
3555 );
3556 entry.insert(
3557 "allowed".to_string(),
3558 Value::string(
3559 p.allowed
3560 .map(|values| values.join(", "))
3561 .unwrap_or_default(),
3562 ),
3563 );
3564 entry.insert("docs".to_string(), Value::string(String::new()));
3565 entry.insert("optional".to_string(), Value::bool(p.optional));
3566 entry.insert(
3567 "options".to_string(),
3568 match p.options {
3569 Some(keys) => Value::list(
3570 keys.iter()
3571 .map(|key| {
3572 let mut option = BTreeMap::new();
3573 option.insert(
3574 "name".to_string(),
3575 Value::string(key.name.to_string()),
3576 );
3577 option.insert(
3578 "value_type".to_string(),
3579 Value::string(render_structural(&key.value)),
3580 );
3581 option.insert(
3582 "required".to_string(),
3583 Value::bool(key.required),
3584 );
3585 option.insert(
3586 "default".to_string(),
3587 Value::string(
3588 key.default.unwrap_or_default().to_string(),
3589 ),
3590 );
3591 Value::map(option)
3592 })
3593 .collect(),
3594 ),
3595 None => Value::string(String::new()),
3596 },
3597 );
3598 Value::map(entry)
3599 })
3600 .collect(),
3601 ),
3602 None => Value::list(Vec::new()),
3606 };
3607 map.insert("params".to_string(), params);
3608 map.insert(
3609 "returns".to_string(),
3610 Value::string(
3611 meta.returns
3612 .as_ref()
3613 .map(render_structural)
3614 .unwrap_or_default(),
3615 ),
3616 );
3617 map.insert("rpn".to_string(), Value::bool(meta.rpn));
3618 map.insert(
3619 "summary".to_string(),
3620 Value::string(meta.summary.to_string()),
3621 );
3622 Value::map(map)
3623}
3624
3625#[derive(Debug, Clone)]
3629pub struct RecordSchema {
3630 pub name: &'static str,
3631 pub fields: std::sync::Arc<[Field]>,
3632}
3633
3634#[derive(Clone)]
3638pub struct HostModule<P: ProcessManager> {
3639 pub name: String,
3640 pub funcs: Vec<HostRegistration<P>>,
3641 pub types: Vec<&'static TypeDescriptor>,
3642 pub record_schemas: Vec<RecordSchema>,
3643 pub states: Vec<ModuleState>,
3650}
3651
3652#[derive(Clone)]
3656pub struct ModuleState {
3657 id: std::any::TypeId,
3658 state: std::sync::Arc<dyn std::any::Any + Send + Sync>,
3659}
3660
3661pub type PreRunInspector = dyn Fn(&[Step]) -> Result<()> + Send + Sync;
3665
3666#[derive(Clone)]
3672pub struct PreRunCheck {
3673 check: Arc<PreRunInspector>,
3674}
3675
3676impl PreRunCheck {
3677 pub fn new(check: impl Fn(&[Step]) -> Result<()> + Send + Sync + 'static) -> Self {
3679 Self {
3680 check: Arc::new(check),
3681 }
3682 }
3683
3684 pub fn run(&self, steps: &[Step]) -> Result<()> {
3686 (self.check)(steps)
3687 }
3688}
3689
3690impl<P: ProcessManager> HostModule<P> {
3691 pub fn with_state<T: Send + Sync + 'static>(mut self, state: std::sync::Arc<T>) -> Self {
3694 self.states.push(ModuleState {
3695 id: std::any::TypeId::of::<T>(),
3696 state,
3697 });
3698 self
3699 }
3700
3701 pub fn check_pre_run(&self, steps: &[Step]) -> Result<()> {
3705 for state in &self.states {
3706 if let Some(check) = state.state.downcast_ref::<PreRunCheck>() {
3707 check.run(steps)?;
3708 }
3709 }
3710 Ok(())
3711 }
3712}
3713
3714impl<P: ProcessManager> ExecState<P> {
3715 pub fn register_module(&mut self, module: HostModule<P>) {
3718 for registration in module.funcs {
3719 match registration {
3720 HostRegistration::Stateful { name, meta, func } => {
3721 self.functions.register_host(&module.name, name, meta, func);
3722 }
3723 HostRegistration::Pure { name, meta, func } => {
3724 self.functions
3725 .register_pure_host(&module.name, name, meta, func);
3726 }
3727 HostRegistration::Both {
3728 name,
3729 meta,
3730 func,
3731 template,
3732 } => {
3733 self.functions
3734 .register_both_host(&module.name, name, meta, func, template);
3735 }
3736 }
3737 }
3738 for descriptor in module.types {
3739 self.register_type(descriptor);
3740 }
3741 for schema in module.record_schemas {
3742 self.register_record_schema(schema.name, schema.fields);
3743 }
3744 for state in module.states {
3745 self.module_states
3746 .insert((module.name.clone(), state.id), state.state);
3747 }
3748 }
3749
3750 pub fn list_functions(&self) -> Vec<FuncMeta> {
3752 let mut out: Vec<FuncMeta> = self.functions.entries_metas().into_iter().collect();
3753 if !out.iter().any(|m| m.name == KEYWORD_INSPECT) {
3755 out.push(FuncMeta {
3756 name: KEYWORD_INSPECT.to_string(),
3757 module: STD_MODULE_NAME.to_string(),
3758 kind: FuncKind::HostCtx,
3759 params: None,
3760 returns: Some(TypeTag::Map),
3761 rpn: false,
3762 summary: "Inspect a variable binding.",
3763 docs: "INSPECT($var): dedicated AST node taking a variable, not a value.",
3764 examples: &[],
3765 });
3766 }
3767 out.sort_by(|a, b| a.name.cmp(&b.name));
3768 out
3769 }
3770
3771 pub fn describe_function(&self, name: &str) -> Option<Value> {
3773 if let Some(meta) = self.functions.meta(name) {
3774 return Some(meta_to_value(&meta));
3775 }
3776 if name == KEYWORD_INSPECT {
3778 return Some(meta_to_value(&FuncMeta {
3779 name: KEYWORD_INSPECT.to_string(),
3780 module: STD_MODULE_NAME.to_string(),
3781 kind: FuncKind::HostCtx,
3782 params: None,
3783 returns: Some(TypeTag::Map),
3784 rpn: false,
3785 summary: "Inspect a variable binding.",
3786 docs: "INSPECT($var): dedicated AST node taking a variable, not a value.",
3787 examples: &[],
3788 }));
3789 }
3790 None
3791 }
3792
3793 pub(super) fn clone_native_pure(&self, name: &str) -> Option<PureFn> {
3794 self.functions.clone_pure_fn(name)
3795 }
3796
3797 pub fn pure_function_table(&self) -> Arc<PureTable> {
3802 self.functions.pure_shared()
3803 }
3804
3805 pub(super) fn clone_native_ctx(&self, name: &str) -> Option<NativeFn<P>> {
3806 self.functions.clone_ctx_fn(name)
3807 }
3808
3809 pub(super) fn native_meta(&self, name: &str) -> Option<FuncMeta> {
3810 self.functions.meta(name)
3811 }
3812}
3813
3814#[cfg(test)]
3815mod tests {
3816 use super::*;
3817
3818 #[test]
3819 fn placeholder_resolver_dispatches_table_entries() {
3820 let echo: PureFn = Arc::new(|args| {
3824 args.into_iter()
3825 .next()
3826 .ok_or_else(|| anyhow::anyhow!("ECHO needs 1 arg"))
3827 });
3828 let mut entries = HashMap::new();
3829 entries.insert("ECHO".to_string(), echo);
3830 let mut table = PureTable::new();
3831 table.insert("T".to_string(), entries);
3832 let resolve = placeholder_resolver(Arc::new(table));
3833 let out = resolve("T", "ECHO", vec![Value::string("hi".to_string())]).expect("dispatch");
3834 assert_eq!(out.as_str().expect("string"), "hi");
3835 let err = format!(
3836 "{:#}",
3837 resolve("T", "NOPE", vec![]).expect_err("unknown must fail")
3838 );
3839 assert!(
3840 err.contains("unknown placeholder function 'T::NOPE'"),
3841 "names the call: {err}"
3842 );
3843 assert!(
3844 err.contains("known functions: T::ECHO"),
3845 "lists known names: {err}"
3846 );
3847 }
3848
3849 #[test]
3850 fn describe_entry_renders_union_spellings() {
3851 let union = oxdock_parser::union_tag!(String, Pipe);
3857 let meta = FuncMeta {
3858 name: "T::F".to_string(),
3859 module: "T".to_string(),
3860 kind: FuncKind::HostPure,
3861 params: Some(vec![FuncParam {
3862 name: "text".to_string(),
3863 param_type: Some(union.clone()),
3864 allowed: None,
3865 docs: "",
3866 options: None,
3867 optional: false,
3868 }]),
3869 returns: Some(union),
3870 rpn: false,
3871 summary: "test-only",
3872 docs: "test-only",
3873 examples: &[],
3874 };
3875 let value = meta_to_value(&meta);
3876 let map = value.as_map().expect("describe value is a map");
3877 let params = map
3878 .get("params")
3879 .expect("params key")
3880 .as_list()
3881 .expect("params is a list");
3882 let first = params[0].as_map().expect("entry is a map");
3883 assert_eq!(
3884 first.get("param_type").and_then(Value::as_str),
3885 Some("STRING|PIPE"),
3886 "param renders the set"
3887 );
3888 assert_eq!(
3889 map.get("returns").and_then(Value::as_str),
3890 Some("STRING|PIPE"),
3891 "returns render the set"
3892 );
3893 }
3894
3895 #[test]
3896 fn describe_entry_carries_optional_flag() {
3897 let meta = FuncMeta {
3901 name: "T::F".to_string(),
3902 module: "T".to_string(),
3903 kind: FuncKind::HostPure,
3904 params: Some(vec![
3905 FuncParam {
3906 name: "url".to_string(),
3907 param_type: Some(TypeTag::String),
3908 allowed: None,
3909 docs: "",
3910 options: None,
3911 optional: false,
3912 },
3913 FuncParam {
3914 name: "options".to_string(),
3915 param_type: Some(TypeTag::Map),
3916 allowed: None,
3917 docs: "",
3918 options: None,
3919 optional: true,
3920 },
3921 ]),
3922 returns: Some(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 let params = map
3931 .get("params")
3932 .expect("params key")
3933 .as_list()
3934 .expect("params is a list");
3935 assert_eq!(params.len(), 2);
3936 let first = params[0].as_map().expect("entry is a map");
3937 let second = params[1].as_map().expect("entry is a map");
3938 assert_eq!(
3939 first.get("optional").and_then(Value::as_bool),
3940 Some(false),
3941 "required param must read false"
3942 );
3943 assert_eq!(
3944 second.get("optional").and_then(Value::as_bool),
3945 Some(true),
3946 "omittable param must read true"
3947 );
3948 }
3949
3950 #[test]
3951 fn template_twins_mirror_string_paths_and_refuse_pipes() {
3952 let pipe = Value::pipe_fresh();
3958 type TwinCase = (&'static str, Box<dyn Fn() -> Result<Value>>);
3959 let cases: Vec<TwinCase> = vec![
3960 (
3961 "TEXT_TRIM",
3962 Box::new(|| text_trim_string(Value::string(" hello ".to_string()))),
3963 ),
3964 (
3965 "TEXT_TRIM_PREFIX",
3966 Box::new(|| {
3967 text_trim_prefix_string(Value::string("v1".to_string()), "v".to_string())
3968 }),
3969 ),
3970 (
3971 "TEXT_TRIM_SUFFIX",
3972 Box::new(|| {
3973 text_trim_suffix_string(Value::string("a.gz".to_string()), "x".to_string())
3974 }),
3975 ),
3976 (
3977 "TEXT_TO_UPPER",
3978 Box::new(|| text_to_upper_string(Value::string("hi".to_string()))),
3979 ),
3980 (
3981 "TEXT_TO_LOWER",
3982 Box::new(|| text_to_lower_string(Value::string("HI".to_string()))),
3983 ),
3984 (
3985 "TEXT_REPLACE",
3986 Box::new(|| {
3987 text_replace_string(
3988 Value::string("ab".to_string()),
3989 "b".to_string(),
3990 "c".to_string(),
3991 )
3992 }),
3993 ),
3994 (
3995 "TEXT_REPLACE_REGEX",
3996 Box::new(|| {
3997 text_replace_regex_string(
3998 Value::string("ab".to_string()),
3999 "b".to_string(),
4000 "c".to_string(),
4001 )
4002 }),
4003 ),
4004 ];
4005 assert_eq!(cases.len(), 7, "every mirror op needs a twin row");
4006 for (name, run) in &cases {
4007 let value = run().unwrap_or_else(|e| panic!("{name} twin must answer strings: {e:#}"));
4008 assert!(
4009 value.as_str().is_some(),
4010 "{name} twin must answer STRING, got {}",
4011 value.type_name()
4012 );
4013 }
4014 assert_eq!(
4015 text_trim_string(Value::string(" hello ".to_string()))
4016 .expect("trim twin")
4017 .as_str(),
4018 Some("hello")
4019 );
4020 let pipe_cases: Vec<(&str, Result<Value>)> = vec![
4022 ("TEXT_TRIM", text_trim_string(pipe.clone())),
4023 (
4024 "TEXT_TRIM_PREFIX",
4025 text_trim_prefix_string(pipe.clone(), "v".to_string()),
4026 ),
4027 (
4028 "TEXT_TRIM_SUFFIX",
4029 text_trim_suffix_string(pipe.clone(), ".gz".to_string()),
4030 ),
4031 ("TEXT_TO_UPPER", text_to_upper_string(pipe.clone())),
4032 ("TEXT_TO_LOWER", text_to_lower_string(pipe.clone())),
4033 (
4034 "TEXT_REPLACE",
4035 text_replace_string(pipe.clone(), "a".to_string(), "b".to_string()),
4036 ),
4037 (
4038 "TEXT_REPLACE_REGEX",
4039 text_replace_regex_string(pipe.clone(), "a".to_string(), "b".to_string()),
4040 ),
4041 ];
4042 for (name, result) in pipe_cases {
4043 let err = result.expect_err(&format!("{name} twin must refuse PIPE"));
4044 assert!(
4045 format!("{err:#}").contains("step IO"),
4046 "{name} refusal names the missing context: {err:#}"
4047 );
4048 }
4049 }
4050
4051 #[test]
4052 fn shell_words_join_split_round_trip() {
4053 let words = vec![
4057 "gh".to_string(),
4058 "issue".to_string(),
4059 "comment".to_string(),
4060 "with spaces".to_string(),
4061 "it's".to_string(),
4062 "say \"hi\"".to_string(),
4063 "$HOME".to_string(),
4064 "$(whoami)".to_string(),
4065 "C:\\path\\to".to_string(),
4066 "naïve café".to_string(),
4067 "".to_string(),
4068 ];
4069 let joined = shell_words::join(&words);
4070 let back = shell_words::split(&joined).expect("join output must parse");
4071 assert_eq!(back, words);
4072 assert!(shell_words::split("unbalanced \"quote").is_err());
4073 }
4074}