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(oxdock_utils::hex_encode(bytes)))
1231}
1232
1233#[oxdock_func(rpn, returns = TypeTag::String)]
1244#[example(
1245 name = "cwd",
1246 code = r###"
1247 IMPORT [STD]
1248 WORKDIR sub
1249 LET $c: STRING = CWD()
1250 ASSERT_CONTAINS $c "sub"
1251 "###
1252)]
1253fn cwd<P: ProcessManager>(cx: &mut StepCtx<P>) -> Result<Value> {
1254 if cx.state.fs.is_snapshot_pending() {
1255 return Ok(Value::string(super::SNAPSHOT_PENDING_DISPLAY.to_string()));
1256 }
1257 let concrete = cx.state.fs.concretize_cwd(&cx.state.cwd);
1258 let real = super::fs_ops::canonical_cwd(cx.state.fs.as_ref(), &concrete)?;
1259 Ok(Value::string(real))
1260}
1261
1262#[oxdock_func(pure, returns = TypeTag::MapOf(std::sync::Arc::new(TypeTag::Any)))]
1268#[example(
1269 name = "parse",
1270 code = r###"
1271 IMPORT [STD]
1272 LET $doc: MAP<ANY> = PARSE_TOML("title = \"demo\"")
1273 ASSERT_EQ $doc.title "demo"
1274 "###
1275)]
1276fn parse_toml(
1277 text: String,
1279) -> Result<Value> {
1280 super::args::parse_toml_from_value(Value::string(text))
1281}
1282
1283#[oxdock_func(pure, returns = TypeTag::Any)]
1292#[example(
1293 name = "parse",
1294 code = r###"
1295 # Parse in-memory JSON text with the same conversion as file loading.
1296 IMPORT [STD]
1297 LET $body: STRING = "{\"a\": 1}"
1298 LET $doc: ANY = PARSE_JSON($body)
1299 ASSERT_EQ $doc.a 1
1300
1301 # Top-level arrays parse to LIST, which is why the return is ANY.
1302 LET $items: LIST<ANY> = PARSE_JSON("[1, 2]")
1303 ASSERT_EQ $items.0 1
1304 ASSERT_EQ $items.1 2
1305 "###
1306)]
1307fn parse_json(
1308 text: String,
1310) -> Result<Value> {
1311 super::args::parse_json_from_value(Value::string(text))
1312}
1313
1314#[oxdock_func(returns = TypeTag::String)]
1320#[example(
1321 name = "describe",
1322 code = r###"
1323 IMPORT [STD]
1324 WRITE "entry.txt" "words"
1325 LET $kind: STRING = PATH_TYPE("entry.txt")
1326 ASSERT_EQ $kind "file"
1327 LET $missing: STRING = PATH_TYPE("no-such-entry.txt")
1328 ASSERT_EQ $missing "absent"
1329 "###
1330)]
1331fn path_type<P: ProcessManager>(
1332 cx: &mut StepCtx<P>,
1333 #[union(String, Path)]
1335 path: Value,
1336) -> Result<Value> {
1337 let text = super::args::string_or_path_text(&path)?;
1338 super::args::path_type_from_value(&[Value::string(text)], cx)
1339}
1340
1341#[oxdock_func(returns = TypeTag::Bool)]
1350#[example(
1351 name = "probe",
1352 code = r###"
1353 # An absent nested path is writable when its ancestor is.
1354 IMPORT [STD]
1355 LET $fresh: BOOL = PATH_WRITABLE("probe-check/nested/file.txt")
1356 ASSERT_EQ $fresh true
1357
1358 # The empty string never aliases the working directory.
1359 LET $empty: BOOL = PATH_WRITABLE("")
1360 ASSERT_EQ $empty false
1361 "###
1362)]
1363fn path_writable<P: ProcessManager>(
1364 cx: &mut StepCtx<P>,
1365 #[union(String, Path)]
1367 path: Value,
1368) -> Result<Value> {
1369 let text = super::args::string_or_path_text(&path)?;
1370 super::args::path_writable_from_value(&[Value::string(text)], cx)
1371}
1372
1373#[oxdock_func(returns = TypeTag::Bool)]
1386#[example(
1387 name = "probe",
1388 code = r###"
1389 # Missing tools read false instead of failing the run.
1390 IMPORT [STD]
1391 LET $missing: BOOL = IS_EXEC("no-such-tool-xyz")
1392 ASSERT_EQ $missing false
1393
1394 # Plain files are not executable on any platform.
1395 WRITE tool.txt payload
1396 LET $plain: BOOL = IS_EXEC("tool.txt")
1397 ASSERT_EQ $plain false
1398 "###
1399)]
1400fn is_exec<P: ProcessManager>(
1401 cx: &mut StepCtx<P>,
1402 #[union(String, Path)]
1404 name: Value,
1405) -> Result<Value> {
1406 let text = super::args::string_or_path_text(&name)?;
1407 super::args::is_exec_from_value(&[Value::string(text)], cx)
1408}
1409
1410#[oxdock_func(pure, returns = TypeTag::Bool)]
1416#[example(
1417 name = "probe",
1418 code = r###"
1419 IMPORT [STD]
1420 LET $m: MAP<ANY> = PARSE_JSON("{\"a\": 1}")
1421 LET $hit: BOOL = HAS_KEY($m, "a")
1422 ASSERT_EQ $hit true
1423 LET $miss: BOOL = HAS_KEY($m, "b")
1424 ASSERT_EQ $miss false
1425 "###
1426)]
1427fn has_key(
1428 map: BTreeMap<String, Value>,
1430 key: String,
1432) -> Result<Value> {
1433 super::args::has_key_from_value(Value::map(map), &key)
1434}
1435
1436#[oxdock_func(pure, returns = TypeTag::MapOf(std::sync::Arc::new(TypeTag::Any)))]
1442#[example(
1443 name = "insert",
1444 code = r###"
1445 IMPORT [STD]
1446 LET $m: MAP<ANY> = MAP_SET({seed: 0}, "a", 1)
1447 ASSERT_EQ $m.a 1
1448 "###
1449)]
1450fn map_set(
1451 map: BTreeMap<String, Value>,
1453 key: String,
1455 value: Value,
1457) -> Result<Value> {
1458 super::args::map_set_from_value(Value::map(map), key, value)
1459}
1460
1461#[oxdock_func(returns = TypeTag::Float, summary = "Draw a random FLOAT uniformly from [0, 1), optionally seeded.")]
1469#[example(
1470 name = "seeded draw",
1471 code = r###"
1472 # A seed draws the same value on every run.
1473 IMPORT [STD]
1474 LET $one: FLOAT = RAND({seed: 7})
1475 LET $two: FLOAT = RAND({seed: 7})
1476 ASSERT_EQ $one $two
1477 "###
1478)]
1479#[example(
1480 name = "unseeded draw",
1481 code = r###"
1482 # Scale a unit draw into a backoff delay between 1 and 11 seconds.
1483 IMPORT [STD]
1484 LET $draw: FLOAT = RAND()
1485 LET $delay: FLOAT = 1.0 + $draw * 10.0
1486 IF $delay < 1.0 {
1487 EXIT 1
1488 }
1489 IF $delay >= 11.0 {
1490 EXIT 1
1491 }
1492 ECHO "retrying in {{ $delay }}s"
1493 "###
1494)]
1495fn rand<P: ProcessManager>(
1496 cx: &mut StepCtx<P>,
1497 #[options("seed?: INT")]
1499 #[optional]
1500 options: BTreeMap<String, Value>,
1501) -> Result<Value> {
1502 let _ = cx;
1503 let seed = options
1506 .get("seed")
1507 .map(|value| value.as_i64().expect("check_options verified INT"));
1508 super::args::rand_float_from_value(seed)
1509}
1510
1511#[oxdock_func(pure, returns = TypeTag::String)]
1517#[example(
1518 name = "encode",
1519 code = r###"
1520 # Encode text to standard base64.
1521 IMPORT [STD]
1522 LET $encoded: STRING = BASE64_ENCODE("hello")
1523 ASSERT_EQ $encoded "aGVsbG8="
1524 "###
1525)]
1526fn base64_encode(
1527 text: String,
1529) -> Result<Value> {
1530 super::args::base64_encode_from_value(Value::string(text))
1531}
1532
1533#[oxdock_func(pure, returns = TypeTag::String)]
1540#[example(
1541 name = "decode",
1542 code = r###"
1543 # Decode standard base64 back to text.
1544 IMPORT [STD]
1545 LET $decoded: STRING = BASE64_DECODE("aGVsbG8=")
1546 ASSERT_EQ $decoded "hello"
1547 "###
1548)]
1549fn base64_decode(
1550 text: String,
1552) -> Result<Value> {
1553 super::args::base64_decode_from_value(Value::string(text))
1554}
1555
1556#[oxdock_func(pure, returns = TypeTag::String)]
1563#[example(
1564 name = "encode",
1565 code = r###"
1566 IMPORT [STD]
1567 LET $json: STRING = TO_JSON({a: 1})
1568 ASSERT_EQ $json "{\"a\":1}\n"
1569 "###
1570)]
1571fn to_json(
1572 #[union(String, Int, Float, Bool, List, Map)]
1574 value: Value,
1575) -> Result<Value> {
1576 super::args::to_json_from_value(value)
1577}
1578
1579#[oxdock_func(pure, returns = TypeTag::String)]
1587#[example(
1588 name = "name the word",
1589 code = r###"
1590 IMPORT [STD]
1591 LET $word: STRING = TYPE_OF(42)
1592 ASSERT_EQ $word "INT"
1593 "###
1594)]
1595fn type_of(
1596 value: Value,
1598) -> Result<Value> {
1599 super::args::type_of_from_value(value)
1600}
1601
1602#[oxdock_func(pure, returns = TypeTag::MapOf(std::sync::Arc::new(TypeTag::Any)))]
1610#[example(
1611 name = "merge",
1612 code = r###"
1613 IMPORT [STD]
1614 LET $m: MAP<ANY> = MERGE_MAPS([{a: 1}, {b: 2}], "overwrite")
1615 ASSERT_EQ $m.a 1
1616 ASSERT_EQ $m.b 2
1617 "###
1618)]
1619fn merge_maps(
1620 maps: Vec<BTreeMap<String, Value>>,
1622 #[values("fail_on_duplicate", "overwrite")]
1624 policy: String,
1625) -> Result<Value> {
1626 super::args::merge_maps_from_value(
1627 Value::list(maps.into_iter().map(Value::map).collect()),
1628 policy,
1629 )
1630}
1631
1632#[oxdock_func(pure, returns = TypeTag::String)]
1637#[example(
1638 name = "report",
1639 code = r###"
1640 # The engine reports its own build version as a dotted string.
1641 IMPORT [STD]
1642 LET $v: STRING = VERSION()
1643 ASSERT_CONTAINS $v "."
1644 "###
1645)]
1646fn version() -> Result<Value> {
1647 Ok(Value::string(env!("CARGO_PKG_VERSION").to_string()))
1648}
1649
1650#[oxdock_func(returns = TypeTag::ListOf(std::sync::Arc::new(TypeTag::String)))]
1655#[example(
1656 name = "list",
1657 code = r###"
1658 IMPORT [STD]
1659 LET $names: LIST<STRING> = FUNCTIONS()
1660 ASSERT_CONTAINS $names "STD::INT"
1661 "###
1662)]
1663fn functions<P: ProcessManager>(cx: &mut StepCtx<P>) -> Result<Value> {
1664 let mut names: Vec<String> = cx
1665 .state
1666 .list_functions()
1667 .into_iter()
1668 .map(|meta| meta.name)
1669 .collect();
1670 names.sort();
1671 names.dedup();
1672 Ok(Value::list(names.into_iter().map(Value::string).collect()))
1673}
1674
1675#[oxdock_func(
1690 returns = TypeTag::Record(std::sync::Arc::from([Field {
1691 name: "name".to_string(),
1692 ty: TypeTag::String,
1693 docs: "Qualified function name.",
1694 optional: false,
1695 }, Field {
1696 name: "module".to_string(),
1697 ty: TypeTag::String,
1698 docs: "Owning module.",
1699 optional: false,
1700 }, Field {
1701 name: "kind".to_string(),
1702 ty: TypeTag::String,
1703 docs: "Origin label (`host` or `script`).",
1704 optional: false,
1705 }, Field {
1706 name: "params".to_string(),
1707 ty: TypeTag::ListOf(std::sync::Arc::new(TypeTag::MapOf(std::sync::Arc::new(
1708 TypeTag::Any,
1709 )))),
1710 docs: "Parameter entries (empty for parameterless functions).",
1711 optional: false,
1712 }, Field {
1713 name: "returns".to_string(),
1714 ty: TypeTag::String,
1715 docs: "Structural return shape (empty when untagged).",
1716 optional: false,
1717 }, Field {
1718 name: "rpn".to_string(),
1719 ty: TypeTag::Bool,
1720 docs: "True when callable in RPN position.",
1721 optional: false,
1722 }, Field {
1723 name: "summary".to_string(),
1724 ty: TypeTag::String,
1725 docs: "One-line description.",
1726 optional: false,
1727 }]))
1728 summary = "Describe one function by qualified name."
1729)]
1730#[example(
1731 name = "describe",
1732 code = r###"
1733 IMPORT [STD]
1734 LET $info: MAP<ANY> = DESCRIBE("STD::INT")
1735 ASSERT_EQ $info.name "STD::INT"
1736 ASSERT_EQ $info.returns "INT"
1737 "###
1738)]
1739fn describe<P: ProcessManager>(
1740 cx: &mut StepCtx<P>,
1741 name: String,
1743) -> Result<Value> {
1744 if split_qualified(&name).is_none() && name != KEYWORD_INSPECT {
1745 anyhow::bail!(
1746 "unknown function `{name}`: DESCRIBE requires a qualified name (e.g. `STD::{name}`)"
1747 );
1748 }
1749 cx.state
1750 .describe_function(&name)
1751 .ok_or_else(|| anyhow::anyhow!("unknown function {name}"))
1752}
1753
1754#[oxdock_func(returns = TypeTag::ListOf(std::sync::Arc::new(TypeTag::String)))]
1760#[example(
1761 name = "list",
1762 code = r###"
1763 IMPORT [STD]
1764 LET $names: LIST<STRING> = TYPES()
1765 ASSERT_CONTAINS $names "STRING"
1766 "###
1767)]
1768fn types<P: ProcessManager>(cx: &mut StepCtx<P>) -> Result<Value> {
1769 Ok(Value::list(
1770 cx.state
1771 .type_names()
1772 .into_iter()
1773 .map(Value::string)
1774 .collect(),
1775 ))
1776}
1777
1778#[oxdock_func(returns = TypeTag::Record(std::sync::Arc::from([Field {
1784 name: "name".to_string(),
1785 ty: TypeTag::String,
1786 docs: "Queried type name.",
1787 optional: false,
1788}, Field {
1789 name: "summary".to_string(),
1790 ty: TypeTag::String,
1791 docs: "One-line description.",
1792 optional: false,
1793}, Field {
1794 name: "docs".to_string(),
1795 ty: TypeTag::String,
1796 docs: "Full documentation text.",
1797 optional: false,
1798}])))]
1799#[example(
1800 name = "describe",
1801 code = r###"
1802 IMPORT [STD]
1803 LET $info: MAP<ANY> = TYPE_DESCRIBE("STRING")
1804 ASSERT_EQ $info.name "STRING"
1805 "###
1806)]
1807fn type_describe<P: ProcessManager>(
1808 cx: &mut StepCtx<P>,
1809 name: String,
1811) -> Result<Value> {
1812 if let Some(descriptor) = cx.state.describe_type(&name) {
1813 let mut map = BTreeMap::new();
1814 map.insert(
1815 "name".to_string(),
1816 Value::string(descriptor.name.to_string()),
1817 );
1818 map.insert(
1819 "summary".to_string(),
1820 Value::string(descriptor.summary.to_string()),
1821 );
1822 map.insert(
1823 "docs".to_string(),
1824 Value::string(descriptor.docs.to_string()),
1825 );
1826 return Ok(Value::map(map));
1827 }
1828 if let Some(target) = cx.state.alias_target(&name) {
1831 let mut map = BTreeMap::new();
1832 map.insert("name".to_string(), Value::string(name.clone()));
1833 map.insert(
1834 "summary".to_string(),
1835 Value::string(format!("Script type alias for {target}.")),
1836 );
1837 map.insert(
1838 "docs".to_string(),
1839 Value::string(format!(
1840 "Declared with TYPE {name} = {target}. The alias expands structurally at every declaration."
1841 )),
1842 );
1843 return Ok(Value::map(map));
1844 }
1845 Err(anyhow::anyhow!("unknown type {name}"))
1846}
1847
1848#[oxdock_func(returns = TypeTag::String)]
1862#[example(
1863 name = "self",
1864 code = r###"
1865 # The running interpreter resolves to a non-empty path.
1866 IMPORT [STD]
1867 LET $exe: STRING = INTERPRETER()
1868 LET $nonempty: BOOL = $exe != ""
1869 ASSERT_EQ $nonempty true
1870 "###
1871)]
1872#[example(
1873 name = "dynamic composition",
1874 code = r###"
1875 # Compose the child script dynamically: the parent interpolates
1876 # its own bindings into the pipe, then runs the interpreter on it.
1877 # Unescaped {{ }} bakes in at compose time; \{{ }} stays literal
1878 # so the child expands it with its own bindings.
1879 # The pipe delivers EOF when the producer step ends, so the child
1880 # reads exactly one script.
1881 IMPORT [STD]
1882 LET $exe: STRING = INTERPRETER()
1883 LET $who: STRING = "Ada"
1884 LET $child: PIPE
1885 WITH_IO [stdout=$child] ECHO """
1886 ECHO "hello {{ $who }}!"
1887 LET $who: STRING = "Grace"
1888 ECHO "child sees \{{ $who }}!"
1889 """
1890 LET $out: STRING = WITH_IO [stdin=$child] RUN [$exe]
1891 ASSERT_CONTAINS $out "hello Ada!"
1892 ASSERT_CONTAINS $out "child sees Grace!"
1893 "###
1894)]
1895fn interpreter<P: ProcessManager>(cx: &mut StepCtx<P>) -> Result<Value> {
1896 if let Some(staged) = cx.state.io.interpreter_override() {
1897 return Ok(Value::string(staged));
1898 }
1899 Ok(Value::string(oxdock_process::interpreter_exe()?))
1900}
1901
1902#[oxdock_func(returns = TypeTag::Bool)]
1910#[example(
1911 name = "main",
1912 code = r###"
1913 # Entry top level runs as main.
1914 IMPORT [STD]
1915 LET $m: BOOL = IS_MAIN()
1916 ASSERT_EQ $m true
1917 "###
1918)]
1919#[example(
1920 name = "library doubles as demo",
1921 fence_meta = "roots:unified",
1922 code = r###"
1923 # A library doubles as a runnable demo: guard the demo with
1924 # IF IS_MAIN() so importing it stays side effect free. The
1925 # parent writes both files, then runs each in a fresh
1926 # interpreter: direct execution prints the demo, importing
1927 # it does not. Unified roots: the child inherits one
1928 # workspace, so parent and child see the same files. The
1929 # exact stdout match proves the demo line stays out of the
1930 # importing run.
1931 IMPORT [STD]
1932
1933 # The library under test: demo guarded by IS_MAIN.
1934 WRITE lib.oxfile """
1935 IMPORT [STD]
1936 FUNC GREET($x: STRING) { RETURN "hi \{{ $x }}" }
1937 EXPORT GREET
1938 IF IS_MAIN() {
1939 ECHO "demo: hi Ada"
1940 }
1941 """
1942
1943 # The importer: calls the library, prints only its own line.
1944 WRITE main.oxfile """
1945 IMPORT ["lib.oxfile" AS LIB]
1946 LET $g: STRING = LIB::GREET("Bo")
1947 ECHO "imported: \{{ $g }}"
1948 """
1949
1950 # Direct run executes the demo.
1951 LET $exe: STRING = INTERPRETER()
1952 LET $direct: STRING = RUN [$exe, "lib.oxfile"]
1953 ASSERT_CONTAINS $direct "demo: hi Ada"
1954
1955 # Importing run stays silent apart from its own line.
1956 LET $via: STRING = RUN [$exe, "main.oxfile"]
1957 ASSERT_EQ $via "imported: hi Bo\n"
1958 "###
1959)]
1960fn is_main<P: ProcessManager>(cx: &mut StepCtx<P>) -> Result<Value> {
1961 let main = match cx.state.module_stack.last() {
1962 None | Some(None) => true,
1963 Some(Some(_)) => false,
1964 };
1965 Ok(Value::bool(main))
1966}
1967
1968#[oxdock_func(returns = TypeTag::Bool)]
1982#[example(
1983 name = "null stdin",
1984 code = r###"
1985 # A null stdin is never a terminal, in every harness.
1986 IMPORT [STD]
1987 LET $term: BOOL = IS_TERMINAL("stdin")
1988 ASSERT_EQ $term false
1989 "###
1990)]
1991fn is_terminal<P: ProcessManager>(
1992 cx: &mut StepCtx<P>,
1993 #[values("stdin", "stdout", "stderr")]
1995 stream_name: String,
1996) -> Result<Value> {
1997 use std::io::IsTerminal;
1998 let terminal = match stream_name.as_str() {
1999 "stdin" => {
2000 if cx.stdin_pipe.is_some() {
2005 false
2006 } else {
2007 match &cx.stdin {
2008 CommandStdin::Null => false,
2009 #[cfg(not(miri))]
2010 CommandStdin::OsPipe(_) => false,
2011 CommandStdin::Stream(_) => false,
2012 CommandStdin::Inherit => std::io::stdin().is_terminal(),
2013 }
2014 }
2015 }
2016 "stdout" => {
2017 if cx.out_pipe.is_some() {
2018 false
2020 } else if cx.state.io.stdout().is_some() {
2021 false
2024 } else {
2025 match &cx.out {
2026 None => std::io::stdout().is_terminal(),
2028 #[cfg(not(miri))]
2030 Some(StreamHandle::Os(_)) => false,
2031 Some(StreamHandle::Stream(_)) => std::io::stdout().is_terminal(),
2041 }
2042 }
2043 }
2044 "stderr" => {
2045 if cx.state.io.stderr().is_some() {
2046 false
2048 } else {
2049 match &cx.err {
2050 None => std::io::stderr().is_terminal(),
2052 #[cfg(not(miri))]
2054 Some(StreamHandle::Os(_)) => false,
2055 Some(StreamHandle::Stream(_)) => false,
2058 }
2059 }
2060 }
2061 _ => anyhow::bail!(
2062 "IS_TERMINAL expects \"stdin\", \"stdout\", or \"stderr\", got {stream_name:?}"
2067 ),
2068 };
2069 Ok(Value::bool(terminal))
2070}
2071
2072#[oxdock_func(returns = TypeTag::Semaphore)]
2080#[example(
2081 name = "mint",
2082 code = r###"
2083 # Mint a semaphore admitting at most two holders.
2084 IMPORT [STD]
2085 LET $sem: SEMAPHORE = SEMAPHORE_NEW(2)
2086
2087 # A fresh semaphore reports its full cap as available.
2088 LET $free: INT = SEMAPHORE_AVAILABLE($sem)
2089 ASSERT_EQ $free 2
2090 "###
2091)]
2092fn semaphore_new<P: ProcessManager>(
2093 cx: &mut StepCtx<P>,
2094 max: i64,
2096) -> Result<Value> {
2097 let _ = cx;
2098 if max <= 0 {
2099 return Err(anyhow::anyhow!(
2100 "SEMAPHORE_NEW() requires a positive max, got {max}"
2101 ));
2102 }
2103 Ok(Value::semaphore(max as usize))
2104}
2105
2106#[oxdock_func(returns = TypeTag::Record(std::sync::Arc::from([Field {
2115 name: "held".to_string(),
2116 ty: TypeTag::Bool,
2117 docs: "`true` with the permit under `permit`, `false` with no `permit` key.",
2118 optional: false,
2119}, Field {
2120 name: "permit".to_string(),
2121 ty: TypeTag::Permit,
2122 docs: "Permit handle; read only when `held`.",
2123 optional: true,
2124}])))]
2125#[example(
2126 name = "acquire",
2127 code = r###"
2128 # First acquire holds with a permit to bind.
2129 IMPORT [STD]
2130 LET $sem: SEMAPHORE = SEMAPHORE_NEW(1)
2131 LET $first: MAP<held: BOOL, permit?: PERMIT> = SEMAPHORE_TRY_ACQUIRE($sem)
2132 ASSERT_EQ $first.held true
2133 LET $permit: PERMIT = $first.permit
2134
2135 # A capped semaphore answers held false with no permit key.
2136 LET $second: MAP<held: BOOL, permit?: PERMIT> = SEMAPHORE_TRY_ACQUIRE($sem)
2137 ASSERT_EQ $second.held false
2138 LET $has_permit: BOOL = HAS_KEY($second, "permit")
2139 ASSERT_EQ $has_permit false
2140 "###
2141)]
2142fn semaphore_try_acquire<P: ProcessManager>(
2143 cx: &mut StepCtx<P>,
2144 sem: Arc<SemaphoreState>,
2146) -> Result<Value> {
2147 let _ = cx;
2148 let mut map = BTreeMap::new();
2149 if sem.try_acquire() {
2150 map.insert("held".to_string(), Value::bool(true));
2151 map.insert("permit".to_string(), Value::permit(&sem));
2152 } else {
2153 map.insert("held".to_string(), Value::bool(false));
2154 }
2155 Ok(Value::map(map))
2156}
2157
2158#[oxdock_func(pure, returns = TypeTag::Int)]
2165#[example(
2166 name = "readout",
2167 code = r###"
2168 # Hold one permit on a cap of two.
2169 IMPORT [STD]
2170 LET $sem: SEMAPHORE = SEMAPHORE_NEW(2)
2171 LET $acq: MAP<held: BOOL, permit?: PERMIT> = SEMAPHORE_TRY_ACQUIRE($sem)
2172 ASSERT_EQ $acq.held true
2173
2174 # One held permit leaves exactly one free.
2175 LET $free: INT = SEMAPHORE_AVAILABLE($sem)
2176 ASSERT_EQ $free 1
2177 "###
2178)]
2179fn semaphore_available(
2180 sem: Arc<SemaphoreState>,
2182) -> Result<Value> {
2183 Ok(Value::int(sem.available() as i64))
2184}
2185
2186#[oxdock_func(
2195 rpn,
2196 returns = TypeTag::union(vec![TypeTag::String, TypeTag::Pipe]),
2197 template = text_trim_string
2198)]
2199#[example(
2200 name = "trim",
2201 code = r###"
2202 # Leading and trailing whitespace falls away.
2203 IMPORT [STD]
2204 LET $clean: STRING = TEXT_TRIM(" hello ")
2205 ASSERT_EQ $clean "hello"
2206 "###
2207)]
2208#[example(
2209 name = "trim pipe mirrors",
2210 code = r###"
2211 # Pipe input mints pipe output with the same transform.
2212 IMPORT [STD]
2213 LET $cap: PIPE
2214 WITH_IO [stdout=$cap] {
2215 ECHO " hello "
2216 }
2217 LET $out: PIPE = TEXT_TRIM($cap)
2218 WITH_IO [stdin=$out] READ_LINE $line
2219 ASSERT_EQ $line "hello"
2220 "###
2221)]
2222#[example(
2223 name = "trim template",
2224 code = r###"
2225 # String inputs run inside placeholders too.
2226 IMPORT [STD]
2227 LET $msg: STRING = 'clean:{{ STD::TEXT_TRIM(" hello ") }}'
2228 ASSERT_EQ $msg "clean:hello"
2229 "###
2230)]
2231#[example(
2232 name = "trim file template",
2233 code = r###"
2234 # EXPAND templates resolve the same registry.
2235 IMPORT [STD]
2236 WRITE "tpl.txt" "clean:\{{ STD::TEXT_TRIM(\" hello \") }}"
2237 LET $out: STRING = EXPAND "tpl.txt"
2238 ASSERT_EQ $out "clean:hello"
2239 "###
2240)]
2241fn text_trim<P: ProcessManager>(
2242 cx: &mut StepCtx<P>,
2243 #[union(String, Pipe)]
2245 text: Value,
2246) -> Result<Value> {
2247 super::args::mirror_stream(cx, "TEXT_TRIM", &text, super::args::TextPump::Trim)
2248}
2249
2250fn text_trim_string(text: Value) -> Result<Value> {
2253 super::args::mirror_string("TEXT_TRIM", &text, super::args::TextPump::Trim)
2254}
2255
2256#[oxdock_func(
2265 rpn,
2266 returns = TypeTag::union(vec![TypeTag::String, TypeTag::Pipe]),
2267 template = text_trim_prefix_string
2268)]
2269#[example(
2270 name = "strip prefix",
2271 code = r###"
2272 # A present prefix falls away; absence returns the input unchanged.
2273 IMPORT [STD]
2274 LET $bare: STRING = TEXT_TRIM_PREFIX("v1.2.3", "v")
2275 ASSERT_EQ $bare "1.2.3"
2276
2277 # Missing prefixes pass through untouched.
2278 LET $same: STRING = TEXT_TRIM_PREFIX("1.2.3", "v")
2279 ASSERT_EQ $same "1.2.3"
2280 "###
2281)]
2282#[example(
2283 name = "strip prefix pipe mirrors",
2284 code = r###"
2285 # Pipe input mints pipe output with the same strip.
2286 IMPORT [STD]
2287 LET $cap: PIPE
2288 WITH_IO [stdout=$cap] {
2289 ECHO "v1.2.3"
2290 }
2291 LET $trimmed: PIPE = TEXT_TRIM($cap)
2292 LET $out: PIPE = TEXT_TRIM_PREFIX($trimmed, "v")
2293 WITH_IO [stdin=$out] READ_LINE $line
2294 ASSERT_EQ $line "1.2.3"
2295 "###
2296)]
2297#[example(
2298 name = "strip prefix template",
2299 code = r###"
2300 # String inputs run inside placeholders too.
2301 IMPORT [STD]
2302 LET $msg: STRING = 'bare:{{ STD::TEXT_TRIM_PREFIX("v1.2.3", "v") }}'
2303 ASSERT_EQ $msg "bare:1.2.3"
2304 "###
2305)]
2306fn text_trim_prefix<P: ProcessManager>(
2307 cx: &mut StepCtx<P>,
2308 #[union(String, Pipe)]
2310 text: Value,
2311 prefix: String,
2313) -> Result<Value> {
2314 super::args::mirror_stream(
2315 cx,
2316 "TEXT_TRIM_PREFIX",
2317 &text,
2318 super::args::TextPump::TrimPrefix(prefix),
2319 )
2320}
2321
2322fn text_trim_prefix_string(text: Value, prefix: String) -> Result<Value> {
2325 super::args::mirror_string(
2326 "TEXT_TRIM_PREFIX",
2327 &text,
2328 super::args::TextPump::TrimPrefix(prefix),
2329 )
2330}
2331
2332#[oxdock_func(
2339 rpn,
2340 returns = TypeTag::union(vec![TypeTag::String, TypeTag::Pipe]),
2341 template = text_trim_suffix_string
2342)]
2343#[example(
2344 name = "strip suffix",
2345 code = r###"
2346 # A present suffix falls away; absence returns the input unchanged.
2347 IMPORT [STD]
2348 LET $bare: STRING = TEXT_TRIM_SUFFIX("archive.tar.gz", ".gz")
2349 ASSERT_EQ $bare "archive.tar"
2350
2351 # Missing suffixes pass through untouched.
2352 LET $same: STRING = TEXT_TRIM_SUFFIX("archive.tar", ".gz")
2353 ASSERT_EQ $same "archive.tar"
2354 "###
2355)]
2356#[example(
2357 name = "strip suffix pipe mirrors",
2358 code = r###"
2359 # Pipe input mints pipe output with the same strip.
2360 IMPORT [STD]
2361 LET $cap: PIPE
2362 WITH_IO [stdout=$cap] {
2363 ECHO "archive.tar.gz"
2364 }
2365 LET $trimmed: PIPE = TEXT_TRIM($cap)
2366 LET $out: PIPE = TEXT_TRIM_SUFFIX($trimmed, ".gz")
2367 WITH_IO [stdin=$out] READ_LINE $line
2368 ASSERT_EQ $line "archive.tar"
2369 "###
2370)]
2371#[example(
2372 name = "strip suffix template",
2373 code = r###"
2374 # String inputs run inside placeholders too.
2375 IMPORT [STD]
2376 LET $msg: STRING = 'bare:{{ STD::TEXT_TRIM_SUFFIX("archive.tar.gz", ".gz") }}'
2377 ASSERT_EQ $msg "bare:archive.tar"
2378 "###
2379)]
2380fn text_trim_suffix<P: ProcessManager>(
2381 cx: &mut StepCtx<P>,
2382 #[union(String, Pipe)]
2384 text: Value,
2385 suffix: String,
2387) -> Result<Value> {
2388 super::args::mirror_stream(
2389 cx,
2390 "TEXT_TRIM_SUFFIX",
2391 &text,
2392 super::args::TextPump::TrimSuffix(suffix),
2393 )
2394}
2395
2396fn text_trim_suffix_string(text: Value, suffix: String) -> Result<Value> {
2399 super::args::mirror_string(
2400 "TEXT_TRIM_SUFFIX",
2401 &text,
2402 super::args::TextPump::TrimSuffix(suffix),
2403 )
2404}
2405
2406#[oxdock_func(returns = TypeTag::String)]
2417#[example(
2418 name = "join path",
2419 code = r###"
2420 # Directory and file stem join with the native separator.
2421 # Source `\\` is one backslash at runtime; `/` works on Windows
2422 # too, native just reads better there.
2423 IMPORT [STD]
2424 LET $p: STRING = PATH_JOIN("some-dir", "some-file")
2425 [family:unix] ASSERT_EQ $p "some-dir/some-file"
2426 [family:windows] ASSERT_EQ $p "some-dir\\some-file"
2427 "###
2428)]
2429fn path_join<P: ProcessManager>(
2430 _cx: &mut StepCtx<P>,
2431 #[union(String, Path)]
2433 dir: Value,
2434 #[union(String, Path)]
2436 name: Value,
2437) -> Result<Value> {
2438 let d = super::args::string_or_path_text(&dir)?;
2439 let n = super::args::string_or_path_text(&name)?;
2440 Ok(Value::string(oxdock_fs::join_native(&d, &n)))
2441}
2442
2443#[oxdock_func(
2450 rpn,
2451 returns = TypeTag::union(vec![TypeTag::String, TypeTag::Pipe]),
2452 template = text_to_upper_string
2453)]
2454#[example(
2455 name = "uppercase",
2456 code = r###"
2457 # Text folds to uppercase.
2458 IMPORT [STD]
2459 LET $loud: STRING = TEXT_TO_UPPER("hello")
2460 ASSERT_EQ $loud "HELLO"
2461 "###
2462)]
2463#[example(
2464 name = "uppercase pipe mirrors",
2465 code = r###"
2466 # Pipe input mints pipe output with the same fold.
2467 IMPORT [STD]
2468 LET $cap: PIPE
2469 WITH_IO [stdout=$cap] {
2470 ECHO "hello"
2471 }
2472 LET $out: PIPE = TEXT_TO_UPPER($cap)
2473 WITH_IO [stdin=$out] READ_LINE $line
2474 ASSERT_EQ $line "HELLO"
2475 "###
2476)]
2477#[example(
2478 name = "uppercase template",
2479 code = r###"
2480 # String inputs run inside placeholders too.
2481 IMPORT [STD]
2482 LET $msg: STRING = 'loud:{{ STD::TEXT_TO_UPPER("hello") }}'
2483 ASSERT_EQ $msg "loud:HELLO"
2484 "###
2485)]
2486fn text_to_upper<P: ProcessManager>(
2487 cx: &mut StepCtx<P>,
2488 #[union(String, Pipe)]
2490 text: Value,
2491) -> Result<Value> {
2492 super::args::mirror_stream(cx, "TEXT_TO_UPPER", &text, super::args::TextPump::ToUpper)
2493}
2494
2495fn text_to_upper_string(text: Value) -> Result<Value> {
2498 super::args::mirror_string("TEXT_TO_UPPER", &text, super::args::TextPump::ToUpper)
2499}
2500
2501#[oxdock_func(
2508 rpn,
2509 returns = TypeTag::union(vec![TypeTag::String, TypeTag::Pipe]),
2510 template = text_to_lower_string
2511)]
2512#[example(
2513 name = "lowercase",
2514 code = r###"
2515 # Text folds to lowercase.
2516 IMPORT [STD]
2517 LET $quiet: STRING = TEXT_TO_LOWER("HELLO")
2518 ASSERT_EQ $quiet "hello"
2519 "###
2520)]
2521#[example(
2522 name = "lowercase pipe mirrors",
2523 code = r###"
2524 # Pipe input mints pipe output with the same fold.
2525 IMPORT [STD]
2526 LET $cap: PIPE
2527 WITH_IO [stdout=$cap] {
2528 ECHO "HELLO"
2529 }
2530 LET $out: PIPE = TEXT_TO_LOWER($cap)
2531 WITH_IO [stdin=$out] READ_LINE $line
2532 ASSERT_EQ $line "hello"
2533 "###
2534)]
2535#[example(
2536 name = "lowercase template",
2537 code = r###"
2538 # String inputs run inside placeholders too.
2539 IMPORT [STD]
2540 LET $msg: STRING = 'quiet:{{ STD::TEXT_TO_LOWER("HELLO") }}'
2541 ASSERT_EQ $msg "quiet:hello"
2542 "###
2543)]
2544fn text_to_lower<P: ProcessManager>(
2545 cx: &mut StepCtx<P>,
2546 #[union(String, Pipe)]
2548 text: Value,
2549) -> Result<Value> {
2550 super::args::mirror_stream(cx, "TEXT_TO_LOWER", &text, super::args::TextPump::ToLower)
2551}
2552
2553fn text_to_lower_string(text: Value) -> Result<Value> {
2556 super::args::mirror_string("TEXT_TO_LOWER", &text, super::args::TextPump::ToLower)
2557}
2558
2559#[oxdock_func(
2570 rpn,
2571 returns = TypeTag::union(vec![TypeTag::String, TypeTag::Pipe]),
2572 template = text_replace_string
2573)]
2574#[example(
2575 name = "replace",
2576 code = r###"
2577 # Every literal occurrence rewrites in place.
2578 IMPORT [STD]
2579 LET $fixed: STRING = TEXT_REPLACE("hello world", "world", "there")
2580 ASSERT_EQ $fixed "hello there"
2581 "###
2582)]
2583#[example(
2584 name = "replace pipe mirrors",
2585 code = r###"
2586 # Pipe input mints pipe output with the same rewrite.
2587 IMPORT [STD]
2588 LET $cap: PIPE
2589 WITH_IO [stdout=$cap] {
2590 ECHO "hello world"
2591 }
2592 LET $trimmed: PIPE = TEXT_TRIM($cap)
2593 LET $out: PIPE = TEXT_REPLACE($trimmed, "world", "there")
2594 WITH_IO [stdin=$out] READ_LINE $line
2595 ASSERT_EQ $line "hello there"
2596 "###
2597)]
2598#[example(
2599 name = "replace template",
2600 code = r###"
2601 # String inputs run inside placeholders too.
2602 IMPORT [STD]
2603 LET $msg: STRING = 'fixed:{{ STD::TEXT_REPLACE("hello world", "world", "there") }}'
2604 ASSERT_EQ $msg "fixed:hello there"
2605 "###
2606)]
2607fn text_replace<P: ProcessManager>(
2608 cx: &mut StepCtx<P>,
2609 #[union(String, Pipe)]
2611 text: Value,
2612 from: String,
2614 to: String,
2616) -> Result<Value> {
2617 super::args::mirror_stream(
2618 cx,
2619 "TEXT_REPLACE",
2620 &text,
2621 super::args::TextPump::ReplaceLiteral { from, to },
2622 )
2623}
2624
2625fn text_replace_string(text: Value, from: String, to: String) -> Result<Value> {
2628 super::args::mirror_string(
2629 "TEXT_REPLACE",
2630 &text,
2631 super::args::TextPump::ReplaceLiteral { from, to },
2632 )
2633}
2634
2635#[oxdock_func(
2647 rpn,
2648 returns = TypeTag::union(vec![TypeTag::String, TypeTag::Pipe]),
2649 template = text_replace_regex_string
2650)]
2651#[example(
2652 name = "replace with captures",
2653 code = r###"
2654 # Capture groups expand in the replacement.
2655 IMPORT [STD]
2656 LET $swapped: STRING = TEXT_REPLACE_REGEX("2026-10-13", "(\\d+)-(\\d+)-(\\d+)", "$3/$2/$1")
2657 ASSERT_EQ $swapped "13/10/2026"
2658 "###
2659)]
2660#[example(
2661 name = "replace regex pipe mirrors",
2662 code = r###"
2663 # Pipe input mints pipe output with the same rewrite.
2664 IMPORT [STD]
2665 LET $cap: PIPE
2666 WITH_IO [stdout=$cap] {
2667 ECHO "2026-10-13"
2668 }
2669 LET $trimmed: PIPE = TEXT_TRIM($cap)
2670 LET $out: PIPE = TEXT_REPLACE_REGEX($trimmed, "(\\d+)-(\\d+)-(\\d+)", "$3/$2/$1")
2671 WITH_IO [stdin=$out] READ_LINE $line
2672 ASSERT_EQ $line "13/10/2026"
2673 "###
2674)]
2675#[example(
2676 name = "replace regex template",
2677 code = r###"
2678 # String inputs run inside placeholders too.
2679 IMPORT [STD]
2680 LET $msg: STRING = 'swapped:{{ STD::TEXT_REPLACE_REGEX("2026-10-13", "(\\d+)-(\\d+)-(\\d+)", "$3/$2/$1") }}'
2681 ASSERT_EQ $msg "swapped:13/10/2026"
2682 "###
2683)]
2684fn text_replace_regex<P: ProcessManager>(
2685 cx: &mut StepCtx<P>,
2686 #[union(String, Pipe)]
2688 text: Value,
2689 pattern: String,
2691 replacement: String,
2693) -> Result<Value> {
2694 if let Some(s) = text.as_str() {
2695 let out =
2696 super::args::text_replace_regex_str(s, &pattern, &replacement, "TEXT_REPLACE_REGEX")?;
2697 return Ok(Value::string(out));
2698 }
2699 let content = super::args::read_pipe_eager(cx, "TEXT_REPLACE_REGEX", &text)?;
2700 let out = super::args::text_replace_regex_str(
2701 &content,
2702 &pattern,
2703 &replacement,
2704 "TEXT_REPLACE_REGEX",
2705 )?;
2706 super::args::write_completed_pipe(cx, "TEXT_REPLACE_REGEX", out)
2707}
2708
2709fn text_replace_regex_string(text: Value, pattern: String, replacement: String) -> Result<Value> {
2712 let Some(s) = text.as_str() else {
2713 return Err(super::args::pipe_needs_step_io("TEXT_REPLACE_REGEX"));
2714 };
2715 let out = super::args::text_replace_regex_str(s, &pattern, &replacement, "TEXT_REPLACE_REGEX")?;
2716 Ok(Value::string(out))
2717}
2718
2719#[oxdock_func(pure, returns = TypeTag::ListOf(std::sync::Arc::new(TypeTag::String)))]
2727#[example(
2728 name = "split",
2729 code = r###"
2730 # Delimiters split into list items.
2731 IMPORT [STD]
2732 LET $parts: LIST<STRING> = TEXT_SPLIT("a,b,c", ",")
2733 ASSERT_EQ $parts.0 "a"
2734 ASSERT_EQ $parts.1 "b"
2735 ASSERT_EQ $parts.2 "c"
2736 "###
2737)]
2738fn text_split(
2739 text: String,
2741 delimiter: String,
2743) -> Result<Value> {
2744 Ok(super::args::text_list_value(super::args::text_split_str(
2745 &text, &delimiter,
2746 )))
2747}
2748
2749#[oxdock_func(pure, returns = TypeTag::String)]
2752#[example(
2753 name = "join",
2754 code = r###"
2755 # List items join with the separator between them.
2756 IMPORT [STD]
2757 LET $joined: STRING = TEXT_JOIN(["a", "b", "c"], ",")
2758 ASSERT_EQ $joined "a,b,c"
2759 "###
2760)]
2761fn text_join(
2762 elements: Vec<String>,
2764 delimiter: String,
2766) -> Result<Value> {
2767 Ok(Value::string(elements.join(delimiter.as_str())))
2768}
2769
2770#[oxdock_func(pure, returns = TypeTag::ListOf(std::sync::Arc::new(TypeTag::String)))]
2782#[example(
2783 name = "split args",
2784 code = r###"
2785 # Quoted segments stay one word.
2786 IMPORT [STD]
2787 LET $argv: LIST<STRING> = SHELL_SPLIT_ARGS("gh issue comment 153 --body-file notes.md")
2788 ASSERT_EQ $argv.0 "gh"
2789 ASSERT_EQ $argv.3 "153"
2790 ASSERT_EQ $argv.5 "notes.md"
2791
2792 # Quotes and escapes parse the shell way.
2793 LET $quoted: LIST<STRING> = SHELL_SPLIT_ARGS("say \"hi there\" 'a b'")
2794 ASSERT_EQ $quoted.0 "say"
2795 ASSERT_EQ $quoted.1 "hi there"
2796 ASSERT_EQ $quoted.2 "a b"
2797 "###
2798)]
2799fn shell_split_args(
2800 command: String,
2802) -> Result<Value> {
2803 match shell_words::split(&command) {
2804 Ok(words) => Ok(super::args::text_list_value(words)),
2805 Err(err) => anyhow::bail!("SHELL_SPLIT_ARGS: {err}"),
2806 }
2807}
2808
2809#[oxdock_func(pure, returns = TypeTag::String)]
2817#[example(
2818 name = "join args",
2819 code = r###"
2820 # Plain words join with spaces and no quoting.
2821 IMPORT [STD]
2822 LET $plain: STRING = SHELL_JOIN_ARGS(["gh", "issue", "list"])
2823 ASSERT_EQ $plain "gh issue list"
2824
2825 # Words with spaces quote, and the round trip is exact.
2826 LET $words: LIST<STRING> = ["say", "hi there", "a'b"]
2827 LET $joined: STRING = SHELL_JOIN_ARGS($words)
2828 LET $back: LIST<STRING> = SHELL_SPLIT_ARGS($joined)
2829 ASSERT_EQ $back.0 "say"
2830 ASSERT_EQ $back.1 "hi there"
2831 ASSERT_EQ $back.2 "a'b"
2832 "###
2833)]
2834fn shell_join_args(
2835 words: Vec<String>,
2837) -> Result<Value> {
2838 Ok(Value::string(shell_words::join(&words)))
2839}
2840
2841#[oxdock_func(pure, returns = TypeTag::ListOf(std::sync::Arc::new(TypeTag::String)))]
2849#[example(
2850 name = "lines",
2851 code = r###"
2852 # Newlines split into line items.
2853 IMPORT [STD]
2854 LET $lines: LIST<STRING> = TEXT_LINES("one\ntwo\nthree")
2855 ASSERT_EQ $lines.0 "one"
2856 ASSERT_EQ $lines.1 "two"
2857 ASSERT_EQ $lines.2 "three"
2858
2859 # Windows endings split the same way after normalization.
2860 LET $crlf: LIST<STRING> = TEXT_LINES("one\r\ntwo\r\nthree")
2861 ASSERT_EQ $crlf.0 "one"
2862 ASSERT_EQ $crlf.1 "two"
2863 ASSERT_EQ $crlf.2 "three"
2864
2865 # Old Mac endings split too, and mixed endings split together because the input normalizes to LF before splitting.
2866 LET $mixed: LIST<STRING> = TEXT_LINES("a\r\nb\nc\rd")
2867 ASSERT_EQ $mixed.0 "a"
2868 ASSERT_EQ $mixed.1 "b"
2869 ASSERT_EQ $mixed.2 "c"
2870 ASSERT_EQ $mixed.3 "d"
2871 "###
2872)]
2873fn text_lines(
2874 text: String,
2876) -> Result<Value> {
2877 Ok(super::args::text_list_value(super::args::text_lines_str(
2878 &text,
2879 )))
2880}
2881
2882#[oxdock_func(pure, returns = TypeTag::ListOf(std::sync::Arc::new(TypeTag::String)))]
2888#[example(
2889 name = "fields",
2890 code = r###"
2891 # Runs of whitespace separate fields; empties never appear.
2892 IMPORT [STD]
2893 LET $fields: LIST<STRING> = TEXT_FIELDS(" abc def ")
2894 ASSERT_EQ $fields.0 "abc"
2895 ASSERT_EQ $fields.1 "def"
2896 "###
2897)]
2898fn text_fields(
2899 text: String,
2901) -> Result<Value> {
2902 Ok(super::args::text_list_value(super::args::text_fields_str(
2903 &text,
2904 )))
2905}
2906
2907#[oxdock_func(pure, returns = TypeTag::ListOf(std::sync::Arc::new(TypeTag::String)))]
2916#[example(
2917 name = "line range",
2918 code = r###"
2919 # Lines 2 through 3 come back as a list, 1-based inclusive.
2920 IMPORT [STD]
2921 LET $window: LIST<STRING> = TEXT_LINES_RANGE("one\ntwo\nthree\nfour", 2, 3)
2922 ASSERT_EQ $window.0 "two"
2923 ASSERT_EQ $window.1 "three"
2924
2925 # Ranges past the end clamp instead of failing.
2926 LET $tail: LIST<STRING> = TEXT_LINES_RANGE("one\ntwo", 2, 9)
2927 ASSERT_EQ $tail.0 "two"
2928 "###
2929)]
2930fn text_lines_range(
2931 text: String,
2933 from: i64,
2935 to: i64,
2937) -> Result<Value> {
2938 Ok(super::args::text_list_value(
2939 super::args::text_lines_range_str(&text, from, to, "TEXT_LINES_RANGE")?,
2940 ))
2941}
2942
2943#[oxdock_func(pure, returns = TypeTag::Bool)]
2951#[example(
2952 name = "match",
2953 code = r###"
2954 # Regex matches report true; misses report false.
2955 IMPORT [STD]
2956 LET $hit: BOOL = TEXT_MATCH("abc123", "\\d+")
2957 ASSERT_EQ $hit true
2958
2959 # A miss is false, not a failure.
2960 LET $miss: BOOL = TEXT_MATCH("abc", "^\\d+$")
2961 ASSERT_EQ $miss false
2962 "###
2963)]
2964fn text_match(
2965 text: String,
2967 pattern: String,
2969) -> Result<Value> {
2970 let re = super::args::text_compile_pattern("TEXT_MATCH", &pattern)?;
2971 Ok(Value::bool(re.is_match(&text)))
2972}
2973
2974#[oxdock_func(pure, name = "BOOL", returns = TypeTag::Bool)]
2983#[example(
2984 name = "convert",
2985 code = r###"
2986 IMPORT [STD]
2987 LET $n: BOOL = BOOL("yes")
2988 ASSERT_EQ $n true
2989 LET $f: BOOL = BOOL("0")
2990 ASSERT_EQ $f false
2991 "###
2992)]
2993fn bool_convert(
2994 #[union(Bool, String)]
2996 val: Value,
2997) -> Result<Value> {
2998 if let Some(b) = val.as_bool() {
2999 return Ok(Value::bool(b));
3000 }
3001 let Some(s) = val.as_str() else {
3002 return Err(anyhow::anyhow!(
3003 "BOOL needs a Bool or String, found {val:?}"
3004 ));
3005 };
3006 match super::args::parse_bool_str(s) {
3007 Some(b) => Ok(Value::bool(b)),
3008 None => anyhow::bail!("BOOL cannot coerce {s:?} to BOOL"),
3009 }
3010}
3011
3012#[oxdock_func(pure, returns = TypeTag::Bool)]
3022#[example(
3023 name = "absent-default",
3024 code = r###"
3025 # Absent names read empty; the default settles the polarity.
3026 IMPORT [STD]
3027 INHERIT_ENV [OXDOCK_TEST_ABSENT_FLAG]
3028 LET $dry: BOOL = BOOL_OR("{{ env:OXDOCK_TEST_ABSENT_FLAG }}", true)
3029 ASSERT_EQ $dry true
3030
3031 # Present values coerce strictly, ignoring the default.
3032 LET $off: BOOL = BOOL_OR("false", true)
3033 ASSERT_EQ $off false
3034 "###
3035)]
3036fn bool_or(
3037 text: String,
3039 default: bool,
3041) -> Result<Value> {
3042 if text.trim().is_empty() {
3043 return Ok(Value::bool(default));
3044 }
3045 match super::args::parse_bool_str(&text) {
3046 Some(b) => Ok(Value::bool(b)),
3047 None => anyhow::bail!("BOOL_OR cannot coerce {text:?} to BOOL"),
3048 }
3049}
3050
3051#[oxdock_func(pure, returns = TypeTag::ListOf(std::sync::Arc::new(TypeTag::String)))]
3060#[example(
3061 name = "extract",
3062 code = r###"
3063 # Index zero is the full match; groups follow in order.
3064 IMPORT [STD]
3065 LET $caps: LIST<STRING> = TEXT_EXTRACT("abc123", "([a-z]+)(\\d+)")
3066 ASSERT_EQ $caps.0 "abc123"
3067 ASSERT_EQ $caps.1 "abc"
3068 ASSERT_EQ $caps.2 "123"
3069 "###
3070)]
3071fn text_extract(
3072 text: String,
3074 pattern: String,
3076) -> Result<Value> {
3077 let groups = super::args::text_extract_str(&text, &pattern, "TEXT_EXTRACT")?;
3078 Ok(super::args::text_list_value(groups))
3079}
3080
3081#[oxdock_func(pure, returns = TypeTag::Bool)]
3088#[example(
3089 name = "starts with",
3090 code = r###"
3091 # Present prefixes report true; misses report false.
3092 IMPORT [STD]
3093 LET $hit: BOOL = TEXT_STARTS_WITH("linux-musl-x64", "linux")
3094 ASSERT_EQ $hit true
3095
3096 # A miss is false, not a failure.
3097 LET $miss: BOOL = TEXT_STARTS_WITH("macos-arm", "linux")
3098 ASSERT_EQ $miss false
3099 "###
3100)]
3101fn text_starts_with(
3102 text: String,
3104 prefix: String,
3106) -> Result<Value> {
3107 Ok(Value::bool(text.starts_with(prefix.as_str())))
3108}
3109
3110#[oxdock_func(pure, returns = TypeTag::Bool)]
3117#[example(
3118 name = "ends with",
3119 code = r###"
3120 # Present suffixes report true; misses report false.
3121 IMPORT [STD]
3122 LET $hit: BOOL = TEXT_ENDS_WITH("x86_64-linux-musl", "linux-musl")
3123 ASSERT_EQ $hit true
3124
3125 # A miss is false, not a failure.
3126 LET $miss: BOOL = TEXT_ENDS_WITH("x86_64-linux-gnu", "linux-musl")
3127 ASSERT_EQ $miss false
3128 "###
3129)]
3130fn text_ends_with(
3131 text: String,
3133 suffix: String,
3135) -> Result<Value> {
3136 Ok(Value::bool(text.ends_with(suffix.as_str())))
3137}
3138
3139#[oxdock_func(pure, returns = TypeTag::Bool)]
3146#[example(
3147 name = "contains",
3148 code = r###"
3149 # Present needles report true; misses report false.
3150 IMPORT [STD]
3151 LET $hit: BOOL = TEXT_CONTAINS("x86_64-linux-musl", "musl")
3152 ASSERT_EQ $hit true
3153
3154 # A miss is false, not a failure.
3155 LET $miss: BOOL = TEXT_CONTAINS("x86_64-linux-gnu", "musl")
3156 ASSERT_EQ $miss false
3157 "###
3158)]
3159fn text_contains(
3160 text: String,
3162 needle: String,
3164) -> Result<Value> {
3165 Ok(Value::bool(text.contains(needle.as_str())))
3166}
3167
3168#[oxdock_func(pure, returns = TypeTag::Int)]
3175#[example(
3176 name = "length",
3177 code = r###"
3178 # Plain text counts one per character.
3179 IMPORT [STD]
3180 LET $n: INT = TEXT_LENGTH("hello")
3181 ASSERT_EQ $n 5
3182
3183 # Multibyte characters count once each, not per byte.
3184 LET $wide: INT = TEXT_LENGTH("héllo")
3185 ASSERT_EQ $wide 5
3186 "###
3187)]
3188fn text_length(
3189 text: String,
3191) -> Result<Value> {
3192 Ok(Value::int(text.chars().count() as i64))
3193}
3194
3195#[oxdock_func(pure, returns = TypeTag::Int)]
3203#[example(
3204 name = "count",
3205 code = r###"
3206 # Every non-overlapping occurrence counts once.
3207 IMPORT [STD]
3208 LET $n: INT = TEXT_COUNT("hello world", "o")
3209 ASSERT_EQ $n 2
3210
3211 # Overlapping candidates never double count.
3212 LET $once: INT = TEXT_COUNT("aaa", "aa")
3213 ASSERT_EQ $once 1
3214 "###
3215)]
3216fn text_count(
3217 text: String,
3219 needle: String,
3221) -> Result<Value> {
3222 let n = super::args::text_count_str(&text, &needle, "TEXT_COUNT")?;
3223 Ok(Value::int(n))
3224}
3225
3226#[oxdock_func(pure, returns = TypeTag::Int)]
3236#[example(
3237 name = "count matches",
3238 code = r###"
3239 # One line matches once no matter how many times it hits.
3240 IMPORT [STD]
3241 LET $n: INT = TEXT_COUNT_MATCHES("test a: test\ntest b: nope\ntest c: test", ": test")
3242 ASSERT_EQ $n 2
3243
3244 # A miss binds zero, never an error.
3245 LET $none: INT = TEXT_COUNT_MATCHES("test b: nope", ": test$")
3246 ASSERT_EQ $none 0
3247 "###
3248)]
3249fn text_count_matches(
3250 text: String,
3252 pattern: String,
3254) -> Result<Value> {
3255 let n = super::args::text_count_matches_str(&text, &pattern, "TEXT_COUNT_MATCHES")?;
3256 Ok(Value::int(n))
3257}
3258
3259#[oxdock_func(pure, returns = TypeTag::ListOf(std::sync::Arc::new(TypeTag::String)))]
3272#[example(
3273 name = "grep",
3274 code = r###"
3275 # Matching lines come back as a list, in order.
3276 IMPORT [STD]
3277 LET $hits: LIST<STRING> = TEXT_GREP("one\ntwo\none more", "^one")
3278 ASSERT_EQ $hits.0 "one"
3279 ASSERT_EQ $hits.1 "one more"
3280
3281 # A miss binds an empty list, never an error.
3282 LET $miss: LIST<STRING> = TEXT_GREP("one\ntwo", "^z")
3283 LET $joined: STRING = TEXT_JOIN($miss, ",")
3284 ASSERT_EQ $joined ""
3285
3286 # The (?i) flag ignores case, so uppercase lines match too.
3287 LET $folded: LIST<STRING> = TEXT_GREP("One\ntwo\nONE more", "(?i)^one")
3288 ASSERT_EQ $folded.0 "One"
3289 ASSERT_EQ $folded.1 "ONE more"
3290 "###
3291)]
3292#[example(
3293 name = "grep invert",
3294 code = r###"
3295 # The invert option keeps every non-matching line instead.
3296 IMPORT [STD]
3297 LET $kept: LIST<STRING> = TEXT_GREP("one\ntwo\none more", "^one", {invert: true})
3298 ASSERT_EQ $kept.0 "two"
3299
3300 # A pattern matching every line binds an empty list, never an error.
3301 LET $none: LIST<STRING> = TEXT_GREP("one\ntwo", "^", {invert: true})
3302 LET $joined: STRING = TEXT_JOIN($none, ",")
3303 ASSERT_EQ $joined ""
3304
3305 # Options ride into placeholders as MAP literals. Placeholder
3306 # strings unescape only backslash and quote, so multiline text
3307 # arrives through a variable.
3308 LET $two_lines: STRING = "one\ntwo"
3309 LET $msg: STRING = 'kept:{{ STD::TEXT_GREP($two_lines, "^one", {invert: true}) }}'
3310 ASSERT_EQ $msg "kept:two"
3311 "###
3312)]
3313fn text_grep(
3314 text: String,
3316 pattern: String,
3318 #[options("invert?: BOOL")]
3320 #[optional]
3321 options: BTreeMap<String, Value>,
3322) -> Result<Value> {
3323 let invert = super::args::text_invert_flag(&options);
3326 Ok(super::args::text_list_value(super::args::text_grep_str(
3327 &text,
3328 &pattern,
3329 invert,
3330 "TEXT_GREP",
3331 )?))
3332}
3333
3334#[oxdock_func(returns = TypeTag::Bool)]
3345#[example(
3346 name = "drain to end",
3347 code = r###"
3348 # Capture two lines, then drain to end of stream with no sentinel line.
3349 IMPORT [STD]
3350 LET $cap: PIPE
3351 WITH_IO [stdout=$cap] {
3352 ECHO "one"
3353 ECHO "two"
3354 }
3355
3356 # The loop exits on close, and the count proves both lines drained.
3357 LET $n: INT = 0
3358 WHILE !EOF($cap) {
3359 WITH_IO [stdin=$cap] READ_LINE $line
3360 $n = $n + 1
3361 }
3362 ASSERT_EQ $n 2
3363 "###
3364)]
3365fn eof<P: ProcessManager>(
3366 cx: &mut StepCtx<P>,
3367 pipe: PipeHandle,
3369) -> Result<Value> {
3370 let info = cx.state.io.inspect_pipe(&pipe);
3371 Ok(Value::bool(info.closed && info.buffered == 0))
3372}
3373
3374fn task_poll_result_fields() -> Arc<[Field]> {
3378 Arc::from(vec![
3379 Field {
3380 name: "state".to_string(),
3381 ty: TypeTag::String,
3382 docs: "Task phase: `running` or `finished`.",
3383 optional: false,
3384 },
3385 Field {
3386 name: "ok".to_string(),
3387 ty: TypeTag::Bool,
3388 docs: "True unless the task failed.",
3389 optional: false,
3390 },
3391 Field {
3392 name: "stdout_tail".to_string(),
3393 ty: TypeTag::String,
3394 docs: "Bounded stdout tail, live while running.",
3395 optional: false,
3396 },
3397 Field {
3398 name: "stderr_tail".to_string(),
3399 ty: TypeTag::String,
3400 docs: "Bounded stderr tail, live while running.",
3401 optional: false,
3402 },
3403 Field {
3404 name: "truncated_bytes".to_string(),
3405 ty: TypeTag::Int,
3406 docs: "Dropped head bytes past the per-stream cap.",
3407 optional: false,
3408 },
3409 Field {
3410 name: "exit_code".to_string(),
3411 ty: TypeTag::Int,
3412 docs: "Process exit code, present once finished.",
3413 optional: true,
3414 },
3415 Field {
3416 name: "result".to_string(),
3417 ty: TypeTag::Any,
3418 docs: "Task `RETURN` value, present on clean finish.",
3419 optional: true,
3420 },
3421 Field {
3422 name: "error".to_string(),
3423 ty: TypeTag::String,
3424 docs: "Failure text, present on failed finish.",
3425 optional: true,
3426 },
3427 ])
3428}
3429
3430#[oxdock_func(returns = TypeTag::Record(task_poll_result_fields()))]
3443#[example(
3444 name = "running poll",
3445 code = r###"
3446 # A sleeping task is still running on the first poll.
3447 IMPORT [STD]
3448 LET $t: HANDLE = ASYNC { SLEEP 30s }
3449 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)
3450 ASSERT_EQ $m.state "running"
3451 ASSERT_EQ $m.ok true
3452 # Clean up the sleeper so the run ends promptly.
3453 CANCEL $t
3454 "###
3455)]
3456#[example(
3457 name = "finished poll",
3458 code = r###"
3459 # A finished task reports its value and final tails, then still awaits.
3460 IMPORT [STD]
3461 LET $t: HANDLE = ASYNC { ECHO "hi"; SLEEP 1s; RETURN "done" }
3462 # Do other work while the task runs; poll once it should be done.
3463 SLEEP 2s
3464 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)
3465 ASSERT_EQ $m.state "finished"
3466 ASSERT_EQ $m.result "done"
3467 LET $o: STRING = AWAIT $t
3468 ASSERT_EQ $o "done"
3469 "###
3470)]
3471fn task_poll<P: ProcessManager>(
3472 cx: &mut StepCtx<P>,
3473 task: HandleValue,
3475) -> Result<Value> {
3476 let entry =
3477 super::handlers::resolve_task_entry_by_id(task.0, &format!("TASK_POLL({})", task.0), cx)?;
3478 let obs = entry.observe_completion();
3479 let (stdout_tail, stderr_tail, dropped) = entry.snapshot_tails();
3480 let mut out = BTreeMap::new();
3481 out.insert(
3482 "state".to_string(),
3483 Value::string(if obs.running { "running" } else { "finished" }.to_string()),
3484 );
3485 out.insert("ok".to_string(), Value::bool(obs.ok));
3486 if !obs.running {
3487 out.insert("exit_code".to_string(), Value::int(obs.exit_code));
3488 }
3489 if let Some(result) = obs.result {
3490 out.insert("result".to_string(), result);
3491 }
3492 if !obs.error.is_empty() {
3493 out.insert("error".to_string(), Value::string(obs.error));
3494 }
3495 out.insert("stdout_tail".to_string(), Value::string(stdout_tail));
3496 out.insert("stderr_tail".to_string(), Value::string(stderr_tail));
3497 out.insert(
3498 "truncated_bytes".to_string(),
3499 Value::int(dropped.min(i64::MAX as u64) as i64),
3500 );
3501 Ok(Value::map(out))
3502}
3503
3504fn meta_to_value(meta: &FuncMeta) -> Value {
3505 let mut map = BTreeMap::new();
3506 map.insert("name".to_string(), Value::string(meta.name.clone()));
3507 map.insert("module".to_string(), Value::string(meta.module.clone()));
3508 map.insert(
3509 "kind".to_string(),
3510 Value::string(meta.kind.label().to_string()),
3511 );
3512 let params = match &meta.params {
3513 Some(params) => Value::list(
3514 params
3515 .iter()
3516 .map(|p| {
3517 let mut entry = BTreeMap::new();
3518 entry.insert("name".to_string(), Value::string(p.name.clone()));
3519 entry.insert(
3520 "param_type".to_string(),
3521 Value::string(
3522 p.param_type
3523 .as_ref()
3524 .map(render_structural)
3525 .unwrap_or_default(),
3526 ),
3527 );
3528 entry.insert(
3529 "allowed".to_string(),
3530 Value::string(
3531 p.allowed
3532 .map(|values| values.join(", "))
3533 .unwrap_or_default(),
3534 ),
3535 );
3536 entry.insert("docs".to_string(), Value::string(String::new()));
3537 entry.insert("optional".to_string(), Value::bool(p.optional));
3538 entry.insert(
3539 "options".to_string(),
3540 match p.options {
3541 Some(keys) => Value::list(
3542 keys.iter()
3543 .map(|key| {
3544 let mut option = BTreeMap::new();
3545 option.insert(
3546 "name".to_string(),
3547 Value::string(key.name.to_string()),
3548 );
3549 option.insert(
3550 "value_type".to_string(),
3551 Value::string(render_structural(&key.value)),
3552 );
3553 option.insert(
3554 "required".to_string(),
3555 Value::bool(key.required),
3556 );
3557 option.insert(
3558 "default".to_string(),
3559 Value::string(
3560 key.default.unwrap_or_default().to_string(),
3561 ),
3562 );
3563 Value::map(option)
3564 })
3565 .collect(),
3566 ),
3567 None => Value::string(String::new()),
3568 },
3569 );
3570 Value::map(entry)
3571 })
3572 .collect(),
3573 ),
3574 None => Value::list(Vec::new()),
3578 };
3579 map.insert("params".to_string(), params);
3580 map.insert(
3581 "returns".to_string(),
3582 Value::string(
3583 meta.returns
3584 .as_ref()
3585 .map(render_structural)
3586 .unwrap_or_default(),
3587 ),
3588 );
3589 map.insert("rpn".to_string(), Value::bool(meta.rpn));
3590 map.insert(
3591 "summary".to_string(),
3592 Value::string(meta.summary.to_string()),
3593 );
3594 Value::map(map)
3595}
3596
3597#[derive(Debug, Clone)]
3601pub struct RecordSchema {
3602 pub name: &'static str,
3603 pub fields: std::sync::Arc<[Field]>,
3604}
3605
3606#[derive(Clone)]
3610pub struct HostModule<P: ProcessManager> {
3611 pub name: String,
3612 pub funcs: Vec<HostRegistration<P>>,
3613 pub types: Vec<&'static TypeDescriptor>,
3614 pub record_schemas: Vec<RecordSchema>,
3615 pub states: Vec<ModuleState>,
3622}
3623
3624#[derive(Clone)]
3628pub struct ModuleState {
3629 id: std::any::TypeId,
3630 state: std::sync::Arc<dyn std::any::Any + Send + Sync>,
3631}
3632
3633pub type PreRunInspector = dyn Fn(&[Step]) -> Result<()> + Send + Sync;
3637
3638#[derive(Clone)]
3644pub struct PreRunCheck {
3645 check: Arc<PreRunInspector>,
3646}
3647
3648impl PreRunCheck {
3649 pub fn new(check: impl Fn(&[Step]) -> Result<()> + Send + Sync + 'static) -> Self {
3651 Self {
3652 check: Arc::new(check),
3653 }
3654 }
3655
3656 pub fn run(&self, steps: &[Step]) -> Result<()> {
3658 (self.check)(steps)
3659 }
3660}
3661
3662impl<P: ProcessManager> HostModule<P> {
3663 pub fn with_state<T: Send + Sync + 'static>(mut self, state: std::sync::Arc<T>) -> Self {
3666 self.states.push(ModuleState {
3667 id: std::any::TypeId::of::<T>(),
3668 state,
3669 });
3670 self
3671 }
3672
3673 pub fn check_pre_run(&self, steps: &[Step]) -> Result<()> {
3677 for state in &self.states {
3678 if let Some(check) = state.state.downcast_ref::<PreRunCheck>() {
3679 check.run(steps)?;
3680 }
3681 }
3682 Ok(())
3683 }
3684}
3685
3686impl<P: ProcessManager> ExecState<P> {
3687 pub fn register_module(&mut self, module: HostModule<P>) {
3690 for registration in module.funcs {
3691 match registration {
3692 HostRegistration::Stateful { name, meta, func } => {
3693 self.functions.register_host(&module.name, name, meta, func);
3694 }
3695 HostRegistration::Pure { name, meta, func } => {
3696 self.functions
3697 .register_pure_host(&module.name, name, meta, func);
3698 }
3699 HostRegistration::Both {
3700 name,
3701 meta,
3702 func,
3703 template,
3704 } => {
3705 self.functions
3706 .register_both_host(&module.name, name, meta, func, template);
3707 }
3708 }
3709 }
3710 for descriptor in module.types {
3711 self.register_type(descriptor);
3712 }
3713 for schema in module.record_schemas {
3714 self.register_record_schema(schema.name, schema.fields);
3715 }
3716 for state in module.states {
3717 self.module_states
3718 .insert((module.name.clone(), state.id), state.state);
3719 }
3720 }
3721
3722 pub fn list_functions(&self) -> Vec<FuncMeta> {
3724 let mut out: Vec<FuncMeta> = self.functions.entries_metas().into_iter().collect();
3725 if !out.iter().any(|m| m.name == KEYWORD_INSPECT) {
3727 out.push(FuncMeta {
3728 name: KEYWORD_INSPECT.to_string(),
3729 module: STD_MODULE_NAME.to_string(),
3730 kind: FuncKind::HostCtx,
3731 params: None,
3732 returns: Some(TypeTag::Map),
3733 rpn: false,
3734 summary: "Inspect a variable binding.",
3735 docs: "INSPECT($var): dedicated AST node taking a variable, not a value.",
3736 examples: &[],
3737 });
3738 }
3739 out.sort_by(|a, b| a.name.cmp(&b.name));
3740 out
3741 }
3742
3743 pub fn describe_function(&self, name: &str) -> Option<Value> {
3745 if let Some(meta) = self.functions.meta(name) {
3746 return Some(meta_to_value(&meta));
3747 }
3748 if name == KEYWORD_INSPECT {
3750 return Some(meta_to_value(&FuncMeta {
3751 name: KEYWORD_INSPECT.to_string(),
3752 module: STD_MODULE_NAME.to_string(),
3753 kind: FuncKind::HostCtx,
3754 params: None,
3755 returns: Some(TypeTag::Map),
3756 rpn: false,
3757 summary: "Inspect a variable binding.",
3758 docs: "INSPECT($var): dedicated AST node taking a variable, not a value.",
3759 examples: &[],
3760 }));
3761 }
3762 None
3763 }
3764
3765 pub(super) fn clone_native_pure(&self, name: &str) -> Option<PureFn> {
3766 self.functions.clone_pure_fn(name)
3767 }
3768
3769 pub fn pure_function_table(&self) -> Arc<PureTable> {
3774 self.functions.pure_shared()
3775 }
3776
3777 pub(super) fn clone_native_ctx(&self, name: &str) -> Option<NativeFn<P>> {
3778 self.functions.clone_ctx_fn(name)
3779 }
3780
3781 pub(super) fn native_meta(&self, name: &str) -> Option<FuncMeta> {
3782 self.functions.meta(name)
3783 }
3784}
3785
3786#[cfg(test)]
3787mod tests {
3788 use super::*;
3789
3790 #[test]
3791 fn describe_entry_renders_union_spellings() {
3792 let union = oxdock_parser::union_tag!(String, Pipe);
3798 let meta = FuncMeta {
3799 name: "T::F".to_string(),
3800 module: "T".to_string(),
3801 kind: FuncKind::HostPure,
3802 params: Some(vec![FuncParam {
3803 name: "text".to_string(),
3804 param_type: Some(union.clone()),
3805 allowed: None,
3806 docs: "",
3807 options: None,
3808 optional: false,
3809 }]),
3810 returns: Some(union),
3811 rpn: false,
3812 summary: "test-only",
3813 docs: "test-only",
3814 examples: &[],
3815 };
3816 let value = meta_to_value(&meta);
3817 let map = value.as_map().expect("describe value is a map");
3818 let params = map
3819 .get("params")
3820 .expect("params key")
3821 .as_list()
3822 .expect("params is a list");
3823 let first = params[0].as_map().expect("entry is a map");
3824 assert_eq!(
3825 first.get("param_type").and_then(Value::as_str),
3826 Some("STRING|PIPE"),
3827 "param renders the set"
3828 );
3829 assert_eq!(
3830 map.get("returns").and_then(Value::as_str),
3831 Some("STRING|PIPE"),
3832 "returns render the set"
3833 );
3834 }
3835
3836 #[test]
3837 fn describe_entry_carries_optional_flag() {
3838 let meta = FuncMeta {
3842 name: "T::F".to_string(),
3843 module: "T".to_string(),
3844 kind: FuncKind::HostPure,
3845 params: Some(vec![
3846 FuncParam {
3847 name: "url".to_string(),
3848 param_type: Some(TypeTag::String),
3849 allowed: None,
3850 docs: "",
3851 options: None,
3852 optional: false,
3853 },
3854 FuncParam {
3855 name: "options".to_string(),
3856 param_type: Some(TypeTag::Map),
3857 allowed: None,
3858 docs: "",
3859 options: None,
3860 optional: true,
3861 },
3862 ]),
3863 returns: Some(TypeTag::String),
3864 rpn: false,
3865 summary: "test-only",
3866 docs: "test-only",
3867 examples: &[],
3868 };
3869 let value = meta_to_value(&meta);
3870 let map = value.as_map().expect("describe value is a map");
3871 let params = map
3872 .get("params")
3873 .expect("params key")
3874 .as_list()
3875 .expect("params is a list");
3876 assert_eq!(params.len(), 2);
3877 let first = params[0].as_map().expect("entry is a map");
3878 let second = params[1].as_map().expect("entry is a map");
3879 assert_eq!(
3880 first.get("optional").and_then(Value::as_bool),
3881 Some(false),
3882 "required param must read false"
3883 );
3884 assert_eq!(
3885 second.get("optional").and_then(Value::as_bool),
3886 Some(true),
3887 "omittable param must read true"
3888 );
3889 }
3890
3891 #[test]
3892 fn template_twins_mirror_string_paths_and_refuse_pipes() {
3893 let pipe = Value::pipe_fresh();
3899 type TwinCase = (&'static str, Box<dyn Fn() -> Result<Value>>);
3900 let cases: Vec<TwinCase> = vec![
3901 (
3902 "TEXT_TRIM",
3903 Box::new(|| text_trim_string(Value::string(" hello ".to_string()))),
3904 ),
3905 (
3906 "TEXT_TRIM_PREFIX",
3907 Box::new(|| {
3908 text_trim_prefix_string(Value::string("v1".to_string()), "v".to_string())
3909 }),
3910 ),
3911 (
3912 "TEXT_TRIM_SUFFIX",
3913 Box::new(|| {
3914 text_trim_suffix_string(Value::string("a.gz".to_string()), "x".to_string())
3915 }),
3916 ),
3917 (
3918 "TEXT_TO_UPPER",
3919 Box::new(|| text_to_upper_string(Value::string("hi".to_string()))),
3920 ),
3921 (
3922 "TEXT_TO_LOWER",
3923 Box::new(|| text_to_lower_string(Value::string("HI".to_string()))),
3924 ),
3925 (
3926 "TEXT_REPLACE",
3927 Box::new(|| {
3928 text_replace_string(
3929 Value::string("ab".to_string()),
3930 "b".to_string(),
3931 "c".to_string(),
3932 )
3933 }),
3934 ),
3935 (
3936 "TEXT_REPLACE_REGEX",
3937 Box::new(|| {
3938 text_replace_regex_string(
3939 Value::string("ab".to_string()),
3940 "b".to_string(),
3941 "c".to_string(),
3942 )
3943 }),
3944 ),
3945 ];
3946 assert_eq!(cases.len(), 7, "every mirror op needs a twin row");
3947 for (name, run) in &cases {
3948 let value = run().unwrap_or_else(|e| panic!("{name} twin must answer strings: {e:#}"));
3949 assert!(
3950 value.as_str().is_some(),
3951 "{name} twin must answer STRING, got {}",
3952 value.type_name()
3953 );
3954 }
3955 assert_eq!(
3956 text_trim_string(Value::string(" hello ".to_string()))
3957 .expect("trim twin")
3958 .as_str(),
3959 Some("hello")
3960 );
3961 let pipe_cases: Vec<(&str, Result<Value>)> = vec![
3963 ("TEXT_TRIM", text_trim_string(pipe.clone())),
3964 (
3965 "TEXT_TRIM_PREFIX",
3966 text_trim_prefix_string(pipe.clone(), "v".to_string()),
3967 ),
3968 (
3969 "TEXT_TRIM_SUFFIX",
3970 text_trim_suffix_string(pipe.clone(), ".gz".to_string()),
3971 ),
3972 ("TEXT_TO_UPPER", text_to_upper_string(pipe.clone())),
3973 ("TEXT_TO_LOWER", text_to_lower_string(pipe.clone())),
3974 (
3975 "TEXT_REPLACE",
3976 text_replace_string(pipe.clone(), "a".to_string(), "b".to_string()),
3977 ),
3978 (
3979 "TEXT_REPLACE_REGEX",
3980 text_replace_regex_string(pipe.clone(), "a".to_string(), "b".to_string()),
3981 ),
3982 ];
3983 for (name, result) in pipe_cases {
3984 let err = result.expect_err(&format!("{name} twin must refuse PIPE"));
3985 assert!(
3986 format!("{err:#}").contains("step IO"),
3987 "{name} refusal names the missing context: {err:#}"
3988 );
3989 }
3990 }
3991
3992 #[test]
3993 fn shell_words_join_split_round_trip() {
3994 let words = vec![
3998 "gh".to_string(),
3999 "issue".to_string(),
4000 "comment".to_string(),
4001 "with spaces".to_string(),
4002 "it's".to_string(),
4003 "say \"hi\"".to_string(),
4004 "$HOME".to_string(),
4005 "$(whoami)".to_string(),
4006 "C:\\path\\to".to_string(),
4007 "naïve café".to_string(),
4008 "".to_string(),
4009 ];
4010 let joined = shell_words::join(&words);
4011 let back = shell_words::split(&joined).expect("join output must parse");
4012 assert_eq!(back, words);
4013 assert!(shell_words::split("unbalanced \"quote").is_err());
4014 }
4015}