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}
231
232pub(super) enum FuncBody<P: ProcessManager> {
237 Script(FuncDefData),
238 Pure(PureFn),
239 Ctx(NativeFn<P>),
240 Both { pure: PureFn, ctx: NativeFn<P> },
241}
242
243impl<P: ProcessManager> Clone for FuncBody<P> {
245 fn clone(&self) -> Self {
246 match self {
247 FuncBody::Script(def) => FuncBody::Script(def.clone()),
248 FuncBody::Pure(func) => FuncBody::Pure(Arc::clone(func)),
249 FuncBody::Ctx(func) => FuncBody::Ctx(Arc::clone(func)),
250 FuncBody::Both { pure, ctx } => FuncBody::Both {
251 pure: Arc::clone(pure),
252 ctx: Arc::clone(ctx),
253 },
254 }
255 }
256}
257
258pub(super) struct FuncEntry<P: ProcessManager> {
262 pub(super) meta: FuncMeta,
263 pub(super) body: FuncBody<P>,
264}
265
266impl<P: ProcessManager> Clone for FuncEntry<P> {
268 fn clone(&self) -> Self {
269 Self {
270 meta: self.meta.clone(),
271 body: self.body.clone(),
272 }
273 }
274}
275
276struct ScopeFrame<P: ProcessManager> {
279 defined: HashSet<String>,
280 shadowed: Vec<(String, FuncEntry<P>)>,
281}
282
283impl<P: ProcessManager> Clone for ScopeFrame<P> {
285 fn clone(&self) -> Self {
286 Self {
287 defined: self.defined.clone(),
288 shadowed: self.shadowed.clone(),
289 }
290 }
291}
292
293pub type PureTable = HashMap<String, HashMap<String, PureFn>>;
303
304pub struct FunctionRegistry<P: ProcessManager> {
305 entries: HashMap<String, FuncEntry<P>>,
306 scopes: Vec<ScopeFrame<P>>,
307 pure_shared: Arc<PureTable>,
308 script_docs: HashMap<String, (String, String)>,
312}
313
314impl<P: ProcessManager> FunctionRegistry<P> {
315 pub(super) fn with_builtins() -> Self {
316 let mut reg = Self {
317 entries: HashMap::new(),
318 pure_shared: Arc::new(HashMap::new()),
319 script_docs: HashMap::new(),
320 scopes: vec![ScopeFrame {
321 defined: HashSet::new(),
322 shadowed: Vec::new(),
323 }],
324 };
325 for host in Self::builtin_registrations() {
329 match host {
330 HostRegistration::Stateful { name, meta, func } => {
331 reg.insert_qualified(STD_MODULE_NAME, name, meta, FuncBody::Ctx(func));
332 }
333 HostRegistration::Pure { name, meta, func } => {
334 reg.insert_qualified(STD_MODULE_NAME, name, meta, FuncBody::Pure(func));
335 }
336 HostRegistration::Both {
337 name,
338 meta,
339 func,
340 template,
341 } => {
342 reg.insert_qualified(
343 STD_MODULE_NAME,
344 name,
345 meta,
346 FuncBody::Both {
347 pure: template,
348 ctx: func,
349 },
350 );
351 }
352 }
353 }
354 reg
355 }
356
357 pub(super) fn builtin_registrations() -> Vec<HostRegistration<P>> {
362 vec![
363 Int::registration(),
364 Float::registration(),
365 FormatByteCount::registration(),
366 ParseByteCount::registration(),
367 FormatDuration::registration(),
368 ParseDuration::registration(),
369 Types::registration(),
370 TypeDescribe::registration(),
371 Glob::registration(),
372 LoadToml::registration(),
373 LoadJson::registration(),
374 ParseToml::registration(),
375 ParseJson::registration(),
376 PathType::registration(),
377 PathWritable::registration(),
378 IsExec::registration(),
379 HasKey::registration(),
380 MapSet::registration(),
381 MergeMaps::registration(),
382 Base64Encode::registration(),
383 Base64Decode::registration(),
384 Rand::registration(),
385 ToJson::registration(),
386 TypeOf::registration(),
387 Functions::registration(),
388 Describe::registration(),
389 IsTerminal::registration(),
390 Eof::registration(),
391 TaskPoll::registration(),
392 Version::registration(),
393 TextTrim::registration(),
394 TextTrimPrefix::registration(),
395 TextTrimSuffix::registration(),
396 PathJoin::registration(),
397 TextToUpper::registration(),
398 TextToLower::registration(),
399 TextReplace::registration(),
400 TextReplaceRegex::registration(),
401 TextSplit::registration(),
402 TextJoin::registration(),
403 TextLines::registration(),
404 TextFields::registration(),
405 TextMatch::registration(),
406 TextExtract::registration(),
407 TextStartsWith::registration(),
408 TextEndsWith::registration(),
409 TextContains::registration(),
410 TextLength::registration(),
411 TextCount::registration(),
412 TextCountMatches::registration(),
413 TextGrep::registration(),
414 TextLinesRange::registration(),
415 SemaphoreNew::registration(),
416 SemaphoreTryAcquire::registration(),
417 SemaphoreAvailable::registration(),
418 ShellSplitArgs::registration(),
419 ShellJoinArgs::registration(),
420 ]
421 }
422
423 pub(super) fn keys(&self) -> HashSet<String> {
426 self.entries.keys().cloned().collect()
427 }
428
429 pub(super) fn get(&self, name: &str) -> Option<FuncEntry<P>> {
431 self.entries.get(name).cloned()
432 }
433
434 fn insert_native(&mut self, name: String, meta: FuncMeta, body: FuncBody<P>) {
435 self.entries.insert(name, FuncEntry { meta, body });
436 self.rebuild_pure_shared();
437 }
438
439 fn rebuild_pure_shared(&mut self) {
445 let mut table: PureTable = HashMap::new();
446 for (name, entry) in &self.entries {
447 let func = match &entry.body {
448 FuncBody::Pure(func) => func,
449 FuncBody::Both { pure, .. } => pure,
450 FuncBody::Script(_) | FuncBody::Ctx(_) => continue,
451 };
452 if let Some((module, base)) = split_qualified(name) {
453 table
454 .entry(module.to_string())
455 .or_default()
456 .insert(base.to_string(), Arc::clone(func));
457 }
458 }
459 self.pure_shared = Arc::new(table);
460 }
461
462 fn insert_qualified(
466 &mut self,
467 module: &str,
468 base: String,
469 mut meta: FuncMeta,
470 body: FuncBody<P>,
471 ) {
472 meta.name = qualify(module, &base);
473 meta.module = module.to_string();
474 if self.entries.contains_key(&meta.name) {
479 panic!("duplicate function registration `{}`", meta.name);
480 }
481 self.insert_native(meta.name.clone(), meta, body);
482 }
483
484 pub(super) fn register_host(
485 &mut self,
486 module: &str,
487 name: String,
488 mut meta: FuncMeta,
489 func: NativeFn<P>,
490 ) {
491 meta.kind = FuncKind::HostCtx;
492 self.insert_qualified(module, name, meta, FuncBody::Ctx(func));
493 }
494
495 pub(super) fn register_pure_host(
496 &mut self,
497 module: &str,
498 name: String,
499 mut meta: FuncMeta,
500 func: PureFn,
501 ) {
502 meta.kind = FuncKind::HostPure;
503 self.insert_qualified(module, name, meta, FuncBody::Pure(func));
504 }
505
506 pub(super) fn register_both_host(
507 &mut self,
508 module: &str,
509 name: String,
510 mut meta: FuncMeta,
511 func: NativeFn<P>,
512 template: PureFn,
513 ) {
514 meta.kind = FuncKind::HostCtx;
515 self.insert_qualified(
516 module,
517 name,
518 meta,
519 FuncBody::Both {
520 pure: template,
521 ctx: func,
522 },
523 );
524 }
525
526 pub(super) fn define_script(
531 &mut self,
532 name: &str,
533 params: &[(String, TypeTag)],
534 body: &[Step],
535 ) -> Result<()> {
536 let qualified = qualify(SCRIPT_MODULE_NAME, name);
537 let shadowable = matches!(
538 self.entries.get(&qualified).map(|entry| &entry.body),
539 Some(FuncBody::Script(_))
540 );
541 let reserved = self
544 .entries
545 .keys()
546 .any(|key| split_qualified(key).is_some_and(|(_, base)| base == name));
547 if reserved && !shadowable {
548 anyhow::bail!("cannot shadow reserved function `{name}`");
549 }
550 if self
551 .scopes
552 .last()
553 .is_some_and(|frame| frame.defined.contains(&qualified))
554 {
555 anyhow::bail!("duplicate function `{name}` in same scope");
556 }
557 let old = self.entries.insert(
558 qualified.clone(),
559 FuncEntry {
560 meta: FuncMeta {
561 name: qualified.clone(),
562 module: SCRIPT_MODULE_NAME.to_string(),
563 kind: FuncKind::Script,
564 params: Some(
565 params
566 .iter()
567 .map(|(name, param_type)| FuncParam {
568 name: name.clone(),
569 param_type: Some(param_type.clone()),
570 allowed: None,
571 docs: "",
574 options: None,
575 optional: false,
576 })
577 .collect(),
578 ),
579 returns: None,
580 rpn: false,
581 summary: "DSL-defined function.",
582 docs: "Defined via FUNC in script.",
583 examples: &[],
584 },
585 body: FuncBody::Script(FuncDefData {
586 params: params.to_vec(),
587 body: body.to_vec(),
588 }),
589 },
590 );
591 if let Some(frame) = self.scopes.last_mut() {
592 frame.defined.insert(qualified.clone());
593 if let Some(old) = old {
594 frame.shadowed.push((qualified, old));
595 }
596 }
597 Ok(())
598 }
599
600 pub(super) fn push_scope(&mut self) {
603 self.scopes.push(ScopeFrame {
604 defined: HashSet::new(),
605 shadowed: Vec::new(),
606 });
607 }
608
609 pub(super) fn pop_scope(&mut self) {
612 let Some(frame) = self.scopes.pop() else {
613 return;
614 };
615 for name in frame.defined {
616 self.entries.remove(&name);
617 }
618 for (name, old) in frame.shadowed {
619 self.entries.insert(name, old);
620 }
621 }
622
623 pub(super) fn contains_script(&self, name: &str) -> bool {
627 matches!(
628 self.entries.get(name).map(|entry| &entry.body),
629 Some(FuncBody::Script(_))
630 )
631 }
632
633 fn clone_pure_fn(&self, name: &str) -> Option<PureFn> {
637 match self.entries.get(name)?.body {
638 FuncBody::Pure(ref func) => Some(Arc::clone(func)),
639 FuncBody::Both { ref pure, .. } => Some(Arc::clone(pure)),
640 _ => None,
641 }
642 }
643
644 pub(super) fn pure_shared(&self) -> Arc<PureTable> {
648 Arc::clone(&self.pure_shared)
649 }
650
651 pub(super) fn all_metas(&self) -> Vec<FuncMeta> {
654 self.entries_metas()
655 }
656
657 fn clone_ctx_fn(&self, name: &str) -> Option<NativeFn<P>> {
662 match self.entries.get(name)?.body {
663 FuncBody::Ctx(ref func) => Some(Arc::clone(func)),
664 FuncBody::Both { ref ctx, .. } => Some(Arc::clone(ctx)),
665 _ => None,
666 }
667 }
668
669 fn meta(&self, name: &str) -> Option<FuncMeta> {
670 self.entries.get(name).map(|entry| entry.meta.clone())
671 }
672
673 fn native_metas(&self) -> Vec<FuncMeta> {
674 let mut out: Vec<FuncMeta> = Vec::new();
675 for entry in self.entries.values() {
676 if !matches!(entry.body, FuncBody::Script(_)) {
677 out.push(entry.meta.clone());
678 }
679 }
680 out.sort_by(|a, b| a.name.cmp(&b.name));
681 out
682 }
683
684 fn entries_metas(&self) -> Vec<FuncMeta> {
687 let mut out: Vec<FuncMeta> = self
688 .entries
689 .values()
690 .map(|entry| entry.meta.clone())
691 .collect();
692 out.sort_by(|a, b| a.name.cmp(&b.name));
693 out
694 }
695
696 pub fn set_script_docs(&mut self, docs: &HashMap<String, (String, String)>) {
699 for (base, pair) in docs {
700 self.script_docs
701 .insert(qualify(SCRIPT_MODULE_NAME, base), pair.clone());
702 }
703 }
704
705 pub fn script_doc_for(&self, qualified: &str) -> Option<(String, String)> {
707 self.script_docs.get(qualified).cloned()
708 }
709
710 pub fn exported_metas(&self, exports: &[String]) -> anyhow::Result<Vec<FuncMeta>> {
713 let mut out = Vec::with_capacity(exports.len());
714 for name in exports {
715 let qualified = match name.split_once("::") {
719 None => qualify(SCRIPT_MODULE_NAME, name),
720 Some(_) => name.clone(),
721 };
722 match self.entries.get(&qualified) {
723 Some(entry) => out.push(entry.meta.clone()),
724 None => anyhow::bail!(
725 "EXPORT `{name}` matches no defined script function or known host function"
726 ),
727 }
728 }
729 Ok(out)
730 }
731}
732
733impl<P: ProcessManager> Clone for FunctionRegistry<P> {
734 fn clone(&self) -> Self {
735 Self {
736 entries: self.entries.clone(),
737 scopes: self.scopes.clone(),
738 pure_shared: Arc::clone(&self.pure_shared),
739 script_docs: self.script_docs.clone(),
740 }
741 }
742}
743
744pub fn builtin_function_names() -> HashSet<String> {
751 let mut names = FunctionRegistry::<DefaultProcessManager>::with_builtins().keys();
752 names.insert(KEYWORD_INSPECT.to_string());
753 names
754}
755
756pub fn builtin_function_metas() -> Vec<FuncMeta> {
760 FunctionRegistry::<DefaultProcessManager>::with_builtins().native_metas()
761}
762
763pub fn std_module_table() -> oxdock_parser::ModuleTable {
768 let functions: HashSet<String> = builtin_function_metas()
770 .into_iter()
771 .map(|meta| base_name(&meta.name).to_string())
772 .collect();
773 oxdock_parser::ModuleTable {
774 modules: HashMap::from([(
775 STD_MODULE_NAME.to_string(),
776 Some(oxdock_parser::ModuleFuncs { functions }),
777 )]),
778 }
779}
780
781#[oxdock_func(pure, returns = TypeTag::Int)]
794#[example(
795 name = "convert",
796 code = r###"
797 IMPORT [STD]
798 LET $n: INT = INT("42")
799 ASSERT_EQ $n 42
800 LET $flag: INT = INT(true)
801 ASSERT_EQ $flag 1
802 "###
803)]
804fn int(
805 #[union(Int, Float, String, Bool)]
807 val: Value,
808) -> Result<Value> {
809 super::args::int_from_value(val)
810}
811
812#[oxdock_func(pure, returns = TypeTag::Float)]
817#[example(
818 name = "convert",
819 code = r###"
820 IMPORT [STD]
821 LET $f: FLOAT = FLOAT("1.5")
822 ASSERT_EQ $f 1.5
823 LET $whole: FLOAT = FLOAT(2)
824 ASSERT_EQ $whole 2.0
825 "###
826)]
827fn float(
828 #[union(Float, Int, String)]
830 val: Value,
831) -> Result<Value> {
832 super::args::float_from_value(val)
833}
834
835#[oxdock_func(pure, returns = TypeTag::String)]
840#[example(
841 name = "format and round-trip",
842 code = r###"
843 # Byte counts render in the largest exact unit.
844 IMPORT [STD]
845 LET $pretty: STRING = FORMAT_BYTE_COUNT(1_048_576)
846 ASSERT_EQ $pretty "1MiB"
847
848 # The pair round-trips through the parser.
849 LET $back: INT = PARSE_BYTE_COUNT($pretty)
850 ASSERT_EQ $back 1_048_576
851 "###
852)]
853fn format_byte_count(
854 bytes: i64,
856) -> Result<Value> {
857 if bytes < 0 {
858 return Err(anyhow::anyhow!(
859 "FORMAT_BYTE_COUNT needs a non-negative byte count, got {bytes}"
860 ));
861 }
862 Ok(Value::string(oxdock_parser::command::format_byte_count(
863 bytes as u64,
864 )))
865}
866
867#[oxdock_func(pure, returns = TypeTag::Int)]
902#[example(
903 name = "parse",
904 code = r###"
905 IMPORT [STD]
906 LET $n: INT = PARSE_BYTE_COUNT("10KB")
907 ASSERT_EQ $n 10_000
908 LET $identity: INT = PARSE_BYTE_COUNT(512)
909 ASSERT_EQ $identity 512
910 "###
911)]
912fn parse_byte_count(
913 #[union(Int, Float, String)]
915 text: Value,
916) -> Result<Value> {
917 if let Some(n) = text.as_i64() {
918 if n < 0 {
919 return Err(anyhow::anyhow!(
920 "PARSE_BYTE_COUNT needs a non-negative byte count, got {n}"
921 ));
922 }
923 return Ok(Value::int(n));
924 }
925 if let Some(f) = text.as_f64() {
926 if f.is_finite() && f.fract() == 0.0 && f >= 0.0 && f <= i64::MAX as f64 {
927 return Ok(Value::int(f as i64));
928 }
929 return Err(anyhow::anyhow!(
930 "PARSE_BYTE_COUNT needs an integral byte count, got {f:?}"
931 ));
932 }
933 let Some(s) = text.as_str() else {
934 return Err(anyhow::anyhow!(
935 "PARSE_BYTE_COUNT needs a token or number, found {text:?}"
936 ));
937 };
938 let n = oxdock_parser::command::parse_byte_count(s)?;
939 let n = i64::try_from(n)
940 .map_err(|_| anyhow::anyhow!("PARSE_BYTE_COUNT out of INT range: {s:?}"))?;
941 Ok(Value::int(n))
942}
943
944#[oxdock_func(pure, returns = TypeTag::String)]
949#[example(
950 name = "format and round-trip",
951 code = r###"
952 # Durations render in the largest exact unit.
953 IMPORT [STD]
954 LET $pretty: STRING = FORMAT_DURATION(90_000)
955 ASSERT_EQ $pretty "90s"
956
957 # The pair round-trips through the parser.
958 LET $back: INT = PARSE_DURATION($pretty)
959 ASSERT_EQ $back 90_000
960 "###
961)]
962fn format_duration(
963 millis: i64,
965) -> Result<Value> {
966 if millis < 0 {
967 return Err(anyhow::anyhow!(
968 "FORMAT_DURATION needs non-negative milliseconds, got {millis}"
969 ));
970 }
971 Ok(Value::string(oxdock_parser::command::format_duration(
972 &std::time::Duration::from_millis(millis as u64),
973 )))
974}
975
976#[oxdock_func(pure, returns = TypeTag::Int)]
982#[example(
983 name = "parse",
984 code = r###"
985 # A bare number means seconds, like TIMEOUT.
986 IMPORT [STD]
987 LET $ms: INT = PARSE_DURATION("2m")
988 ASSERT_EQ $ms 120_000
989
990 # Milliseconds stay exact.
991 LET $exact: INT = PARSE_DURATION("1500ms")
992 ASSERT_EQ $exact 1_500
993
994 # One optional space separates number from unit.
995 LET $spaced: INT = PARSE_DURATION("1 h")
996 ASSERT_EQ $spaced 3_600_000
997 "###
998)]
999fn parse_duration(
1000 text: String,
1002) -> Result<Value> {
1003 let duration = oxdock_parser::command::parse_duration(&text)?;
1004 let millis = i64::try_from(duration.as_millis())
1005 .map_err(|_| anyhow::anyhow!("PARSE_DURATION out of INT range: {text:?}"))?;
1006 Ok(Value::int(millis))
1007}
1008
1009#[oxdock_func(rpn, returns = TypeTag::ListOf(std::sync::Arc::new(TypeTag::String)))]
1014#[example(
1015 name = "match",
1016 code = r###"
1017 IMPORT [STD]
1018 WRITE "notes-a.md" "a"
1019 WRITE "notes-b.md" "b"
1020 WRITE "other.txt" "c"
1021 LET $found: LIST<STRING> = GLOB("notes-*.md")
1022 ASSERT_EQ $found.0 "notes-a.md"
1023 ASSERT_EQ $found.1 "notes-b.md"
1024 "###
1025)]
1026fn glob<P: ProcessManager>(
1027 cx: &mut StepCtx<P>,
1028 #[union(String, Path)]
1030 pattern: Value,
1031) -> Result<Value> {
1032 let text = super::args::string_or_path_text(&pattern)?;
1033 super::args::glob_from_value(&[Value::string(text)], cx)
1034}
1035
1036#[oxdock_func(rpn, returns = TypeTag::MapOf(std::sync::Arc::new(TypeTag::Any)))]
1041#[example(
1042 name = "load",
1043 code = r###"
1044 IMPORT [STD]
1045 WRITE "cfg.toml" "title = \"demo\""
1046 LET $cfg: MAP<ANY> = LOAD_TOML("cfg.toml")
1047 ASSERT_EQ $cfg.title "demo"
1048 "###
1049)]
1050fn load_toml<P: ProcessManager>(
1051 cx: &mut StepCtx<P>,
1052 #[union(String, Path)]
1054 path: Value,
1055) -> Result<Value> {
1056 let text = super::args::string_or_path_text(&path)?;
1057 super::args::load_toml_from_value(&[Value::string(text)], cx)
1058}
1059
1060#[oxdock_func(rpn, returns = TypeTag::Any)]
1068#[example(
1069 name = "load",
1070 code = r###"
1071 IMPORT [STD]
1072 WRITE "data.json" "{\"a\": 1}"
1073 LET $doc: MAP<ANY> = LOAD_JSON("data.json")
1074 ASSERT_EQ $doc.a 1
1075 "###
1076)]
1077fn load_json<P: ProcessManager>(
1078 cx: &mut StepCtx<P>,
1079 #[union(String, Path)]
1081 path: Value,
1082) -> Result<Value> {
1083 let text = super::args::string_or_path_text(&path)?;
1084 super::args::load_json_from_value(&[Value::string(text)], cx)
1085}
1086
1087#[oxdock_func(pure, returns = TypeTag::MapOf(std::sync::Arc::new(TypeTag::Any)))]
1093#[example(
1094 name = "parse",
1095 code = r###"
1096 IMPORT [STD]
1097 LET $doc: MAP<ANY> = PARSE_TOML("title = \"demo\"")
1098 ASSERT_EQ $doc.title "demo"
1099 "###
1100)]
1101fn parse_toml(
1102 text: String,
1104) -> Result<Value> {
1105 super::args::parse_toml_from_value(Value::string(text))
1106}
1107
1108#[oxdock_func(pure, returns = TypeTag::Any)]
1117#[example(
1118 name = "parse",
1119 code = r###"
1120 # Parse in-memory JSON text with the same conversion as file loading.
1121 IMPORT [STD]
1122 LET $body: STRING = "{\"a\": 1}"
1123 LET $doc: ANY = PARSE_JSON($body)
1124 ASSERT_EQ $doc.a 1
1125
1126 # Top-level arrays parse to LIST, which is why the return is ANY.
1127 LET $items: LIST<ANY> = PARSE_JSON("[1, 2]")
1128 ASSERT_EQ $items.0 1
1129 ASSERT_EQ $items.1 2
1130 "###
1131)]
1132fn parse_json(
1133 text: String,
1135) -> Result<Value> {
1136 super::args::parse_json_from_value(Value::string(text))
1137}
1138
1139#[oxdock_func(returns = TypeTag::String)]
1145#[example(
1146 name = "describe",
1147 code = r###"
1148 IMPORT [STD]
1149 WRITE "entry.txt" "words"
1150 LET $kind: STRING = PATH_TYPE("entry.txt")
1151 ASSERT_EQ $kind "file"
1152 LET $missing: STRING = PATH_TYPE("no-such-entry.txt")
1153 ASSERT_EQ $missing "absent"
1154 "###
1155)]
1156fn path_type<P: ProcessManager>(
1157 cx: &mut StepCtx<P>,
1158 #[union(String, Path)]
1160 path: Value,
1161) -> Result<Value> {
1162 let text = super::args::string_or_path_text(&path)?;
1163 super::args::path_type_from_value(&[Value::string(text)], cx)
1164}
1165
1166#[oxdock_func(returns = TypeTag::Bool)]
1175#[example(
1176 name = "probe",
1177 code = r###"
1178 # An absent nested path is writable when its ancestor is.
1179 IMPORT [STD]
1180 LET $fresh: BOOL = PATH_WRITABLE("probe-check/nested/file.txt")
1181 ASSERT_EQ $fresh true
1182
1183 # The empty string never aliases the working directory.
1184 LET $empty: BOOL = PATH_WRITABLE("")
1185 ASSERT_EQ $empty false
1186 "###
1187)]
1188fn path_writable<P: ProcessManager>(
1189 cx: &mut StepCtx<P>,
1190 #[union(String, Path)]
1192 path: Value,
1193) -> Result<Value> {
1194 let text = super::args::string_or_path_text(&path)?;
1195 super::args::path_writable_from_value(&[Value::string(text)], cx)
1196}
1197
1198#[oxdock_func(returns = TypeTag::Bool)]
1211#[example(
1212 name = "probe",
1213 code = r###"
1214 # Missing tools read false instead of failing the run.
1215 IMPORT [STD]
1216 LET $missing: BOOL = IS_EXEC("no-such-tool-xyz")
1217 ASSERT_EQ $missing false
1218
1219 # Plain files are not executable on any platform.
1220 WRITE tool.txt payload
1221 LET $plain: BOOL = IS_EXEC("tool.txt")
1222 ASSERT_EQ $plain false
1223 "###
1224)]
1225fn is_exec<P: ProcessManager>(
1226 cx: &mut StepCtx<P>,
1227 #[union(String, Path)]
1229 name: Value,
1230) -> Result<Value> {
1231 let text = super::args::string_or_path_text(&name)?;
1232 super::args::is_exec_from_value(&[Value::string(text)], cx)
1233}
1234
1235#[oxdock_func(pure, returns = TypeTag::Bool)]
1241#[example(
1242 name = "probe",
1243 code = r###"
1244 IMPORT [STD]
1245 LET $m: MAP<ANY> = PARSE_JSON("{\"a\": 1}")
1246 LET $hit: BOOL = HAS_KEY($m, "a")
1247 ASSERT_EQ $hit true
1248 LET $miss: BOOL = HAS_KEY($m, "b")
1249 ASSERT_EQ $miss false
1250 "###
1251)]
1252fn has_key(
1253 map: BTreeMap<String, Value>,
1255 key: String,
1257) -> Result<Value> {
1258 super::args::has_key_from_value(Value::map(map), &key)
1259}
1260
1261#[oxdock_func(pure, returns = TypeTag::MapOf(std::sync::Arc::new(TypeTag::Any)))]
1267#[example(
1268 name = "insert",
1269 code = r###"
1270 IMPORT [STD]
1271 LET $m: MAP<ANY> = MAP_SET({seed: 0}, "a", 1)
1272 ASSERT_EQ $m.a 1
1273 "###
1274)]
1275fn map_set(
1276 map: BTreeMap<String, Value>,
1278 key: String,
1280 value: Value,
1282) -> Result<Value> {
1283 super::args::map_set_from_value(Value::map(map), key, value)
1284}
1285
1286#[oxdock_func(returns = TypeTag::Float, summary = "Draw a random FLOAT uniformly from [0, 1), optionally seeded.")]
1294#[example(
1295 name = "seeded draw",
1296 code = r###"
1297 # A seed draws the same value on every run.
1298 IMPORT [STD]
1299 LET $one: FLOAT = RAND({seed: 7})
1300 LET $two: FLOAT = RAND({seed: 7})
1301 ASSERT_EQ $one $two
1302 "###
1303)]
1304#[example(
1305 name = "unseeded draw",
1306 code = r###"
1307 # Scale a unit draw into a backoff delay between 1 and 11 seconds.
1308 IMPORT [STD]
1309 LET $draw: FLOAT = RAND()
1310 LET $delay: FLOAT = 1.0 + $draw * 10.0
1311 IF $delay < 1.0 {
1312 EXIT 1
1313 }
1314 IF $delay >= 11.0 {
1315 EXIT 1
1316 }
1317 ECHO "retrying in {{ $delay }}s"
1318 "###
1319)]
1320fn rand<P: ProcessManager>(
1321 cx: &mut StepCtx<P>,
1322 #[options("seed?: INT")]
1324 #[optional]
1325 options: BTreeMap<String, Value>,
1326) -> Result<Value> {
1327 let _ = cx;
1328 let seed = options
1331 .get("seed")
1332 .map(|value| value.as_i64().expect("check_options verified INT"));
1333 super::args::rand_float_from_value(seed)
1334}
1335
1336#[oxdock_func(pure, returns = TypeTag::String)]
1342#[example(
1343 name = "encode",
1344 code = r###"
1345 # Encode text to standard base64.
1346 IMPORT [STD]
1347 LET $encoded: STRING = BASE64_ENCODE("hello")
1348 ASSERT_EQ $encoded "aGVsbG8="
1349 "###
1350)]
1351fn base64_encode(
1352 text: String,
1354) -> Result<Value> {
1355 super::args::base64_encode_from_value(Value::string(text))
1356}
1357
1358#[oxdock_func(pure, returns = TypeTag::String)]
1365#[example(
1366 name = "decode",
1367 code = r###"
1368 # Decode standard base64 back to text.
1369 IMPORT [STD]
1370 LET $decoded: STRING = BASE64_DECODE("aGVsbG8=")
1371 ASSERT_EQ $decoded "hello"
1372 "###
1373)]
1374fn base64_decode(
1375 text: String,
1377) -> Result<Value> {
1378 super::args::base64_decode_from_value(Value::string(text))
1379}
1380
1381#[oxdock_func(pure, returns = TypeTag::String)]
1388#[example(
1389 name = "encode",
1390 code = r###"
1391 IMPORT [STD]
1392 LET $json: STRING = TO_JSON({a: 1})
1393 ASSERT_EQ $json "{\"a\":1}\n"
1394 "###
1395)]
1396fn to_json(
1397 #[union(String, Int, Float, Bool, List, Map)]
1399 value: Value,
1400) -> Result<Value> {
1401 super::args::to_json_from_value(value)
1402}
1403
1404#[oxdock_func(pure, returns = TypeTag::String)]
1412#[example(
1413 name = "name the word",
1414 code = r###"
1415 IMPORT [STD]
1416 LET $word: STRING = TYPE_OF(42)
1417 ASSERT_EQ $word "INT"
1418 "###
1419)]
1420fn type_of(
1421 value: Value,
1423) -> Result<Value> {
1424 super::args::type_of_from_value(value)
1425}
1426
1427#[oxdock_func(pure, returns = TypeTag::MapOf(std::sync::Arc::new(TypeTag::Any)))]
1435#[example(
1436 name = "merge",
1437 code = r###"
1438 IMPORT [STD]
1439 LET $m: MAP<ANY> = MERGE_MAPS([{a: 1}, {b: 2}], "overwrite")
1440 ASSERT_EQ $m.a 1
1441 ASSERT_EQ $m.b 2
1442 "###
1443)]
1444fn merge_maps(
1445 maps: Vec<BTreeMap<String, Value>>,
1447 #[values("fail_on_duplicate", "overwrite")]
1449 policy: String,
1450) -> Result<Value> {
1451 super::args::merge_maps_from_value(
1452 Value::list(maps.into_iter().map(Value::map).collect()),
1453 policy,
1454 )
1455}
1456
1457#[oxdock_func(pure, returns = TypeTag::String)]
1462#[example(
1463 name = "report",
1464 code = r###"
1465 # The engine reports its own build version as a dotted string.
1466 IMPORT [STD]
1467 LET $v: STRING = VERSION()
1468 ASSERT_CONTAINS $v "."
1469 "###
1470)]
1471fn version() -> Result<Value> {
1472 Ok(Value::string(env!("CARGO_PKG_VERSION").to_string()))
1473}
1474
1475#[oxdock_func(returns = TypeTag::ListOf(std::sync::Arc::new(TypeTag::String)))]
1480#[example(
1481 name = "list",
1482 code = r###"
1483 IMPORT [STD]
1484 LET $names: LIST<STRING> = FUNCTIONS()
1485 ASSERT_CONTAINS $names "STD::INT"
1486 "###
1487)]
1488fn functions<P: ProcessManager>(cx: &mut StepCtx<P>) -> Result<Value> {
1489 let mut names: Vec<String> = cx
1490 .state
1491 .list_functions()
1492 .into_iter()
1493 .map(|meta| meta.name)
1494 .collect();
1495 names.sort();
1496 names.dedup();
1497 Ok(Value::list(names.into_iter().map(Value::string).collect()))
1498}
1499
1500#[oxdock_func(
1515 returns = TypeTag::Record(std::sync::Arc::from([Field {
1516 name: "name".to_string(),
1517 ty: TypeTag::String,
1518 docs: "Qualified function name.",
1519 optional: false,
1520 }, Field {
1521 name: "module".to_string(),
1522 ty: TypeTag::String,
1523 docs: "Owning module.",
1524 optional: false,
1525 }, Field {
1526 name: "kind".to_string(),
1527 ty: TypeTag::String,
1528 docs: "Origin label (`host` or `script`).",
1529 optional: false,
1530 }, Field {
1531 name: "params".to_string(),
1532 ty: TypeTag::ListOf(std::sync::Arc::new(TypeTag::MapOf(std::sync::Arc::new(
1533 TypeTag::Any,
1534 )))),
1535 docs: "Parameter entries (empty for parameterless functions).",
1536 optional: false,
1537 }, Field {
1538 name: "returns".to_string(),
1539 ty: TypeTag::String,
1540 docs: "Structural return shape (empty when untagged).",
1541 optional: false,
1542 }, Field {
1543 name: "rpn".to_string(),
1544 ty: TypeTag::Bool,
1545 docs: "True when callable in RPN position.",
1546 optional: false,
1547 }, Field {
1548 name: "summary".to_string(),
1549 ty: TypeTag::String,
1550 docs: "One-line description.",
1551 optional: false,
1552 }]))
1553 summary = "Describe one function by qualified name."
1554)]
1555#[example(
1556 name = "describe",
1557 code = r###"
1558 IMPORT [STD]
1559 LET $info: MAP<ANY> = DESCRIBE("STD::INT")
1560 ASSERT_EQ $info.name "STD::INT"
1561 ASSERT_EQ $info.returns "INT"
1562 "###
1563)]
1564fn describe<P: ProcessManager>(
1565 cx: &mut StepCtx<P>,
1566 name: String,
1568) -> Result<Value> {
1569 if split_qualified(&name).is_none() && name != KEYWORD_INSPECT {
1570 anyhow::bail!(
1571 "unknown function `{name}`: DESCRIBE requires a qualified name (e.g. `STD::{name}`)"
1572 );
1573 }
1574 cx.state
1575 .describe_function(&name)
1576 .ok_or_else(|| anyhow::anyhow!("unknown function {name}"))
1577}
1578
1579#[oxdock_func(returns = TypeTag::ListOf(std::sync::Arc::new(TypeTag::String)))]
1585#[example(
1586 name = "list",
1587 code = r###"
1588 IMPORT [STD]
1589 LET $names: LIST<STRING> = TYPES()
1590 ASSERT_CONTAINS $names "STRING"
1591 "###
1592)]
1593fn types<P: ProcessManager>(cx: &mut StepCtx<P>) -> Result<Value> {
1594 Ok(Value::list(
1595 cx.state
1596 .type_names()
1597 .into_iter()
1598 .map(Value::string)
1599 .collect(),
1600 ))
1601}
1602
1603#[oxdock_func(returns = TypeTag::Record(std::sync::Arc::from([Field {
1609 name: "name".to_string(),
1610 ty: TypeTag::String,
1611 docs: "Queried type name.",
1612 optional: false,
1613}, Field {
1614 name: "summary".to_string(),
1615 ty: TypeTag::String,
1616 docs: "One-line description.",
1617 optional: false,
1618}, Field {
1619 name: "docs".to_string(),
1620 ty: TypeTag::String,
1621 docs: "Full documentation text.",
1622 optional: false,
1623}])))]
1624#[example(
1625 name = "describe",
1626 code = r###"
1627 IMPORT [STD]
1628 LET $info: MAP<ANY> = TYPE_DESCRIBE("STRING")
1629 ASSERT_EQ $info.name "STRING"
1630 "###
1631)]
1632fn type_describe<P: ProcessManager>(
1633 cx: &mut StepCtx<P>,
1634 name: String,
1636) -> Result<Value> {
1637 if let Some(descriptor) = cx.state.describe_type(&name) {
1638 let mut map = BTreeMap::new();
1639 map.insert(
1640 "name".to_string(),
1641 Value::string(descriptor.name.to_string()),
1642 );
1643 map.insert(
1644 "summary".to_string(),
1645 Value::string(descriptor.summary.to_string()),
1646 );
1647 map.insert(
1648 "docs".to_string(),
1649 Value::string(descriptor.docs.to_string()),
1650 );
1651 return Ok(Value::map(map));
1652 }
1653 if let Some(target) = cx.state.alias_target(&name) {
1656 let mut map = BTreeMap::new();
1657 map.insert("name".to_string(), Value::string(name.clone()));
1658 map.insert(
1659 "summary".to_string(),
1660 Value::string(format!("Script type alias for {target}.")),
1661 );
1662 map.insert(
1663 "docs".to_string(),
1664 Value::string(format!(
1665 "Declared with TYPE {name} = {target}. The alias expands structurally at every declaration."
1666 )),
1667 );
1668 return Ok(Value::map(map));
1669 }
1670 Err(anyhow::anyhow!("unknown type {name}"))
1671}
1672
1673#[oxdock_func(returns = TypeTag::Bool)]
1687#[example(
1688 name = "null stdin",
1689 code = r###"
1690 # A null stdin is never a terminal, in every harness.
1691 IMPORT [STD]
1692 LET $term: BOOL = IS_TERMINAL("stdin")
1693 ASSERT_EQ $term false
1694 "###
1695)]
1696fn is_terminal<P: ProcessManager>(
1697 cx: &mut StepCtx<P>,
1698 #[values("stdin", "stdout", "stderr")]
1700 stream_name: String,
1701) -> Result<Value> {
1702 use std::io::IsTerminal;
1703 let terminal = match stream_name.as_str() {
1704 "stdin" => {
1705 if cx.stdin_pipe.is_some() {
1710 false
1711 } else {
1712 match &cx.stdin {
1713 CommandStdin::Null => false,
1714 #[cfg(not(miri))]
1715 CommandStdin::OsPipe(_) => false,
1716 CommandStdin::Stream(_) => false,
1717 CommandStdin::Inherit => std::io::stdin().is_terminal(),
1718 }
1719 }
1720 }
1721 "stdout" => {
1722 if cx.out_pipe.is_some() {
1723 false
1725 } else if cx.state.io.stdout().is_some() {
1726 false
1729 } else {
1730 match &cx.out {
1731 None => std::io::stdout().is_terminal(),
1733 #[cfg(not(miri))]
1735 Some(StreamHandle::Os(_)) => false,
1736 Some(StreamHandle::Stream(_)) => std::io::stdout().is_terminal(),
1746 }
1747 }
1748 }
1749 "stderr" => {
1750 if cx.state.io.stderr().is_some() {
1751 false
1753 } else {
1754 match &cx.err {
1755 None => std::io::stderr().is_terminal(),
1757 #[cfg(not(miri))]
1759 Some(StreamHandle::Os(_)) => false,
1760 Some(StreamHandle::Stream(_)) => false,
1763 }
1764 }
1765 }
1766 _ => anyhow::bail!(
1767 "IS_TERMINAL expects \"stdin\", \"stdout\", or \"stderr\", got {stream_name:?}"
1772 ),
1773 };
1774 Ok(Value::bool(terminal))
1775}
1776
1777#[oxdock_func(returns = TypeTag::Semaphore)]
1785#[example(
1786 name = "mint",
1787 code = r###"
1788 # Mint a semaphore admitting at most two holders.
1789 IMPORT [STD]
1790 LET $sem: SEMAPHORE = SEMAPHORE_NEW(2)
1791
1792 # A fresh semaphore reports its full cap as available.
1793 LET $free: INT = SEMAPHORE_AVAILABLE($sem)
1794 ASSERT_EQ $free 2
1795 "###
1796)]
1797fn semaphore_new<P: ProcessManager>(
1798 cx: &mut StepCtx<P>,
1799 max: i64,
1801) -> Result<Value> {
1802 let _ = cx;
1803 if max <= 0 {
1804 return Err(anyhow::anyhow!(
1805 "SEMAPHORE_NEW() requires a positive max, got {max}"
1806 ));
1807 }
1808 Ok(Value::semaphore(max as usize))
1809}
1810
1811#[oxdock_func(returns = TypeTag::Record(std::sync::Arc::from([Field {
1820 name: "held".to_string(),
1821 ty: TypeTag::Bool,
1822 docs: "`true` with the permit under `permit`, `false` with no `permit` key.",
1823 optional: false,
1824}, Field {
1825 name: "permit".to_string(),
1826 ty: TypeTag::Permit,
1827 docs: "Permit handle; read only when `held`.",
1828 optional: true,
1829}])))]
1830#[example(
1831 name = "acquire",
1832 code = r###"
1833 # First acquire holds with a permit to bind.
1834 IMPORT [STD]
1835 LET $sem: SEMAPHORE = SEMAPHORE_NEW(1)
1836 LET $first: MAP<held: BOOL, permit?: PERMIT> = SEMAPHORE_TRY_ACQUIRE($sem)
1837 ASSERT_EQ $first.held true
1838 LET $permit: PERMIT = $first.permit
1839
1840 # A capped semaphore answers held false with no permit key.
1841 LET $second: MAP<held: BOOL, permit?: PERMIT> = SEMAPHORE_TRY_ACQUIRE($sem)
1842 ASSERT_EQ $second.held false
1843 LET $has_permit: BOOL = HAS_KEY($second, "permit")
1844 ASSERT_EQ $has_permit false
1845 "###
1846)]
1847fn semaphore_try_acquire<P: ProcessManager>(
1848 cx: &mut StepCtx<P>,
1849 sem: Arc<SemaphoreState>,
1851) -> Result<Value> {
1852 let _ = cx;
1853 let mut map = BTreeMap::new();
1854 if sem.try_acquire() {
1855 map.insert("held".to_string(), Value::bool(true));
1856 map.insert("permit".to_string(), Value::permit(&sem));
1857 } else {
1858 map.insert("held".to_string(), Value::bool(false));
1859 }
1860 Ok(Value::map(map))
1861}
1862
1863#[oxdock_func(pure, returns = TypeTag::Int)]
1870#[example(
1871 name = "readout",
1872 code = r###"
1873 # Hold one permit on a cap of two.
1874 IMPORT [STD]
1875 LET $sem: SEMAPHORE = SEMAPHORE_NEW(2)
1876 LET $acq: MAP<held: BOOL, permit?: PERMIT> = SEMAPHORE_TRY_ACQUIRE($sem)
1877 ASSERT_EQ $acq.held true
1878
1879 # One held permit leaves exactly one free.
1880 LET $free: INT = SEMAPHORE_AVAILABLE($sem)
1881 ASSERT_EQ $free 1
1882 "###
1883)]
1884fn semaphore_available(
1885 sem: Arc<SemaphoreState>,
1887) -> Result<Value> {
1888 Ok(Value::int(sem.available() as i64))
1889}
1890
1891#[oxdock_func(
1900 rpn,
1901 returns = TypeTag::union(vec![TypeTag::String, TypeTag::Pipe]),
1902 template = text_trim_string
1903)]
1904#[example(
1905 name = "trim",
1906 code = r###"
1907 # Leading and trailing whitespace falls away.
1908 IMPORT [STD]
1909 LET $clean: STRING = TEXT_TRIM(" hello ")
1910 ASSERT_EQ $clean "hello"
1911 "###
1912)]
1913#[example(
1914 name = "trim pipe mirrors",
1915 code = r###"
1916 # Pipe input mints pipe output with the same transform.
1917 IMPORT [STD]
1918 LET $cap: PIPE
1919 WITH_IO [stdout=$cap] {
1920 ECHO " hello "
1921 }
1922 LET $out: PIPE = TEXT_TRIM($cap)
1923 WITH_IO [stdin=$out] READ_LINE $line
1924 ASSERT_EQ $line "hello"
1925 "###
1926)]
1927#[example(
1928 name = "trim template",
1929 code = r###"
1930 # String inputs run inside placeholders too.
1931 IMPORT [STD]
1932 LET $msg: STRING = 'clean:{{ STD::TEXT_TRIM(" hello ") }}'
1933 ASSERT_EQ $msg "clean:hello"
1934 "###
1935)]
1936#[example(
1937 name = "trim file template",
1938 code = r###"
1939 # EXPAND templates resolve the same registry.
1940 IMPORT [STD]
1941 WRITE "tpl.txt" "clean:\{{ STD::TEXT_TRIM(\" hello \") }}"
1942 LET $out: STRING = EXPAND "tpl.txt"
1943 ASSERT_EQ $out "clean:hello"
1944 "###
1945)]
1946fn text_trim<P: ProcessManager>(
1947 cx: &mut StepCtx<P>,
1948 #[union(String, Pipe)]
1950 text: Value,
1951) -> Result<Value> {
1952 super::args::mirror_stream(cx, "TEXT_TRIM", &text, super::args::TextPump::Trim)
1953}
1954
1955fn text_trim_string(text: Value) -> Result<Value> {
1958 super::args::mirror_string("TEXT_TRIM", &text, super::args::TextPump::Trim)
1959}
1960
1961#[oxdock_func(
1970 rpn,
1971 returns = TypeTag::union(vec![TypeTag::String, TypeTag::Pipe]),
1972 template = text_trim_prefix_string
1973)]
1974#[example(
1975 name = "strip prefix",
1976 code = r###"
1977 # A present prefix falls away; absence returns the input unchanged.
1978 IMPORT [STD]
1979 LET $bare: STRING = TEXT_TRIM_PREFIX("v1.2.3", "v")
1980 ASSERT_EQ $bare "1.2.3"
1981
1982 # Missing prefixes pass through untouched.
1983 LET $same: STRING = TEXT_TRIM_PREFIX("1.2.3", "v")
1984 ASSERT_EQ $same "1.2.3"
1985 "###
1986)]
1987#[example(
1988 name = "strip prefix pipe mirrors",
1989 code = r###"
1990 # Pipe input mints pipe output with the same strip.
1991 IMPORT [STD]
1992 LET $cap: PIPE
1993 WITH_IO [stdout=$cap] {
1994 ECHO "v1.2.3"
1995 }
1996 LET $trimmed: PIPE = TEXT_TRIM($cap)
1997 LET $out: PIPE = TEXT_TRIM_PREFIX($trimmed, "v")
1998 WITH_IO [stdin=$out] READ_LINE $line
1999 ASSERT_EQ $line "1.2.3"
2000 "###
2001)]
2002#[example(
2003 name = "strip prefix template",
2004 code = r###"
2005 # String inputs run inside placeholders too.
2006 IMPORT [STD]
2007 LET $msg: STRING = 'bare:{{ STD::TEXT_TRIM_PREFIX("v1.2.3", "v") }}'
2008 ASSERT_EQ $msg "bare:1.2.3"
2009 "###
2010)]
2011fn text_trim_prefix<P: ProcessManager>(
2012 cx: &mut StepCtx<P>,
2013 #[union(String, Pipe)]
2015 text: Value,
2016 prefix: String,
2018) -> Result<Value> {
2019 super::args::mirror_stream(
2020 cx,
2021 "TEXT_TRIM_PREFIX",
2022 &text,
2023 super::args::TextPump::TrimPrefix(prefix),
2024 )
2025}
2026
2027fn text_trim_prefix_string(text: Value, prefix: String) -> Result<Value> {
2030 super::args::mirror_string(
2031 "TEXT_TRIM_PREFIX",
2032 &text,
2033 super::args::TextPump::TrimPrefix(prefix),
2034 )
2035}
2036
2037#[oxdock_func(
2044 rpn,
2045 returns = TypeTag::union(vec![TypeTag::String, TypeTag::Pipe]),
2046 template = text_trim_suffix_string
2047)]
2048#[example(
2049 name = "strip suffix",
2050 code = r###"
2051 # A present suffix falls away; absence returns the input unchanged.
2052 IMPORT [STD]
2053 LET $bare: STRING = TEXT_TRIM_SUFFIX("archive.tar.gz", ".gz")
2054 ASSERT_EQ $bare "archive.tar"
2055
2056 # Missing suffixes pass through untouched.
2057 LET $same: STRING = TEXT_TRIM_SUFFIX("archive.tar", ".gz")
2058 ASSERT_EQ $same "archive.tar"
2059 "###
2060)]
2061#[example(
2062 name = "strip suffix pipe mirrors",
2063 code = r###"
2064 # Pipe input mints pipe output with the same strip.
2065 IMPORT [STD]
2066 LET $cap: PIPE
2067 WITH_IO [stdout=$cap] {
2068 ECHO "archive.tar.gz"
2069 }
2070 LET $trimmed: PIPE = TEXT_TRIM($cap)
2071 LET $out: PIPE = TEXT_TRIM_SUFFIX($trimmed, ".gz")
2072 WITH_IO [stdin=$out] READ_LINE $line
2073 ASSERT_EQ $line "archive.tar"
2074 "###
2075)]
2076#[example(
2077 name = "strip suffix template",
2078 code = r###"
2079 # String inputs run inside placeholders too.
2080 IMPORT [STD]
2081 LET $msg: STRING = 'bare:{{ STD::TEXT_TRIM_SUFFIX("archive.tar.gz", ".gz") }}'
2082 ASSERT_EQ $msg "bare:archive.tar"
2083 "###
2084)]
2085fn text_trim_suffix<P: ProcessManager>(
2086 cx: &mut StepCtx<P>,
2087 #[union(String, Pipe)]
2089 text: Value,
2090 suffix: String,
2092) -> Result<Value> {
2093 super::args::mirror_stream(
2094 cx,
2095 "TEXT_TRIM_SUFFIX",
2096 &text,
2097 super::args::TextPump::TrimSuffix(suffix),
2098 )
2099}
2100
2101fn text_trim_suffix_string(text: Value, suffix: String) -> Result<Value> {
2104 super::args::mirror_string(
2105 "TEXT_TRIM_SUFFIX",
2106 &text,
2107 super::args::TextPump::TrimSuffix(suffix),
2108 )
2109}
2110
2111#[oxdock_func(returns = TypeTag::String)]
2122#[example(
2123 name = "join path",
2124 code = r###"
2125 # Directory and file stem join with the native separator.
2126 # Source `\\` is one backslash at runtime; `/` works on Windows
2127 # too, native just reads better there.
2128 IMPORT [STD]
2129 LET $p: STRING = PATH_JOIN("some-dir", "some-file")
2130 [family:unix] ASSERT_EQ $p "some-dir/some-file"
2131 [family:windows] ASSERT_EQ $p "some-dir\\some-file"
2132 "###
2133)]
2134fn path_join<P: ProcessManager>(
2135 _cx: &mut StepCtx<P>,
2136 #[union(String, Path)]
2138 dir: Value,
2139 #[union(String, Path)]
2141 name: Value,
2142) -> Result<Value> {
2143 let d = super::args::string_or_path_text(&dir)?;
2144 let n = super::args::string_or_path_text(&name)?;
2145 Ok(Value::string(oxdock_fs::join_native(&d, &n)))
2146}
2147
2148#[oxdock_func(
2155 rpn,
2156 returns = TypeTag::union(vec![TypeTag::String, TypeTag::Pipe]),
2157 template = text_to_upper_string
2158)]
2159#[example(
2160 name = "uppercase",
2161 code = r###"
2162 # Text folds to uppercase.
2163 IMPORT [STD]
2164 LET $loud: STRING = TEXT_TO_UPPER("hello")
2165 ASSERT_EQ $loud "HELLO"
2166 "###
2167)]
2168#[example(
2169 name = "uppercase pipe mirrors",
2170 code = r###"
2171 # Pipe input mints pipe output with the same fold.
2172 IMPORT [STD]
2173 LET $cap: PIPE
2174 WITH_IO [stdout=$cap] {
2175 ECHO "hello"
2176 }
2177 LET $out: PIPE = TEXT_TO_UPPER($cap)
2178 WITH_IO [stdin=$out] READ_LINE $line
2179 ASSERT_EQ $line "HELLO"
2180 "###
2181)]
2182#[example(
2183 name = "uppercase template",
2184 code = r###"
2185 # String inputs run inside placeholders too.
2186 IMPORT [STD]
2187 LET $msg: STRING = 'loud:{{ STD::TEXT_TO_UPPER("hello") }}'
2188 ASSERT_EQ $msg "loud:HELLO"
2189 "###
2190)]
2191fn text_to_upper<P: ProcessManager>(
2192 cx: &mut StepCtx<P>,
2193 #[union(String, Pipe)]
2195 text: Value,
2196) -> Result<Value> {
2197 super::args::mirror_stream(cx, "TEXT_TO_UPPER", &text, super::args::TextPump::ToUpper)
2198}
2199
2200fn text_to_upper_string(text: Value) -> Result<Value> {
2203 super::args::mirror_string("TEXT_TO_UPPER", &text, super::args::TextPump::ToUpper)
2204}
2205
2206#[oxdock_func(
2213 rpn,
2214 returns = TypeTag::union(vec![TypeTag::String, TypeTag::Pipe]),
2215 template = text_to_lower_string
2216)]
2217#[example(
2218 name = "lowercase",
2219 code = r###"
2220 # Text folds to lowercase.
2221 IMPORT [STD]
2222 LET $quiet: STRING = TEXT_TO_LOWER("HELLO")
2223 ASSERT_EQ $quiet "hello"
2224 "###
2225)]
2226#[example(
2227 name = "lowercase pipe mirrors",
2228 code = r###"
2229 # Pipe input mints pipe output with the same fold.
2230 IMPORT [STD]
2231 LET $cap: PIPE
2232 WITH_IO [stdout=$cap] {
2233 ECHO "HELLO"
2234 }
2235 LET $out: PIPE = TEXT_TO_LOWER($cap)
2236 WITH_IO [stdin=$out] READ_LINE $line
2237 ASSERT_EQ $line "hello"
2238 "###
2239)]
2240#[example(
2241 name = "lowercase template",
2242 code = r###"
2243 # String inputs run inside placeholders too.
2244 IMPORT [STD]
2245 LET $msg: STRING = 'quiet:{{ STD::TEXT_TO_LOWER("HELLO") }}'
2246 ASSERT_EQ $msg "quiet:hello"
2247 "###
2248)]
2249fn text_to_lower<P: ProcessManager>(
2250 cx: &mut StepCtx<P>,
2251 #[union(String, Pipe)]
2253 text: Value,
2254) -> Result<Value> {
2255 super::args::mirror_stream(cx, "TEXT_TO_LOWER", &text, super::args::TextPump::ToLower)
2256}
2257
2258fn text_to_lower_string(text: Value) -> Result<Value> {
2261 super::args::mirror_string("TEXT_TO_LOWER", &text, super::args::TextPump::ToLower)
2262}
2263
2264#[oxdock_func(
2275 rpn,
2276 returns = TypeTag::union(vec![TypeTag::String, TypeTag::Pipe]),
2277 template = text_replace_string
2278)]
2279#[example(
2280 name = "replace",
2281 code = r###"
2282 # Every literal occurrence rewrites in place.
2283 IMPORT [STD]
2284 LET $fixed: STRING = TEXT_REPLACE("hello world", "world", "there")
2285 ASSERT_EQ $fixed "hello there"
2286 "###
2287)]
2288#[example(
2289 name = "replace pipe mirrors",
2290 code = r###"
2291 # Pipe input mints pipe output with the same rewrite.
2292 IMPORT [STD]
2293 LET $cap: PIPE
2294 WITH_IO [stdout=$cap] {
2295 ECHO "hello world"
2296 }
2297 LET $trimmed: PIPE = TEXT_TRIM($cap)
2298 LET $out: PIPE = TEXT_REPLACE($trimmed, "world", "there")
2299 WITH_IO [stdin=$out] READ_LINE $line
2300 ASSERT_EQ $line "hello there"
2301 "###
2302)]
2303#[example(
2304 name = "replace template",
2305 code = r###"
2306 # String inputs run inside placeholders too.
2307 IMPORT [STD]
2308 LET $msg: STRING = 'fixed:{{ STD::TEXT_REPLACE("hello world", "world", "there") }}'
2309 ASSERT_EQ $msg "fixed:hello there"
2310 "###
2311)]
2312fn text_replace<P: ProcessManager>(
2313 cx: &mut StepCtx<P>,
2314 #[union(String, Pipe)]
2316 text: Value,
2317 from: String,
2319 to: String,
2321) -> Result<Value> {
2322 super::args::mirror_stream(
2323 cx,
2324 "TEXT_REPLACE",
2325 &text,
2326 super::args::TextPump::ReplaceLiteral { from, to },
2327 )
2328}
2329
2330fn text_replace_string(text: Value, from: String, to: String) -> Result<Value> {
2333 super::args::mirror_string(
2334 "TEXT_REPLACE",
2335 &text,
2336 super::args::TextPump::ReplaceLiteral { from, to },
2337 )
2338}
2339
2340#[oxdock_func(
2352 rpn,
2353 returns = TypeTag::union(vec![TypeTag::String, TypeTag::Pipe]),
2354 template = text_replace_regex_string
2355)]
2356#[example(
2357 name = "replace with captures",
2358 code = r###"
2359 # Capture groups expand in the replacement.
2360 IMPORT [STD]
2361 LET $swapped: STRING = TEXT_REPLACE_REGEX("2026-10-13", "(\\d+)-(\\d+)-(\\d+)", "$3/$2/$1")
2362 ASSERT_EQ $swapped "13/10/2026"
2363 "###
2364)]
2365#[example(
2366 name = "replace regex pipe mirrors",
2367 code = r###"
2368 # Pipe input mints pipe output with the same rewrite.
2369 IMPORT [STD]
2370 LET $cap: PIPE
2371 WITH_IO [stdout=$cap] {
2372 ECHO "2026-10-13"
2373 }
2374 LET $trimmed: PIPE = TEXT_TRIM($cap)
2375 LET $out: PIPE = TEXT_REPLACE_REGEX($trimmed, "(\\d+)-(\\d+)-(\\d+)", "$3/$2/$1")
2376 WITH_IO [stdin=$out] READ_LINE $line
2377 ASSERT_EQ $line "13/10/2026"
2378 "###
2379)]
2380#[example(
2381 name = "replace regex template",
2382 code = r###"
2383 # String inputs run inside placeholders too.
2384 IMPORT [STD]
2385 LET $msg: STRING = 'swapped:{{ STD::TEXT_REPLACE_REGEX("2026-10-13", "(\\d+)-(\\d+)-(\\d+)", "$3/$2/$1") }}'
2386 ASSERT_EQ $msg "swapped:13/10/2026"
2387 "###
2388)]
2389fn text_replace_regex<P: ProcessManager>(
2390 cx: &mut StepCtx<P>,
2391 #[union(String, Pipe)]
2393 text: Value,
2394 pattern: String,
2396 replacement: String,
2398) -> Result<Value> {
2399 if let Some(s) = text.as_str() {
2400 let out =
2401 super::args::text_replace_regex_str(s, &pattern, &replacement, "TEXT_REPLACE_REGEX")?;
2402 return Ok(Value::string(out));
2403 }
2404 let content = super::args::read_pipe_eager(cx, "TEXT_REPLACE_REGEX", &text)?;
2405 let out = super::args::text_replace_regex_str(
2406 &content,
2407 &pattern,
2408 &replacement,
2409 "TEXT_REPLACE_REGEX",
2410 )?;
2411 super::args::write_completed_pipe(cx, "TEXT_REPLACE_REGEX", out)
2412}
2413
2414fn text_replace_regex_string(text: Value, pattern: String, replacement: String) -> Result<Value> {
2417 let Some(s) = text.as_str() else {
2418 return Err(super::args::pipe_needs_step_io("TEXT_REPLACE_REGEX"));
2419 };
2420 let out = super::args::text_replace_regex_str(s, &pattern, &replacement, "TEXT_REPLACE_REGEX")?;
2421 Ok(Value::string(out))
2422}
2423
2424#[oxdock_func(pure, returns = TypeTag::ListOf(std::sync::Arc::new(TypeTag::String)))]
2432#[example(
2433 name = "split",
2434 code = r###"
2435 # Delimiters split into list items.
2436 IMPORT [STD]
2437 LET $parts: LIST<STRING> = TEXT_SPLIT("a,b,c", ",")
2438 ASSERT_EQ $parts.0 "a"
2439 ASSERT_EQ $parts.1 "b"
2440 ASSERT_EQ $parts.2 "c"
2441 "###
2442)]
2443fn text_split(
2444 text: String,
2446 delimiter: String,
2448) -> Result<Value> {
2449 Ok(super::args::text_list_value(super::args::text_split_str(
2450 &text, &delimiter,
2451 )))
2452}
2453
2454#[oxdock_func(pure, returns = TypeTag::String)]
2457#[example(
2458 name = "join",
2459 code = r###"
2460 # List items join with the separator between them.
2461 IMPORT [STD]
2462 LET $joined: STRING = TEXT_JOIN(["a", "b", "c"], ",")
2463 ASSERT_EQ $joined "a,b,c"
2464 "###
2465)]
2466fn text_join(
2467 elements: Vec<String>,
2469 delimiter: String,
2471) -> Result<Value> {
2472 Ok(Value::string(elements.join(delimiter.as_str())))
2473}
2474
2475#[oxdock_func(pure, returns = TypeTag::ListOf(std::sync::Arc::new(TypeTag::String)))]
2487#[example(
2488 name = "split args",
2489 code = r###"
2490 # Quoted segments stay one word.
2491 IMPORT [STD]
2492 LET $argv: LIST<STRING> = SHELL_SPLIT_ARGS("gh issue comment 153 --body-file notes.md")
2493 ASSERT_EQ $argv.0 "gh"
2494 ASSERT_EQ $argv.3 "153"
2495 ASSERT_EQ $argv.5 "notes.md"
2496
2497 # Quotes and escapes parse the shell way.
2498 LET $quoted: LIST<STRING> = SHELL_SPLIT_ARGS("say \"hi there\" 'a b'")
2499 ASSERT_EQ $quoted.0 "say"
2500 ASSERT_EQ $quoted.1 "hi there"
2501 ASSERT_EQ $quoted.2 "a b"
2502 "###
2503)]
2504fn shell_split_args(
2505 command: String,
2507) -> Result<Value> {
2508 match shell_words::split(&command) {
2509 Ok(words) => Ok(super::args::text_list_value(words)),
2510 Err(err) => anyhow::bail!("SHELL_SPLIT_ARGS: {err}"),
2511 }
2512}
2513
2514#[oxdock_func(pure, returns = TypeTag::String)]
2522#[example(
2523 name = "join args",
2524 code = r###"
2525 # Plain words join with spaces and no quoting.
2526 IMPORT [STD]
2527 LET $plain: STRING = SHELL_JOIN_ARGS(["gh", "issue", "list"])
2528 ASSERT_EQ $plain "gh issue list"
2529
2530 # Words with spaces quote, and the round trip is exact.
2531 LET $words: LIST<STRING> = ["say", "hi there", "a'b"]
2532 LET $joined: STRING = SHELL_JOIN_ARGS($words)
2533 LET $back: LIST<STRING> = SHELL_SPLIT_ARGS($joined)
2534 ASSERT_EQ $back.0 "say"
2535 ASSERT_EQ $back.1 "hi there"
2536 ASSERT_EQ $back.2 "a'b"
2537 "###
2538)]
2539fn shell_join_args(
2540 words: Vec<String>,
2542) -> Result<Value> {
2543 Ok(Value::string(shell_words::join(&words)))
2544}
2545
2546#[oxdock_func(pure, returns = TypeTag::ListOf(std::sync::Arc::new(TypeTag::String)))]
2554#[example(
2555 name = "lines",
2556 code = r###"
2557 # Newlines split into line items.
2558 IMPORT [STD]
2559 LET $lines: LIST<STRING> = TEXT_LINES("one\ntwo\nthree")
2560 ASSERT_EQ $lines.0 "one"
2561 ASSERT_EQ $lines.1 "two"
2562 ASSERT_EQ $lines.2 "three"
2563
2564 # Windows endings split the same way after normalization.
2565 LET $crlf: LIST<STRING> = TEXT_LINES("one\r\ntwo\r\nthree")
2566 ASSERT_EQ $crlf.0 "one"
2567 ASSERT_EQ $crlf.1 "two"
2568 ASSERT_EQ $crlf.2 "three"
2569
2570 # Old Mac endings split too, and mixed endings split together because the input normalizes to LF before splitting.
2571 LET $mixed: LIST<STRING> = TEXT_LINES("a\r\nb\nc\rd")
2572 ASSERT_EQ $mixed.0 "a"
2573 ASSERT_EQ $mixed.1 "b"
2574 ASSERT_EQ $mixed.2 "c"
2575 ASSERT_EQ $mixed.3 "d"
2576 "###
2577)]
2578fn text_lines(
2579 text: String,
2581) -> Result<Value> {
2582 Ok(super::args::text_list_value(super::args::text_lines_str(
2583 &text,
2584 )))
2585}
2586
2587#[oxdock_func(pure, returns = TypeTag::ListOf(std::sync::Arc::new(TypeTag::String)))]
2593#[example(
2594 name = "fields",
2595 code = r###"
2596 # Runs of whitespace separate fields; empties never appear.
2597 IMPORT [STD]
2598 LET $fields: LIST<STRING> = TEXT_FIELDS(" abc def ")
2599 ASSERT_EQ $fields.0 "abc"
2600 ASSERT_EQ $fields.1 "def"
2601 "###
2602)]
2603fn text_fields(
2604 text: String,
2606) -> Result<Value> {
2607 Ok(super::args::text_list_value(super::args::text_fields_str(
2608 &text,
2609 )))
2610}
2611
2612#[oxdock_func(pure, returns = TypeTag::ListOf(std::sync::Arc::new(TypeTag::String)))]
2621#[example(
2622 name = "line range",
2623 code = r###"
2624 # Lines 2 through 3 come back as a list, 1-based inclusive.
2625 IMPORT [STD]
2626 LET $window: LIST<STRING> = TEXT_LINES_RANGE("one\ntwo\nthree\nfour", 2, 3)
2627 ASSERT_EQ $window.0 "two"
2628 ASSERT_EQ $window.1 "three"
2629
2630 # Ranges past the end clamp instead of failing.
2631 LET $tail: LIST<STRING> = TEXT_LINES_RANGE("one\ntwo", 2, 9)
2632 ASSERT_EQ $tail.0 "two"
2633 "###
2634)]
2635fn text_lines_range(
2636 text: String,
2638 from: i64,
2640 to: i64,
2642) -> Result<Value> {
2643 Ok(super::args::text_list_value(
2644 super::args::text_lines_range_str(&text, from, to, "TEXT_LINES_RANGE")?,
2645 ))
2646}
2647
2648#[oxdock_func(pure, returns = TypeTag::Bool)]
2656#[example(
2657 name = "match",
2658 code = r###"
2659 # Regex matches report true; misses report false.
2660 IMPORT [STD]
2661 LET $hit: BOOL = TEXT_MATCH("abc123", "\\d+")
2662 ASSERT_EQ $hit true
2663
2664 # A miss is false, not a failure.
2665 LET $miss: BOOL = TEXT_MATCH("abc", "^\\d+$")
2666 ASSERT_EQ $miss false
2667 "###
2668)]
2669fn text_match(
2670 text: String,
2672 pattern: String,
2674) -> Result<Value> {
2675 let re = super::args::text_compile_pattern("TEXT_MATCH", &pattern)?;
2676 Ok(Value::bool(re.is_match(&text)))
2677}
2678
2679#[oxdock_func(pure, returns = TypeTag::ListOf(std::sync::Arc::new(TypeTag::String)))]
2688#[example(
2689 name = "extract",
2690 code = r###"
2691 # Index zero is the full match; groups follow in order.
2692 IMPORT [STD]
2693 LET $caps: LIST<STRING> = TEXT_EXTRACT("abc123", "([a-z]+)(\\d+)")
2694 ASSERT_EQ $caps.0 "abc123"
2695 ASSERT_EQ $caps.1 "abc"
2696 ASSERT_EQ $caps.2 "123"
2697 "###
2698)]
2699fn text_extract(
2700 text: String,
2702 pattern: String,
2704) -> Result<Value> {
2705 let groups = super::args::text_extract_str(&text, &pattern, "TEXT_EXTRACT")?;
2706 Ok(super::args::text_list_value(groups))
2707}
2708
2709#[oxdock_func(pure, returns = TypeTag::Bool)]
2716#[example(
2717 name = "starts with",
2718 code = r###"
2719 # Present prefixes report true; misses report false.
2720 IMPORT [STD]
2721 LET $hit: BOOL = TEXT_STARTS_WITH("linux-musl-x64", "linux")
2722 ASSERT_EQ $hit true
2723
2724 # A miss is false, not a failure.
2725 LET $miss: BOOL = TEXT_STARTS_WITH("macos-arm", "linux")
2726 ASSERT_EQ $miss false
2727 "###
2728)]
2729fn text_starts_with(
2730 text: String,
2732 prefix: String,
2734) -> Result<Value> {
2735 Ok(Value::bool(text.starts_with(prefix.as_str())))
2736}
2737
2738#[oxdock_func(pure, returns = TypeTag::Bool)]
2745#[example(
2746 name = "ends with",
2747 code = r###"
2748 # Present suffixes report true; misses report false.
2749 IMPORT [STD]
2750 LET $hit: BOOL = TEXT_ENDS_WITH("x86_64-linux-musl", "linux-musl")
2751 ASSERT_EQ $hit true
2752
2753 # A miss is false, not a failure.
2754 LET $miss: BOOL = TEXT_ENDS_WITH("x86_64-linux-gnu", "linux-musl")
2755 ASSERT_EQ $miss false
2756 "###
2757)]
2758fn text_ends_with(
2759 text: String,
2761 suffix: String,
2763) -> Result<Value> {
2764 Ok(Value::bool(text.ends_with(suffix.as_str())))
2765}
2766
2767#[oxdock_func(pure, returns = TypeTag::Bool)]
2774#[example(
2775 name = "contains",
2776 code = r###"
2777 # Present needles report true; misses report false.
2778 IMPORT [STD]
2779 LET $hit: BOOL = TEXT_CONTAINS("x86_64-linux-musl", "musl")
2780 ASSERT_EQ $hit true
2781
2782 # A miss is false, not a failure.
2783 LET $miss: BOOL = TEXT_CONTAINS("x86_64-linux-gnu", "musl")
2784 ASSERT_EQ $miss false
2785 "###
2786)]
2787fn text_contains(
2788 text: String,
2790 needle: String,
2792) -> Result<Value> {
2793 Ok(Value::bool(text.contains(needle.as_str())))
2794}
2795
2796#[oxdock_func(pure, returns = TypeTag::Int)]
2803#[example(
2804 name = "length",
2805 code = r###"
2806 # Plain text counts one per character.
2807 IMPORT [STD]
2808 LET $n: INT = TEXT_LENGTH("hello")
2809 ASSERT_EQ $n 5
2810
2811 # Multibyte characters count once each, not per byte.
2812 LET $wide: INT = TEXT_LENGTH("héllo")
2813 ASSERT_EQ $wide 5
2814 "###
2815)]
2816fn text_length(
2817 text: String,
2819) -> Result<Value> {
2820 Ok(Value::int(text.chars().count() as i64))
2821}
2822
2823#[oxdock_func(pure, returns = TypeTag::Int)]
2831#[example(
2832 name = "count",
2833 code = r###"
2834 # Every non-overlapping occurrence counts once.
2835 IMPORT [STD]
2836 LET $n: INT = TEXT_COUNT("hello world", "o")
2837 ASSERT_EQ $n 2
2838
2839 # Overlapping candidates never double count.
2840 LET $once: INT = TEXT_COUNT("aaa", "aa")
2841 ASSERT_EQ $once 1
2842 "###
2843)]
2844fn text_count(
2845 text: String,
2847 needle: String,
2849) -> Result<Value> {
2850 let n = super::args::text_count_str(&text, &needle, "TEXT_COUNT")?;
2851 Ok(Value::int(n))
2852}
2853
2854#[oxdock_func(pure, returns = TypeTag::Int)]
2864#[example(
2865 name = "count matches",
2866 code = r###"
2867 # One line matches once no matter how many times it hits.
2868 IMPORT [STD]
2869 LET $n: INT = TEXT_COUNT_MATCHES("test a: test\ntest b: nope\ntest c: test", ": test")
2870 ASSERT_EQ $n 2
2871
2872 # A miss binds zero, never an error.
2873 LET $none: INT = TEXT_COUNT_MATCHES("test b: nope", ": test$")
2874 ASSERT_EQ $none 0
2875 "###
2876)]
2877fn text_count_matches(
2878 text: String,
2880 pattern: String,
2882) -> Result<Value> {
2883 let n = super::args::text_count_matches_str(&text, &pattern, "TEXT_COUNT_MATCHES")?;
2884 Ok(Value::int(n))
2885}
2886
2887#[oxdock_func(pure, returns = TypeTag::ListOf(std::sync::Arc::new(TypeTag::String)))]
2900#[example(
2901 name = "grep",
2902 code = r###"
2903 # Matching lines come back as a list, in order.
2904 IMPORT [STD]
2905 LET $hits: LIST<STRING> = TEXT_GREP("one\ntwo\none more", "^one")
2906 ASSERT_EQ $hits.0 "one"
2907 ASSERT_EQ $hits.1 "one more"
2908
2909 # A miss binds an empty list, never an error.
2910 LET $miss: LIST<STRING> = TEXT_GREP("one\ntwo", "^z")
2911 LET $joined: STRING = TEXT_JOIN($miss, ",")
2912 ASSERT_EQ $joined ""
2913
2914 # The (?i) flag ignores case, so uppercase lines match too.
2915 LET $folded: LIST<STRING> = TEXT_GREP("One\ntwo\nONE more", "(?i)^one")
2916 ASSERT_EQ $folded.0 "One"
2917 ASSERT_EQ $folded.1 "ONE more"
2918 "###
2919)]
2920#[example(
2921 name = "grep invert",
2922 code = r###"
2923 # The invert option keeps every non-matching line instead.
2924 IMPORT [STD]
2925 LET $kept: LIST<STRING> = TEXT_GREP("one\ntwo\none more", "^one", {invert: true})
2926 ASSERT_EQ $kept.0 "two"
2927
2928 # A pattern matching every line binds an empty list, never an error.
2929 LET $none: LIST<STRING> = TEXT_GREP("one\ntwo", "^", {invert: true})
2930 LET $joined: STRING = TEXT_JOIN($none, ",")
2931 ASSERT_EQ $joined ""
2932
2933 # Options ride into placeholders as MAP literals. Placeholder
2934 # strings unescape only backslash and quote, so multiline text
2935 # arrives through a variable.
2936 LET $two_lines: STRING = "one\ntwo"
2937 LET $msg: STRING = 'kept:{{ STD::TEXT_GREP($two_lines, "^one", {invert: true}) }}'
2938 ASSERT_EQ $msg "kept:two"
2939 "###
2940)]
2941fn text_grep(
2942 text: String,
2944 pattern: String,
2946 #[options("invert?: BOOL")]
2948 #[optional]
2949 options: BTreeMap<String, Value>,
2950) -> Result<Value> {
2951 let invert = super::args::text_invert_flag(&options);
2954 Ok(super::args::text_list_value(super::args::text_grep_str(
2955 &text,
2956 &pattern,
2957 invert,
2958 "TEXT_GREP",
2959 )?))
2960}
2961
2962#[oxdock_func(returns = TypeTag::Bool)]
2973#[example(
2974 name = "drain to end",
2975 code = r###"
2976 # Capture two lines, then drain to end of stream with no sentinel line.
2977 IMPORT [STD]
2978 LET $cap: PIPE
2979 WITH_IO [stdout=$cap] {
2980 ECHO "one"
2981 ECHO "two"
2982 }
2983
2984 # The loop exits on close, and the count proves both lines drained.
2985 LET $n: INT = 0
2986 WHILE !EOF($cap) {
2987 WITH_IO [stdin=$cap] READ_LINE $line
2988 $n = $n + 1
2989 }
2990 ASSERT_EQ $n 2
2991 "###
2992)]
2993fn eof<P: ProcessManager>(
2994 cx: &mut StepCtx<P>,
2995 pipe: PipeHandle,
2997) -> Result<Value> {
2998 let info = cx.state.io.inspect_pipe(&pipe);
2999 Ok(Value::bool(info.closed && info.buffered == 0))
3000}
3001
3002fn task_poll_result_fields() -> Arc<[Field]> {
3006 Arc::from(vec![
3007 Field {
3008 name: "state".to_string(),
3009 ty: TypeTag::String,
3010 docs: "Task phase: `running` or `finished`.",
3011 optional: false,
3012 },
3013 Field {
3014 name: "ok".to_string(),
3015 ty: TypeTag::Bool,
3016 docs: "True unless the task failed.",
3017 optional: false,
3018 },
3019 Field {
3020 name: "stdout_tail".to_string(),
3021 ty: TypeTag::String,
3022 docs: "Bounded stdout tail, live while running.",
3023 optional: false,
3024 },
3025 Field {
3026 name: "stderr_tail".to_string(),
3027 ty: TypeTag::String,
3028 docs: "Bounded stderr tail, live while running.",
3029 optional: false,
3030 },
3031 Field {
3032 name: "truncated_bytes".to_string(),
3033 ty: TypeTag::Int,
3034 docs: "Dropped head bytes past the per-stream cap.",
3035 optional: false,
3036 },
3037 Field {
3038 name: "exit_code".to_string(),
3039 ty: TypeTag::Int,
3040 docs: "Process exit code, present once finished.",
3041 optional: true,
3042 },
3043 Field {
3044 name: "result".to_string(),
3045 ty: TypeTag::Any,
3046 docs: "Task `RETURN` value, present on clean finish.",
3047 optional: true,
3048 },
3049 Field {
3050 name: "error".to_string(),
3051 ty: TypeTag::String,
3052 docs: "Failure text, present on failed finish.",
3053 optional: true,
3054 },
3055 ])
3056}
3057
3058#[oxdock_func(returns = TypeTag::Record(task_poll_result_fields()))]
3071#[example(
3072 name = "running poll",
3073 code = r###"
3074 # A sleeping task is still running on the first poll.
3075 IMPORT [STD]
3076 LET $t: HANDLE = ASYNC { SLEEP 30s }
3077 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)
3078 ASSERT_EQ $m.state "running"
3079 ASSERT_EQ $m.ok true
3080 # Clean up the sleeper so the run ends promptly.
3081 CANCEL $t
3082 "###
3083)]
3084#[example(
3085 name = "finished poll",
3086 code = r###"
3087 # A finished task reports its value and final tails, then still awaits.
3088 IMPORT [STD]
3089 LET $t: HANDLE = ASYNC { ECHO "hi"; SLEEP 1s; RETURN "done" }
3090 # Do other work while the task runs; poll once it should be done.
3091 SLEEP 2s
3092 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)
3093 ASSERT_EQ $m.state "finished"
3094 ASSERT_EQ $m.result "done"
3095 LET $o: STRING = AWAIT $t
3096 ASSERT_EQ $o "done"
3097 "###
3098)]
3099fn task_poll<P: ProcessManager>(
3100 cx: &mut StepCtx<P>,
3101 task: HandleValue,
3103) -> Result<Value> {
3104 let entry =
3105 super::handlers::resolve_task_entry_by_id(task.0, &format!("TASK_POLL({})", task.0), cx)?;
3106 let obs = entry.observe_completion();
3107 let (stdout_tail, stderr_tail, dropped) = entry.snapshot_tails();
3108 let mut out = BTreeMap::new();
3109 out.insert(
3110 "state".to_string(),
3111 Value::string(if obs.running { "running" } else { "finished" }.to_string()),
3112 );
3113 out.insert("ok".to_string(), Value::bool(obs.ok));
3114 if !obs.running {
3115 out.insert("exit_code".to_string(), Value::int(obs.exit_code));
3116 }
3117 if let Some(result) = obs.result {
3118 out.insert("result".to_string(), result);
3119 }
3120 if !obs.error.is_empty() {
3121 out.insert("error".to_string(), Value::string(obs.error));
3122 }
3123 out.insert("stdout_tail".to_string(), Value::string(stdout_tail));
3124 out.insert("stderr_tail".to_string(), Value::string(stderr_tail));
3125 out.insert(
3126 "truncated_bytes".to_string(),
3127 Value::int(dropped.min(i64::MAX as u64) as i64),
3128 );
3129 Ok(Value::map(out))
3130}
3131
3132fn meta_to_value(meta: &FuncMeta) -> Value {
3133 let mut map = BTreeMap::new();
3134 map.insert("name".to_string(), Value::string(meta.name.clone()));
3135 map.insert("module".to_string(), Value::string(meta.module.clone()));
3136 map.insert(
3137 "kind".to_string(),
3138 Value::string(meta.kind.label().to_string()),
3139 );
3140 let params = match &meta.params {
3141 Some(params) => Value::list(
3142 params
3143 .iter()
3144 .map(|p| {
3145 let mut entry = BTreeMap::new();
3146 entry.insert("name".to_string(), Value::string(p.name.clone()));
3147 entry.insert(
3148 "param_type".to_string(),
3149 Value::string(
3150 p.param_type
3151 .as_ref()
3152 .map(render_structural)
3153 .unwrap_or_default(),
3154 ),
3155 );
3156 entry.insert(
3157 "allowed".to_string(),
3158 Value::string(
3159 p.allowed
3160 .map(|values| values.join(", "))
3161 .unwrap_or_default(),
3162 ),
3163 );
3164 entry.insert("docs".to_string(), Value::string(String::new()));
3165 entry.insert("optional".to_string(), Value::bool(p.optional));
3166 entry.insert(
3167 "options".to_string(),
3168 match p.options {
3169 Some(keys) => Value::list(
3170 keys.iter()
3171 .map(|key| {
3172 let mut option = BTreeMap::new();
3173 option.insert(
3174 "name".to_string(),
3175 Value::string(key.name.to_string()),
3176 );
3177 option.insert(
3178 "value_type".to_string(),
3179 Value::string(render_structural(&key.value)),
3180 );
3181 option.insert(
3182 "required".to_string(),
3183 Value::bool(key.required),
3184 );
3185 option.insert(
3186 "default".to_string(),
3187 Value::string(
3188 key.default.unwrap_or_default().to_string(),
3189 ),
3190 );
3191 Value::map(option)
3192 })
3193 .collect(),
3194 ),
3195 None => Value::string(String::new()),
3196 },
3197 );
3198 Value::map(entry)
3199 })
3200 .collect(),
3201 ),
3202 None => Value::list(Vec::new()),
3206 };
3207 map.insert("params".to_string(), params);
3208 map.insert(
3209 "returns".to_string(),
3210 Value::string(
3211 meta.returns
3212 .as_ref()
3213 .map(render_structural)
3214 .unwrap_or_default(),
3215 ),
3216 );
3217 map.insert("rpn".to_string(), Value::bool(meta.rpn));
3218 map.insert(
3219 "summary".to_string(),
3220 Value::string(meta.summary.to_string()),
3221 );
3222 Value::map(map)
3223}
3224
3225#[derive(Debug, Clone)]
3229pub struct RecordSchema {
3230 pub name: &'static str,
3231 pub fields: std::sync::Arc<[Field]>,
3232}
3233
3234#[derive(Clone)]
3238pub struct HostModule<P: ProcessManager> {
3239 pub name: String,
3240 pub funcs: Vec<HostRegistration<P>>,
3241 pub types: Vec<&'static TypeDescriptor>,
3242 pub record_schemas: Vec<RecordSchema>,
3243 pub states: Vec<ModuleState>,
3250}
3251
3252#[derive(Clone)]
3256pub struct ModuleState {
3257 id: std::any::TypeId,
3258 state: std::sync::Arc<dyn std::any::Any + Send + Sync>,
3259}
3260
3261pub type PreRunInspector = dyn Fn(&[Step]) -> Result<()> + Send + Sync;
3265
3266#[derive(Clone)]
3272pub struct PreRunCheck {
3273 check: Arc<PreRunInspector>,
3274}
3275
3276impl PreRunCheck {
3277 pub fn new(check: impl Fn(&[Step]) -> Result<()> + Send + Sync + 'static) -> Self {
3279 Self {
3280 check: Arc::new(check),
3281 }
3282 }
3283
3284 pub fn run(&self, steps: &[Step]) -> Result<()> {
3286 (self.check)(steps)
3287 }
3288}
3289
3290impl<P: ProcessManager> HostModule<P> {
3291 pub fn with_state<T: Send + Sync + 'static>(mut self, state: std::sync::Arc<T>) -> Self {
3294 self.states.push(ModuleState {
3295 id: std::any::TypeId::of::<T>(),
3296 state,
3297 });
3298 self
3299 }
3300
3301 pub fn check_pre_run(&self, steps: &[Step]) -> Result<()> {
3305 for state in &self.states {
3306 if let Some(check) = state.state.downcast_ref::<PreRunCheck>() {
3307 check.run(steps)?;
3308 }
3309 }
3310 Ok(())
3311 }
3312}
3313
3314impl<P: ProcessManager> ExecState<P> {
3315 pub fn register_module(&mut self, module: HostModule<P>) {
3318 for registration in module.funcs {
3319 match registration {
3320 HostRegistration::Stateful { name, meta, func } => {
3321 self.functions.register_host(&module.name, name, meta, func);
3322 }
3323 HostRegistration::Pure { name, meta, func } => {
3324 self.functions
3325 .register_pure_host(&module.name, name, meta, func);
3326 }
3327 HostRegistration::Both {
3328 name,
3329 meta,
3330 func,
3331 template,
3332 } => {
3333 self.functions
3334 .register_both_host(&module.name, name, meta, func, template);
3335 }
3336 }
3337 }
3338 for descriptor in module.types {
3339 self.register_type(descriptor);
3340 }
3341 for schema in module.record_schemas {
3342 self.register_record_schema(schema.name, schema.fields);
3343 }
3344 for state in module.states {
3345 self.module_states
3346 .insert((module.name.clone(), state.id), state.state);
3347 }
3348 }
3349
3350 pub fn list_functions(&self) -> Vec<FuncMeta> {
3352 let mut out: Vec<FuncMeta> = self.functions.entries_metas().into_iter().collect();
3353 if !out.iter().any(|m| m.name == KEYWORD_INSPECT) {
3355 out.push(FuncMeta {
3356 name: KEYWORD_INSPECT.to_string(),
3357 module: STD_MODULE_NAME.to_string(),
3358 kind: FuncKind::HostCtx,
3359 params: None,
3360 returns: Some(TypeTag::Map),
3361 rpn: false,
3362 summary: "Inspect a variable binding.",
3363 docs: "INSPECT($var): dedicated AST node taking a variable, not a value.",
3364 examples: &[],
3365 });
3366 }
3367 out.sort_by(|a, b| a.name.cmp(&b.name));
3368 out
3369 }
3370
3371 pub fn describe_function(&self, name: &str) -> Option<Value> {
3373 if let Some(meta) = self.functions.meta(name) {
3374 return Some(meta_to_value(&meta));
3375 }
3376 if name == KEYWORD_INSPECT {
3378 return Some(meta_to_value(&FuncMeta {
3379 name: KEYWORD_INSPECT.to_string(),
3380 module: STD_MODULE_NAME.to_string(),
3381 kind: FuncKind::HostCtx,
3382 params: None,
3383 returns: Some(TypeTag::Map),
3384 rpn: false,
3385 summary: "Inspect a variable binding.",
3386 docs: "INSPECT($var): dedicated AST node taking a variable, not a value.",
3387 examples: &[],
3388 }));
3389 }
3390 None
3391 }
3392
3393 pub(super) fn clone_native_pure(&self, name: &str) -> Option<PureFn> {
3394 self.functions.clone_pure_fn(name)
3395 }
3396
3397 pub fn pure_function_table(&self) -> Arc<PureTable> {
3402 self.functions.pure_shared()
3403 }
3404
3405 pub(super) fn clone_native_ctx(&self, name: &str) -> Option<NativeFn<P>> {
3406 self.functions.clone_ctx_fn(name)
3407 }
3408
3409 pub(super) fn native_meta(&self, name: &str) -> Option<FuncMeta> {
3410 self.functions.meta(name)
3411 }
3412}
3413
3414#[cfg(test)]
3415mod tests {
3416 use super::*;
3417
3418 #[test]
3419 fn describe_entry_renders_union_spellings() {
3420 let union = oxdock_parser::union_tag!(String, Pipe);
3426 let meta = FuncMeta {
3427 name: "T::F".to_string(),
3428 module: "T".to_string(),
3429 kind: FuncKind::HostPure,
3430 params: Some(vec![FuncParam {
3431 name: "text".to_string(),
3432 param_type: Some(union.clone()),
3433 allowed: None,
3434 docs: "",
3435 options: None,
3436 optional: false,
3437 }]),
3438 returns: Some(union),
3439 rpn: false,
3440 summary: "test-only",
3441 docs: "test-only",
3442 examples: &[],
3443 };
3444 let value = meta_to_value(&meta);
3445 let map = value.as_map().expect("describe value is a map");
3446 let params = map
3447 .get("params")
3448 .expect("params key")
3449 .as_list()
3450 .expect("params is a list");
3451 let first = params[0].as_map().expect("entry is a map");
3452 assert_eq!(
3453 first.get("param_type").and_then(Value::as_str),
3454 Some("STRING|PIPE"),
3455 "param renders the set"
3456 );
3457 assert_eq!(
3458 map.get("returns").and_then(Value::as_str),
3459 Some("STRING|PIPE"),
3460 "returns render the set"
3461 );
3462 }
3463
3464 #[test]
3465 fn describe_entry_carries_optional_flag() {
3466 let meta = FuncMeta {
3470 name: "T::F".to_string(),
3471 module: "T".to_string(),
3472 kind: FuncKind::HostPure,
3473 params: Some(vec![
3474 FuncParam {
3475 name: "url".to_string(),
3476 param_type: Some(TypeTag::String),
3477 allowed: None,
3478 docs: "",
3479 options: None,
3480 optional: false,
3481 },
3482 FuncParam {
3483 name: "options".to_string(),
3484 param_type: Some(TypeTag::Map),
3485 allowed: None,
3486 docs: "",
3487 options: None,
3488 optional: true,
3489 },
3490 ]),
3491 returns: Some(TypeTag::String),
3492 rpn: false,
3493 summary: "test-only",
3494 docs: "test-only",
3495 examples: &[],
3496 };
3497 let value = meta_to_value(&meta);
3498 let map = value.as_map().expect("describe value is a map");
3499 let params = map
3500 .get("params")
3501 .expect("params key")
3502 .as_list()
3503 .expect("params is a list");
3504 assert_eq!(params.len(), 2);
3505 let first = params[0].as_map().expect("entry is a map");
3506 let second = params[1].as_map().expect("entry is a map");
3507 assert_eq!(
3508 first.get("optional").and_then(Value::as_bool),
3509 Some(false),
3510 "required param must read false"
3511 );
3512 assert_eq!(
3513 second.get("optional").and_then(Value::as_bool),
3514 Some(true),
3515 "omittable param must read true"
3516 );
3517 }
3518
3519 #[test]
3520 fn template_twins_mirror_string_paths_and_refuse_pipes() {
3521 let pipe = Value::pipe_fresh();
3527 type TwinCase = (&'static str, Box<dyn Fn() -> Result<Value>>);
3528 let cases: Vec<TwinCase> = vec![
3529 (
3530 "TEXT_TRIM",
3531 Box::new(|| text_trim_string(Value::string(" hello ".to_string()))),
3532 ),
3533 (
3534 "TEXT_TRIM_PREFIX",
3535 Box::new(|| {
3536 text_trim_prefix_string(Value::string("v1".to_string()), "v".to_string())
3537 }),
3538 ),
3539 (
3540 "TEXT_TRIM_SUFFIX",
3541 Box::new(|| {
3542 text_trim_suffix_string(Value::string("a.gz".to_string()), "x".to_string())
3543 }),
3544 ),
3545 (
3546 "TEXT_TO_UPPER",
3547 Box::new(|| text_to_upper_string(Value::string("hi".to_string()))),
3548 ),
3549 (
3550 "TEXT_TO_LOWER",
3551 Box::new(|| text_to_lower_string(Value::string("HI".to_string()))),
3552 ),
3553 (
3554 "TEXT_REPLACE",
3555 Box::new(|| {
3556 text_replace_string(
3557 Value::string("ab".to_string()),
3558 "b".to_string(),
3559 "c".to_string(),
3560 )
3561 }),
3562 ),
3563 (
3564 "TEXT_REPLACE_REGEX",
3565 Box::new(|| {
3566 text_replace_regex_string(
3567 Value::string("ab".to_string()),
3568 "b".to_string(),
3569 "c".to_string(),
3570 )
3571 }),
3572 ),
3573 ];
3574 assert_eq!(cases.len(), 7, "every mirror op needs a twin row");
3575 for (name, run) in &cases {
3576 let value = run().unwrap_or_else(|e| panic!("{name} twin must answer strings: {e:#}"));
3577 assert!(
3578 value.as_str().is_some(),
3579 "{name} twin must answer STRING, got {}",
3580 value.type_name()
3581 );
3582 }
3583 assert_eq!(
3584 text_trim_string(Value::string(" hello ".to_string()))
3585 .expect("trim twin")
3586 .as_str(),
3587 Some("hello")
3588 );
3589 let pipe_cases: Vec<(&str, Result<Value>)> = vec![
3591 ("TEXT_TRIM", text_trim_string(pipe.clone())),
3592 (
3593 "TEXT_TRIM_PREFIX",
3594 text_trim_prefix_string(pipe.clone(), "v".to_string()),
3595 ),
3596 (
3597 "TEXT_TRIM_SUFFIX",
3598 text_trim_suffix_string(pipe.clone(), ".gz".to_string()),
3599 ),
3600 ("TEXT_TO_UPPER", text_to_upper_string(pipe.clone())),
3601 ("TEXT_TO_LOWER", text_to_lower_string(pipe.clone())),
3602 (
3603 "TEXT_REPLACE",
3604 text_replace_string(pipe.clone(), "a".to_string(), "b".to_string()),
3605 ),
3606 (
3607 "TEXT_REPLACE_REGEX",
3608 text_replace_regex_string(pipe.clone(), "a".to_string(), "b".to_string()),
3609 ),
3610 ];
3611 for (name, result) in pipe_cases {
3612 let err = result.expect_err(&format!("{name} twin must refuse PIPE"));
3613 assert!(
3614 format!("{err:#}").contains("step IO"),
3615 "{name} refusal names the missing context: {err:#}"
3616 );
3617 }
3618 }
3619
3620 #[test]
3621 fn shell_words_join_split_round_trip() {
3622 let words = vec![
3626 "gh".to_string(),
3627 "issue".to_string(),
3628 "comment".to_string(),
3629 "with spaces".to_string(),
3630 "it's".to_string(),
3631 "say \"hi\"".to_string(),
3632 "$HOME".to_string(),
3633 "$(whoami)".to_string(),
3634 "C:\\path\\to".to_string(),
3635 "naïve café".to_string(),
3636 "".to_string(),
3637 ];
3638 let joined = shell_words::join(&words);
3639 let back = shell_words::split(&joined).expect("join output must parse");
3640 assert_eq!(back, words);
3641 assert!(shell_words::split("unbalanced \"quote").is_err());
3642 }
3643}