1use std::collections::{BTreeMap, HashMap, HashSet};
2use std::sync::Arc;
3
4use anyhow::Result;
5use oxdock_func_macro::oxdock_func;
6use oxdock_parser::{
7 Field, KEYWORD_INSPECT, SCRIPT_MODULE_NAME, STD_MODULE_NAME, SemaphoreState, Step, TypeTag,
8 Value, base_name, qualify, render_structural, split_qualified,
9};
10use oxdock_pipe::PipeHandle;
11use oxdock_process::{CommandStdin, DefaultProcessManager, ProcessManager};
12
13use super::io::StreamHandle;
14use super::state::ExecState;
15use super::steps::StepCtx;
16use super::typing::TypeDescriptor;
17
18#[derive(Debug, Clone, Copy, PartialEq, Eq)]
24pub enum FuncKind {
25 Script,
26 HostCtx,
27 HostPure,
28}
29
30impl FuncKind {
31 pub fn label(&self) -> &'static str {
32 match self {
33 FuncKind::Script => "script",
34 FuncKind::HostCtx | FuncKind::HostPure => "host",
35 }
36 }
37}
38
39#[derive(Debug, Clone)]
57pub struct FuncParam {
58 pub name: String,
59 pub param_type: Option<TypeTag>,
60 pub allowed: Option<&'static [&'static str]>,
61 pub docs: &'static str,
62 pub options: Option<&'static [ParamOption]>,
63 pub optional: bool,
64}
65
66pub fn required_arity(params: &[FuncParam]) -> usize {
71 params
72 .iter()
73 .rev()
74 .take_while(|param| param.optional)
75 .fold(params.len(), |count, _| count - 1)
76}
77
78pub fn fill_optional_args(params: &[FuncParam], mut values: Vec<Value>) -> Vec<Value> {
83 assert!(
84 values.len() <= params.len(),
85 "arity gate must run before fill_optional_args"
86 );
87 assert!(
88 values.len() >= required_arity(params),
89 "arity gate must run before fill_optional_args"
90 );
91 while values.len() < params.len() {
92 values.push(Value::map(BTreeMap::new()));
93 }
94 values
95}
96
97#[derive(Debug, Clone)]
104pub struct ParamOption {
105 pub name: &'static str,
106 pub value: TypeTag,
107 pub required: bool,
108 pub default: Option<&'static str>,
109}
110
111#[derive(Debug, Clone)]
117pub struct FuncMeta {
118 pub name: String,
119 pub module: String,
123 pub kind: FuncKind,
124 pub params: Option<Vec<FuncParam>>,
125 pub returns: Option<TypeTag>,
126 pub rpn: bool,
127 pub summary: &'static str,
128 pub docs: &'static str,
129 pub examples: &'static [crate::Example],
135}
136
137pub type PureFn = Arc<dyn Fn(Vec<Value>) -> Result<Value> + Send + Sync>;
140
141pub type NativeFn<P> = Arc<dyn Fn(&mut StepCtx<P>, Vec<Value>) -> Result<Value> + Send + Sync>;
143
144pub trait OxDockFn<P: ProcessManager> {
148 fn registration() -> HostRegistration<P>;
151}
152
153pub enum HostRegistration<P: ProcessManager> {
162 Stateful {
163 name: String,
164 meta: FuncMeta,
165 func: NativeFn<P>,
166 },
167 Pure {
168 name: String,
169 meta: FuncMeta,
170 func: PureFn,
171 },
172 Both {
173 name: String,
174 meta: FuncMeta,
175 func: NativeFn<P>,
176 template: PureFn,
177 },
178}
179
180impl<P: ProcessManager> Clone for HostRegistration<P> {
183 fn clone(&self) -> Self {
184 match self {
185 HostRegistration::Stateful { name, meta, func } => HostRegistration::Stateful {
186 name: name.clone(),
187 meta: meta.clone(),
188 func: Arc::clone(func),
189 },
190 HostRegistration::Pure { name, meta, func } => HostRegistration::Pure {
191 name: name.clone(),
192 meta: meta.clone(),
193 func: Arc::clone(func),
194 },
195 HostRegistration::Both {
196 name,
197 meta,
198 func,
199 template,
200 } => HostRegistration::Both {
201 name: name.clone(),
202 meta: meta.clone(),
203 func: Arc::clone(func),
204 template: Arc::clone(template),
205 },
206 }
207 }
208}
209
210impl<P: ProcessManager> HostRegistration<P> {
211 pub fn meta(&self) -> &FuncMeta {
214 match self {
215 HostRegistration::Stateful { meta, .. } => meta,
216 HostRegistration::Pure { meta, .. } => meta,
217 HostRegistration::Both { meta, .. } => meta,
218 }
219 }
220}
221
222#[derive(Debug, Clone)]
226pub(super) struct FuncDefData {
227 pub(super) params: Vec<(String, TypeTag)>,
228 pub(super) body: Vec<Step>,
229}
230
231pub(super) enum FuncBody<P: ProcessManager> {
236 Script(FuncDefData),
237 Pure(PureFn),
238 Ctx(NativeFn<P>),
239 Both { pure: PureFn, ctx: NativeFn<P> },
240}
241
242impl<P: ProcessManager> Clone for FuncBody<P> {
244 fn clone(&self) -> Self {
245 match self {
246 FuncBody::Script(def) => FuncBody::Script(def.clone()),
247 FuncBody::Pure(func) => FuncBody::Pure(Arc::clone(func)),
248 FuncBody::Ctx(func) => FuncBody::Ctx(Arc::clone(func)),
249 FuncBody::Both { pure, ctx } => FuncBody::Both {
250 pure: Arc::clone(pure),
251 ctx: Arc::clone(ctx),
252 },
253 }
254 }
255}
256
257pub(super) struct FuncEntry<P: ProcessManager> {
261 pub(super) meta: FuncMeta,
262 pub(super) body: FuncBody<P>,
263}
264
265impl<P: ProcessManager> Clone for FuncEntry<P> {
267 fn clone(&self) -> Self {
268 Self {
269 meta: self.meta.clone(),
270 body: self.body.clone(),
271 }
272 }
273}
274
275struct ScopeFrame<P: ProcessManager> {
278 defined: HashSet<String>,
279 shadowed: Vec<(String, FuncEntry<P>)>,
280}
281
282impl<P: ProcessManager> Clone for ScopeFrame<P> {
284 fn clone(&self) -> Self {
285 Self {
286 defined: self.defined.clone(),
287 shadowed: self.shadowed.clone(),
288 }
289 }
290}
291
292pub type PureTable = HashMap<String, HashMap<String, PureFn>>;
302
303pub struct FunctionRegistry<P: ProcessManager> {
304 entries: HashMap<String, FuncEntry<P>>,
305 scopes: Vec<ScopeFrame<P>>,
306 pure_shared: Arc<PureTable>,
307}
308
309impl<P: ProcessManager> FunctionRegistry<P> {
310 pub(super) fn with_builtins() -> Self {
311 let mut reg = Self {
312 entries: HashMap::new(),
313 pure_shared: Arc::new(HashMap::new()),
314 scopes: vec![ScopeFrame {
315 defined: HashSet::new(),
316 shadowed: Vec::new(),
317 }],
318 };
319 for host in Self::builtin_registrations() {
323 match host {
324 HostRegistration::Stateful { name, meta, func } => {
325 reg.insert_qualified(STD_MODULE_NAME, name, meta, FuncBody::Ctx(func));
326 }
327 HostRegistration::Pure { name, meta, func } => {
328 reg.insert_qualified(STD_MODULE_NAME, name, meta, FuncBody::Pure(func));
329 }
330 HostRegistration::Both {
331 name,
332 meta,
333 func,
334 template,
335 } => {
336 reg.insert_qualified(
337 STD_MODULE_NAME,
338 name,
339 meta,
340 FuncBody::Both {
341 pure: template,
342 ctx: func,
343 },
344 );
345 }
346 }
347 }
348 reg
349 }
350
351 pub(super) fn builtin_registrations() -> Vec<HostRegistration<P>> {
356 vec![
357 Int::registration(),
358 Float::registration(),
359 FormatByteCount::registration(),
360 ParseByteCount::registration(),
361 FormatDuration::registration(),
362 ParseDuration::registration(),
363 Types::registration(),
364 TypeDescribe::registration(),
365 Glob::registration(),
366 LoadToml::registration(),
367 LoadJson::registration(),
368 ParseToml::registration(),
369 ParseJson::registration(),
370 PathType::registration(),
371 PathWritable::registration(),
372 IsExec::registration(),
373 HasKey::registration(),
374 MapSet::registration(),
375 MergeMaps::registration(),
376 Base64Encode::registration(),
377 Base64Decode::registration(),
378 Rand::registration(),
379 ToJson::registration(),
380 TypeOf::registration(),
381 Functions::registration(),
382 Describe::registration(),
383 IsTerminal::registration(),
384 Eof::registration(),
385 TextTrim::registration(),
386 TextTrimPrefix::registration(),
387 TextTrimSuffix::registration(),
388 TextToUpper::registration(),
389 TextToLower::registration(),
390 TextReplace::registration(),
391 TextReplaceRegex::registration(),
392 TextSplit::registration(),
393 TextJoin::registration(),
394 TextLines::registration(),
395 TextFields::registration(),
396 TextMatch::registration(),
397 TextExtract::registration(),
398 TextStartsWith::registration(),
399 TextEndsWith::registration(),
400 TextContains::registration(),
401 TextLength::registration(),
402 TextCount::registration(),
403 TextCountMatches::registration(),
404 TextGrep::registration(),
405 TextLinesRange::registration(),
406 SemaphoreNew::registration(),
407 SemaphoreTryAcquire::registration(),
408 SemaphoreAvailable::registration(),
409 ]
410 }
411
412 pub(super) fn keys(&self) -> HashSet<String> {
415 self.entries.keys().cloned().collect()
416 }
417
418 pub(super) fn get(&self, name: &str) -> Option<FuncEntry<P>> {
420 self.entries.get(name).cloned()
421 }
422
423 fn insert_native(&mut self, name: String, meta: FuncMeta, body: FuncBody<P>) {
424 self.entries.insert(name, FuncEntry { meta, body });
425 self.rebuild_pure_shared();
426 }
427
428 fn rebuild_pure_shared(&mut self) {
434 let mut table: PureTable = HashMap::new();
435 for (name, entry) in &self.entries {
436 let func = match &entry.body {
437 FuncBody::Pure(func) => func,
438 FuncBody::Both { pure, .. } => pure,
439 FuncBody::Script(_) | FuncBody::Ctx(_) => continue,
440 };
441 if let Some((module, base)) = split_qualified(name) {
442 table
443 .entry(module.to_string())
444 .or_default()
445 .insert(base.to_string(), Arc::clone(func));
446 }
447 }
448 self.pure_shared = Arc::new(table);
449 }
450
451 fn insert_qualified(
455 &mut self,
456 module: &str,
457 base: String,
458 mut meta: FuncMeta,
459 body: FuncBody<P>,
460 ) {
461 meta.name = qualify(module, &base);
462 meta.module = module.to_string();
463 if self.entries.contains_key(&meta.name) {
468 panic!("duplicate function registration `{}`", meta.name);
469 }
470 self.insert_native(meta.name.clone(), meta, body);
471 }
472
473 pub(super) fn register_host(
474 &mut self,
475 module: &str,
476 name: String,
477 mut meta: FuncMeta,
478 func: NativeFn<P>,
479 ) {
480 meta.kind = FuncKind::HostCtx;
481 self.insert_qualified(module, name, meta, FuncBody::Ctx(func));
482 }
483
484 pub(super) fn register_pure_host(
485 &mut self,
486 module: &str,
487 name: String,
488 mut meta: FuncMeta,
489 func: PureFn,
490 ) {
491 meta.kind = FuncKind::HostPure;
492 self.insert_qualified(module, name, meta, FuncBody::Pure(func));
493 }
494
495 pub(super) fn register_both_host(
496 &mut self,
497 module: &str,
498 name: String,
499 mut meta: FuncMeta,
500 func: NativeFn<P>,
501 template: PureFn,
502 ) {
503 meta.kind = FuncKind::HostCtx;
504 self.insert_qualified(
505 module,
506 name,
507 meta,
508 FuncBody::Both {
509 pure: template,
510 ctx: func,
511 },
512 );
513 }
514
515 pub(super) fn define_script(
520 &mut self,
521 name: &str,
522 params: &[(String, TypeTag)],
523 body: &[Step],
524 ) -> Result<()> {
525 let qualified = qualify(SCRIPT_MODULE_NAME, name);
526 let shadowable = matches!(
527 self.entries.get(&qualified).map(|entry| &entry.body),
528 Some(FuncBody::Script(_))
529 );
530 let reserved = self
533 .entries
534 .keys()
535 .any(|key| split_qualified(key).is_some_and(|(_, base)| base == name));
536 if reserved && !shadowable {
537 anyhow::bail!("cannot shadow reserved function `{name}`");
538 }
539 if self
540 .scopes
541 .last()
542 .is_some_and(|frame| frame.defined.contains(&qualified))
543 {
544 anyhow::bail!("duplicate function `{name}` in same scope");
545 }
546 let old = self.entries.insert(
547 qualified.clone(),
548 FuncEntry {
549 meta: FuncMeta {
550 name: qualified.clone(),
551 module: SCRIPT_MODULE_NAME.to_string(),
552 kind: FuncKind::Script,
553 params: Some(
554 params
555 .iter()
556 .map(|(name, param_type)| FuncParam {
557 name: name.clone(),
558 param_type: Some(param_type.clone()),
559 allowed: None,
560 docs: "",
563 options: None,
564 optional: false,
565 })
566 .collect(),
567 ),
568 returns: None,
569 rpn: false,
570 summary: "DSL-defined function.",
571 docs: "Defined via FUNC in script.",
572 examples: &[],
573 },
574 body: FuncBody::Script(FuncDefData {
575 params: params.to_vec(),
576 body: body.to_vec(),
577 }),
578 },
579 );
580 if let Some(frame) = self.scopes.last_mut() {
581 frame.defined.insert(qualified.clone());
582 if let Some(old) = old {
583 frame.shadowed.push((qualified, old));
584 }
585 }
586 Ok(())
587 }
588
589 pub(super) fn push_scope(&mut self) {
592 self.scopes.push(ScopeFrame {
593 defined: HashSet::new(),
594 shadowed: Vec::new(),
595 });
596 }
597
598 pub(super) fn pop_scope(&mut self) {
601 let Some(frame) = self.scopes.pop() else {
602 return;
603 };
604 for name in frame.defined {
605 self.entries.remove(&name);
606 }
607 for (name, old) in frame.shadowed {
608 self.entries.insert(name, old);
609 }
610 }
611
612 pub(super) fn contains_script(&self, name: &str) -> bool {
616 matches!(
617 self.entries.get(name).map(|entry| &entry.body),
618 Some(FuncBody::Script(_))
619 )
620 }
621
622 fn clone_pure_fn(&self, name: &str) -> Option<PureFn> {
626 match self.entries.get(name)?.body {
627 FuncBody::Pure(ref func) => Some(Arc::clone(func)),
628 FuncBody::Both { ref pure, .. } => Some(Arc::clone(pure)),
629 _ => None,
630 }
631 }
632
633 pub(super) fn pure_shared(&self) -> Arc<PureTable> {
637 Arc::clone(&self.pure_shared)
638 }
639
640 pub(super) fn all_metas(&self) -> Vec<FuncMeta> {
643 self.entries_metas()
644 }
645
646 fn clone_ctx_fn(&self, name: &str) -> Option<NativeFn<P>> {
651 match self.entries.get(name)?.body {
652 FuncBody::Ctx(ref func) => Some(Arc::clone(func)),
653 FuncBody::Both { ref ctx, .. } => Some(Arc::clone(ctx)),
654 _ => None,
655 }
656 }
657
658 fn meta(&self, name: &str) -> Option<FuncMeta> {
659 self.entries.get(name).map(|entry| entry.meta.clone())
660 }
661
662 fn native_metas(&self) -> Vec<FuncMeta> {
663 let mut out: Vec<FuncMeta> = Vec::new();
664 for entry in self.entries.values() {
665 if !matches!(entry.body, FuncBody::Script(_)) {
666 out.push(entry.meta.clone());
667 }
668 }
669 out.sort_by(|a, b| a.name.cmp(&b.name));
670 out
671 }
672
673 fn entries_metas(&self) -> Vec<FuncMeta> {
676 let mut out: Vec<FuncMeta> = self
677 .entries
678 .values()
679 .map(|entry| entry.meta.clone())
680 .collect();
681 out.sort_by(|a, b| a.name.cmp(&b.name));
682 out
683 }
684}
685
686impl<P: ProcessManager> Clone for FunctionRegistry<P> {
687 fn clone(&self) -> Self {
688 Self {
689 entries: self.entries.clone(),
690 scopes: self.scopes.clone(),
691 pure_shared: Arc::clone(&self.pure_shared),
692 }
693 }
694}
695
696pub fn builtin_function_names() -> HashSet<String> {
703 let mut names = FunctionRegistry::<DefaultProcessManager>::with_builtins().keys();
704 names.insert(KEYWORD_INSPECT.to_string());
705 names
706}
707
708pub fn builtin_function_metas() -> Vec<FuncMeta> {
712 FunctionRegistry::<DefaultProcessManager>::with_builtins().native_metas()
713}
714
715pub fn std_module_table() -> oxdock_parser::ModuleTable {
720 let functions: HashSet<String> = builtin_function_metas()
722 .into_iter()
723 .map(|meta| base_name(&meta.name).to_string())
724 .collect();
725 oxdock_parser::ModuleTable {
726 modules: HashMap::from([(
727 STD_MODULE_NAME.to_string(),
728 Some(oxdock_parser::ModuleFuncs { functions }),
729 )]),
730 }
731}
732
733#[oxdock_func(pure, returns = TypeTag::Int)]
746#[example(
747 name = "convert",
748 code = r###"
749 IMPORT [STD]
750 LET $n: INT = INT("42")
751 ASSERT_EQ $n 42
752 LET $flag: INT = INT(true)
753 ASSERT_EQ $flag 1
754 "###
755)]
756fn int(
757 #[union(Int, Float, String, Bool)]
759 val: Value,
760) -> Result<Value> {
761 super::args::int_from_value(val)
762}
763
764#[oxdock_func(pure, returns = TypeTag::Float)]
769#[example(
770 name = "convert",
771 code = r###"
772 IMPORT [STD]
773 LET $f: FLOAT = FLOAT("1.5")
774 ASSERT_EQ $f 1.5
775 LET $whole: FLOAT = FLOAT(2)
776 ASSERT_EQ $whole 2.0
777 "###
778)]
779fn float(
780 #[union(Float, Int, String)]
782 val: Value,
783) -> Result<Value> {
784 super::args::float_from_value(val)
785}
786
787#[oxdock_func(pure, returns = TypeTag::String)]
792#[example(
793 name = "format and round-trip",
794 code = r###"
795 # Byte counts render in the largest exact unit.
796 IMPORT [STD]
797 LET $pretty: STRING = FORMAT_BYTE_COUNT(1_048_576)
798 ASSERT_EQ $pretty "1MiB"
799
800 # The pair round-trips through the parser.
801 LET $back: INT = PARSE_BYTE_COUNT($pretty)
802 ASSERT_EQ $back 1_048_576
803 "###
804)]
805fn format_byte_count(
806 bytes: i64,
808) -> Result<Value> {
809 if bytes < 0 {
810 return Err(anyhow::anyhow!(
811 "FORMAT_BYTE_COUNT needs a non-negative byte count, got {bytes}"
812 ));
813 }
814 Ok(Value::string(oxdock_parser::command::format_byte_count(
815 bytes as u64,
816 )))
817}
818
819#[oxdock_func(pure, returns = TypeTag::Int)]
854#[example(
855 name = "parse",
856 code = r###"
857 IMPORT [STD]
858 LET $n: INT = PARSE_BYTE_COUNT("10KB")
859 ASSERT_EQ $n 10_000
860 LET $identity: INT = PARSE_BYTE_COUNT(512)
861 ASSERT_EQ $identity 512
862 "###
863)]
864fn parse_byte_count(
865 #[union(Int, Float, String)]
867 text: Value,
868) -> Result<Value> {
869 if let Some(n) = text.as_i64() {
870 if n < 0 {
871 return Err(anyhow::anyhow!(
872 "PARSE_BYTE_COUNT needs a non-negative byte count, got {n}"
873 ));
874 }
875 return Ok(Value::int(n));
876 }
877 if let Some(f) = text.as_f64() {
878 if f.is_finite() && f.fract() == 0.0 && f >= 0.0 && f <= i64::MAX as f64 {
879 return Ok(Value::int(f as i64));
880 }
881 return Err(anyhow::anyhow!(
882 "PARSE_BYTE_COUNT needs an integral byte count, got {f:?}"
883 ));
884 }
885 let Some(s) = text.as_str() else {
886 return Err(anyhow::anyhow!(
887 "PARSE_BYTE_COUNT needs a token or number, found {text:?}"
888 ));
889 };
890 let n = oxdock_parser::command::parse_byte_count(s)?;
891 let n = i64::try_from(n)
892 .map_err(|_| anyhow::anyhow!("PARSE_BYTE_COUNT out of INT range: {s:?}"))?;
893 Ok(Value::int(n))
894}
895
896#[oxdock_func(pure, returns = TypeTag::String)]
901#[example(
902 name = "format and round-trip",
903 code = r###"
904 # Durations render in the largest exact unit.
905 IMPORT [STD]
906 LET $pretty: STRING = FORMAT_DURATION(90_000)
907 ASSERT_EQ $pretty "90s"
908
909 # The pair round-trips through the parser.
910 LET $back: INT = PARSE_DURATION($pretty)
911 ASSERT_EQ $back 90_000
912 "###
913)]
914fn format_duration(
915 millis: i64,
917) -> Result<Value> {
918 if millis < 0 {
919 return Err(anyhow::anyhow!(
920 "FORMAT_DURATION needs non-negative milliseconds, got {millis}"
921 ));
922 }
923 Ok(Value::string(oxdock_parser::command::format_duration(
924 &std::time::Duration::from_millis(millis as u64),
925 )))
926}
927
928#[oxdock_func(pure, returns = TypeTag::Int)]
934#[example(
935 name = "parse",
936 code = r###"
937 # A bare number means seconds, like TIMEOUT.
938 IMPORT [STD]
939 LET $ms: INT = PARSE_DURATION("2m")
940 ASSERT_EQ $ms 120_000
941
942 # Milliseconds stay exact.
943 LET $exact: INT = PARSE_DURATION("1500ms")
944 ASSERT_EQ $exact 1_500
945
946 # One optional space separates number from unit.
947 LET $spaced: INT = PARSE_DURATION("1 h")
948 ASSERT_EQ $spaced 3_600_000
949 "###
950)]
951fn parse_duration(
952 text: String,
954) -> Result<Value> {
955 let duration = oxdock_parser::command::parse_duration(&text)?;
956 let millis = i64::try_from(duration.as_millis())
957 .map_err(|_| anyhow::anyhow!("PARSE_DURATION out of INT range: {text:?}"))?;
958 Ok(Value::int(millis))
959}
960
961#[oxdock_func(rpn, returns = TypeTag::ListOf(std::sync::Arc::new(TypeTag::String)))]
966#[example(
967 name = "match",
968 code = r###"
969 IMPORT [STD]
970 WRITE "notes-a.md" "a"
971 WRITE "notes-b.md" "b"
972 WRITE "other.txt" "c"
973 LET $found: LIST<STRING> = GLOB("notes-*.md")
974 ASSERT_EQ $found.0 "notes-a.md"
975 ASSERT_EQ $found.1 "notes-b.md"
976 "###
977)]
978fn glob<P: ProcessManager>(
979 cx: &mut StepCtx<P>,
980 #[union(String, Path)]
982 pattern: Value,
983) -> Result<Value> {
984 let text = super::args::string_or_path_text(&pattern)?;
985 super::args::glob_from_value(&[Value::string(text)], cx)
986}
987
988#[oxdock_func(rpn, returns = TypeTag::MapOf(std::sync::Arc::new(TypeTag::Any)))]
993#[example(
994 name = "load",
995 code = r###"
996 IMPORT [STD]
997 WRITE "cfg.toml" "title = \"demo\""
998 LET $cfg: MAP<ANY> = LOAD_TOML("cfg.toml")
999 ASSERT_EQ $cfg.title "demo"
1000 "###
1001)]
1002fn load_toml<P: ProcessManager>(
1003 cx: &mut StepCtx<P>,
1004 #[union(String, Path)]
1006 path: Value,
1007) -> Result<Value> {
1008 let text = super::args::string_or_path_text(&path)?;
1009 super::args::load_toml_from_value(&[Value::string(text)], cx)
1010}
1011
1012#[oxdock_func(rpn, returns = TypeTag::Any)]
1020#[example(
1021 name = "load",
1022 code = r###"
1023 IMPORT [STD]
1024 WRITE "data.json" "{\"a\": 1}"
1025 LET $doc: MAP<ANY> = LOAD_JSON("data.json")
1026 ASSERT_EQ $doc.a 1
1027 "###
1028)]
1029fn load_json<P: ProcessManager>(
1030 cx: &mut StepCtx<P>,
1031 #[union(String, Path)]
1033 path: Value,
1034) -> Result<Value> {
1035 let text = super::args::string_or_path_text(&path)?;
1036 super::args::load_json_from_value(&[Value::string(text)], cx)
1037}
1038
1039#[oxdock_func(pure, returns = TypeTag::MapOf(std::sync::Arc::new(TypeTag::Any)))]
1045#[example(
1046 name = "parse",
1047 code = r###"
1048 IMPORT [STD]
1049 LET $doc: MAP<ANY> = PARSE_TOML("title = \"demo\"")
1050 ASSERT_EQ $doc.title "demo"
1051 "###
1052)]
1053fn parse_toml(
1054 text: String,
1056) -> Result<Value> {
1057 super::args::parse_toml_from_value(Value::string(text))
1058}
1059
1060#[oxdock_func(pure, returns = TypeTag::Any)]
1069#[example(
1070 name = "parse",
1071 code = r###"
1072 # Parse in-memory JSON text with the same conversion as file loading.
1073 IMPORT [STD]
1074 LET $body: STRING = "{\"a\": 1}"
1075 LET $doc: ANY = PARSE_JSON($body)
1076 ASSERT_EQ $doc.a 1
1077
1078 # Top-level arrays parse to LIST, which is why the return is ANY.
1079 LET $items: LIST<ANY> = PARSE_JSON("[1, 2]")
1080 ASSERT_EQ $items.0 1
1081 ASSERT_EQ $items.1 2
1082 "###
1083)]
1084fn parse_json(
1085 text: String,
1087) -> Result<Value> {
1088 super::args::parse_json_from_value(Value::string(text))
1089}
1090
1091#[oxdock_func(returns = TypeTag::String)]
1097#[example(
1098 name = "describe",
1099 code = r###"
1100 IMPORT [STD]
1101 WRITE "entry.txt" "words"
1102 LET $kind: STRING = PATH_TYPE("entry.txt")
1103 ASSERT_EQ $kind "file"
1104 LET $missing: STRING = PATH_TYPE("no-such-entry.txt")
1105 ASSERT_EQ $missing "absent"
1106 "###
1107)]
1108fn path_type<P: ProcessManager>(
1109 cx: &mut StepCtx<P>,
1110 #[union(String, Path)]
1112 path: Value,
1113) -> Result<Value> {
1114 let text = super::args::string_or_path_text(&path)?;
1115 super::args::path_type_from_value(&[Value::string(text)], cx)
1116}
1117
1118#[oxdock_func(returns = TypeTag::Bool)]
1127#[example(
1128 name = "probe",
1129 code = r###"
1130 # An absent nested path is writable when its ancestor is.
1131 IMPORT [STD]
1132 LET $fresh: BOOL = PATH_WRITABLE("probe-check/nested/file.txt")
1133 ASSERT_EQ $fresh true
1134
1135 # The empty string never aliases the working directory.
1136 LET $empty: BOOL = PATH_WRITABLE("")
1137 ASSERT_EQ $empty false
1138 "###
1139)]
1140fn path_writable<P: ProcessManager>(
1141 cx: &mut StepCtx<P>,
1142 #[union(String, Path)]
1144 path: Value,
1145) -> Result<Value> {
1146 let text = super::args::string_or_path_text(&path)?;
1147 super::args::path_writable_from_value(&[Value::string(text)], cx)
1148}
1149
1150#[oxdock_func(returns = TypeTag::Bool)]
1163#[example(
1164 name = "probe",
1165 code = r###"
1166 # Missing tools read false instead of failing the run.
1167 IMPORT [STD]
1168 LET $missing: BOOL = IS_EXEC("no-such-tool-xyz")
1169 ASSERT_EQ $missing false
1170
1171 # Plain files are not executable on any platform.
1172 WRITE tool.txt payload
1173 LET $plain: BOOL = IS_EXEC("tool.txt")
1174 ASSERT_EQ $plain false
1175 "###
1176)]
1177fn is_exec<P: ProcessManager>(
1178 cx: &mut StepCtx<P>,
1179 #[union(String, Path)]
1181 name: Value,
1182) -> Result<Value> {
1183 let text = super::args::string_or_path_text(&name)?;
1184 super::args::is_exec_from_value(&[Value::string(text)], cx)
1185}
1186
1187#[oxdock_func(pure, returns = TypeTag::Bool)]
1193#[example(
1194 name = "probe",
1195 code = r###"
1196 IMPORT [STD]
1197 LET $m: MAP<ANY> = PARSE_JSON("{\"a\": 1}")
1198 LET $hit: BOOL = HAS_KEY($m, "a")
1199 ASSERT_EQ $hit true
1200 LET $miss: BOOL = HAS_KEY($m, "b")
1201 ASSERT_EQ $miss false
1202 "###
1203)]
1204fn has_key(
1205 map: BTreeMap<String, Value>,
1207 key: String,
1209) -> Result<Value> {
1210 super::args::has_key_from_value(Value::map(map), &key)
1211}
1212
1213#[oxdock_func(pure, returns = TypeTag::MapOf(std::sync::Arc::new(TypeTag::Any)))]
1219#[example(
1220 name = "insert",
1221 code = r###"
1222 IMPORT [STD]
1223 LET $m: MAP<ANY> = MAP_SET({seed: 0}, "a", 1)
1224 ASSERT_EQ $m.a 1
1225 "###
1226)]
1227fn map_set(
1228 map: BTreeMap<String, Value>,
1230 key: String,
1232 value: Value,
1234) -> Result<Value> {
1235 super::args::map_set_from_value(Value::map(map), key, value)
1236}
1237
1238#[oxdock_func(returns = TypeTag::Float, summary = "Draw a random FLOAT uniformly from [0, 1), optionally seeded.")]
1246#[example(
1247 name = "seeded draw",
1248 code = r###"
1249 # A seed draws the same value on every run.
1250 IMPORT [STD]
1251 LET $one: FLOAT = RAND({seed: 7})
1252 LET $two: FLOAT = RAND({seed: 7})
1253 ASSERT_EQ $one $two
1254 "###
1255)]
1256#[example(
1257 name = "unseeded draw",
1258 code = r###"
1259 # Scale a unit draw into a backoff delay between 1 and 11 seconds.
1260 IMPORT [STD]
1261 LET $draw: FLOAT = RAND()
1262 LET $delay: FLOAT = 1.0 + $draw * 10.0
1263 IF $delay < 1.0 {
1264 EXIT 1
1265 }
1266 IF $delay >= 11.0 {
1267 EXIT 1
1268 }
1269 ECHO "retrying in {{ $delay }}s"
1270 "###
1271)]
1272fn rand<P: ProcessManager>(
1273 cx: &mut StepCtx<P>,
1274 #[options("seed?: INT")]
1276 #[optional]
1277 options: BTreeMap<String, Value>,
1278) -> Result<Value> {
1279 let _ = cx;
1280 let seed = options
1283 .get("seed")
1284 .map(|value| value.as_i64().expect("check_options verified INT"));
1285 super::args::rand_float_from_value(seed)
1286}
1287
1288#[oxdock_func(pure, returns = TypeTag::String)]
1294#[example(
1295 name = "encode",
1296 code = r###"
1297 # Encode text to standard base64.
1298 IMPORT [STD]
1299 LET $encoded: STRING = BASE64_ENCODE("hello")
1300 ASSERT_EQ $encoded "aGVsbG8="
1301 "###
1302)]
1303fn base64_encode(
1304 text: String,
1306) -> Result<Value> {
1307 super::args::base64_encode_from_value(Value::string(text))
1308}
1309
1310#[oxdock_func(pure, returns = TypeTag::String)]
1317#[example(
1318 name = "decode",
1319 code = r###"
1320 # Decode standard base64 back to text.
1321 IMPORT [STD]
1322 LET $decoded: STRING = BASE64_DECODE("aGVsbG8=")
1323 ASSERT_EQ $decoded "hello"
1324 "###
1325)]
1326fn base64_decode(
1327 text: String,
1329) -> Result<Value> {
1330 super::args::base64_decode_from_value(Value::string(text))
1331}
1332
1333#[oxdock_func(pure, returns = TypeTag::String)]
1340#[example(
1341 name = "encode",
1342 code = r###"
1343 IMPORT [STD]
1344 LET $json: STRING = TO_JSON({a: 1})
1345 ASSERT_EQ $json "{\"a\":1}\n"
1346 "###
1347)]
1348fn to_json(
1349 #[union(String, Int, Float, Bool, List, Map)]
1351 value: Value,
1352) -> Result<Value> {
1353 super::args::to_json_from_value(value)
1354}
1355
1356#[oxdock_func(pure, returns = TypeTag::String)]
1364#[example(
1365 name = "name the word",
1366 code = r###"
1367 IMPORT [STD]
1368 LET $word: STRING = TYPE_OF(42)
1369 ASSERT_EQ $word "INT"
1370 "###
1371)]
1372fn type_of(
1373 value: Value,
1375) -> Result<Value> {
1376 super::args::type_of_from_value(value)
1377}
1378
1379#[oxdock_func(pure, returns = TypeTag::MapOf(std::sync::Arc::new(TypeTag::Any)))]
1387#[example(
1388 name = "merge",
1389 code = r###"
1390 IMPORT [STD]
1391 LET $m: MAP<ANY> = MERGE_MAPS([{a: 1}, {b: 2}], "overwrite")
1392 ASSERT_EQ $m.a 1
1393 ASSERT_EQ $m.b 2
1394 "###
1395)]
1396fn merge_maps(
1397 maps: Vec<BTreeMap<String, Value>>,
1399 #[values("fail_on_duplicate", "overwrite")]
1401 policy: String,
1402) -> Result<Value> {
1403 super::args::merge_maps_from_value(
1404 Value::list(maps.into_iter().map(Value::map).collect()),
1405 policy,
1406 )
1407}
1408
1409#[oxdock_func(returns = TypeTag::ListOf(std::sync::Arc::new(TypeTag::String)))]
1414#[example(
1415 name = "list",
1416 code = r###"
1417 IMPORT [STD]
1418 LET $names: LIST<STRING> = FUNCTIONS()
1419 ASSERT_CONTAINS $names "STD::INT"
1420 "###
1421)]
1422fn functions<P: ProcessManager>(cx: &mut StepCtx<P>) -> Result<Value> {
1423 let mut names: Vec<String> = cx
1424 .state
1425 .list_functions()
1426 .into_iter()
1427 .map(|meta| meta.name)
1428 .collect();
1429 names.sort();
1430 names.dedup();
1431 Ok(Value::list(names.into_iter().map(Value::string).collect()))
1432}
1433
1434#[oxdock_func(
1449 returns = TypeTag::Record(std::sync::Arc::from([Field {
1450 name: "name".to_string(),
1451 ty: TypeTag::String,
1452 docs: "Qualified function name.",
1453 optional: false,
1454 }, Field {
1455 name: "module".to_string(),
1456 ty: TypeTag::String,
1457 docs: "Owning module.",
1458 optional: false,
1459 }, Field {
1460 name: "kind".to_string(),
1461 ty: TypeTag::String,
1462 docs: "Origin label (`host` or `script`).",
1463 optional: false,
1464 }, Field {
1465 name: "params".to_string(),
1466 ty: TypeTag::ListOf(std::sync::Arc::new(TypeTag::MapOf(std::sync::Arc::new(
1467 TypeTag::Any,
1468 )))),
1469 docs: "Parameter entries (empty for parameterless functions).",
1470 optional: false,
1471 }, Field {
1472 name: "returns".to_string(),
1473 ty: TypeTag::String,
1474 docs: "Structural return shape (empty when untagged).",
1475 optional: false,
1476 }, Field {
1477 name: "rpn".to_string(),
1478 ty: TypeTag::Bool,
1479 docs: "True when callable in RPN position.",
1480 optional: false,
1481 }, Field {
1482 name: "summary".to_string(),
1483 ty: TypeTag::String,
1484 docs: "One-line description.",
1485 optional: false,
1486 }]))
1487 summary = "Describe one function by qualified name."
1488)]
1489#[example(
1490 name = "describe",
1491 code = r###"
1492 IMPORT [STD]
1493 LET $info: MAP<ANY> = DESCRIBE("STD::INT")
1494 ASSERT_EQ $info.name "STD::INT"
1495 ASSERT_EQ $info.returns "INT"
1496 "###
1497)]
1498fn describe<P: ProcessManager>(
1499 cx: &mut StepCtx<P>,
1500 name: String,
1502) -> Result<Value> {
1503 if split_qualified(&name).is_none() && name != KEYWORD_INSPECT {
1504 anyhow::bail!(
1505 "unknown function `{name}`: DESCRIBE requires a qualified name (e.g. `STD::{name}`)"
1506 );
1507 }
1508 cx.state
1509 .describe_function(&name)
1510 .ok_or_else(|| anyhow::anyhow!("unknown function {name}"))
1511}
1512
1513#[oxdock_func(returns = TypeTag::ListOf(std::sync::Arc::new(TypeTag::String)))]
1519#[example(
1520 name = "list",
1521 code = r###"
1522 IMPORT [STD]
1523 LET $names: LIST<STRING> = TYPES()
1524 ASSERT_CONTAINS $names "STRING"
1525 "###
1526)]
1527fn types<P: ProcessManager>(cx: &mut StepCtx<P>) -> Result<Value> {
1528 Ok(Value::list(
1529 cx.state
1530 .type_names()
1531 .into_iter()
1532 .map(Value::string)
1533 .collect(),
1534 ))
1535}
1536
1537#[oxdock_func(returns = TypeTag::Record(std::sync::Arc::from([Field {
1543 name: "name".to_string(),
1544 ty: TypeTag::String,
1545 docs: "Queried type name.",
1546 optional: false,
1547}, Field {
1548 name: "summary".to_string(),
1549 ty: TypeTag::String,
1550 docs: "One-line description.",
1551 optional: false,
1552}, Field {
1553 name: "docs".to_string(),
1554 ty: TypeTag::String,
1555 docs: "Full documentation text.",
1556 optional: false,
1557}])))]
1558#[example(
1559 name = "describe",
1560 code = r###"
1561 IMPORT [STD]
1562 LET $info: MAP<ANY> = TYPE_DESCRIBE("STRING")
1563 ASSERT_EQ $info.name "STRING"
1564 "###
1565)]
1566fn type_describe<P: ProcessManager>(
1567 cx: &mut StepCtx<P>,
1568 name: String,
1570) -> Result<Value> {
1571 if let Some(descriptor) = cx.state.describe_type(&name) {
1572 let mut map = BTreeMap::new();
1573 map.insert(
1574 "name".to_string(),
1575 Value::string(descriptor.name.to_string()),
1576 );
1577 map.insert(
1578 "summary".to_string(),
1579 Value::string(descriptor.summary.to_string()),
1580 );
1581 map.insert(
1582 "docs".to_string(),
1583 Value::string(descriptor.docs.to_string()),
1584 );
1585 return Ok(Value::map(map));
1586 }
1587 if let Some(target) = cx.state.alias_target(&name) {
1590 let mut map = BTreeMap::new();
1591 map.insert("name".to_string(), Value::string(name.clone()));
1592 map.insert(
1593 "summary".to_string(),
1594 Value::string(format!("Script type alias for {target}.")),
1595 );
1596 map.insert(
1597 "docs".to_string(),
1598 Value::string(format!(
1599 "Declared with TYPE {name} = {target}. The alias expands structurally at every declaration."
1600 )),
1601 );
1602 return Ok(Value::map(map));
1603 }
1604 Err(anyhow::anyhow!("unknown type {name}"))
1605}
1606
1607#[oxdock_func(returns = TypeTag::Bool)]
1621#[example(
1622 name = "null stdin",
1623 code = r###"
1624 # A null stdin is never a terminal, in every harness.
1625 IMPORT [STD]
1626 LET $term: BOOL = IS_TERMINAL("stdin")
1627 ASSERT_EQ $term false
1628 "###
1629)]
1630fn is_terminal<P: ProcessManager>(
1631 cx: &mut StepCtx<P>,
1632 #[values("stdin", "stdout", "stderr")]
1634 stream_name: String,
1635) -> Result<Value> {
1636 use std::io::IsTerminal;
1637 let terminal = match stream_name.as_str() {
1638 "stdin" => {
1639 if cx.stdin_pipe.is_some() {
1644 false
1645 } else {
1646 match &cx.stdin {
1647 CommandStdin::Null => false,
1648 #[cfg(not(miri))]
1649 CommandStdin::OsPipe(_) => false,
1650 CommandStdin::Stream(_) => false,
1651 CommandStdin::Inherit => std::io::stdin().is_terminal(),
1652 }
1653 }
1654 }
1655 "stdout" => {
1656 if cx.out_pipe.is_some() {
1657 false
1659 } else if cx.state.io.stdout().is_some() {
1660 false
1663 } else {
1664 match &cx.out {
1665 None => std::io::stdout().is_terminal(),
1667 #[cfg(not(miri))]
1669 Some(StreamHandle::Os(_)) => false,
1670 Some(StreamHandle::Stream(_)) => std::io::stdout().is_terminal(),
1680 }
1681 }
1682 }
1683 "stderr" => {
1684 if cx.state.io.stderr().is_some() {
1685 false
1687 } else {
1688 match &cx.err {
1689 None => std::io::stderr().is_terminal(),
1691 #[cfg(not(miri))]
1693 Some(StreamHandle::Os(_)) => false,
1694 Some(StreamHandle::Stream(_)) => false,
1697 }
1698 }
1699 }
1700 _ => anyhow::bail!(
1701 "IS_TERMINAL expects \"stdin\", \"stdout\", or \"stderr\", got {stream_name:?}"
1706 ),
1707 };
1708 Ok(Value::bool(terminal))
1709}
1710
1711#[oxdock_func(returns = TypeTag::Semaphore)]
1719#[example(
1720 name = "mint",
1721 code = r###"
1722 # Mint a semaphore admitting at most two holders.
1723 IMPORT [STD]
1724 LET $sem: SEMAPHORE = SEMAPHORE_NEW(2)
1725
1726 # A fresh semaphore reports its full cap as available.
1727 LET $free: INT = SEMAPHORE_AVAILABLE($sem)
1728 ASSERT_EQ $free 2
1729 "###
1730)]
1731fn semaphore_new<P: ProcessManager>(
1732 cx: &mut StepCtx<P>,
1733 max: i64,
1735) -> Result<Value> {
1736 let _ = cx;
1737 if max <= 0 {
1738 return Err(anyhow::anyhow!(
1739 "SEMAPHORE_NEW() requires a positive max, got {max}"
1740 ));
1741 }
1742 Ok(Value::semaphore(max as usize))
1743}
1744
1745#[oxdock_func(returns = TypeTag::Record(std::sync::Arc::from([Field {
1754 name: "held".to_string(),
1755 ty: TypeTag::Bool,
1756 docs: "`true` with the permit under `permit`, `false` with no `permit` key.",
1757 optional: false,
1758}, Field {
1759 name: "permit".to_string(),
1760 ty: TypeTag::Permit,
1761 docs: "Permit handle; read only when `held`.",
1762 optional: true,
1763}])))]
1764#[example(
1765 name = "acquire",
1766 code = r###"
1767 # First acquire holds with a permit to bind.
1768 IMPORT [STD]
1769 LET $sem: SEMAPHORE = SEMAPHORE_NEW(1)
1770 LET $first: MAP<held: BOOL, permit?: PERMIT> = SEMAPHORE_TRY_ACQUIRE($sem)
1771 ASSERT_EQ $first.held true
1772 LET $permit: PERMIT = $first.permit
1773
1774 # A capped semaphore answers held false with no permit key.
1775 LET $second: MAP<held: BOOL, permit?: PERMIT> = SEMAPHORE_TRY_ACQUIRE($sem)
1776 ASSERT_EQ $second.held false
1777 LET $has_permit: BOOL = HAS_KEY($second, "permit")
1778 ASSERT_EQ $has_permit false
1779 "###
1780)]
1781fn semaphore_try_acquire<P: ProcessManager>(
1782 cx: &mut StepCtx<P>,
1783 sem: Arc<SemaphoreState>,
1785) -> Result<Value> {
1786 let _ = cx;
1787 let mut map = BTreeMap::new();
1788 if sem.try_acquire() {
1789 map.insert("held".to_string(), Value::bool(true));
1790 map.insert("permit".to_string(), Value::permit(&sem));
1791 } else {
1792 map.insert("held".to_string(), Value::bool(false));
1793 }
1794 Ok(Value::map(map))
1795}
1796
1797#[oxdock_func(pure, returns = TypeTag::Int)]
1804#[example(
1805 name = "readout",
1806 code = r###"
1807 # Hold one permit on a cap of two.
1808 IMPORT [STD]
1809 LET $sem: SEMAPHORE = SEMAPHORE_NEW(2)
1810 LET $acq: MAP<held: BOOL, permit?: PERMIT> = SEMAPHORE_TRY_ACQUIRE($sem)
1811 ASSERT_EQ $acq.held true
1812
1813 # One held permit leaves exactly one free.
1814 LET $free: INT = SEMAPHORE_AVAILABLE($sem)
1815 ASSERT_EQ $free 1
1816 "###
1817)]
1818fn semaphore_available(
1819 sem: Arc<SemaphoreState>,
1821) -> Result<Value> {
1822 Ok(Value::int(sem.available() as i64))
1823}
1824
1825#[oxdock_func(
1834 rpn,
1835 returns = TypeTag::union(vec![TypeTag::String, TypeTag::Pipe]),
1836 template = text_trim_string
1837)]
1838#[example(
1839 name = "trim",
1840 code = r###"
1841 # Leading and trailing whitespace falls away.
1842 IMPORT [STD]
1843 LET $clean: STRING = TEXT_TRIM(" hello ")
1844 ASSERT_EQ $clean "hello"
1845 "###
1846)]
1847#[example(
1848 name = "trim pipe mirrors",
1849 code = r###"
1850 # Pipe input mints pipe output with the same transform.
1851 IMPORT [STD]
1852 LET $cap: PIPE
1853 WITH_IO [stdout=$cap] {
1854 ECHO " hello "
1855 }
1856 LET $out: PIPE = TEXT_TRIM($cap)
1857 WITH_IO [stdin=$out] READ_LINE $line
1858 ASSERT_EQ $line "hello"
1859 "###
1860)]
1861#[example(
1862 name = "trim template",
1863 code = r###"
1864 # String inputs run inside placeholders too.
1865 IMPORT [STD]
1866 LET $msg: STRING = 'clean:{{ STD::TEXT_TRIM(" hello ") }}'
1867 ASSERT_EQ $msg "clean:hello"
1868 "###
1869)]
1870#[example(
1871 name = "trim file template",
1872 code = r###"
1873 # EXPAND templates resolve the same registry.
1874 IMPORT [STD]
1875 WRITE "tpl.txt" "clean:\{{ STD::TEXT_TRIM(\" hello \") }}"
1876 LET $out: STRING = EXPAND "tpl.txt"
1877 ASSERT_EQ $out "clean:hello"
1878 "###
1879)]
1880fn text_trim<P: ProcessManager>(
1881 cx: &mut StepCtx<P>,
1882 #[union(String, Pipe)]
1884 text: Value,
1885) -> Result<Value> {
1886 super::args::mirror_stream(cx, "TEXT_TRIM", &text, super::args::TextPump::Trim)
1887}
1888
1889fn text_trim_string(text: Value) -> Result<Value> {
1892 super::args::mirror_string("TEXT_TRIM", &text, super::args::TextPump::Trim)
1893}
1894
1895#[oxdock_func(
1904 rpn,
1905 returns = TypeTag::union(vec![TypeTag::String, TypeTag::Pipe]),
1906 template = text_trim_prefix_string
1907)]
1908#[example(
1909 name = "strip prefix",
1910 code = r###"
1911 # A present prefix falls away; absence returns the input unchanged.
1912 IMPORT [STD]
1913 LET $bare: STRING = TEXT_TRIM_PREFIX("v1.2.3", "v")
1914 ASSERT_EQ $bare "1.2.3"
1915
1916 # Missing prefixes pass through untouched.
1917 LET $same: STRING = TEXT_TRIM_PREFIX("1.2.3", "v")
1918 ASSERT_EQ $same "1.2.3"
1919 "###
1920)]
1921#[example(
1922 name = "strip prefix pipe mirrors",
1923 code = r###"
1924 # Pipe input mints pipe output with the same strip.
1925 IMPORT [STD]
1926 LET $cap: PIPE
1927 WITH_IO [stdout=$cap] {
1928 ECHO "v1.2.3"
1929 }
1930 LET $trimmed: PIPE = TEXT_TRIM($cap)
1931 LET $out: PIPE = TEXT_TRIM_PREFIX($trimmed, "v")
1932 WITH_IO [stdin=$out] READ_LINE $line
1933 ASSERT_EQ $line "1.2.3"
1934 "###
1935)]
1936#[example(
1937 name = "strip prefix template",
1938 code = r###"
1939 # String inputs run inside placeholders too.
1940 IMPORT [STD]
1941 LET $msg: STRING = 'bare:{{ STD::TEXT_TRIM_PREFIX("v1.2.3", "v") }}'
1942 ASSERT_EQ $msg "bare:1.2.3"
1943 "###
1944)]
1945fn text_trim_prefix<P: ProcessManager>(
1946 cx: &mut StepCtx<P>,
1947 #[union(String, Pipe)]
1949 text: Value,
1950 prefix: String,
1952) -> Result<Value> {
1953 super::args::mirror_stream(
1954 cx,
1955 "TEXT_TRIM_PREFIX",
1956 &text,
1957 super::args::TextPump::TrimPrefix(prefix),
1958 )
1959}
1960
1961fn text_trim_prefix_string(text: Value, prefix: String) -> Result<Value> {
1964 super::args::mirror_string(
1965 "TEXT_TRIM_PREFIX",
1966 &text,
1967 super::args::TextPump::TrimPrefix(prefix),
1968 )
1969}
1970
1971#[oxdock_func(
1978 rpn,
1979 returns = TypeTag::union(vec![TypeTag::String, TypeTag::Pipe]),
1980 template = text_trim_suffix_string
1981)]
1982#[example(
1983 name = "strip suffix",
1984 code = r###"
1985 # A present suffix falls away; absence returns the input unchanged.
1986 IMPORT [STD]
1987 LET $bare: STRING = TEXT_TRIM_SUFFIX("archive.tar.gz", ".gz")
1988 ASSERT_EQ $bare "archive.tar"
1989
1990 # Missing suffixes pass through untouched.
1991 LET $same: STRING = TEXT_TRIM_SUFFIX("archive.tar", ".gz")
1992 ASSERT_EQ $same "archive.tar"
1993 "###
1994)]
1995#[example(
1996 name = "strip suffix pipe mirrors",
1997 code = r###"
1998 # Pipe input mints pipe output with the same strip.
1999 IMPORT [STD]
2000 LET $cap: PIPE
2001 WITH_IO [stdout=$cap] {
2002 ECHO "archive.tar.gz"
2003 }
2004 LET $trimmed: PIPE = TEXT_TRIM($cap)
2005 LET $out: PIPE = TEXT_TRIM_SUFFIX($trimmed, ".gz")
2006 WITH_IO [stdin=$out] READ_LINE $line
2007 ASSERT_EQ $line "archive.tar"
2008 "###
2009)]
2010#[example(
2011 name = "strip suffix template",
2012 code = r###"
2013 # String inputs run inside placeholders too.
2014 IMPORT [STD]
2015 LET $msg: STRING = 'bare:{{ STD::TEXT_TRIM_SUFFIX("archive.tar.gz", ".gz") }}'
2016 ASSERT_EQ $msg "bare:archive.tar"
2017 "###
2018)]
2019fn text_trim_suffix<P: ProcessManager>(
2020 cx: &mut StepCtx<P>,
2021 #[union(String, Pipe)]
2023 text: Value,
2024 suffix: String,
2026) -> Result<Value> {
2027 super::args::mirror_stream(
2028 cx,
2029 "TEXT_TRIM_SUFFIX",
2030 &text,
2031 super::args::TextPump::TrimSuffix(suffix),
2032 )
2033}
2034
2035fn text_trim_suffix_string(text: Value, suffix: String) -> Result<Value> {
2038 super::args::mirror_string(
2039 "TEXT_TRIM_SUFFIX",
2040 &text,
2041 super::args::TextPump::TrimSuffix(suffix),
2042 )
2043}
2044
2045#[oxdock_func(
2052 rpn,
2053 returns = TypeTag::union(vec![TypeTag::String, TypeTag::Pipe]),
2054 template = text_to_upper_string
2055)]
2056#[example(
2057 name = "uppercase",
2058 code = r###"
2059 # Text folds to uppercase.
2060 IMPORT [STD]
2061 LET $loud: STRING = TEXT_TO_UPPER("hello")
2062 ASSERT_EQ $loud "HELLO"
2063 "###
2064)]
2065#[example(
2066 name = "uppercase pipe mirrors",
2067 code = r###"
2068 # Pipe input mints pipe output with the same fold.
2069 IMPORT [STD]
2070 LET $cap: PIPE
2071 WITH_IO [stdout=$cap] {
2072 ECHO "hello"
2073 }
2074 LET $out: PIPE = TEXT_TO_UPPER($cap)
2075 WITH_IO [stdin=$out] READ_LINE $line
2076 ASSERT_EQ $line "HELLO"
2077 "###
2078)]
2079#[example(
2080 name = "uppercase template",
2081 code = r###"
2082 # String inputs run inside placeholders too.
2083 IMPORT [STD]
2084 LET $msg: STRING = 'loud:{{ STD::TEXT_TO_UPPER("hello") }}'
2085 ASSERT_EQ $msg "loud:HELLO"
2086 "###
2087)]
2088fn text_to_upper<P: ProcessManager>(
2089 cx: &mut StepCtx<P>,
2090 #[union(String, Pipe)]
2092 text: Value,
2093) -> Result<Value> {
2094 super::args::mirror_stream(cx, "TEXT_TO_UPPER", &text, super::args::TextPump::ToUpper)
2095}
2096
2097fn text_to_upper_string(text: Value) -> Result<Value> {
2100 super::args::mirror_string("TEXT_TO_UPPER", &text, super::args::TextPump::ToUpper)
2101}
2102
2103#[oxdock_func(
2110 rpn,
2111 returns = TypeTag::union(vec![TypeTag::String, TypeTag::Pipe]),
2112 template = text_to_lower_string
2113)]
2114#[example(
2115 name = "lowercase",
2116 code = r###"
2117 # Text folds to lowercase.
2118 IMPORT [STD]
2119 LET $quiet: STRING = TEXT_TO_LOWER("HELLO")
2120 ASSERT_EQ $quiet "hello"
2121 "###
2122)]
2123#[example(
2124 name = "lowercase pipe mirrors",
2125 code = r###"
2126 # Pipe input mints pipe output with the same fold.
2127 IMPORT [STD]
2128 LET $cap: PIPE
2129 WITH_IO [stdout=$cap] {
2130 ECHO "HELLO"
2131 }
2132 LET $out: PIPE = TEXT_TO_LOWER($cap)
2133 WITH_IO [stdin=$out] READ_LINE $line
2134 ASSERT_EQ $line "hello"
2135 "###
2136)]
2137#[example(
2138 name = "lowercase template",
2139 code = r###"
2140 # String inputs run inside placeholders too.
2141 IMPORT [STD]
2142 LET $msg: STRING = 'quiet:{{ STD::TEXT_TO_LOWER("HELLO") }}'
2143 ASSERT_EQ $msg "quiet:hello"
2144 "###
2145)]
2146fn text_to_lower<P: ProcessManager>(
2147 cx: &mut StepCtx<P>,
2148 #[union(String, Pipe)]
2150 text: Value,
2151) -> Result<Value> {
2152 super::args::mirror_stream(cx, "TEXT_TO_LOWER", &text, super::args::TextPump::ToLower)
2153}
2154
2155fn text_to_lower_string(text: Value) -> Result<Value> {
2158 super::args::mirror_string("TEXT_TO_LOWER", &text, super::args::TextPump::ToLower)
2159}
2160
2161#[oxdock_func(
2172 rpn,
2173 returns = TypeTag::union(vec![TypeTag::String, TypeTag::Pipe]),
2174 template = text_replace_string
2175)]
2176#[example(
2177 name = "replace",
2178 code = r###"
2179 # Every literal occurrence rewrites in place.
2180 IMPORT [STD]
2181 LET $fixed: STRING = TEXT_REPLACE("hello world", "world", "there")
2182 ASSERT_EQ $fixed "hello there"
2183 "###
2184)]
2185#[example(
2186 name = "replace pipe mirrors",
2187 code = r###"
2188 # Pipe input mints pipe output with the same rewrite.
2189 IMPORT [STD]
2190 LET $cap: PIPE
2191 WITH_IO [stdout=$cap] {
2192 ECHO "hello world"
2193 }
2194 LET $trimmed: PIPE = TEXT_TRIM($cap)
2195 LET $out: PIPE = TEXT_REPLACE($trimmed, "world", "there")
2196 WITH_IO [stdin=$out] READ_LINE $line
2197 ASSERT_EQ $line "hello there"
2198 "###
2199)]
2200#[example(
2201 name = "replace template",
2202 code = r###"
2203 # String inputs run inside placeholders too.
2204 IMPORT [STD]
2205 LET $msg: STRING = 'fixed:{{ STD::TEXT_REPLACE("hello world", "world", "there") }}'
2206 ASSERT_EQ $msg "fixed:hello there"
2207 "###
2208)]
2209fn text_replace<P: ProcessManager>(
2210 cx: &mut StepCtx<P>,
2211 #[union(String, Pipe)]
2213 text: Value,
2214 from: String,
2216 to: String,
2218) -> Result<Value> {
2219 super::args::mirror_stream(
2220 cx,
2221 "TEXT_REPLACE",
2222 &text,
2223 super::args::TextPump::ReplaceLiteral { from, to },
2224 )
2225}
2226
2227fn text_replace_string(text: Value, from: String, to: String) -> Result<Value> {
2230 super::args::mirror_string(
2231 "TEXT_REPLACE",
2232 &text,
2233 super::args::TextPump::ReplaceLiteral { from, to },
2234 )
2235}
2236
2237#[oxdock_func(
2249 rpn,
2250 returns = TypeTag::union(vec![TypeTag::String, TypeTag::Pipe]),
2251 template = text_replace_regex_string
2252)]
2253#[example(
2254 name = "replace with captures",
2255 code = r###"
2256 # Capture groups expand in the replacement.
2257 IMPORT [STD]
2258 LET $swapped: STRING = TEXT_REPLACE_REGEX("2026-10-13", "(\\d+)-(\\d+)-(\\d+)", "$3/$2/$1")
2259 ASSERT_EQ $swapped "13/10/2026"
2260 "###
2261)]
2262#[example(
2263 name = "replace regex pipe mirrors",
2264 code = r###"
2265 # Pipe input mints pipe output with the same rewrite.
2266 IMPORT [STD]
2267 LET $cap: PIPE
2268 WITH_IO [stdout=$cap] {
2269 ECHO "2026-10-13"
2270 }
2271 LET $trimmed: PIPE = TEXT_TRIM($cap)
2272 LET $out: PIPE = TEXT_REPLACE_REGEX($trimmed, "(\\d+)-(\\d+)-(\\d+)", "$3/$2/$1")
2273 WITH_IO [stdin=$out] READ_LINE $line
2274 ASSERT_EQ $line "13/10/2026"
2275 "###
2276)]
2277#[example(
2278 name = "replace regex template",
2279 code = r###"
2280 # String inputs run inside placeholders too.
2281 IMPORT [STD]
2282 LET $msg: STRING = 'swapped:{{ STD::TEXT_REPLACE_REGEX("2026-10-13", "(\\d+)-(\\d+)-(\\d+)", "$3/$2/$1") }}'
2283 ASSERT_EQ $msg "swapped:13/10/2026"
2284 "###
2285)]
2286fn text_replace_regex<P: ProcessManager>(
2287 cx: &mut StepCtx<P>,
2288 #[union(String, Pipe)]
2290 text: Value,
2291 pattern: String,
2293 replacement: String,
2295) -> Result<Value> {
2296 if let Some(s) = text.as_str() {
2297 let out =
2298 super::args::text_replace_regex_str(s, &pattern, &replacement, "TEXT_REPLACE_REGEX")?;
2299 return Ok(Value::string(out));
2300 }
2301 let content = super::args::read_pipe_eager(cx, "TEXT_REPLACE_REGEX", &text)?;
2302 let out = super::args::text_replace_regex_str(
2303 &content,
2304 &pattern,
2305 &replacement,
2306 "TEXT_REPLACE_REGEX",
2307 )?;
2308 super::args::write_completed_pipe(cx, "TEXT_REPLACE_REGEX", out)
2309}
2310
2311fn text_replace_regex_string(text: Value, pattern: String, replacement: String) -> Result<Value> {
2314 let Some(s) = text.as_str() else {
2315 return Err(super::args::pipe_needs_step_io("TEXT_REPLACE_REGEX"));
2316 };
2317 let out = super::args::text_replace_regex_str(s, &pattern, &replacement, "TEXT_REPLACE_REGEX")?;
2318 Ok(Value::string(out))
2319}
2320
2321#[oxdock_func(pure, returns = TypeTag::ListOf(std::sync::Arc::new(TypeTag::String)))]
2329#[example(
2330 name = "split",
2331 code = r###"
2332 # Delimiters split into list items.
2333 IMPORT [STD]
2334 LET $parts: LIST<STRING> = TEXT_SPLIT("a,b,c", ",")
2335 ASSERT_EQ $parts.0 "a"
2336 ASSERT_EQ $parts.1 "b"
2337 ASSERT_EQ $parts.2 "c"
2338 "###
2339)]
2340fn text_split(
2341 text: String,
2343 delimiter: String,
2345) -> Result<Value> {
2346 Ok(super::args::text_list_value(super::args::text_split_str(
2347 &text, &delimiter,
2348 )))
2349}
2350
2351#[oxdock_func(pure, returns = TypeTag::String)]
2354#[example(
2355 name = "join",
2356 code = r###"
2357 # List items join with the separator between them.
2358 IMPORT [STD]
2359 LET $joined: STRING = TEXT_JOIN(["a", "b", "c"], ",")
2360 ASSERT_EQ $joined "a,b,c"
2361 "###
2362)]
2363fn text_join(
2364 elements: Vec<String>,
2366 delimiter: String,
2368) -> Result<Value> {
2369 Ok(Value::string(elements.join(delimiter.as_str())))
2370}
2371
2372#[oxdock_func(pure, returns = TypeTag::ListOf(std::sync::Arc::new(TypeTag::String)))]
2380#[example(
2381 name = "lines",
2382 code = r###"
2383 # Newlines split into line items.
2384 IMPORT [STD]
2385 LET $lines: LIST<STRING> = TEXT_LINES("one\ntwo\nthree")
2386 ASSERT_EQ $lines.0 "one"
2387 ASSERT_EQ $lines.1 "two"
2388 ASSERT_EQ $lines.2 "three"
2389
2390 # Windows endings split the same way after normalization.
2391 LET $crlf: LIST<STRING> = TEXT_LINES("one\r\ntwo\r\nthree")
2392 ASSERT_EQ $crlf.0 "one"
2393 ASSERT_EQ $crlf.1 "two"
2394 ASSERT_EQ $crlf.2 "three"
2395
2396 # Old Mac endings split too, and mixed endings split together because the input normalizes to LF before splitting.
2397 LET $mixed: LIST<STRING> = TEXT_LINES("a\r\nb\nc\rd")
2398 ASSERT_EQ $mixed.0 "a"
2399 ASSERT_EQ $mixed.1 "b"
2400 ASSERT_EQ $mixed.2 "c"
2401 ASSERT_EQ $mixed.3 "d"
2402 "###
2403)]
2404fn text_lines(
2405 text: String,
2407) -> Result<Value> {
2408 Ok(super::args::text_list_value(super::args::text_lines_str(
2409 &text,
2410 )))
2411}
2412
2413#[oxdock_func(pure, returns = TypeTag::ListOf(std::sync::Arc::new(TypeTag::String)))]
2419#[example(
2420 name = "fields",
2421 code = r###"
2422 # Runs of whitespace separate fields; empties never appear.
2423 IMPORT [STD]
2424 LET $fields: LIST<STRING> = TEXT_FIELDS(" abc def ")
2425 ASSERT_EQ $fields.0 "abc"
2426 ASSERT_EQ $fields.1 "def"
2427 "###
2428)]
2429fn text_fields(
2430 text: String,
2432) -> Result<Value> {
2433 Ok(super::args::text_list_value(super::args::text_fields_str(
2434 &text,
2435 )))
2436}
2437
2438#[oxdock_func(pure, returns = TypeTag::ListOf(std::sync::Arc::new(TypeTag::String)))]
2447#[example(
2448 name = "line range",
2449 code = r###"
2450 # Lines 2 through 3 come back as a list, 1-based inclusive.
2451 IMPORT [STD]
2452 LET $window: LIST<STRING> = TEXT_LINES_RANGE("one\ntwo\nthree\nfour", 2, 3)
2453 ASSERT_EQ $window.0 "two"
2454 ASSERT_EQ $window.1 "three"
2455
2456 # Ranges past the end clamp instead of failing.
2457 LET $tail: LIST<STRING> = TEXT_LINES_RANGE("one\ntwo", 2, 9)
2458 ASSERT_EQ $tail.0 "two"
2459 "###
2460)]
2461fn text_lines_range(
2462 text: String,
2464 from: i64,
2466 to: i64,
2468) -> Result<Value> {
2469 Ok(super::args::text_list_value(
2470 super::args::text_lines_range_str(&text, from, to, "TEXT_LINES_RANGE")?,
2471 ))
2472}
2473
2474#[oxdock_func(pure, returns = TypeTag::Bool)]
2482#[example(
2483 name = "match",
2484 code = r###"
2485 # Regex matches report true; misses report false.
2486 IMPORT [STD]
2487 LET $hit: BOOL = TEXT_MATCH("abc123", "\\d+")
2488 ASSERT_EQ $hit true
2489
2490 # A miss is false, not a failure.
2491 LET $miss: BOOL = TEXT_MATCH("abc", "^\\d+$")
2492 ASSERT_EQ $miss false
2493 "###
2494)]
2495fn text_match(
2496 text: String,
2498 pattern: String,
2500) -> Result<Value> {
2501 let re = super::args::text_compile_pattern("TEXT_MATCH", &pattern)?;
2502 Ok(Value::bool(re.is_match(&text)))
2503}
2504
2505#[oxdock_func(pure, returns = TypeTag::ListOf(std::sync::Arc::new(TypeTag::String)))]
2514#[example(
2515 name = "extract",
2516 code = r###"
2517 # Index zero is the full match; groups follow in order.
2518 IMPORT [STD]
2519 LET $caps: LIST<STRING> = TEXT_EXTRACT("abc123", "([a-z]+)(\\d+)")
2520 ASSERT_EQ $caps.0 "abc123"
2521 ASSERT_EQ $caps.1 "abc"
2522 ASSERT_EQ $caps.2 "123"
2523 "###
2524)]
2525fn text_extract(
2526 text: String,
2528 pattern: String,
2530) -> Result<Value> {
2531 let groups = super::args::text_extract_str(&text, &pattern, "TEXT_EXTRACT")?;
2532 Ok(super::args::text_list_value(groups))
2533}
2534
2535#[oxdock_func(pure, returns = TypeTag::Bool)]
2542#[example(
2543 name = "starts with",
2544 code = r###"
2545 # Present prefixes report true; misses report false.
2546 IMPORT [STD]
2547 LET $hit: BOOL = TEXT_STARTS_WITH("linux-musl-x64", "linux")
2548 ASSERT_EQ $hit true
2549
2550 # A miss is false, not a failure.
2551 LET $miss: BOOL = TEXT_STARTS_WITH("macos-arm", "linux")
2552 ASSERT_EQ $miss false
2553 "###
2554)]
2555fn text_starts_with(
2556 text: String,
2558 prefix: String,
2560) -> Result<Value> {
2561 Ok(Value::bool(text.starts_with(prefix.as_str())))
2562}
2563
2564#[oxdock_func(pure, returns = TypeTag::Bool)]
2571#[example(
2572 name = "ends with",
2573 code = r###"
2574 # Present suffixes report true; misses report false.
2575 IMPORT [STD]
2576 LET $hit: BOOL = TEXT_ENDS_WITH("x86_64-linux-musl", "linux-musl")
2577 ASSERT_EQ $hit true
2578
2579 # A miss is false, not a failure.
2580 LET $miss: BOOL = TEXT_ENDS_WITH("x86_64-linux-gnu", "linux-musl")
2581 ASSERT_EQ $miss false
2582 "###
2583)]
2584fn text_ends_with(
2585 text: String,
2587 suffix: String,
2589) -> Result<Value> {
2590 Ok(Value::bool(text.ends_with(suffix.as_str())))
2591}
2592
2593#[oxdock_func(pure, returns = TypeTag::Bool)]
2600#[example(
2601 name = "contains",
2602 code = r###"
2603 # Present needles report true; misses report false.
2604 IMPORT [STD]
2605 LET $hit: BOOL = TEXT_CONTAINS("x86_64-linux-musl", "musl")
2606 ASSERT_EQ $hit true
2607
2608 # A miss is false, not a failure.
2609 LET $miss: BOOL = TEXT_CONTAINS("x86_64-linux-gnu", "musl")
2610 ASSERT_EQ $miss false
2611 "###
2612)]
2613fn text_contains(
2614 text: String,
2616 needle: String,
2618) -> Result<Value> {
2619 Ok(Value::bool(text.contains(needle.as_str())))
2620}
2621
2622#[oxdock_func(pure, returns = TypeTag::Int)]
2629#[example(
2630 name = "length",
2631 code = r###"
2632 # Plain text counts one per character.
2633 IMPORT [STD]
2634 LET $n: INT = TEXT_LENGTH("hello")
2635 ASSERT_EQ $n 5
2636
2637 # Multibyte characters count once each, not per byte.
2638 LET $wide: INT = TEXT_LENGTH("héllo")
2639 ASSERT_EQ $wide 5
2640 "###
2641)]
2642fn text_length(
2643 text: String,
2645) -> Result<Value> {
2646 Ok(Value::int(text.chars().count() as i64))
2647}
2648
2649#[oxdock_func(pure, returns = TypeTag::Int)]
2657#[example(
2658 name = "count",
2659 code = r###"
2660 # Every non-overlapping occurrence counts once.
2661 IMPORT [STD]
2662 LET $n: INT = TEXT_COUNT("hello world", "o")
2663 ASSERT_EQ $n 2
2664
2665 # Overlapping candidates never double count.
2666 LET $once: INT = TEXT_COUNT("aaa", "aa")
2667 ASSERT_EQ $once 1
2668 "###
2669)]
2670fn text_count(
2671 text: String,
2673 needle: String,
2675) -> Result<Value> {
2676 let n = super::args::text_count_str(&text, &needle, "TEXT_COUNT")?;
2677 Ok(Value::int(n))
2678}
2679
2680#[oxdock_func(pure, returns = TypeTag::Int)]
2690#[example(
2691 name = "count matches",
2692 code = r###"
2693 # One line matches once no matter how many times it hits.
2694 IMPORT [STD]
2695 LET $n: INT = TEXT_COUNT_MATCHES("test a: test\ntest b: nope\ntest c: test", ": test")
2696 ASSERT_EQ $n 2
2697
2698 # A miss binds zero, never an error.
2699 LET $none: INT = TEXT_COUNT_MATCHES("test b: nope", ": test$")
2700 ASSERT_EQ $none 0
2701 "###
2702)]
2703fn text_count_matches(
2704 text: String,
2706 pattern: String,
2708) -> Result<Value> {
2709 let n = super::args::text_count_matches_str(&text, &pattern, "TEXT_COUNT_MATCHES")?;
2710 Ok(Value::int(n))
2711}
2712
2713#[oxdock_func(pure, returns = TypeTag::ListOf(std::sync::Arc::new(TypeTag::String)))]
2726#[example(
2727 name = "grep",
2728 code = r###"
2729 # Matching lines come back as a list, in order.
2730 IMPORT [STD]
2731 LET $hits: LIST<STRING> = TEXT_GREP("one\ntwo\none more", "^one")
2732 ASSERT_EQ $hits.0 "one"
2733 ASSERT_EQ $hits.1 "one more"
2734
2735 # A miss binds an empty list, never an error.
2736 LET $miss: LIST<STRING> = TEXT_GREP("one\ntwo", "^z")
2737 LET $joined: STRING = TEXT_JOIN($miss, ",")
2738 ASSERT_EQ $joined ""
2739
2740 # The (?i) flag ignores case, so uppercase lines match too.
2741 LET $folded: LIST<STRING> = TEXT_GREP("One\ntwo\nONE more", "(?i)^one")
2742 ASSERT_EQ $folded.0 "One"
2743 ASSERT_EQ $folded.1 "ONE more"
2744 "###
2745)]
2746#[example(
2747 name = "grep invert",
2748 code = r###"
2749 # The invert option keeps every non-matching line instead.
2750 IMPORT [STD]
2751 LET $kept: LIST<STRING> = TEXT_GREP("one\ntwo\none more", "^one", {invert: true})
2752 ASSERT_EQ $kept.0 "two"
2753
2754 # A pattern matching every line binds an empty list, never an error.
2755 LET $none: LIST<STRING> = TEXT_GREP("one\ntwo", "^", {invert: true})
2756 LET $joined: STRING = TEXT_JOIN($none, ",")
2757 ASSERT_EQ $joined ""
2758
2759 # Options ride into placeholders as MAP literals. Placeholder
2760 # strings unescape only backslash and quote, so multiline text
2761 # arrives through a variable.
2762 LET $two_lines: STRING = "one\ntwo"
2763 LET $msg: STRING = 'kept:{{ STD::TEXT_GREP($two_lines, "^one", {invert: true}) }}'
2764 ASSERT_EQ $msg "kept:two"
2765 "###
2766)]
2767fn text_grep(
2768 text: String,
2770 pattern: String,
2772 #[options("invert?: BOOL")]
2774 #[optional]
2775 options: BTreeMap<String, Value>,
2776) -> Result<Value> {
2777 let invert = super::args::text_invert_flag(&options);
2780 Ok(super::args::text_list_value(super::args::text_grep_str(
2781 &text,
2782 &pattern,
2783 invert,
2784 "TEXT_GREP",
2785 )?))
2786}
2787
2788#[oxdock_func(returns = TypeTag::Bool)]
2799#[example(
2800 name = "drain to end",
2801 code = r###"
2802 # Capture two lines, then drain to end of stream with no sentinel line.
2803 IMPORT [STD]
2804 LET $cap: PIPE
2805 WITH_IO [stdout=$cap] {
2806 ECHO "one"
2807 ECHO "two"
2808 }
2809
2810 # The loop exits on close, and the count proves both lines drained.
2811 LET $n: INT = 0
2812 WHILE !EOF($cap) {
2813 WITH_IO [stdin=$cap] READ_LINE $line
2814 $n = $n + 1
2815 }
2816 ASSERT_EQ $n 2
2817 "###
2818)]
2819fn eof<P: ProcessManager>(
2820 cx: &mut StepCtx<P>,
2821 pipe: PipeHandle,
2823) -> Result<Value> {
2824 let info = cx.state.io.inspect_pipe(&pipe);
2825 Ok(Value::bool(info.closed && info.buffered == 0))
2826}
2827
2828fn meta_to_value(meta: &FuncMeta) -> Value {
2829 let mut map = BTreeMap::new();
2830 map.insert("name".to_string(), Value::string(meta.name.clone()));
2831 map.insert("module".to_string(), Value::string(meta.module.clone()));
2832 map.insert(
2833 "kind".to_string(),
2834 Value::string(meta.kind.label().to_string()),
2835 );
2836 let params = match &meta.params {
2837 Some(params) => Value::list(
2838 params
2839 .iter()
2840 .map(|p| {
2841 let mut entry = BTreeMap::new();
2842 entry.insert("name".to_string(), Value::string(p.name.clone()));
2843 entry.insert(
2844 "param_type".to_string(),
2845 Value::string(
2846 p.param_type
2847 .as_ref()
2848 .map(render_structural)
2849 .unwrap_or_default(),
2850 ),
2851 );
2852 entry.insert(
2853 "allowed".to_string(),
2854 Value::string(
2855 p.allowed
2856 .map(|values| values.join(", "))
2857 .unwrap_or_default(),
2858 ),
2859 );
2860 entry.insert("docs".to_string(), Value::string(String::new()));
2861 entry.insert("optional".to_string(), Value::bool(p.optional));
2862 entry.insert(
2863 "options".to_string(),
2864 match p.options {
2865 Some(keys) => Value::list(
2866 keys.iter()
2867 .map(|key| {
2868 let mut option = BTreeMap::new();
2869 option.insert(
2870 "name".to_string(),
2871 Value::string(key.name.to_string()),
2872 );
2873 option.insert(
2874 "value_type".to_string(),
2875 Value::string(render_structural(&key.value)),
2876 );
2877 option.insert(
2878 "required".to_string(),
2879 Value::bool(key.required),
2880 );
2881 option.insert(
2882 "default".to_string(),
2883 Value::string(
2884 key.default.unwrap_or_default().to_string(),
2885 ),
2886 );
2887 Value::map(option)
2888 })
2889 .collect(),
2890 ),
2891 None => Value::string(String::new()),
2892 },
2893 );
2894 Value::map(entry)
2895 })
2896 .collect(),
2897 ),
2898 None => Value::list(Vec::new()),
2902 };
2903 map.insert("params".to_string(), params);
2904 map.insert(
2905 "returns".to_string(),
2906 Value::string(
2907 meta.returns
2908 .as_ref()
2909 .map(render_structural)
2910 .unwrap_or_default(),
2911 ),
2912 );
2913 map.insert("rpn".to_string(), Value::bool(meta.rpn));
2914 map.insert(
2915 "summary".to_string(),
2916 Value::string(meta.summary.to_string()),
2917 );
2918 Value::map(map)
2919}
2920
2921#[derive(Debug, Clone)]
2925pub struct RecordSchema {
2926 pub name: &'static str,
2927 pub fields: std::sync::Arc<[Field]>,
2928}
2929
2930#[derive(Clone)]
2934pub struct HostModule<P: ProcessManager> {
2935 pub name: String,
2936 pub funcs: Vec<HostRegistration<P>>,
2937 pub types: Vec<&'static TypeDescriptor>,
2938 pub record_schemas: Vec<RecordSchema>,
2939 pub states: Vec<ModuleState>,
2946}
2947
2948#[derive(Clone)]
2952pub struct ModuleState {
2953 id: std::any::TypeId,
2954 state: std::sync::Arc<dyn std::any::Any + Send + Sync>,
2955}
2956
2957pub type PreRunInspector = dyn Fn(&[Step]) -> Result<()> + Send + Sync;
2961
2962#[derive(Clone)]
2968pub struct PreRunCheck {
2969 check: Arc<PreRunInspector>,
2970}
2971
2972impl PreRunCheck {
2973 pub fn new(check: impl Fn(&[Step]) -> Result<()> + Send + Sync + 'static) -> Self {
2975 Self {
2976 check: Arc::new(check),
2977 }
2978 }
2979
2980 pub fn run(&self, steps: &[Step]) -> Result<()> {
2982 (self.check)(steps)
2983 }
2984}
2985
2986impl<P: ProcessManager> HostModule<P> {
2987 pub fn with_state<T: Send + Sync + 'static>(mut self, state: std::sync::Arc<T>) -> Self {
2990 self.states.push(ModuleState {
2991 id: std::any::TypeId::of::<T>(),
2992 state,
2993 });
2994 self
2995 }
2996
2997 pub fn check_pre_run(&self, steps: &[Step]) -> Result<()> {
3001 for state in &self.states {
3002 if let Some(check) = state.state.downcast_ref::<PreRunCheck>() {
3003 check.run(steps)?;
3004 }
3005 }
3006 Ok(())
3007 }
3008}
3009
3010impl<P: ProcessManager> ExecState<P> {
3011 pub fn register_module(&mut self, module: HostModule<P>) {
3014 for registration in module.funcs {
3015 match registration {
3016 HostRegistration::Stateful { name, meta, func } => {
3017 self.functions.register_host(&module.name, name, meta, func);
3018 }
3019 HostRegistration::Pure { name, meta, func } => {
3020 self.functions
3021 .register_pure_host(&module.name, name, meta, func);
3022 }
3023 HostRegistration::Both {
3024 name,
3025 meta,
3026 func,
3027 template,
3028 } => {
3029 self.functions
3030 .register_both_host(&module.name, name, meta, func, template);
3031 }
3032 }
3033 }
3034 for descriptor in module.types {
3035 self.register_type(descriptor);
3036 }
3037 for schema in module.record_schemas {
3038 self.register_record_schema(schema.name, schema.fields);
3039 }
3040 for state in module.states {
3041 self.module_states
3042 .insert((module.name.clone(), state.id), state.state);
3043 }
3044 }
3045
3046 pub fn list_functions(&self) -> Vec<FuncMeta> {
3048 let mut out: Vec<FuncMeta> = self.functions.entries_metas().into_iter().collect();
3049 if !out.iter().any(|m| m.name == KEYWORD_INSPECT) {
3051 out.push(FuncMeta {
3052 name: KEYWORD_INSPECT.to_string(),
3053 module: STD_MODULE_NAME.to_string(),
3054 kind: FuncKind::HostCtx,
3055 params: None,
3056 returns: Some(TypeTag::Map),
3057 rpn: false,
3058 summary: "Inspect a variable binding.",
3059 docs: "INSPECT($var): dedicated AST node taking a variable, not a value.",
3060 examples: &[],
3061 });
3062 }
3063 out.sort_by(|a, b| a.name.cmp(&b.name));
3064 out
3065 }
3066
3067 pub fn describe_function(&self, name: &str) -> Option<Value> {
3069 if let Some(meta) = self.functions.meta(name) {
3070 return Some(meta_to_value(&meta));
3071 }
3072 if name == KEYWORD_INSPECT {
3074 return Some(meta_to_value(&FuncMeta {
3075 name: KEYWORD_INSPECT.to_string(),
3076 module: STD_MODULE_NAME.to_string(),
3077 kind: FuncKind::HostCtx,
3078 params: None,
3079 returns: Some(TypeTag::Map),
3080 rpn: false,
3081 summary: "Inspect a variable binding.",
3082 docs: "INSPECT($var): dedicated AST node taking a variable, not a value.",
3083 examples: &[],
3084 }));
3085 }
3086 None
3087 }
3088
3089 pub(super) fn clone_native_pure(&self, name: &str) -> Option<PureFn> {
3090 self.functions.clone_pure_fn(name)
3091 }
3092
3093 pub fn pure_function_table(&self) -> Arc<PureTable> {
3098 self.functions.pure_shared()
3099 }
3100
3101 pub(super) fn clone_native_ctx(&self, name: &str) -> Option<NativeFn<P>> {
3102 self.functions.clone_ctx_fn(name)
3103 }
3104
3105 pub(super) fn native_meta(&self, name: &str) -> Option<FuncMeta> {
3106 self.functions.meta(name)
3107 }
3108}
3109
3110#[cfg(test)]
3111mod tests {
3112 use super::*;
3113
3114 #[test]
3115 fn describe_entry_renders_union_spellings() {
3116 let union = oxdock_parser::union_tag!(String, Pipe);
3122 let meta = FuncMeta {
3123 name: "T::F".to_string(),
3124 module: "T".to_string(),
3125 kind: FuncKind::HostPure,
3126 params: Some(vec![FuncParam {
3127 name: "text".to_string(),
3128 param_type: Some(union.clone()),
3129 allowed: None,
3130 docs: "",
3131 options: None,
3132 optional: false,
3133 }]),
3134 returns: Some(union),
3135 rpn: false,
3136 summary: "test-only",
3137 docs: "test-only",
3138 examples: &[],
3139 };
3140 let value = meta_to_value(&meta);
3141 let map = value.as_map().expect("describe value is a map");
3142 let params = map
3143 .get("params")
3144 .expect("params key")
3145 .as_list()
3146 .expect("params is a list");
3147 let first = params[0].as_map().expect("entry is a map");
3148 assert_eq!(
3149 first.get("param_type").and_then(Value::as_str),
3150 Some("STRING|PIPE"),
3151 "param renders the set"
3152 );
3153 assert_eq!(
3154 map.get("returns").and_then(Value::as_str),
3155 Some("STRING|PIPE"),
3156 "returns render the set"
3157 );
3158 }
3159
3160 #[test]
3161 fn describe_entry_carries_optional_flag() {
3162 let meta = FuncMeta {
3166 name: "T::F".to_string(),
3167 module: "T".to_string(),
3168 kind: FuncKind::HostPure,
3169 params: Some(vec![
3170 FuncParam {
3171 name: "url".to_string(),
3172 param_type: Some(TypeTag::String),
3173 allowed: None,
3174 docs: "",
3175 options: None,
3176 optional: false,
3177 },
3178 FuncParam {
3179 name: "options".to_string(),
3180 param_type: Some(TypeTag::Map),
3181 allowed: None,
3182 docs: "",
3183 options: None,
3184 optional: true,
3185 },
3186 ]),
3187 returns: Some(TypeTag::String),
3188 rpn: false,
3189 summary: "test-only",
3190 docs: "test-only",
3191 examples: &[],
3192 };
3193 let value = meta_to_value(&meta);
3194 let map = value.as_map().expect("describe value is a map");
3195 let params = map
3196 .get("params")
3197 .expect("params key")
3198 .as_list()
3199 .expect("params is a list");
3200 assert_eq!(params.len(), 2);
3201 let first = params[0].as_map().expect("entry is a map");
3202 let second = params[1].as_map().expect("entry is a map");
3203 assert_eq!(
3204 first.get("optional").and_then(Value::as_bool),
3205 Some(false),
3206 "required param must read false"
3207 );
3208 assert_eq!(
3209 second.get("optional").and_then(Value::as_bool),
3210 Some(true),
3211 "omittable param must read true"
3212 );
3213 }
3214
3215 #[test]
3216 fn template_twins_mirror_string_paths_and_refuse_pipes() {
3217 let pipe = Value::pipe_fresh();
3223 type TwinCase = (&'static str, Box<dyn Fn() -> Result<Value>>);
3224 let cases: Vec<TwinCase> = vec![
3225 (
3226 "TEXT_TRIM",
3227 Box::new(|| text_trim_string(Value::string(" hello ".to_string()))),
3228 ),
3229 (
3230 "TEXT_TRIM_PREFIX",
3231 Box::new(|| {
3232 text_trim_prefix_string(Value::string("v1".to_string()), "v".to_string())
3233 }),
3234 ),
3235 (
3236 "TEXT_TRIM_SUFFIX",
3237 Box::new(|| {
3238 text_trim_suffix_string(Value::string("a.gz".to_string()), "x".to_string())
3239 }),
3240 ),
3241 (
3242 "TEXT_TO_UPPER",
3243 Box::new(|| text_to_upper_string(Value::string("hi".to_string()))),
3244 ),
3245 (
3246 "TEXT_TO_LOWER",
3247 Box::new(|| text_to_lower_string(Value::string("HI".to_string()))),
3248 ),
3249 (
3250 "TEXT_REPLACE",
3251 Box::new(|| {
3252 text_replace_string(
3253 Value::string("ab".to_string()),
3254 "b".to_string(),
3255 "c".to_string(),
3256 )
3257 }),
3258 ),
3259 (
3260 "TEXT_REPLACE_REGEX",
3261 Box::new(|| {
3262 text_replace_regex_string(
3263 Value::string("ab".to_string()),
3264 "b".to_string(),
3265 "c".to_string(),
3266 )
3267 }),
3268 ),
3269 ];
3270 assert_eq!(cases.len(), 7, "every mirror op needs a twin row");
3271 for (name, run) in &cases {
3272 let value = run().unwrap_or_else(|e| panic!("{name} twin must answer strings: {e:#}"));
3273 assert!(
3274 value.as_str().is_some(),
3275 "{name} twin must answer STRING, got {}",
3276 value.type_name()
3277 );
3278 }
3279 assert_eq!(
3280 text_trim_string(Value::string(" hello ".to_string()))
3281 .expect("trim twin")
3282 .as_str(),
3283 Some("hello")
3284 );
3285 let pipe_cases: Vec<(&str, Result<Value>)> = vec![
3287 ("TEXT_TRIM", text_trim_string(pipe.clone())),
3288 (
3289 "TEXT_TRIM_PREFIX",
3290 text_trim_prefix_string(pipe.clone(), "v".to_string()),
3291 ),
3292 (
3293 "TEXT_TRIM_SUFFIX",
3294 text_trim_suffix_string(pipe.clone(), ".gz".to_string()),
3295 ),
3296 ("TEXT_TO_UPPER", text_to_upper_string(pipe.clone())),
3297 ("TEXT_TO_LOWER", text_to_lower_string(pipe.clone())),
3298 (
3299 "TEXT_REPLACE",
3300 text_replace_string(pipe.clone(), "a".to_string(), "b".to_string()),
3301 ),
3302 (
3303 "TEXT_REPLACE_REGEX",
3304 text_replace_regex_string(pipe.clone(), "a".to_string(), "b".to_string()),
3305 ),
3306 ];
3307 for (name, result) in pipe_cases {
3308 let err = result.expect_err(&format!("{name} twin must refuse PIPE"));
3309 assert!(
3310 format!("{err:#}").contains("step IO"),
3311 "{name} refusal names the missing context: {err:#}"
3312 );
3313 }
3314 }
3315}