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 struct FunctionRegistry<P: ProcessManager> {
310 entries: HashMap<String, FuncEntry<P>>,
311 scopes: Vec<ScopeFrame<P>>,
312 pure_shared: Arc<PureTable>,
313 script_docs: HashMap<String, (String, String)>,
317}
318
319impl<P: ProcessManager> FunctionRegistry<P> {
320 pub(super) fn with_builtins() -> Self {
321 let mut reg = Self {
322 entries: HashMap::new(),
323 pure_shared: Arc::new(HashMap::new()),
324 script_docs: HashMap::new(),
325 scopes: vec![ScopeFrame {
326 defined: HashSet::new(),
327 shadowed: Vec::new(),
328 }],
329 };
330 for host in Self::builtin_registrations() {
334 match host {
335 HostRegistration::Stateful { name, meta, func } => {
336 reg.insert_qualified(STD_MODULE_NAME, name, meta, FuncBody::Ctx(func));
337 }
338 HostRegistration::Pure { name, meta, func } => {
339 reg.insert_qualified(STD_MODULE_NAME, name, meta, FuncBody::Pure(func));
340 }
341 HostRegistration::Both {
342 name,
343 meta,
344 func,
345 template,
346 } => {
347 reg.insert_qualified(
348 STD_MODULE_NAME,
349 name,
350 meta,
351 FuncBody::Both {
352 pure: template,
353 ctx: func,
354 },
355 );
356 }
357 }
358 }
359 reg
360 }
361
362 pub(super) fn builtin_registrations() -> Vec<HostRegistration<P>> {
367 vec![
368 Int::registration(),
369 Float::registration(),
370 BoolConvert::registration(),
371 BoolOr::registration(),
372 FormatByteCount::registration(),
373 ParseByteCount::registration(),
374 FormatDuration::registration(),
375 ParseDuration::registration(),
376 Types::registration(),
377 TypeDescribe::registration(),
378 Glob::registration(),
379 LoadToml::registration(),
380 LoadJson::registration(),
381 HashSha256::registration(),
382 Cwd::registration(),
383 ParseToml::registration(),
384 ParseJson::registration(),
385 PathType::registration(),
386 PathWritable::registration(),
387 IsExec::registration(),
388 HasKey::registration(),
389 MapSet::registration(),
390 MergeMaps::registration(),
391 Base64Encode::registration(),
392 Base64Decode::registration(),
393 Rand::registration(),
394 ToJson::registration(),
395 TypeOf::registration(),
396 Functions::registration(),
397 Describe::registration(),
398 IsMain::registration(),
399 IsTerminal::registration(),
400 Eof::registration(),
401 TaskPoll::registration(),
402 Version::registration(),
403 Interpreter::registration(),
404 TextTrim::registration(),
405 TextTrimPrefix::registration(),
406 TextTrimSuffix::registration(),
407 PathJoin::registration(),
408 TextToUpper::registration(),
409 TextToLower::registration(),
410 TextReplace::registration(),
411 TextReplaceRegex::registration(),
412 TextSplit::registration(),
413 TextJoin::registration(),
414 TextLines::registration(),
415 TextFields::registration(),
416 TextMatch::registration(),
417 TextExtract::registration(),
418 TextStartsWith::registration(),
419 TextEndsWith::registration(),
420 TextContains::registration(),
421 TextLength::registration(),
422 TextCount::registration(),
423 TextCountMatches::registration(),
424 TextGrep::registration(),
425 TextLinesRange::registration(),
426 SemaphoreNew::registration(),
427 SemaphoreTryAcquire::registration(),
428 SemaphoreAvailable::registration(),
429 ShellSplitArgs::registration(),
430 ShellJoinArgs::registration(),
431 ]
432 }
433
434 pub(super) fn keys(&self) -> HashSet<String> {
437 self.entries.keys().cloned().collect()
438 }
439
440 pub(super) fn get(&self, name: &str) -> Option<FuncEntry<P>> {
442 self.entries.get(name).cloned()
443 }
444
445 fn insert_native(&mut self, name: String, meta: FuncMeta, body: FuncBody<P>) {
446 self.entries.insert(name, FuncEntry { meta, body });
447 self.rebuild_pure_shared();
448 }
449
450 fn rebuild_pure_shared(&mut self) {
456 let mut table: PureTable = HashMap::new();
457 for (name, entry) in &self.entries {
458 let func = match &entry.body {
459 FuncBody::Pure(func) => func,
460 FuncBody::Both { pure, .. } => pure,
461 FuncBody::Script(_) | FuncBody::Ctx(_) => continue,
462 };
463 if let Some((module, base)) = split_qualified(name) {
464 table
465 .entry(module.to_string())
466 .or_default()
467 .insert(base.to_string(), Arc::clone(func));
468 }
469 }
470 self.pure_shared = Arc::new(table);
471 }
472
473 fn insert_qualified(
477 &mut self,
478 module: &str,
479 base: String,
480 mut meta: FuncMeta,
481 body: FuncBody<P>,
482 ) {
483 meta.name = qualify(module, &base);
484 meta.module = module.to_string();
485 if self.entries.contains_key(&meta.name) {
490 panic!("duplicate function registration `{}`", meta.name);
491 }
492 self.insert_native(meta.name.clone(), meta, body);
493 }
494
495 pub(super) fn register_host(
496 &mut self,
497 module: &str,
498 name: String,
499 mut meta: FuncMeta,
500 func: NativeFn<P>,
501 ) {
502 meta.kind = FuncKind::HostCtx;
503 self.insert_qualified(module, name, meta, FuncBody::Ctx(func));
504 }
505
506 pub(super) fn register_pure_host(
507 &mut self,
508 module: &str,
509 name: String,
510 mut meta: FuncMeta,
511 func: PureFn,
512 ) {
513 meta.kind = FuncKind::HostPure;
514 self.insert_qualified(module, name, meta, FuncBody::Pure(func));
515 }
516
517 pub(super) fn register_both_host(
518 &mut self,
519 module: &str,
520 name: String,
521 mut meta: FuncMeta,
522 func: NativeFn<P>,
523 template: PureFn,
524 ) {
525 meta.kind = FuncKind::HostCtx;
526 self.insert_qualified(
527 module,
528 name,
529 meta,
530 FuncBody::Both {
531 pure: template,
532 ctx: func,
533 },
534 );
535 }
536
537 pub(super) fn define_script(
542 &mut self,
543 name: &str,
544 params: &[(String, TypeTag)],
545 body: &[Step],
546 module: Option<&str>,
547 ) -> Result<()> {
548 let qualified = qualify(SCRIPT_MODULE_NAME, name);
549 let shadowable = matches!(
550 self.entries.get(&qualified).map(|entry| &entry.body),
551 Some(FuncBody::Script(_))
552 );
553 let reserved = self.entries.iter().any(|(key, entry)| {
558 split_qualified(key).is_some_and(|(_, base)| base == name)
559 && !matches!(entry.body, FuncBody::Script(_))
560 });
561 if reserved && !shadowable {
562 anyhow::bail!("cannot shadow reserved function `{name}`");
563 }
564 if self
565 .scopes
566 .last()
567 .is_some_and(|frame| frame.defined.contains(&qualified))
568 {
569 anyhow::bail!("duplicate function `{name}` in same scope");
570 }
571 let old = self.entries.insert(
572 qualified.clone(),
573 FuncEntry {
574 meta: FuncMeta {
575 name: qualified.clone(),
576 module: SCRIPT_MODULE_NAME.to_string(),
577 kind: FuncKind::Script,
578 params: Some(
579 params
580 .iter()
581 .map(|(name, param_type)| FuncParam {
582 name: name.clone(),
583 param_type: Some(param_type.clone()),
584 allowed: None,
585 docs: "",
588 options: None,
589 optional: false,
590 })
591 .collect(),
592 ),
593 returns: None,
594 rpn: false,
595 summary: "DSL-defined function.",
596 docs: "Defined via FUNC in script.",
597 examples: &[],
598 },
599 body: FuncBody::Script(FuncDefData {
600 params: params.to_vec(),
601 body: body.to_vec(),
602 module: module.map(|m| m.to_string()),
603 }),
604 },
605 );
606 if let Some(frame) = self.scopes.last_mut() {
607 frame.defined.insert(qualified.clone());
608 if let Some(old) = old {
609 frame.shadowed.push((qualified, old));
610 }
611 }
612 Ok(())
613 }
614
615 pub(super) fn define_aliased_in(
623 &mut self,
624 depth: usize,
625 alias: &str,
626 name: &str,
627 params: &[(String, TypeTag)],
628 body: &[Step],
629 module: Option<&str>,
630 ) -> Result<()> {
631 let qualified = qualify(alias, name);
632 let shadowable = matches!(
633 self.entries.get(&qualified).map(|entry| &entry.body),
634 Some(FuncBody::Script(_))
635 );
636 let reserved = self.entries.iter().any(|(key, entry)| {
640 split_qualified(key).is_some_and(|(_, base)| base == name)
641 && !matches!(entry.body, FuncBody::Script(_))
642 });
643 if reserved && !shadowable {
644 anyhow::bail!("cannot shadow reserved function `{name}`");
645 }
646 let depth_in_range = depth < self.scopes.len();
650 let frame_idx = if depth_in_range {
651 depth
652 } else {
653 self.scopes.len().saturating_sub(1)
654 };
655 if self
656 .scopes
657 .get(frame_idx)
658 .is_some_and(|frame| frame.defined.contains(&qualified))
659 {
660 anyhow::bail!("duplicate function `{name}` in same scope");
661 }
662 let old = self.entries.insert(
663 qualified.clone(),
664 FuncEntry {
665 meta: FuncMeta {
666 name: qualified.clone(),
667 module: alias.to_string(),
668 kind: FuncKind::Script,
669 params: Some(
670 params
671 .iter()
672 .map(|(name, param_type)| FuncParam {
673 name: name.clone(),
674 param_type: Some(param_type.clone()),
675 allowed: None,
676 docs: "",
677 options: None,
678 optional: false,
679 })
680 .collect(),
681 ),
682 returns: None,
683 rpn: false,
684 summary: "DSL-defined function.",
685 docs: "Defined via FUNC in an imported script.",
686 examples: &[],
687 },
688 body: FuncBody::Script(FuncDefData {
689 params: params.to_vec(),
690 body: body.to_vec(),
691 module: module.map(|m| m.to_string()),
692 }),
693 },
694 );
695 if let Some(frame) = self.scopes.get_mut(frame_idx) {
696 frame.defined.insert(qualified.clone());
697 if let Some(old) = old {
698 frame.shadowed.push((qualified, old));
699 }
700 }
701 Ok(())
702 }
703
704 pub(super) fn scope_depth(&self) -> usize {
707 self.scopes.len()
708 }
709
710 pub(super) fn push_scope(&mut self) {
713 self.scopes.push(ScopeFrame {
714 defined: HashSet::new(),
715 shadowed: Vec::new(),
716 });
717 }
718
719 pub(super) fn pop_scope(&mut self) {
722 let Some(frame) = self.scopes.pop() else {
723 return;
724 };
725 for name in frame.defined {
726 self.entries.remove(&name);
727 }
728 for (name, old) in frame.shadowed {
729 self.entries.insert(name, old);
730 }
731 }
732
733 pub(super) fn contains_script(&self, name: &str) -> bool {
737 matches!(
738 self.entries.get(name).map(|entry| &entry.body),
739 Some(FuncBody::Script(_))
740 )
741 }
742
743 fn clone_pure_fn(&self, name: &str) -> Option<PureFn> {
747 match self.entries.get(name)?.body {
748 FuncBody::Pure(ref func) => Some(Arc::clone(func)),
749 FuncBody::Both { ref pure, .. } => Some(Arc::clone(pure)),
750 _ => None,
751 }
752 }
753
754 pub(super) fn pure_shared(&self) -> Arc<PureTable> {
758 Arc::clone(&self.pure_shared)
759 }
760
761 pub(super) fn all_metas(&self) -> Vec<FuncMeta> {
764 self.entries_metas()
765 }
766
767 fn clone_ctx_fn(&self, name: &str) -> Option<NativeFn<P>> {
772 match self.entries.get(name)?.body {
773 FuncBody::Ctx(ref func) => Some(Arc::clone(func)),
774 FuncBody::Both { ref ctx, .. } => Some(Arc::clone(ctx)),
775 _ => None,
776 }
777 }
778
779 fn meta(&self, name: &str) -> Option<FuncMeta> {
780 self.entries.get(name).map(|entry| entry.meta.clone())
781 }
782
783 fn native_metas(&self) -> Vec<FuncMeta> {
784 let mut out: Vec<FuncMeta> = Vec::new();
785 for entry in self.entries.values() {
786 if !matches!(entry.body, FuncBody::Script(_)) {
787 out.push(entry.meta.clone());
788 }
789 }
790 out.sort_by(|a, b| a.name.cmp(&b.name));
791 out
792 }
793
794 fn entries_metas(&self) -> Vec<FuncMeta> {
797 let mut out: Vec<FuncMeta> = self
798 .entries
799 .values()
800 .map(|entry| entry.meta.clone())
801 .collect();
802 out.sort_by(|a, b| a.name.cmp(&b.name));
803 out
804 }
805
806 pub fn set_script_docs(&mut self, docs: &HashMap<String, (String, String)>) {
809 for (base, pair) in docs {
810 self.script_docs
811 .insert(qualify(SCRIPT_MODULE_NAME, base), pair.clone());
812 }
813 }
814
815 pub fn script_doc_for(&self, qualified: &str) -> Option<(String, String)> {
817 self.script_docs.get(qualified).cloned()
818 }
819
820 pub fn exported_metas(&self, func_exports: &[String]) -> anyhow::Result<Vec<FuncMeta>> {
823 let mut out = Vec::with_capacity(func_exports.len());
824 for name in func_exports {
825 let qualified = match name.split_once("::") {
829 None => qualify(SCRIPT_MODULE_NAME, name),
830 Some(_) => name.clone(),
831 };
832 match self.entries.get(&qualified) {
833 Some(entry) => out.push(entry.meta.clone()),
834 None => anyhow::bail!(
835 "EXPORT `{name}` matches no defined script function or known host function"
836 ),
837 }
838 }
839 Ok(out)
840 }
841}
842
843impl<P: ProcessManager> Clone for FunctionRegistry<P> {
844 fn clone(&self) -> Self {
845 Self {
846 entries: self.entries.clone(),
847 scopes: self.scopes.clone(),
848 pure_shared: Arc::clone(&self.pure_shared),
849 script_docs: self.script_docs.clone(),
850 }
851 }
852}
853
854pub fn builtin_function_names() -> HashSet<String> {
861 let mut names = FunctionRegistry::<DefaultProcessManager>::with_builtins().keys();
862 names.insert(KEYWORD_INSPECT.to_string());
863 names
864}
865
866pub fn builtin_function_metas() -> Vec<FuncMeta> {
870 FunctionRegistry::<DefaultProcessManager>::with_builtins().native_metas()
871}
872
873pub fn std_module_table() -> oxdock_parser::ModuleTable {
878 let func_names: HashSet<String> = builtin_function_metas()
880 .into_iter()
881 .map(|meta| base_name(&meta.name).to_string())
882 .collect();
883 oxdock_parser::ModuleTable {
884 modules: HashMap::from([(
885 STD_MODULE_NAME.to_string(),
886 Some(oxdock_parser::ModuleFuncs { func_names }),
887 )]),
888 }
889}
890
891#[oxdock_func(pure, returns = TypeTag::Int)]
904#[example(
905 name = "convert",
906 code = r###"
907 IMPORT [STD]
908 LET $n: INT = INT("42")
909 ASSERT_EQ $n 42
910 LET $flag: INT = INT(true)
911 ASSERT_EQ $flag 1
912 "###
913)]
914fn int(
915 #[union(Int, Float, String, Bool)]
917 val: Value,
918) -> Result<Value> {
919 super::args::int_from_value(val)
920}
921
922#[oxdock_func(pure, returns = TypeTag::Float)]
927#[example(
928 name = "convert",
929 code = r###"
930 IMPORT [STD]
931 LET $f: FLOAT = FLOAT("1.5")
932 ASSERT_EQ $f 1.5
933 LET $whole: FLOAT = FLOAT(2)
934 ASSERT_EQ $whole 2.0
935 "###
936)]
937fn float(
938 #[union(Float, Int, String)]
940 val: Value,
941) -> Result<Value> {
942 super::args::float_from_value(val)
943}
944
945#[oxdock_func(pure, returns = TypeTag::String)]
950#[example(
951 name = "format and round-trip",
952 code = r###"
953 # Byte counts render in the largest exact unit.
954 IMPORT [STD]
955 LET $pretty: STRING = FORMAT_BYTE_COUNT(1_048_576)
956 ASSERT_EQ $pretty "1MiB"
957
958 # The pair round-trips through the parser.
959 LET $back: INT = PARSE_BYTE_COUNT($pretty)
960 ASSERT_EQ $back 1_048_576
961 "###
962)]
963fn format_byte_count(
964 bytes: i64,
966) -> Result<Value> {
967 if bytes < 0 {
968 return Err(anyhow::anyhow!(
969 "FORMAT_BYTE_COUNT needs a non-negative byte count, got {bytes}"
970 ));
971 }
972 Ok(Value::string(oxdock_parser::command::format_byte_count(
973 bytes as u64,
974 )))
975}
976
977#[oxdock_func(pure, returns = TypeTag::Int)]
1012#[example(
1013 name = "parse",
1014 code = r###"
1015 IMPORT [STD]
1016 LET $n: INT = PARSE_BYTE_COUNT("10KB")
1017 ASSERT_EQ $n 10_000
1018 LET $identity: INT = PARSE_BYTE_COUNT(512)
1019 ASSERT_EQ $identity 512
1020 "###
1021)]
1022fn parse_byte_count(
1023 #[union(Int, Float, String)]
1025 text: Value,
1026) -> Result<Value> {
1027 if let Some(n) = text.as_i64() {
1028 if n < 0 {
1029 return Err(anyhow::anyhow!(
1030 "PARSE_BYTE_COUNT needs a non-negative byte count, got {n}"
1031 ));
1032 }
1033 return Ok(Value::int(n));
1034 }
1035 if let Some(f) = text.as_f64() {
1036 if f.is_finite() && f.fract() == 0.0 && f >= 0.0 && f <= i64::MAX as f64 {
1037 return Ok(Value::int(f as i64));
1038 }
1039 return Err(anyhow::anyhow!(
1040 "PARSE_BYTE_COUNT needs an integral byte count, got {f:?}"
1041 ));
1042 }
1043 let Some(s) = text.as_str() else {
1044 return Err(anyhow::anyhow!(
1045 "PARSE_BYTE_COUNT needs a token or number, found {text:?}"
1046 ));
1047 };
1048 let n = oxdock_parser::command::parse_byte_count(s)?;
1049 let n = i64::try_from(n)
1050 .map_err(|_| anyhow::anyhow!("PARSE_BYTE_COUNT out of INT range: {s:?}"))?;
1051 Ok(Value::int(n))
1052}
1053
1054#[oxdock_func(pure, returns = TypeTag::String)]
1059#[example(
1060 name = "format and round-trip",
1061 code = r###"
1062 # Durations render in the largest exact unit.
1063 IMPORT [STD]
1064 LET $pretty: STRING = FORMAT_DURATION(90_000)
1065 ASSERT_EQ $pretty "90s"
1066
1067 # The pair round-trips through the parser.
1068 LET $back: INT = PARSE_DURATION($pretty)
1069 ASSERT_EQ $back 90_000
1070 "###
1071)]
1072fn format_duration(
1073 millis: i64,
1075) -> Result<Value> {
1076 if millis < 0 {
1077 return Err(anyhow::anyhow!(
1078 "FORMAT_DURATION needs non-negative milliseconds, got {millis}"
1079 ));
1080 }
1081 Ok(Value::string(oxdock_parser::command::format_duration(
1082 &std::time::Duration::from_millis(millis as u64),
1083 )))
1084}
1085
1086#[oxdock_func(pure, returns = TypeTag::Int)]
1092#[example(
1093 name = "parse",
1094 code = r###"
1095 # A bare number means seconds, like TIMEOUT.
1096 IMPORT [STD]
1097 LET $ms: INT = PARSE_DURATION("2m")
1098 ASSERT_EQ $ms 120_000
1099
1100 # Milliseconds stay exact.
1101 LET $exact: INT = PARSE_DURATION("1500ms")
1102 ASSERT_EQ $exact 1_500
1103
1104 # One optional space separates number from unit.
1105 LET $spaced: INT = PARSE_DURATION("1 h")
1106 ASSERT_EQ $spaced 3_600_000
1107 "###
1108)]
1109fn parse_duration(
1110 text: String,
1112) -> Result<Value> {
1113 let duration = oxdock_parser::command::parse_duration(&text)?;
1114 let millis = i64::try_from(duration.as_millis())
1115 .map_err(|_| anyhow::anyhow!("PARSE_DURATION out of INT range: {text:?}"))?;
1116 Ok(Value::int(millis))
1117}
1118
1119#[oxdock_func(rpn, returns = TypeTag::ListOf(std::sync::Arc::new(TypeTag::String)))]
1124#[example(
1125 name = "match",
1126 code = r###"
1127 IMPORT [STD]
1128 WRITE "notes-a.md" "a"
1129 WRITE "notes-b.md" "b"
1130 WRITE "other.txt" "c"
1131 LET $found: LIST<STRING> = GLOB("notes-*.md")
1132 ASSERT_EQ $found.0 "notes-a.md"
1133 ASSERT_EQ $found.1 "notes-b.md"
1134 "###
1135)]
1136fn glob<P: ProcessManager>(
1137 cx: &mut StepCtx<P>,
1138 #[union(String, Path)]
1140 pattern: Value,
1141) -> Result<Value> {
1142 let text = super::args::string_or_path_text(&pattern)?;
1143 super::args::glob_from_value(&[Value::string(text)], cx)
1144}
1145
1146#[oxdock_func(rpn, returns = TypeTag::MapOf(std::sync::Arc::new(TypeTag::Any)))]
1151#[example(
1152 name = "load",
1153 code = r###"
1154 IMPORT [STD]
1155 WRITE "cfg.toml" "title = \"demo\""
1156 LET $cfg: MAP<ANY> = LOAD_TOML("cfg.toml")
1157 ASSERT_EQ $cfg.title "demo"
1158 "###
1159)]
1160fn load_toml<P: ProcessManager>(
1161 cx: &mut StepCtx<P>,
1162 #[union(String, Path)]
1164 path: Value,
1165) -> Result<Value> {
1166 let text = super::args::string_or_path_text(&path)?;
1167 super::args::load_toml_from_value(&[Value::string(text)], cx)
1168}
1169
1170#[oxdock_func(rpn, returns = TypeTag::Any)]
1178#[example(
1179 name = "load",
1180 code = r###"
1181 IMPORT [STD]
1182 WRITE "data.json" "{\"a\": 1}"
1183 LET $doc: MAP<ANY> = LOAD_JSON("data.json")
1184 ASSERT_EQ $doc.a 1
1185 "###
1186)]
1187fn load_json<P: ProcessManager>(
1188 cx: &mut StepCtx<P>,
1189 #[union(String, Path)]
1191 path: Value,
1192) -> Result<Value> {
1193 let text = super::args::string_or_path_text(&path)?;
1194 super::args::load_json_from_value(&[Value::string(text)], cx)
1195}
1196
1197#[oxdock_func(rpn, returns = TypeTag::String)]
1207#[example(
1208 name = "hash",
1209 code = r###"
1210 IMPORT [STD]
1211 WRITE payload.txt hello
1212 LET $digest: STRING = HASH_SHA256("payload.txt")
1213 ASSERT_EQ $digest "2cf24dba5fb0a30e26e83b2ac5b9e29e1b161e5c1fa7425e73043362938b9824"
1214 "###
1215)]
1216fn hash_sha256<P: ProcessManager>(
1217 cx: &mut StepCtx<P>,
1218 #[union(String, Path)]
1220 path: Value,
1221) -> Result<Value> {
1222 use sha2::Digest;
1223
1224 let text = super::args::string_or_path_text(&path)?;
1225 let target = cx.state.fs.resolve_read(&cx.state.cwd, &text)?;
1226 let mut hasher = sha2::Sha256::new();
1227 super::fs_ops::hash_path(cx.state.fs.as_ref(), &target, "", &mut hasher)?;
1228 let digest = hasher.finalize();
1229 let bytes: &[u8] = digest.as_ref();
1230 Ok(Value::string(
1231 bytes.iter().map(|b| format!("{b:02x}")).collect(),
1232 ))
1233}
1234
1235#[oxdock_func(rpn, returns = TypeTag::String)]
1246#[example(
1247 name = "cwd",
1248 code = r###"
1249 IMPORT [STD]
1250 WORKDIR sub
1251 LET $c: STRING = CWD()
1252 ASSERT_CONTAINS $c "sub"
1253 "###
1254)]
1255fn cwd<P: ProcessManager>(cx: &mut StepCtx<P>) -> Result<Value> {
1256 if cx.state.fs.is_snapshot_pending() {
1257 return Ok(Value::string(super::SNAPSHOT_PENDING_DISPLAY.to_string()));
1258 }
1259 let concrete = cx.state.fs.concretize_cwd(&cx.state.cwd);
1260 let real = super::fs_ops::canonical_cwd(cx.state.fs.as_ref(), &concrete)?;
1261 Ok(Value::string(real))
1262}
1263
1264#[oxdock_func(pure, returns = TypeTag::MapOf(std::sync::Arc::new(TypeTag::Any)))]
1270#[example(
1271 name = "parse",
1272 code = r###"
1273 IMPORT [STD]
1274 LET $doc: MAP<ANY> = PARSE_TOML("title = \"demo\"")
1275 ASSERT_EQ $doc.title "demo"
1276 "###
1277)]
1278fn parse_toml(
1279 text: String,
1281) -> Result<Value> {
1282 super::args::parse_toml_from_value(Value::string(text))
1283}
1284
1285#[oxdock_func(pure, returns = TypeTag::Any)]
1294#[example(
1295 name = "parse",
1296 code = r###"
1297 # Parse in-memory JSON text with the same conversion as file loading.
1298 IMPORT [STD]
1299 LET $body: STRING = "{\"a\": 1}"
1300 LET $doc: ANY = PARSE_JSON($body)
1301 ASSERT_EQ $doc.a 1
1302
1303 # Top-level arrays parse to LIST, which is why the return is ANY.
1304 LET $items: LIST<ANY> = PARSE_JSON("[1, 2]")
1305 ASSERT_EQ $items.0 1
1306 ASSERT_EQ $items.1 2
1307 "###
1308)]
1309fn parse_json(
1310 text: String,
1312) -> Result<Value> {
1313 super::args::parse_json_from_value(Value::string(text))
1314}
1315
1316#[oxdock_func(returns = TypeTag::String)]
1322#[example(
1323 name = "describe",
1324 code = r###"
1325 IMPORT [STD]
1326 WRITE "entry.txt" "words"
1327 LET $kind: STRING = PATH_TYPE("entry.txt")
1328 ASSERT_EQ $kind "file"
1329 LET $missing: STRING = PATH_TYPE("no-such-entry.txt")
1330 ASSERT_EQ $missing "absent"
1331 "###
1332)]
1333fn path_type<P: ProcessManager>(
1334 cx: &mut StepCtx<P>,
1335 #[union(String, Path)]
1337 path: Value,
1338) -> Result<Value> {
1339 let text = super::args::string_or_path_text(&path)?;
1340 super::args::path_type_from_value(&[Value::string(text)], cx)
1341}
1342
1343#[oxdock_func(returns = TypeTag::Bool)]
1352#[example(
1353 name = "probe",
1354 code = r###"
1355 # An absent nested path is writable when its ancestor is.
1356 IMPORT [STD]
1357 LET $fresh: BOOL = PATH_WRITABLE("probe-check/nested/file.txt")
1358 ASSERT_EQ $fresh true
1359
1360 # The empty string never aliases the working directory.
1361 LET $empty: BOOL = PATH_WRITABLE("")
1362 ASSERT_EQ $empty false
1363 "###
1364)]
1365fn path_writable<P: ProcessManager>(
1366 cx: &mut StepCtx<P>,
1367 #[union(String, Path)]
1369 path: Value,
1370) -> Result<Value> {
1371 let text = super::args::string_or_path_text(&path)?;
1372 super::args::path_writable_from_value(&[Value::string(text)], cx)
1373}
1374
1375#[oxdock_func(returns = TypeTag::Bool)]
1388#[example(
1389 name = "probe",
1390 code = r###"
1391 # Missing tools read false instead of failing the run.
1392 IMPORT [STD]
1393 LET $missing: BOOL = IS_EXEC("no-such-tool-xyz")
1394 ASSERT_EQ $missing false
1395
1396 # Plain files are not executable on any platform.
1397 WRITE tool.txt payload
1398 LET $plain: BOOL = IS_EXEC("tool.txt")
1399 ASSERT_EQ $plain false
1400 "###
1401)]
1402fn is_exec<P: ProcessManager>(
1403 cx: &mut StepCtx<P>,
1404 #[union(String, Path)]
1406 name: Value,
1407) -> Result<Value> {
1408 let text = super::args::string_or_path_text(&name)?;
1409 super::args::is_exec_from_value(&[Value::string(text)], cx)
1410}
1411
1412#[oxdock_func(pure, returns = TypeTag::Bool)]
1418#[example(
1419 name = "probe",
1420 code = r###"
1421 IMPORT [STD]
1422 LET $m: MAP<ANY> = PARSE_JSON("{\"a\": 1}")
1423 LET $hit: BOOL = HAS_KEY($m, "a")
1424 ASSERT_EQ $hit true
1425 LET $miss: BOOL = HAS_KEY($m, "b")
1426 ASSERT_EQ $miss false
1427 "###
1428)]
1429fn has_key(
1430 map: BTreeMap<String, Value>,
1432 key: String,
1434) -> Result<Value> {
1435 super::args::has_key_from_value(Value::map(map), &key)
1436}
1437
1438#[oxdock_func(pure, returns = TypeTag::MapOf(std::sync::Arc::new(TypeTag::Any)))]
1444#[example(
1445 name = "insert",
1446 code = r###"
1447 IMPORT [STD]
1448 LET $m: MAP<ANY> = MAP_SET({seed: 0}, "a", 1)
1449 ASSERT_EQ $m.a 1
1450 "###
1451)]
1452fn map_set(
1453 map: BTreeMap<String, Value>,
1455 key: String,
1457 value: Value,
1459) -> Result<Value> {
1460 super::args::map_set_from_value(Value::map(map), key, value)
1461}
1462
1463#[oxdock_func(returns = TypeTag::Float, summary = "Draw a random FLOAT uniformly from [0, 1), optionally seeded.")]
1471#[example(
1472 name = "seeded draw",
1473 code = r###"
1474 # A seed draws the same value on every run.
1475 IMPORT [STD]
1476 LET $one: FLOAT = RAND({seed: 7})
1477 LET $two: FLOAT = RAND({seed: 7})
1478 ASSERT_EQ $one $two
1479 "###
1480)]
1481#[example(
1482 name = "unseeded draw",
1483 code = r###"
1484 # Scale a unit draw into a backoff delay between 1 and 11 seconds.
1485 IMPORT [STD]
1486 LET $draw: FLOAT = RAND()
1487 LET $delay: FLOAT = 1.0 + $draw * 10.0
1488 IF $delay < 1.0 {
1489 EXIT 1
1490 }
1491 IF $delay >= 11.0 {
1492 EXIT 1
1493 }
1494 ECHO "retrying in {{ $delay }}s"
1495 "###
1496)]
1497fn rand<P: ProcessManager>(
1498 cx: &mut StepCtx<P>,
1499 #[options("seed?: INT")]
1501 #[optional]
1502 options: BTreeMap<String, Value>,
1503) -> Result<Value> {
1504 let _ = cx;
1505 let seed = options
1508 .get("seed")
1509 .map(|value| value.as_i64().expect("check_options verified INT"));
1510 super::args::rand_float_from_value(seed)
1511}
1512
1513#[oxdock_func(pure, returns = TypeTag::String)]
1519#[example(
1520 name = "encode",
1521 code = r###"
1522 # Encode text to standard base64.
1523 IMPORT [STD]
1524 LET $encoded: STRING = BASE64_ENCODE("hello")
1525 ASSERT_EQ $encoded "aGVsbG8="
1526 "###
1527)]
1528fn base64_encode(
1529 text: String,
1531) -> Result<Value> {
1532 super::args::base64_encode_from_value(Value::string(text))
1533}
1534
1535#[oxdock_func(pure, returns = TypeTag::String)]
1542#[example(
1543 name = "decode",
1544 code = r###"
1545 # Decode standard base64 back to text.
1546 IMPORT [STD]
1547 LET $decoded: STRING = BASE64_DECODE("aGVsbG8=")
1548 ASSERT_EQ $decoded "hello"
1549 "###
1550)]
1551fn base64_decode(
1552 text: String,
1554) -> Result<Value> {
1555 super::args::base64_decode_from_value(Value::string(text))
1556}
1557
1558#[oxdock_func(pure, returns = TypeTag::String)]
1565#[example(
1566 name = "encode",
1567 code = r###"
1568 IMPORT [STD]
1569 LET $json: STRING = TO_JSON({a: 1})
1570 ASSERT_EQ $json "{\"a\":1}\n"
1571 "###
1572)]
1573fn to_json(
1574 #[union(String, Int, Float, Bool, List, Map)]
1576 value: Value,
1577) -> Result<Value> {
1578 super::args::to_json_from_value(value)
1579}
1580
1581#[oxdock_func(pure, returns = TypeTag::String)]
1589#[example(
1590 name = "name the word",
1591 code = r###"
1592 IMPORT [STD]
1593 LET $word: STRING = TYPE_OF(42)
1594 ASSERT_EQ $word "INT"
1595 "###
1596)]
1597fn type_of(
1598 value: Value,
1600) -> Result<Value> {
1601 super::args::type_of_from_value(value)
1602}
1603
1604#[oxdock_func(pure, returns = TypeTag::MapOf(std::sync::Arc::new(TypeTag::Any)))]
1612#[example(
1613 name = "merge",
1614 code = r###"
1615 IMPORT [STD]
1616 LET $m: MAP<ANY> = MERGE_MAPS([{a: 1}, {b: 2}], "overwrite")
1617 ASSERT_EQ $m.a 1
1618 ASSERT_EQ $m.b 2
1619 "###
1620)]
1621fn merge_maps(
1622 maps: Vec<BTreeMap<String, Value>>,
1624 #[values("fail_on_duplicate", "overwrite")]
1626 policy: String,
1627) -> Result<Value> {
1628 super::args::merge_maps_from_value(
1629 Value::list(maps.into_iter().map(Value::map).collect()),
1630 policy,
1631 )
1632}
1633
1634#[oxdock_func(pure, returns = TypeTag::String)]
1639#[example(
1640 name = "report",
1641 code = r###"
1642 # The engine reports its own build version as a dotted string.
1643 IMPORT [STD]
1644 LET $v: STRING = VERSION()
1645 ASSERT_CONTAINS $v "."
1646 "###
1647)]
1648fn version() -> Result<Value> {
1649 Ok(Value::string(env!("CARGO_PKG_VERSION").to_string()))
1650}
1651
1652#[oxdock_func(returns = TypeTag::ListOf(std::sync::Arc::new(TypeTag::String)))]
1657#[example(
1658 name = "list",
1659 code = r###"
1660 IMPORT [STD]
1661 LET $names: LIST<STRING> = FUNCTIONS()
1662 ASSERT_CONTAINS $names "STD::INT"
1663 "###
1664)]
1665fn functions<P: ProcessManager>(cx: &mut StepCtx<P>) -> Result<Value> {
1666 let mut names: Vec<String> = cx
1667 .state
1668 .list_functions()
1669 .into_iter()
1670 .map(|meta| meta.name)
1671 .collect();
1672 names.sort();
1673 names.dedup();
1674 Ok(Value::list(names.into_iter().map(Value::string).collect()))
1675}
1676
1677#[oxdock_func(
1692 returns = TypeTag::Record(std::sync::Arc::from([Field {
1693 name: "name".to_string(),
1694 ty: TypeTag::String,
1695 docs: "Qualified function name.",
1696 optional: false,
1697 }, Field {
1698 name: "module".to_string(),
1699 ty: TypeTag::String,
1700 docs: "Owning module.",
1701 optional: false,
1702 }, Field {
1703 name: "kind".to_string(),
1704 ty: TypeTag::String,
1705 docs: "Origin label (`host` or `script`).",
1706 optional: false,
1707 }, Field {
1708 name: "params".to_string(),
1709 ty: TypeTag::ListOf(std::sync::Arc::new(TypeTag::MapOf(std::sync::Arc::new(
1710 TypeTag::Any,
1711 )))),
1712 docs: "Parameter entries (empty for parameterless functions).",
1713 optional: false,
1714 }, Field {
1715 name: "returns".to_string(),
1716 ty: TypeTag::String,
1717 docs: "Structural return shape (empty when untagged).",
1718 optional: false,
1719 }, Field {
1720 name: "rpn".to_string(),
1721 ty: TypeTag::Bool,
1722 docs: "True when callable in RPN position.",
1723 optional: false,
1724 }, Field {
1725 name: "summary".to_string(),
1726 ty: TypeTag::String,
1727 docs: "One-line description.",
1728 optional: false,
1729 }]))
1730 summary = "Describe one function by qualified name."
1731)]
1732#[example(
1733 name = "describe",
1734 code = r###"
1735 IMPORT [STD]
1736 LET $info: MAP<ANY> = DESCRIBE("STD::INT")
1737 ASSERT_EQ $info.name "STD::INT"
1738 ASSERT_EQ $info.returns "INT"
1739 "###
1740)]
1741fn describe<P: ProcessManager>(
1742 cx: &mut StepCtx<P>,
1743 name: String,
1745) -> Result<Value> {
1746 if split_qualified(&name).is_none() && name != KEYWORD_INSPECT {
1747 anyhow::bail!(
1748 "unknown function `{name}`: DESCRIBE requires a qualified name (e.g. `STD::{name}`)"
1749 );
1750 }
1751 cx.state
1752 .describe_function(&name)
1753 .ok_or_else(|| anyhow::anyhow!("unknown function {name}"))
1754}
1755
1756#[oxdock_func(returns = TypeTag::ListOf(std::sync::Arc::new(TypeTag::String)))]
1762#[example(
1763 name = "list",
1764 code = r###"
1765 IMPORT [STD]
1766 LET $names: LIST<STRING> = TYPES()
1767 ASSERT_CONTAINS $names "STRING"
1768 "###
1769)]
1770fn types<P: ProcessManager>(cx: &mut StepCtx<P>) -> Result<Value> {
1771 Ok(Value::list(
1772 cx.state
1773 .type_names()
1774 .into_iter()
1775 .map(Value::string)
1776 .collect(),
1777 ))
1778}
1779
1780#[oxdock_func(returns = TypeTag::Record(std::sync::Arc::from([Field {
1786 name: "name".to_string(),
1787 ty: TypeTag::String,
1788 docs: "Queried type name.",
1789 optional: false,
1790}, Field {
1791 name: "summary".to_string(),
1792 ty: TypeTag::String,
1793 docs: "One-line description.",
1794 optional: false,
1795}, Field {
1796 name: "docs".to_string(),
1797 ty: TypeTag::String,
1798 docs: "Full documentation text.",
1799 optional: false,
1800}])))]
1801#[example(
1802 name = "describe",
1803 code = r###"
1804 IMPORT [STD]
1805 LET $info: MAP<ANY> = TYPE_DESCRIBE("STRING")
1806 ASSERT_EQ $info.name "STRING"
1807 "###
1808)]
1809fn type_describe<P: ProcessManager>(
1810 cx: &mut StepCtx<P>,
1811 name: String,
1813) -> Result<Value> {
1814 if let Some(descriptor) = cx.state.describe_type(&name) {
1815 let mut map = BTreeMap::new();
1816 map.insert(
1817 "name".to_string(),
1818 Value::string(descriptor.name.to_string()),
1819 );
1820 map.insert(
1821 "summary".to_string(),
1822 Value::string(descriptor.summary.to_string()),
1823 );
1824 map.insert(
1825 "docs".to_string(),
1826 Value::string(descriptor.docs.to_string()),
1827 );
1828 return Ok(Value::map(map));
1829 }
1830 if let Some(target) = cx.state.alias_target(&name) {
1833 let mut map = BTreeMap::new();
1834 map.insert("name".to_string(), Value::string(name.clone()));
1835 map.insert(
1836 "summary".to_string(),
1837 Value::string(format!("Script type alias for {target}.")),
1838 );
1839 map.insert(
1840 "docs".to_string(),
1841 Value::string(format!(
1842 "Declared with TYPE {name} = {target}. The alias expands structurally at every declaration."
1843 )),
1844 );
1845 return Ok(Value::map(map));
1846 }
1847 Err(anyhow::anyhow!("unknown type {name}"))
1848}
1849
1850#[oxdock_func(returns = TypeTag::String)]
1864#[example(
1865 name = "self",
1866 code = r###"
1867 # The running interpreter resolves to a non-empty path.
1868 IMPORT [STD]
1869 LET $exe: STRING = INTERPRETER()
1870 LET $nonempty: BOOL = $exe != ""
1871 ASSERT_EQ $nonempty true
1872 "###
1873)]
1874#[example(
1875 name = "dynamic composition",
1876 code = r###"
1877 # Compose the child script dynamically: the parent interpolates
1878 # its own bindings into the pipe, then runs the interpreter on it.
1879 # Unescaped {{ }} bakes in at compose time; \{{ }} stays literal
1880 # so the child expands it with its own bindings.
1881 # The pipe delivers EOF when the producer step ends, so the child
1882 # reads exactly one script.
1883 IMPORT [STD]
1884 LET $exe: STRING = INTERPRETER()
1885 LET $who: STRING = "Ada"
1886 LET $child: PIPE
1887 WITH_IO [stdout=$child] ECHO """
1888 ECHO "hello {{ $who }}!"
1889 LET $who: STRING = "Grace"
1890 ECHO "child sees \{{ $who }}!"
1891 """
1892 LET $out: STRING = WITH_IO [stdin=$child] RUN [$exe]
1893 ASSERT_CONTAINS $out "hello Ada!"
1894 ASSERT_CONTAINS $out "child sees Grace!"
1895 "###
1896)]
1897fn interpreter<P: ProcessManager>(cx: &mut StepCtx<P>) -> Result<Value> {
1898 if let Some(staged) = cx.state.io.interpreter_override() {
1899 return Ok(Value::string(staged));
1900 }
1901 Ok(Value::string(oxdock_process::interpreter_exe()?))
1902}
1903
1904#[oxdock_func(returns = TypeTag::Bool)]
1912#[example(
1913 name = "main",
1914 code = r###"
1915 # Entry top level runs as main.
1916 IMPORT [STD]
1917 LET $m: BOOL = IS_MAIN()
1918 ASSERT_EQ $m true
1919 "###
1920)]
1921#[example(
1922 name = "library doubles as demo",
1923 fence_meta = "roots:unified",
1924 code = r###"
1925 # A library doubles as a runnable demo: guard the demo with
1926 # IF IS_MAIN() so importing it stays side effect free. The
1927 # parent writes both files, then runs each in a fresh
1928 # interpreter: direct execution prints the demo, importing
1929 # it does not. Unified roots: the child inherits one
1930 # workspace, so parent and child see the same files. The
1931 # exact stdout match proves the demo line stays out of the
1932 # importing run.
1933 IMPORT [STD]
1934
1935 # The library under test: demo guarded by IS_MAIN.
1936 WRITE lib.oxfile """
1937 IMPORT [STD]
1938 FUNC GREET($x: STRING) { RETURN "hi \{{ $x }}" }
1939 EXPORT GREET
1940 IF IS_MAIN() {
1941 ECHO "demo: hi Ada"
1942 }
1943 """
1944
1945 # The importer: calls the library, prints only its own line.
1946 WRITE main.oxfile """
1947 IMPORT ["lib.oxfile" AS LIB]
1948 LET $g: STRING = LIB::GREET("Bo")
1949 ECHO "imported: \{{ $g }}"
1950 """
1951
1952 # Direct run executes the demo.
1953 LET $exe: STRING = INTERPRETER()
1954 LET $direct: STRING = RUN [$exe, "lib.oxfile"]
1955 ASSERT_CONTAINS $direct "demo: hi Ada"
1956
1957 # Importing run stays silent apart from its own line.
1958 LET $via: STRING = RUN [$exe, "main.oxfile"]
1959 ASSERT_EQ $via "imported: hi Bo\n"
1960 "###
1961)]
1962fn is_main<P: ProcessManager>(cx: &mut StepCtx<P>) -> Result<Value> {
1963 let main = match cx.state.module_stack.last() {
1964 None | Some(None) => true,
1965 Some(Some(_)) => false,
1966 };
1967 Ok(Value::bool(main))
1968}
1969
1970#[oxdock_func(returns = TypeTag::Bool)]
1984#[example(
1985 name = "null stdin",
1986 code = r###"
1987 # A null stdin is never a terminal, in every harness.
1988 IMPORT [STD]
1989 LET $term: BOOL = IS_TERMINAL("stdin")
1990 ASSERT_EQ $term false
1991 "###
1992)]
1993fn is_terminal<P: ProcessManager>(
1994 cx: &mut StepCtx<P>,
1995 #[values("stdin", "stdout", "stderr")]
1997 stream_name: String,
1998) -> Result<Value> {
1999 use std::io::IsTerminal;
2000 let terminal = match stream_name.as_str() {
2001 "stdin" => {
2002 if cx.stdin_pipe.is_some() {
2007 false
2008 } else {
2009 match &cx.stdin {
2010 CommandStdin::Null => false,
2011 #[cfg(not(miri))]
2012 CommandStdin::OsPipe(_) => false,
2013 CommandStdin::Stream(_) => false,
2014 CommandStdin::Inherit => std::io::stdin().is_terminal(),
2015 }
2016 }
2017 }
2018 "stdout" => {
2019 if cx.out_pipe.is_some() {
2020 false
2022 } else if cx.state.io.stdout().is_some() {
2023 false
2026 } else {
2027 match &cx.out {
2028 None => std::io::stdout().is_terminal(),
2030 #[cfg(not(miri))]
2032 Some(StreamHandle::Os(_)) => false,
2033 Some(StreamHandle::Stream(_)) => std::io::stdout().is_terminal(),
2043 }
2044 }
2045 }
2046 "stderr" => {
2047 if cx.state.io.stderr().is_some() {
2048 false
2050 } else {
2051 match &cx.err {
2052 None => std::io::stderr().is_terminal(),
2054 #[cfg(not(miri))]
2056 Some(StreamHandle::Os(_)) => false,
2057 Some(StreamHandle::Stream(_)) => false,
2060 }
2061 }
2062 }
2063 _ => anyhow::bail!(
2064 "IS_TERMINAL expects \"stdin\", \"stdout\", or \"stderr\", got {stream_name:?}"
2069 ),
2070 };
2071 Ok(Value::bool(terminal))
2072}
2073
2074#[oxdock_func(returns = TypeTag::Semaphore)]
2082#[example(
2083 name = "mint",
2084 code = r###"
2085 # Mint a semaphore admitting at most two holders.
2086 IMPORT [STD]
2087 LET $sem: SEMAPHORE = SEMAPHORE_NEW(2)
2088
2089 # A fresh semaphore reports its full cap as available.
2090 LET $free: INT = SEMAPHORE_AVAILABLE($sem)
2091 ASSERT_EQ $free 2
2092 "###
2093)]
2094fn semaphore_new<P: ProcessManager>(
2095 cx: &mut StepCtx<P>,
2096 max: i64,
2098) -> Result<Value> {
2099 let _ = cx;
2100 if max <= 0 {
2101 return Err(anyhow::anyhow!(
2102 "SEMAPHORE_NEW() requires a positive max, got {max}"
2103 ));
2104 }
2105 Ok(Value::semaphore(max as usize))
2106}
2107
2108#[oxdock_func(returns = TypeTag::Record(std::sync::Arc::from([Field {
2117 name: "held".to_string(),
2118 ty: TypeTag::Bool,
2119 docs: "`true` with the permit under `permit`, `false` with no `permit` key.",
2120 optional: false,
2121}, Field {
2122 name: "permit".to_string(),
2123 ty: TypeTag::Permit,
2124 docs: "Permit handle; read only when `held`.",
2125 optional: true,
2126}])))]
2127#[example(
2128 name = "acquire",
2129 code = r###"
2130 # First acquire holds with a permit to bind.
2131 IMPORT [STD]
2132 LET $sem: SEMAPHORE = SEMAPHORE_NEW(1)
2133 LET $first: MAP<held: BOOL, permit?: PERMIT> = SEMAPHORE_TRY_ACQUIRE($sem)
2134 ASSERT_EQ $first.held true
2135 LET $permit: PERMIT = $first.permit
2136
2137 # A capped semaphore answers held false with no permit key.
2138 LET $second: MAP<held: BOOL, permit?: PERMIT> = SEMAPHORE_TRY_ACQUIRE($sem)
2139 ASSERT_EQ $second.held false
2140 LET $has_permit: BOOL = HAS_KEY($second, "permit")
2141 ASSERT_EQ $has_permit false
2142 "###
2143)]
2144fn semaphore_try_acquire<P: ProcessManager>(
2145 cx: &mut StepCtx<P>,
2146 sem: Arc<SemaphoreState>,
2148) -> Result<Value> {
2149 let _ = cx;
2150 let mut map = BTreeMap::new();
2151 if sem.try_acquire() {
2152 map.insert("held".to_string(), Value::bool(true));
2153 map.insert("permit".to_string(), Value::permit(&sem));
2154 } else {
2155 map.insert("held".to_string(), Value::bool(false));
2156 }
2157 Ok(Value::map(map))
2158}
2159
2160#[oxdock_func(pure, returns = TypeTag::Int)]
2167#[example(
2168 name = "readout",
2169 code = r###"
2170 # Hold one permit on a cap of two.
2171 IMPORT [STD]
2172 LET $sem: SEMAPHORE = SEMAPHORE_NEW(2)
2173 LET $acq: MAP<held: BOOL, permit?: PERMIT> = SEMAPHORE_TRY_ACQUIRE($sem)
2174 ASSERT_EQ $acq.held true
2175
2176 # One held permit leaves exactly one free.
2177 LET $free: INT = SEMAPHORE_AVAILABLE($sem)
2178 ASSERT_EQ $free 1
2179 "###
2180)]
2181fn semaphore_available(
2182 sem: Arc<SemaphoreState>,
2184) -> Result<Value> {
2185 Ok(Value::int(sem.available() as i64))
2186}
2187
2188#[oxdock_func(
2197 rpn,
2198 returns = TypeTag::union(vec![TypeTag::String, TypeTag::Pipe]),
2199 template = text_trim_string
2200)]
2201#[example(
2202 name = "trim",
2203 code = r###"
2204 # Leading and trailing whitespace falls away.
2205 IMPORT [STD]
2206 LET $clean: STRING = TEXT_TRIM(" hello ")
2207 ASSERT_EQ $clean "hello"
2208 "###
2209)]
2210#[example(
2211 name = "trim pipe mirrors",
2212 code = r###"
2213 # Pipe input mints pipe output with the same transform.
2214 IMPORT [STD]
2215 LET $cap: PIPE
2216 WITH_IO [stdout=$cap] {
2217 ECHO " hello "
2218 }
2219 LET $out: PIPE = TEXT_TRIM($cap)
2220 WITH_IO [stdin=$out] READ_LINE $line
2221 ASSERT_EQ $line "hello"
2222 "###
2223)]
2224#[example(
2225 name = "trim template",
2226 code = r###"
2227 # String inputs run inside placeholders too.
2228 IMPORT [STD]
2229 LET $msg: STRING = 'clean:{{ STD::TEXT_TRIM(" hello ") }}'
2230 ASSERT_EQ $msg "clean:hello"
2231 "###
2232)]
2233#[example(
2234 name = "trim file template",
2235 code = r###"
2236 # EXPAND templates resolve the same registry.
2237 IMPORT [STD]
2238 WRITE "tpl.txt" "clean:\{{ STD::TEXT_TRIM(\" hello \") }}"
2239 LET $out: STRING = EXPAND "tpl.txt"
2240 ASSERT_EQ $out "clean:hello"
2241 "###
2242)]
2243fn text_trim<P: ProcessManager>(
2244 cx: &mut StepCtx<P>,
2245 #[union(String, Pipe)]
2247 text: Value,
2248) -> Result<Value> {
2249 super::args::mirror_stream(cx, "TEXT_TRIM", &text, super::args::TextPump::Trim)
2250}
2251
2252fn text_trim_string(text: Value) -> Result<Value> {
2255 super::args::mirror_string("TEXT_TRIM", &text, super::args::TextPump::Trim)
2256}
2257
2258#[oxdock_func(
2267 rpn,
2268 returns = TypeTag::union(vec![TypeTag::String, TypeTag::Pipe]),
2269 template = text_trim_prefix_string
2270)]
2271#[example(
2272 name = "strip prefix",
2273 code = r###"
2274 # A present prefix falls away; absence returns the input unchanged.
2275 IMPORT [STD]
2276 LET $bare: STRING = TEXT_TRIM_PREFIX("v1.2.3", "v")
2277 ASSERT_EQ $bare "1.2.3"
2278
2279 # Missing prefixes pass through untouched.
2280 LET $same: STRING = TEXT_TRIM_PREFIX("1.2.3", "v")
2281 ASSERT_EQ $same "1.2.3"
2282 "###
2283)]
2284#[example(
2285 name = "strip prefix pipe mirrors",
2286 code = r###"
2287 # Pipe input mints pipe output with the same strip.
2288 IMPORT [STD]
2289 LET $cap: PIPE
2290 WITH_IO [stdout=$cap] {
2291 ECHO "v1.2.3"
2292 }
2293 LET $trimmed: PIPE = TEXT_TRIM($cap)
2294 LET $out: PIPE = TEXT_TRIM_PREFIX($trimmed, "v")
2295 WITH_IO [stdin=$out] READ_LINE $line
2296 ASSERT_EQ $line "1.2.3"
2297 "###
2298)]
2299#[example(
2300 name = "strip prefix template",
2301 code = r###"
2302 # String inputs run inside placeholders too.
2303 IMPORT [STD]
2304 LET $msg: STRING = 'bare:{{ STD::TEXT_TRIM_PREFIX("v1.2.3", "v") }}'
2305 ASSERT_EQ $msg "bare:1.2.3"
2306 "###
2307)]
2308fn text_trim_prefix<P: ProcessManager>(
2309 cx: &mut StepCtx<P>,
2310 #[union(String, Pipe)]
2312 text: Value,
2313 prefix: String,
2315) -> Result<Value> {
2316 super::args::mirror_stream(
2317 cx,
2318 "TEXT_TRIM_PREFIX",
2319 &text,
2320 super::args::TextPump::TrimPrefix(prefix),
2321 )
2322}
2323
2324fn text_trim_prefix_string(text: Value, prefix: String) -> Result<Value> {
2327 super::args::mirror_string(
2328 "TEXT_TRIM_PREFIX",
2329 &text,
2330 super::args::TextPump::TrimPrefix(prefix),
2331 )
2332}
2333
2334#[oxdock_func(
2341 rpn,
2342 returns = TypeTag::union(vec![TypeTag::String, TypeTag::Pipe]),
2343 template = text_trim_suffix_string
2344)]
2345#[example(
2346 name = "strip suffix",
2347 code = r###"
2348 # A present suffix falls away; absence returns the input unchanged.
2349 IMPORT [STD]
2350 LET $bare: STRING = TEXT_TRIM_SUFFIX("archive.tar.gz", ".gz")
2351 ASSERT_EQ $bare "archive.tar"
2352
2353 # Missing suffixes pass through untouched.
2354 LET $same: STRING = TEXT_TRIM_SUFFIX("archive.tar", ".gz")
2355 ASSERT_EQ $same "archive.tar"
2356 "###
2357)]
2358#[example(
2359 name = "strip suffix pipe mirrors",
2360 code = r###"
2361 # Pipe input mints pipe output with the same strip.
2362 IMPORT [STD]
2363 LET $cap: PIPE
2364 WITH_IO [stdout=$cap] {
2365 ECHO "archive.tar.gz"
2366 }
2367 LET $trimmed: PIPE = TEXT_TRIM($cap)
2368 LET $out: PIPE = TEXT_TRIM_SUFFIX($trimmed, ".gz")
2369 WITH_IO [stdin=$out] READ_LINE $line
2370 ASSERT_EQ $line "archive.tar"
2371 "###
2372)]
2373#[example(
2374 name = "strip suffix template",
2375 code = r###"
2376 # String inputs run inside placeholders too.
2377 IMPORT [STD]
2378 LET $msg: STRING = 'bare:{{ STD::TEXT_TRIM_SUFFIX("archive.tar.gz", ".gz") }}'
2379 ASSERT_EQ $msg "bare:archive.tar"
2380 "###
2381)]
2382fn text_trim_suffix<P: ProcessManager>(
2383 cx: &mut StepCtx<P>,
2384 #[union(String, Pipe)]
2386 text: Value,
2387 suffix: String,
2389) -> Result<Value> {
2390 super::args::mirror_stream(
2391 cx,
2392 "TEXT_TRIM_SUFFIX",
2393 &text,
2394 super::args::TextPump::TrimSuffix(suffix),
2395 )
2396}
2397
2398fn text_trim_suffix_string(text: Value, suffix: String) -> Result<Value> {
2401 super::args::mirror_string(
2402 "TEXT_TRIM_SUFFIX",
2403 &text,
2404 super::args::TextPump::TrimSuffix(suffix),
2405 )
2406}
2407
2408#[oxdock_func(returns = TypeTag::String)]
2419#[example(
2420 name = "join path",
2421 code = r###"
2422 # Directory and file stem join with the native separator.
2423 # Source `\\` is one backslash at runtime; `/` works on Windows
2424 # too, native just reads better there.
2425 IMPORT [STD]
2426 LET $p: STRING = PATH_JOIN("some-dir", "some-file")
2427 [family:unix] ASSERT_EQ $p "some-dir/some-file"
2428 [family:windows] ASSERT_EQ $p "some-dir\\some-file"
2429 "###
2430)]
2431fn path_join<P: ProcessManager>(
2432 _cx: &mut StepCtx<P>,
2433 #[union(String, Path)]
2435 dir: Value,
2436 #[union(String, Path)]
2438 name: Value,
2439) -> Result<Value> {
2440 let d = super::args::string_or_path_text(&dir)?;
2441 let n = super::args::string_or_path_text(&name)?;
2442 Ok(Value::string(oxdock_fs::join_native(&d, &n)))
2443}
2444
2445#[oxdock_func(
2452 rpn,
2453 returns = TypeTag::union(vec![TypeTag::String, TypeTag::Pipe]),
2454 template = text_to_upper_string
2455)]
2456#[example(
2457 name = "uppercase",
2458 code = r###"
2459 # Text folds to uppercase.
2460 IMPORT [STD]
2461 LET $loud: STRING = TEXT_TO_UPPER("hello")
2462 ASSERT_EQ $loud "HELLO"
2463 "###
2464)]
2465#[example(
2466 name = "uppercase pipe mirrors",
2467 code = r###"
2468 # Pipe input mints pipe output with the same fold.
2469 IMPORT [STD]
2470 LET $cap: PIPE
2471 WITH_IO [stdout=$cap] {
2472 ECHO "hello"
2473 }
2474 LET $out: PIPE = TEXT_TO_UPPER($cap)
2475 WITH_IO [stdin=$out] READ_LINE $line
2476 ASSERT_EQ $line "HELLO"
2477 "###
2478)]
2479#[example(
2480 name = "uppercase template",
2481 code = r###"
2482 # String inputs run inside placeholders too.
2483 IMPORT [STD]
2484 LET $msg: STRING = 'loud:{{ STD::TEXT_TO_UPPER("hello") }}'
2485 ASSERT_EQ $msg "loud:HELLO"
2486 "###
2487)]
2488fn text_to_upper<P: ProcessManager>(
2489 cx: &mut StepCtx<P>,
2490 #[union(String, Pipe)]
2492 text: Value,
2493) -> Result<Value> {
2494 super::args::mirror_stream(cx, "TEXT_TO_UPPER", &text, super::args::TextPump::ToUpper)
2495}
2496
2497fn text_to_upper_string(text: Value) -> Result<Value> {
2500 super::args::mirror_string("TEXT_TO_UPPER", &text, super::args::TextPump::ToUpper)
2501}
2502
2503#[oxdock_func(
2510 rpn,
2511 returns = TypeTag::union(vec![TypeTag::String, TypeTag::Pipe]),
2512 template = text_to_lower_string
2513)]
2514#[example(
2515 name = "lowercase",
2516 code = r###"
2517 # Text folds to lowercase.
2518 IMPORT [STD]
2519 LET $quiet: STRING = TEXT_TO_LOWER("HELLO")
2520 ASSERT_EQ $quiet "hello"
2521 "###
2522)]
2523#[example(
2524 name = "lowercase pipe mirrors",
2525 code = r###"
2526 # Pipe input mints pipe output with the same fold.
2527 IMPORT [STD]
2528 LET $cap: PIPE
2529 WITH_IO [stdout=$cap] {
2530 ECHO "HELLO"
2531 }
2532 LET $out: PIPE = TEXT_TO_LOWER($cap)
2533 WITH_IO [stdin=$out] READ_LINE $line
2534 ASSERT_EQ $line "hello"
2535 "###
2536)]
2537#[example(
2538 name = "lowercase template",
2539 code = r###"
2540 # String inputs run inside placeholders too.
2541 IMPORT [STD]
2542 LET $msg: STRING = 'quiet:{{ STD::TEXT_TO_LOWER("HELLO") }}'
2543 ASSERT_EQ $msg "quiet:hello"
2544 "###
2545)]
2546fn text_to_lower<P: ProcessManager>(
2547 cx: &mut StepCtx<P>,
2548 #[union(String, Pipe)]
2550 text: Value,
2551) -> Result<Value> {
2552 super::args::mirror_stream(cx, "TEXT_TO_LOWER", &text, super::args::TextPump::ToLower)
2553}
2554
2555fn text_to_lower_string(text: Value) -> Result<Value> {
2558 super::args::mirror_string("TEXT_TO_LOWER", &text, super::args::TextPump::ToLower)
2559}
2560
2561#[oxdock_func(
2572 rpn,
2573 returns = TypeTag::union(vec![TypeTag::String, TypeTag::Pipe]),
2574 template = text_replace_string
2575)]
2576#[example(
2577 name = "replace",
2578 code = r###"
2579 # Every literal occurrence rewrites in place.
2580 IMPORT [STD]
2581 LET $fixed: STRING = TEXT_REPLACE("hello world", "world", "there")
2582 ASSERT_EQ $fixed "hello there"
2583 "###
2584)]
2585#[example(
2586 name = "replace pipe mirrors",
2587 code = r###"
2588 # Pipe input mints pipe output with the same rewrite.
2589 IMPORT [STD]
2590 LET $cap: PIPE
2591 WITH_IO [stdout=$cap] {
2592 ECHO "hello world"
2593 }
2594 LET $trimmed: PIPE = TEXT_TRIM($cap)
2595 LET $out: PIPE = TEXT_REPLACE($trimmed, "world", "there")
2596 WITH_IO [stdin=$out] READ_LINE $line
2597 ASSERT_EQ $line "hello there"
2598 "###
2599)]
2600#[example(
2601 name = "replace template",
2602 code = r###"
2603 # String inputs run inside placeholders too.
2604 IMPORT [STD]
2605 LET $msg: STRING = 'fixed:{{ STD::TEXT_REPLACE("hello world", "world", "there") }}'
2606 ASSERT_EQ $msg "fixed:hello there"
2607 "###
2608)]
2609fn text_replace<P: ProcessManager>(
2610 cx: &mut StepCtx<P>,
2611 #[union(String, Pipe)]
2613 text: Value,
2614 from: String,
2616 to: String,
2618) -> Result<Value> {
2619 super::args::mirror_stream(
2620 cx,
2621 "TEXT_REPLACE",
2622 &text,
2623 super::args::TextPump::ReplaceLiteral { from, to },
2624 )
2625}
2626
2627fn text_replace_string(text: Value, from: String, to: String) -> Result<Value> {
2630 super::args::mirror_string(
2631 "TEXT_REPLACE",
2632 &text,
2633 super::args::TextPump::ReplaceLiteral { from, to },
2634 )
2635}
2636
2637#[oxdock_func(
2649 rpn,
2650 returns = TypeTag::union(vec![TypeTag::String, TypeTag::Pipe]),
2651 template = text_replace_regex_string
2652)]
2653#[example(
2654 name = "replace with captures",
2655 code = r###"
2656 # Capture groups expand in the replacement.
2657 IMPORT [STD]
2658 LET $swapped: STRING = TEXT_REPLACE_REGEX("2026-10-13", "(\\d+)-(\\d+)-(\\d+)", "$3/$2/$1")
2659 ASSERT_EQ $swapped "13/10/2026"
2660 "###
2661)]
2662#[example(
2663 name = "replace regex pipe mirrors",
2664 code = r###"
2665 # Pipe input mints pipe output with the same rewrite.
2666 IMPORT [STD]
2667 LET $cap: PIPE
2668 WITH_IO [stdout=$cap] {
2669 ECHO "2026-10-13"
2670 }
2671 LET $trimmed: PIPE = TEXT_TRIM($cap)
2672 LET $out: PIPE = TEXT_REPLACE_REGEX($trimmed, "(\\d+)-(\\d+)-(\\d+)", "$3/$2/$1")
2673 WITH_IO [stdin=$out] READ_LINE $line
2674 ASSERT_EQ $line "13/10/2026"
2675 "###
2676)]
2677#[example(
2678 name = "replace regex template",
2679 code = r###"
2680 # String inputs run inside placeholders too.
2681 IMPORT [STD]
2682 LET $msg: STRING = 'swapped:{{ STD::TEXT_REPLACE_REGEX("2026-10-13", "(\\d+)-(\\d+)-(\\d+)", "$3/$2/$1") }}'
2683 ASSERT_EQ $msg "swapped:13/10/2026"
2684 "###
2685)]
2686fn text_replace_regex<P: ProcessManager>(
2687 cx: &mut StepCtx<P>,
2688 #[union(String, Pipe)]
2690 text: Value,
2691 pattern: String,
2693 replacement: String,
2695) -> Result<Value> {
2696 if let Some(s) = text.as_str() {
2697 let out =
2698 super::args::text_replace_regex_str(s, &pattern, &replacement, "TEXT_REPLACE_REGEX")?;
2699 return Ok(Value::string(out));
2700 }
2701 let content = super::args::read_pipe_eager(cx, "TEXT_REPLACE_REGEX", &text)?;
2702 let out = super::args::text_replace_regex_str(
2703 &content,
2704 &pattern,
2705 &replacement,
2706 "TEXT_REPLACE_REGEX",
2707 )?;
2708 super::args::write_completed_pipe(cx, "TEXT_REPLACE_REGEX", out)
2709}
2710
2711fn text_replace_regex_string(text: Value, pattern: String, replacement: String) -> Result<Value> {
2714 let Some(s) = text.as_str() else {
2715 return Err(super::args::pipe_needs_step_io("TEXT_REPLACE_REGEX"));
2716 };
2717 let out = super::args::text_replace_regex_str(s, &pattern, &replacement, "TEXT_REPLACE_REGEX")?;
2718 Ok(Value::string(out))
2719}
2720
2721#[oxdock_func(pure, returns = TypeTag::ListOf(std::sync::Arc::new(TypeTag::String)))]
2729#[example(
2730 name = "split",
2731 code = r###"
2732 # Delimiters split into list items.
2733 IMPORT [STD]
2734 LET $parts: LIST<STRING> = TEXT_SPLIT("a,b,c", ",")
2735 ASSERT_EQ $parts.0 "a"
2736 ASSERT_EQ $parts.1 "b"
2737 ASSERT_EQ $parts.2 "c"
2738 "###
2739)]
2740fn text_split(
2741 text: String,
2743 delimiter: String,
2745) -> Result<Value> {
2746 Ok(super::args::text_list_value(super::args::text_split_str(
2747 &text, &delimiter,
2748 )))
2749}
2750
2751#[oxdock_func(pure, returns = TypeTag::String)]
2754#[example(
2755 name = "join",
2756 code = r###"
2757 # List items join with the separator between them.
2758 IMPORT [STD]
2759 LET $joined: STRING = TEXT_JOIN(["a", "b", "c"], ",")
2760 ASSERT_EQ $joined "a,b,c"
2761 "###
2762)]
2763fn text_join(
2764 elements: Vec<String>,
2766 delimiter: String,
2768) -> Result<Value> {
2769 Ok(Value::string(elements.join(delimiter.as_str())))
2770}
2771
2772#[oxdock_func(pure, returns = TypeTag::ListOf(std::sync::Arc::new(TypeTag::String)))]
2784#[example(
2785 name = "split args",
2786 code = r###"
2787 # Quoted segments stay one word.
2788 IMPORT [STD]
2789 LET $argv: LIST<STRING> = SHELL_SPLIT_ARGS("gh issue comment 153 --body-file notes.md")
2790 ASSERT_EQ $argv.0 "gh"
2791 ASSERT_EQ $argv.3 "153"
2792 ASSERT_EQ $argv.5 "notes.md"
2793
2794 # Quotes and escapes parse the shell way.
2795 LET $quoted: LIST<STRING> = SHELL_SPLIT_ARGS("say \"hi there\" 'a b'")
2796 ASSERT_EQ $quoted.0 "say"
2797 ASSERT_EQ $quoted.1 "hi there"
2798 ASSERT_EQ $quoted.2 "a b"
2799 "###
2800)]
2801fn shell_split_args(
2802 command: String,
2804) -> Result<Value> {
2805 match shell_words::split(&command) {
2806 Ok(words) => Ok(super::args::text_list_value(words)),
2807 Err(err) => anyhow::bail!("SHELL_SPLIT_ARGS: {err}"),
2808 }
2809}
2810
2811#[oxdock_func(pure, returns = TypeTag::String)]
2819#[example(
2820 name = "join args",
2821 code = r###"
2822 # Plain words join with spaces and no quoting.
2823 IMPORT [STD]
2824 LET $plain: STRING = SHELL_JOIN_ARGS(["gh", "issue", "list"])
2825 ASSERT_EQ $plain "gh issue list"
2826
2827 # Words with spaces quote, and the round trip is exact.
2828 LET $words: LIST<STRING> = ["say", "hi there", "a'b"]
2829 LET $joined: STRING = SHELL_JOIN_ARGS($words)
2830 LET $back: LIST<STRING> = SHELL_SPLIT_ARGS($joined)
2831 ASSERT_EQ $back.0 "say"
2832 ASSERT_EQ $back.1 "hi there"
2833 ASSERT_EQ $back.2 "a'b"
2834 "###
2835)]
2836fn shell_join_args(
2837 words: Vec<String>,
2839) -> Result<Value> {
2840 Ok(Value::string(shell_words::join(&words)))
2841}
2842
2843#[oxdock_func(pure, returns = TypeTag::ListOf(std::sync::Arc::new(TypeTag::String)))]
2851#[example(
2852 name = "lines",
2853 code = r###"
2854 # Newlines split into line items.
2855 IMPORT [STD]
2856 LET $lines: LIST<STRING> = TEXT_LINES("one\ntwo\nthree")
2857 ASSERT_EQ $lines.0 "one"
2858 ASSERT_EQ $lines.1 "two"
2859 ASSERT_EQ $lines.2 "three"
2860
2861 # Windows endings split the same way after normalization.
2862 LET $crlf: LIST<STRING> = TEXT_LINES("one\r\ntwo\r\nthree")
2863 ASSERT_EQ $crlf.0 "one"
2864 ASSERT_EQ $crlf.1 "two"
2865 ASSERT_EQ $crlf.2 "three"
2866
2867 # Old Mac endings split too, and mixed endings split together because the input normalizes to LF before splitting.
2868 LET $mixed: LIST<STRING> = TEXT_LINES("a\r\nb\nc\rd")
2869 ASSERT_EQ $mixed.0 "a"
2870 ASSERT_EQ $mixed.1 "b"
2871 ASSERT_EQ $mixed.2 "c"
2872 ASSERT_EQ $mixed.3 "d"
2873 "###
2874)]
2875fn text_lines(
2876 text: String,
2878) -> Result<Value> {
2879 Ok(super::args::text_list_value(super::args::text_lines_str(
2880 &text,
2881 )))
2882}
2883
2884#[oxdock_func(pure, returns = TypeTag::ListOf(std::sync::Arc::new(TypeTag::String)))]
2890#[example(
2891 name = "fields",
2892 code = r###"
2893 # Runs of whitespace separate fields; empties never appear.
2894 IMPORT [STD]
2895 LET $fields: LIST<STRING> = TEXT_FIELDS(" abc def ")
2896 ASSERT_EQ $fields.0 "abc"
2897 ASSERT_EQ $fields.1 "def"
2898 "###
2899)]
2900fn text_fields(
2901 text: String,
2903) -> Result<Value> {
2904 Ok(super::args::text_list_value(super::args::text_fields_str(
2905 &text,
2906 )))
2907}
2908
2909#[oxdock_func(pure, returns = TypeTag::ListOf(std::sync::Arc::new(TypeTag::String)))]
2918#[example(
2919 name = "line range",
2920 code = r###"
2921 # Lines 2 through 3 come back as a list, 1-based inclusive.
2922 IMPORT [STD]
2923 LET $window: LIST<STRING> = TEXT_LINES_RANGE("one\ntwo\nthree\nfour", 2, 3)
2924 ASSERT_EQ $window.0 "two"
2925 ASSERT_EQ $window.1 "three"
2926
2927 # Ranges past the end clamp instead of failing.
2928 LET $tail: LIST<STRING> = TEXT_LINES_RANGE("one\ntwo", 2, 9)
2929 ASSERT_EQ $tail.0 "two"
2930 "###
2931)]
2932fn text_lines_range(
2933 text: String,
2935 from: i64,
2937 to: i64,
2939) -> Result<Value> {
2940 Ok(super::args::text_list_value(
2941 super::args::text_lines_range_str(&text, from, to, "TEXT_LINES_RANGE")?,
2942 ))
2943}
2944
2945#[oxdock_func(pure, returns = TypeTag::Bool)]
2953#[example(
2954 name = "match",
2955 code = r###"
2956 # Regex matches report true; misses report false.
2957 IMPORT [STD]
2958 LET $hit: BOOL = TEXT_MATCH("abc123", "\\d+")
2959 ASSERT_EQ $hit true
2960
2961 # A miss is false, not a failure.
2962 LET $miss: BOOL = TEXT_MATCH("abc", "^\\d+$")
2963 ASSERT_EQ $miss false
2964 "###
2965)]
2966fn text_match(
2967 text: String,
2969 pattern: String,
2971) -> Result<Value> {
2972 let re = super::args::text_compile_pattern("TEXT_MATCH", &pattern)?;
2973 Ok(Value::bool(re.is_match(&text)))
2974}
2975
2976#[oxdock_func(pure, name = "BOOL", returns = TypeTag::Bool)]
2985#[example(
2986 name = "convert",
2987 code = r###"
2988 IMPORT [STD]
2989 LET $n: BOOL = BOOL("yes")
2990 ASSERT_EQ $n true
2991 LET $f: BOOL = BOOL("0")
2992 ASSERT_EQ $f false
2993 "###
2994)]
2995fn bool_convert(
2996 #[union(Bool, String)]
2998 val: Value,
2999) -> Result<Value> {
3000 if let Some(b) = val.as_bool() {
3001 return Ok(Value::bool(b));
3002 }
3003 let Some(s) = val.as_str() else {
3004 return Err(anyhow::anyhow!(
3005 "BOOL needs a Bool or String, found {val:?}"
3006 ));
3007 };
3008 match super::args::parse_bool_str(s) {
3009 Some(b) => Ok(Value::bool(b)),
3010 None => anyhow::bail!("BOOL cannot coerce {s:?} to BOOL"),
3011 }
3012}
3013
3014#[oxdock_func(pure, returns = TypeTag::Bool)]
3024#[example(
3025 name = "absent-default",
3026 code = r###"
3027 # Absent names read empty; the default settles the polarity.
3028 IMPORT [STD]
3029 INHERIT_ENV [OXDOCK_TEST_ABSENT_FLAG]
3030 LET $dry: BOOL = BOOL_OR("{{ env:OXDOCK_TEST_ABSENT_FLAG }}", true)
3031 ASSERT_EQ $dry true
3032
3033 # Present values coerce strictly, ignoring the default.
3034 LET $off: BOOL = BOOL_OR("false", true)
3035 ASSERT_EQ $off false
3036 "###
3037)]
3038fn bool_or(
3039 text: String,
3041 default: bool,
3043) -> Result<Value> {
3044 if text.trim().is_empty() {
3045 return Ok(Value::bool(default));
3046 }
3047 match super::args::parse_bool_str(&text) {
3048 Some(b) => Ok(Value::bool(b)),
3049 None => anyhow::bail!("BOOL_OR cannot coerce {text:?} to BOOL"),
3050 }
3051}
3052
3053#[oxdock_func(pure, returns = TypeTag::ListOf(std::sync::Arc::new(TypeTag::String)))]
3062#[example(
3063 name = "extract",
3064 code = r###"
3065 # Index zero is the full match; groups follow in order.
3066 IMPORT [STD]
3067 LET $caps: LIST<STRING> = TEXT_EXTRACT("abc123", "([a-z]+)(\\d+)")
3068 ASSERT_EQ $caps.0 "abc123"
3069 ASSERT_EQ $caps.1 "abc"
3070 ASSERT_EQ $caps.2 "123"
3071 "###
3072)]
3073fn text_extract(
3074 text: String,
3076 pattern: String,
3078) -> Result<Value> {
3079 let groups = super::args::text_extract_str(&text, &pattern, "TEXT_EXTRACT")?;
3080 Ok(super::args::text_list_value(groups))
3081}
3082
3083#[oxdock_func(pure, returns = TypeTag::Bool)]
3090#[example(
3091 name = "starts with",
3092 code = r###"
3093 # Present prefixes report true; misses report false.
3094 IMPORT [STD]
3095 LET $hit: BOOL = TEXT_STARTS_WITH("linux-musl-x64", "linux")
3096 ASSERT_EQ $hit true
3097
3098 # A miss is false, not a failure.
3099 LET $miss: BOOL = TEXT_STARTS_WITH("macos-arm", "linux")
3100 ASSERT_EQ $miss false
3101 "###
3102)]
3103fn text_starts_with(
3104 text: String,
3106 prefix: String,
3108) -> Result<Value> {
3109 Ok(Value::bool(text.starts_with(prefix.as_str())))
3110}
3111
3112#[oxdock_func(pure, returns = TypeTag::Bool)]
3119#[example(
3120 name = "ends with",
3121 code = r###"
3122 # Present suffixes report true; misses report false.
3123 IMPORT [STD]
3124 LET $hit: BOOL = TEXT_ENDS_WITH("x86_64-linux-musl", "linux-musl")
3125 ASSERT_EQ $hit true
3126
3127 # A miss is false, not a failure.
3128 LET $miss: BOOL = TEXT_ENDS_WITH("x86_64-linux-gnu", "linux-musl")
3129 ASSERT_EQ $miss false
3130 "###
3131)]
3132fn text_ends_with(
3133 text: String,
3135 suffix: String,
3137) -> Result<Value> {
3138 Ok(Value::bool(text.ends_with(suffix.as_str())))
3139}
3140
3141#[oxdock_func(pure, returns = TypeTag::Bool)]
3148#[example(
3149 name = "contains",
3150 code = r###"
3151 # Present needles report true; misses report false.
3152 IMPORT [STD]
3153 LET $hit: BOOL = TEXT_CONTAINS("x86_64-linux-musl", "musl")
3154 ASSERT_EQ $hit true
3155
3156 # A miss is false, not a failure.
3157 LET $miss: BOOL = TEXT_CONTAINS("x86_64-linux-gnu", "musl")
3158 ASSERT_EQ $miss false
3159 "###
3160)]
3161fn text_contains(
3162 text: String,
3164 needle: String,
3166) -> Result<Value> {
3167 Ok(Value::bool(text.contains(needle.as_str())))
3168}
3169
3170#[oxdock_func(pure, returns = TypeTag::Int)]
3177#[example(
3178 name = "length",
3179 code = r###"
3180 # Plain text counts one per character.
3181 IMPORT [STD]
3182 LET $n: INT = TEXT_LENGTH("hello")
3183 ASSERT_EQ $n 5
3184
3185 # Multibyte characters count once each, not per byte.
3186 LET $wide: INT = TEXT_LENGTH("héllo")
3187 ASSERT_EQ $wide 5
3188 "###
3189)]
3190fn text_length(
3191 text: String,
3193) -> Result<Value> {
3194 Ok(Value::int(text.chars().count() as i64))
3195}
3196
3197#[oxdock_func(pure, returns = TypeTag::Int)]
3205#[example(
3206 name = "count",
3207 code = r###"
3208 # Every non-overlapping occurrence counts once.
3209 IMPORT [STD]
3210 LET $n: INT = TEXT_COUNT("hello world", "o")
3211 ASSERT_EQ $n 2
3212
3213 # Overlapping candidates never double count.
3214 LET $once: INT = TEXT_COUNT("aaa", "aa")
3215 ASSERT_EQ $once 1
3216 "###
3217)]
3218fn text_count(
3219 text: String,
3221 needle: String,
3223) -> Result<Value> {
3224 let n = super::args::text_count_str(&text, &needle, "TEXT_COUNT")?;
3225 Ok(Value::int(n))
3226}
3227
3228#[oxdock_func(pure, returns = TypeTag::Int)]
3238#[example(
3239 name = "count matches",
3240 code = r###"
3241 # One line matches once no matter how many times it hits.
3242 IMPORT [STD]
3243 LET $n: INT = TEXT_COUNT_MATCHES("test a: test\ntest b: nope\ntest c: test", ": test")
3244 ASSERT_EQ $n 2
3245
3246 # A miss binds zero, never an error.
3247 LET $none: INT = TEXT_COUNT_MATCHES("test b: nope", ": test$")
3248 ASSERT_EQ $none 0
3249 "###
3250)]
3251fn text_count_matches(
3252 text: String,
3254 pattern: String,
3256) -> Result<Value> {
3257 let n = super::args::text_count_matches_str(&text, &pattern, "TEXT_COUNT_MATCHES")?;
3258 Ok(Value::int(n))
3259}
3260
3261#[oxdock_func(pure, returns = TypeTag::ListOf(std::sync::Arc::new(TypeTag::String)))]
3274#[example(
3275 name = "grep",
3276 code = r###"
3277 # Matching lines come back as a list, in order.
3278 IMPORT [STD]
3279 LET $hits: LIST<STRING> = TEXT_GREP("one\ntwo\none more", "^one")
3280 ASSERT_EQ $hits.0 "one"
3281 ASSERT_EQ $hits.1 "one more"
3282
3283 # A miss binds an empty list, never an error.
3284 LET $miss: LIST<STRING> = TEXT_GREP("one\ntwo", "^z")
3285 LET $joined: STRING = TEXT_JOIN($miss, ",")
3286 ASSERT_EQ $joined ""
3287
3288 # The (?i) flag ignores case, so uppercase lines match too.
3289 LET $folded: LIST<STRING> = TEXT_GREP("One\ntwo\nONE more", "(?i)^one")
3290 ASSERT_EQ $folded.0 "One"
3291 ASSERT_EQ $folded.1 "ONE more"
3292 "###
3293)]
3294#[example(
3295 name = "grep invert",
3296 code = r###"
3297 # The invert option keeps every non-matching line instead.
3298 IMPORT [STD]
3299 LET $kept: LIST<STRING> = TEXT_GREP("one\ntwo\none more", "^one", {invert: true})
3300 ASSERT_EQ $kept.0 "two"
3301
3302 # A pattern matching every line binds an empty list, never an error.
3303 LET $none: LIST<STRING> = TEXT_GREP("one\ntwo", "^", {invert: true})
3304 LET $joined: STRING = TEXT_JOIN($none, ",")
3305 ASSERT_EQ $joined ""
3306
3307 # Options ride into placeholders as MAP literals. Placeholder
3308 # strings unescape only backslash and quote, so multiline text
3309 # arrives through a variable.
3310 LET $two_lines: STRING = "one\ntwo"
3311 LET $msg: STRING = 'kept:{{ STD::TEXT_GREP($two_lines, "^one", {invert: true}) }}'
3312 ASSERT_EQ $msg "kept:two"
3313 "###
3314)]
3315fn text_grep(
3316 text: String,
3318 pattern: String,
3320 #[options("invert?: BOOL")]
3322 #[optional]
3323 options: BTreeMap<String, Value>,
3324) -> Result<Value> {
3325 let invert = super::args::text_invert_flag(&options);
3328 Ok(super::args::text_list_value(super::args::text_grep_str(
3329 &text,
3330 &pattern,
3331 invert,
3332 "TEXT_GREP",
3333 )?))
3334}
3335
3336#[oxdock_func(returns = TypeTag::Bool)]
3347#[example(
3348 name = "drain to end",
3349 code = r###"
3350 # Capture two lines, then drain to end of stream with no sentinel line.
3351 IMPORT [STD]
3352 LET $cap: PIPE
3353 WITH_IO [stdout=$cap] {
3354 ECHO "one"
3355 ECHO "two"
3356 }
3357
3358 # The loop exits on close, and the count proves both lines drained.
3359 LET $n: INT = 0
3360 WHILE !EOF($cap) {
3361 WITH_IO [stdin=$cap] READ_LINE $line
3362 $n = $n + 1
3363 }
3364 ASSERT_EQ $n 2
3365 "###
3366)]
3367fn eof<P: ProcessManager>(
3368 cx: &mut StepCtx<P>,
3369 pipe: PipeHandle,
3371) -> Result<Value> {
3372 let info = cx.state.io.inspect_pipe(&pipe);
3373 Ok(Value::bool(info.closed && info.buffered == 0))
3374}
3375
3376fn task_poll_result_fields() -> Arc<[Field]> {
3380 Arc::from(vec![
3381 Field {
3382 name: "state".to_string(),
3383 ty: TypeTag::String,
3384 docs: "Task phase: `running` or `finished`.",
3385 optional: false,
3386 },
3387 Field {
3388 name: "ok".to_string(),
3389 ty: TypeTag::Bool,
3390 docs: "True unless the task failed.",
3391 optional: false,
3392 },
3393 Field {
3394 name: "stdout_tail".to_string(),
3395 ty: TypeTag::String,
3396 docs: "Bounded stdout tail, live while running.",
3397 optional: false,
3398 },
3399 Field {
3400 name: "stderr_tail".to_string(),
3401 ty: TypeTag::String,
3402 docs: "Bounded stderr tail, live while running.",
3403 optional: false,
3404 },
3405 Field {
3406 name: "truncated_bytes".to_string(),
3407 ty: TypeTag::Int,
3408 docs: "Dropped head bytes past the per-stream cap.",
3409 optional: false,
3410 },
3411 Field {
3412 name: "exit_code".to_string(),
3413 ty: TypeTag::Int,
3414 docs: "Process exit code, present once finished.",
3415 optional: true,
3416 },
3417 Field {
3418 name: "result".to_string(),
3419 ty: TypeTag::Any,
3420 docs: "Task `RETURN` value, present on clean finish.",
3421 optional: true,
3422 },
3423 Field {
3424 name: "error".to_string(),
3425 ty: TypeTag::String,
3426 docs: "Failure text, present on failed finish.",
3427 optional: true,
3428 },
3429 ])
3430}
3431
3432#[oxdock_func(returns = TypeTag::Record(task_poll_result_fields()))]
3445#[example(
3446 name = "running poll",
3447 code = r###"
3448 # A sleeping task is still running on the first poll.
3449 IMPORT [STD]
3450 LET $t: HANDLE = ASYNC { SLEEP 30s }
3451 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)
3452 ASSERT_EQ $m.state "running"
3453 ASSERT_EQ $m.ok true
3454 # Clean up the sleeper so the run ends promptly.
3455 CANCEL $t
3456 "###
3457)]
3458#[example(
3459 name = "finished poll",
3460 code = r###"
3461 # A finished task reports its value and final tails, then still awaits.
3462 IMPORT [STD]
3463 LET $t: HANDLE = ASYNC { ECHO "hi"; SLEEP 1s; RETURN "done" }
3464 # Do other work while the task runs; poll once it should be done.
3465 SLEEP 2s
3466 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)
3467 ASSERT_EQ $m.state "finished"
3468 ASSERT_EQ $m.result "done"
3469 LET $o: STRING = AWAIT $t
3470 ASSERT_EQ $o "done"
3471 "###
3472)]
3473fn task_poll<P: ProcessManager>(
3474 cx: &mut StepCtx<P>,
3475 task: HandleValue,
3477) -> Result<Value> {
3478 let entry =
3479 super::handlers::resolve_task_entry_by_id(task.0, &format!("TASK_POLL({})", task.0), cx)?;
3480 let obs = entry.observe_completion();
3481 let (stdout_tail, stderr_tail, dropped) = entry.snapshot_tails();
3482 let mut out = BTreeMap::new();
3483 out.insert(
3484 "state".to_string(),
3485 Value::string(if obs.running { "running" } else { "finished" }.to_string()),
3486 );
3487 out.insert("ok".to_string(), Value::bool(obs.ok));
3488 if !obs.running {
3489 out.insert("exit_code".to_string(), Value::int(obs.exit_code));
3490 }
3491 if let Some(result) = obs.result {
3492 out.insert("result".to_string(), result);
3493 }
3494 if !obs.error.is_empty() {
3495 out.insert("error".to_string(), Value::string(obs.error));
3496 }
3497 out.insert("stdout_tail".to_string(), Value::string(stdout_tail));
3498 out.insert("stderr_tail".to_string(), Value::string(stderr_tail));
3499 out.insert(
3500 "truncated_bytes".to_string(),
3501 Value::int(dropped.min(i64::MAX as u64) as i64),
3502 );
3503 Ok(Value::map(out))
3504}
3505
3506fn meta_to_value(meta: &FuncMeta) -> Value {
3507 let mut map = BTreeMap::new();
3508 map.insert("name".to_string(), Value::string(meta.name.clone()));
3509 map.insert("module".to_string(), Value::string(meta.module.clone()));
3510 map.insert(
3511 "kind".to_string(),
3512 Value::string(meta.kind.label().to_string()),
3513 );
3514 let params = match &meta.params {
3515 Some(params) => Value::list(
3516 params
3517 .iter()
3518 .map(|p| {
3519 let mut entry = BTreeMap::new();
3520 entry.insert("name".to_string(), Value::string(p.name.clone()));
3521 entry.insert(
3522 "param_type".to_string(),
3523 Value::string(
3524 p.param_type
3525 .as_ref()
3526 .map(render_structural)
3527 .unwrap_or_default(),
3528 ),
3529 );
3530 entry.insert(
3531 "allowed".to_string(),
3532 Value::string(
3533 p.allowed
3534 .map(|values| values.join(", "))
3535 .unwrap_or_default(),
3536 ),
3537 );
3538 entry.insert("docs".to_string(), Value::string(String::new()));
3539 entry.insert("optional".to_string(), Value::bool(p.optional));
3540 entry.insert(
3541 "options".to_string(),
3542 match p.options {
3543 Some(keys) => Value::list(
3544 keys.iter()
3545 .map(|key| {
3546 let mut option = BTreeMap::new();
3547 option.insert(
3548 "name".to_string(),
3549 Value::string(key.name.to_string()),
3550 );
3551 option.insert(
3552 "value_type".to_string(),
3553 Value::string(render_structural(&key.value)),
3554 );
3555 option.insert(
3556 "required".to_string(),
3557 Value::bool(key.required),
3558 );
3559 option.insert(
3560 "default".to_string(),
3561 Value::string(
3562 key.default.unwrap_or_default().to_string(),
3563 ),
3564 );
3565 Value::map(option)
3566 })
3567 .collect(),
3568 ),
3569 None => Value::string(String::new()),
3570 },
3571 );
3572 Value::map(entry)
3573 })
3574 .collect(),
3575 ),
3576 None => Value::list(Vec::new()),
3580 };
3581 map.insert("params".to_string(), params);
3582 map.insert(
3583 "returns".to_string(),
3584 Value::string(
3585 meta.returns
3586 .as_ref()
3587 .map(render_structural)
3588 .unwrap_or_default(),
3589 ),
3590 );
3591 map.insert("rpn".to_string(), Value::bool(meta.rpn));
3592 map.insert(
3593 "summary".to_string(),
3594 Value::string(meta.summary.to_string()),
3595 );
3596 Value::map(map)
3597}
3598
3599#[derive(Debug, Clone)]
3603pub struct RecordSchema {
3604 pub name: &'static str,
3605 pub fields: std::sync::Arc<[Field]>,
3606}
3607
3608#[derive(Clone)]
3612pub struct HostModule<P: ProcessManager> {
3613 pub name: String,
3614 pub funcs: Vec<HostRegistration<P>>,
3615 pub types: Vec<&'static TypeDescriptor>,
3616 pub record_schemas: Vec<RecordSchema>,
3617 pub states: Vec<ModuleState>,
3624}
3625
3626#[derive(Clone)]
3630pub struct ModuleState {
3631 id: std::any::TypeId,
3632 state: std::sync::Arc<dyn std::any::Any + Send + Sync>,
3633}
3634
3635pub type PreRunInspector = dyn Fn(&[Step]) -> Result<()> + Send + Sync;
3639
3640#[derive(Clone)]
3646pub struct PreRunCheck {
3647 check: Arc<PreRunInspector>,
3648}
3649
3650impl PreRunCheck {
3651 pub fn new(check: impl Fn(&[Step]) -> Result<()> + Send + Sync + 'static) -> Self {
3653 Self {
3654 check: Arc::new(check),
3655 }
3656 }
3657
3658 pub fn run(&self, steps: &[Step]) -> Result<()> {
3660 (self.check)(steps)
3661 }
3662}
3663
3664impl<P: ProcessManager> HostModule<P> {
3665 pub fn with_state<T: Send + Sync + 'static>(mut self, state: std::sync::Arc<T>) -> Self {
3668 self.states.push(ModuleState {
3669 id: std::any::TypeId::of::<T>(),
3670 state,
3671 });
3672 self
3673 }
3674
3675 pub fn check_pre_run(&self, steps: &[Step]) -> Result<()> {
3679 for state in &self.states {
3680 if let Some(check) = state.state.downcast_ref::<PreRunCheck>() {
3681 check.run(steps)?;
3682 }
3683 }
3684 Ok(())
3685 }
3686}
3687
3688impl<P: ProcessManager> ExecState<P> {
3689 pub fn register_module(&mut self, module: HostModule<P>) {
3692 for registration in module.funcs {
3693 match registration {
3694 HostRegistration::Stateful { name, meta, func } => {
3695 self.functions.register_host(&module.name, name, meta, func);
3696 }
3697 HostRegistration::Pure { name, meta, func } => {
3698 self.functions
3699 .register_pure_host(&module.name, name, meta, func);
3700 }
3701 HostRegistration::Both {
3702 name,
3703 meta,
3704 func,
3705 template,
3706 } => {
3707 self.functions
3708 .register_both_host(&module.name, name, meta, func, template);
3709 }
3710 }
3711 }
3712 for descriptor in module.types {
3713 self.register_type(descriptor);
3714 }
3715 for schema in module.record_schemas {
3716 self.register_record_schema(schema.name, schema.fields);
3717 }
3718 for state in module.states {
3719 self.module_states
3720 .insert((module.name.clone(), state.id), state.state);
3721 }
3722 }
3723
3724 pub fn list_functions(&self) -> Vec<FuncMeta> {
3726 let mut out: Vec<FuncMeta> = self.functions.entries_metas().into_iter().collect();
3727 if !out.iter().any(|m| m.name == KEYWORD_INSPECT) {
3729 out.push(FuncMeta {
3730 name: KEYWORD_INSPECT.to_string(),
3731 module: STD_MODULE_NAME.to_string(),
3732 kind: FuncKind::HostCtx,
3733 params: None,
3734 returns: Some(TypeTag::Map),
3735 rpn: false,
3736 summary: "Inspect a variable binding.",
3737 docs: "INSPECT($var): dedicated AST node taking a variable, not a value.",
3738 examples: &[],
3739 });
3740 }
3741 out.sort_by(|a, b| a.name.cmp(&b.name));
3742 out
3743 }
3744
3745 pub fn describe_function(&self, name: &str) -> Option<Value> {
3747 if let Some(meta) = self.functions.meta(name) {
3748 return Some(meta_to_value(&meta));
3749 }
3750 if name == KEYWORD_INSPECT {
3752 return Some(meta_to_value(&FuncMeta {
3753 name: KEYWORD_INSPECT.to_string(),
3754 module: STD_MODULE_NAME.to_string(),
3755 kind: FuncKind::HostCtx,
3756 params: None,
3757 returns: Some(TypeTag::Map),
3758 rpn: false,
3759 summary: "Inspect a variable binding.",
3760 docs: "INSPECT($var): dedicated AST node taking a variable, not a value.",
3761 examples: &[],
3762 }));
3763 }
3764 None
3765 }
3766
3767 pub(super) fn clone_native_pure(&self, name: &str) -> Option<PureFn> {
3768 self.functions.clone_pure_fn(name)
3769 }
3770
3771 pub fn pure_function_table(&self) -> Arc<PureTable> {
3776 self.functions.pure_shared()
3777 }
3778
3779 pub(super) fn clone_native_ctx(&self, name: &str) -> Option<NativeFn<P>> {
3780 self.functions.clone_ctx_fn(name)
3781 }
3782
3783 pub(super) fn native_meta(&self, name: &str) -> Option<FuncMeta> {
3784 self.functions.meta(name)
3785 }
3786}
3787
3788#[cfg(test)]
3789mod tests {
3790 use super::*;
3791
3792 #[test]
3793 fn describe_entry_renders_union_spellings() {
3794 let union = oxdock_parser::union_tag!(String, Pipe);
3800 let meta = FuncMeta {
3801 name: "T::F".to_string(),
3802 module: "T".to_string(),
3803 kind: FuncKind::HostPure,
3804 params: Some(vec![FuncParam {
3805 name: "text".to_string(),
3806 param_type: Some(union.clone()),
3807 allowed: None,
3808 docs: "",
3809 options: None,
3810 optional: false,
3811 }]),
3812 returns: Some(union),
3813 rpn: false,
3814 summary: "test-only",
3815 docs: "test-only",
3816 examples: &[],
3817 };
3818 let value = meta_to_value(&meta);
3819 let map = value.as_map().expect("describe value is a map");
3820 let params = map
3821 .get("params")
3822 .expect("params key")
3823 .as_list()
3824 .expect("params is a list");
3825 let first = params[0].as_map().expect("entry is a map");
3826 assert_eq!(
3827 first.get("param_type").and_then(Value::as_str),
3828 Some("STRING|PIPE"),
3829 "param renders the set"
3830 );
3831 assert_eq!(
3832 map.get("returns").and_then(Value::as_str),
3833 Some("STRING|PIPE"),
3834 "returns render the set"
3835 );
3836 }
3837
3838 #[test]
3839 fn describe_entry_carries_optional_flag() {
3840 let meta = FuncMeta {
3844 name: "T::F".to_string(),
3845 module: "T".to_string(),
3846 kind: FuncKind::HostPure,
3847 params: Some(vec![
3848 FuncParam {
3849 name: "url".to_string(),
3850 param_type: Some(TypeTag::String),
3851 allowed: None,
3852 docs: "",
3853 options: None,
3854 optional: false,
3855 },
3856 FuncParam {
3857 name: "options".to_string(),
3858 param_type: Some(TypeTag::Map),
3859 allowed: None,
3860 docs: "",
3861 options: None,
3862 optional: true,
3863 },
3864 ]),
3865 returns: Some(TypeTag::String),
3866 rpn: false,
3867 summary: "test-only",
3868 docs: "test-only",
3869 examples: &[],
3870 };
3871 let value = meta_to_value(&meta);
3872 let map = value.as_map().expect("describe value is a map");
3873 let params = map
3874 .get("params")
3875 .expect("params key")
3876 .as_list()
3877 .expect("params is a list");
3878 assert_eq!(params.len(), 2);
3879 let first = params[0].as_map().expect("entry is a map");
3880 let second = params[1].as_map().expect("entry is a map");
3881 assert_eq!(
3882 first.get("optional").and_then(Value::as_bool),
3883 Some(false),
3884 "required param must read false"
3885 );
3886 assert_eq!(
3887 second.get("optional").and_then(Value::as_bool),
3888 Some(true),
3889 "omittable param must read true"
3890 );
3891 }
3892
3893 #[test]
3894 fn template_twins_mirror_string_paths_and_refuse_pipes() {
3895 let pipe = Value::pipe_fresh();
3901 type TwinCase = (&'static str, Box<dyn Fn() -> Result<Value>>);
3902 let cases: Vec<TwinCase> = vec![
3903 (
3904 "TEXT_TRIM",
3905 Box::new(|| text_trim_string(Value::string(" hello ".to_string()))),
3906 ),
3907 (
3908 "TEXT_TRIM_PREFIX",
3909 Box::new(|| {
3910 text_trim_prefix_string(Value::string("v1".to_string()), "v".to_string())
3911 }),
3912 ),
3913 (
3914 "TEXT_TRIM_SUFFIX",
3915 Box::new(|| {
3916 text_trim_suffix_string(Value::string("a.gz".to_string()), "x".to_string())
3917 }),
3918 ),
3919 (
3920 "TEXT_TO_UPPER",
3921 Box::new(|| text_to_upper_string(Value::string("hi".to_string()))),
3922 ),
3923 (
3924 "TEXT_TO_LOWER",
3925 Box::new(|| text_to_lower_string(Value::string("HI".to_string()))),
3926 ),
3927 (
3928 "TEXT_REPLACE",
3929 Box::new(|| {
3930 text_replace_string(
3931 Value::string("ab".to_string()),
3932 "b".to_string(),
3933 "c".to_string(),
3934 )
3935 }),
3936 ),
3937 (
3938 "TEXT_REPLACE_REGEX",
3939 Box::new(|| {
3940 text_replace_regex_string(
3941 Value::string("ab".to_string()),
3942 "b".to_string(),
3943 "c".to_string(),
3944 )
3945 }),
3946 ),
3947 ];
3948 assert_eq!(cases.len(), 7, "every mirror op needs a twin row");
3949 for (name, run) in &cases {
3950 let value = run().unwrap_or_else(|e| panic!("{name} twin must answer strings: {e:#}"));
3951 assert!(
3952 value.as_str().is_some(),
3953 "{name} twin must answer STRING, got {}",
3954 value.type_name()
3955 );
3956 }
3957 assert_eq!(
3958 text_trim_string(Value::string(" hello ".to_string()))
3959 .expect("trim twin")
3960 .as_str(),
3961 Some("hello")
3962 );
3963 let pipe_cases: Vec<(&str, Result<Value>)> = vec![
3965 ("TEXT_TRIM", text_trim_string(pipe.clone())),
3966 (
3967 "TEXT_TRIM_PREFIX",
3968 text_trim_prefix_string(pipe.clone(), "v".to_string()),
3969 ),
3970 (
3971 "TEXT_TRIM_SUFFIX",
3972 text_trim_suffix_string(pipe.clone(), ".gz".to_string()),
3973 ),
3974 ("TEXT_TO_UPPER", text_to_upper_string(pipe.clone())),
3975 ("TEXT_TO_LOWER", text_to_lower_string(pipe.clone())),
3976 (
3977 "TEXT_REPLACE",
3978 text_replace_string(pipe.clone(), "a".to_string(), "b".to_string()),
3979 ),
3980 (
3981 "TEXT_REPLACE_REGEX",
3982 text_replace_regex_string(pipe.clone(), "a".to_string(), "b".to_string()),
3983 ),
3984 ];
3985 for (name, result) in pipe_cases {
3986 let err = result.expect_err(&format!("{name} twin must refuse PIPE"));
3987 assert!(
3988 format!("{err:#}").contains("step IO"),
3989 "{name} refusal names the missing context: {err:#}"
3990 );
3991 }
3992 }
3993
3994 #[test]
3995 fn shell_words_join_split_round_trip() {
3996 let words = vec![
4000 "gh".to_string(),
4001 "issue".to_string(),
4002 "comment".to_string(),
4003 "with spaces".to_string(),
4004 "it's".to_string(),
4005 "say \"hi\"".to_string(),
4006 "$HOME".to_string(),
4007 "$(whoami)".to_string(),
4008 "C:\\path\\to".to_string(),
4009 "naïve café".to_string(),
4010 "".to_string(),
4011 ];
4012 let joined = shell_words::join(&words);
4013 let back = shell_words::split(&joined).expect("join output must parse");
4014 assert_eq!(back, words);
4015 assert!(shell_words::split("unbalanced \"quote").is_err());
4016 }
4017}