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 TextToUpper::registration(),
397 TextToLower::registration(),
398 TextReplace::registration(),
399 TextReplaceRegex::registration(),
400 TextSplit::registration(),
401 TextJoin::registration(),
402 TextLines::registration(),
403 TextFields::registration(),
404 TextMatch::registration(),
405 TextExtract::registration(),
406 TextStartsWith::registration(),
407 TextEndsWith::registration(),
408 TextContains::registration(),
409 TextLength::registration(),
410 TextCount::registration(),
411 TextCountMatches::registration(),
412 TextGrep::registration(),
413 TextLinesRange::registration(),
414 SemaphoreNew::registration(),
415 SemaphoreTryAcquire::registration(),
416 SemaphoreAvailable::registration(),
417 ShellSplitArgs::registration(),
418 ShellJoinArgs::registration(),
419 ]
420 }
421
422 pub(super) fn keys(&self) -> HashSet<String> {
425 self.entries.keys().cloned().collect()
426 }
427
428 pub(super) fn get(&self, name: &str) -> Option<FuncEntry<P>> {
430 self.entries.get(name).cloned()
431 }
432
433 fn insert_native(&mut self, name: String, meta: FuncMeta, body: FuncBody<P>) {
434 self.entries.insert(name, FuncEntry { meta, body });
435 self.rebuild_pure_shared();
436 }
437
438 fn rebuild_pure_shared(&mut self) {
444 let mut table: PureTable = HashMap::new();
445 for (name, entry) in &self.entries {
446 let func = match &entry.body {
447 FuncBody::Pure(func) => func,
448 FuncBody::Both { pure, .. } => pure,
449 FuncBody::Script(_) | FuncBody::Ctx(_) => continue,
450 };
451 if let Some((module, base)) = split_qualified(name) {
452 table
453 .entry(module.to_string())
454 .or_default()
455 .insert(base.to_string(), Arc::clone(func));
456 }
457 }
458 self.pure_shared = Arc::new(table);
459 }
460
461 fn insert_qualified(
465 &mut self,
466 module: &str,
467 base: String,
468 mut meta: FuncMeta,
469 body: FuncBody<P>,
470 ) {
471 meta.name = qualify(module, &base);
472 meta.module = module.to_string();
473 if self.entries.contains_key(&meta.name) {
478 panic!("duplicate function registration `{}`", meta.name);
479 }
480 self.insert_native(meta.name.clone(), meta, body);
481 }
482
483 pub(super) fn register_host(
484 &mut self,
485 module: &str,
486 name: String,
487 mut meta: FuncMeta,
488 func: NativeFn<P>,
489 ) {
490 meta.kind = FuncKind::HostCtx;
491 self.insert_qualified(module, name, meta, FuncBody::Ctx(func));
492 }
493
494 pub(super) fn register_pure_host(
495 &mut self,
496 module: &str,
497 name: String,
498 mut meta: FuncMeta,
499 func: PureFn,
500 ) {
501 meta.kind = FuncKind::HostPure;
502 self.insert_qualified(module, name, meta, FuncBody::Pure(func));
503 }
504
505 pub(super) fn register_both_host(
506 &mut self,
507 module: &str,
508 name: String,
509 mut meta: FuncMeta,
510 func: NativeFn<P>,
511 template: PureFn,
512 ) {
513 meta.kind = FuncKind::HostCtx;
514 self.insert_qualified(
515 module,
516 name,
517 meta,
518 FuncBody::Both {
519 pure: template,
520 ctx: func,
521 },
522 );
523 }
524
525 pub(super) fn define_script(
530 &mut self,
531 name: &str,
532 params: &[(String, TypeTag)],
533 body: &[Step],
534 ) -> Result<()> {
535 let qualified = qualify(SCRIPT_MODULE_NAME, name);
536 let shadowable = matches!(
537 self.entries.get(&qualified).map(|entry| &entry.body),
538 Some(FuncBody::Script(_))
539 );
540 let reserved = self
543 .entries
544 .keys()
545 .any(|key| split_qualified(key).is_some_and(|(_, base)| base == name));
546 if reserved && !shadowable {
547 anyhow::bail!("cannot shadow reserved function `{name}`");
548 }
549 if self
550 .scopes
551 .last()
552 .is_some_and(|frame| frame.defined.contains(&qualified))
553 {
554 anyhow::bail!("duplicate function `{name}` in same scope");
555 }
556 let old = self.entries.insert(
557 qualified.clone(),
558 FuncEntry {
559 meta: FuncMeta {
560 name: qualified.clone(),
561 module: SCRIPT_MODULE_NAME.to_string(),
562 kind: FuncKind::Script,
563 params: Some(
564 params
565 .iter()
566 .map(|(name, param_type)| FuncParam {
567 name: name.clone(),
568 param_type: Some(param_type.clone()),
569 allowed: None,
570 docs: "",
573 options: None,
574 optional: false,
575 })
576 .collect(),
577 ),
578 returns: None,
579 rpn: false,
580 summary: "DSL-defined function.",
581 docs: "Defined via FUNC in script.",
582 examples: &[],
583 },
584 body: FuncBody::Script(FuncDefData {
585 params: params.to_vec(),
586 body: body.to_vec(),
587 }),
588 },
589 );
590 if let Some(frame) = self.scopes.last_mut() {
591 frame.defined.insert(qualified.clone());
592 if let Some(old) = old {
593 frame.shadowed.push((qualified, old));
594 }
595 }
596 Ok(())
597 }
598
599 pub(super) fn push_scope(&mut self) {
602 self.scopes.push(ScopeFrame {
603 defined: HashSet::new(),
604 shadowed: Vec::new(),
605 });
606 }
607
608 pub(super) fn pop_scope(&mut self) {
611 let Some(frame) = self.scopes.pop() else {
612 return;
613 };
614 for name in frame.defined {
615 self.entries.remove(&name);
616 }
617 for (name, old) in frame.shadowed {
618 self.entries.insert(name, old);
619 }
620 }
621
622 pub(super) fn contains_script(&self, name: &str) -> bool {
626 matches!(
627 self.entries.get(name).map(|entry| &entry.body),
628 Some(FuncBody::Script(_))
629 )
630 }
631
632 fn clone_pure_fn(&self, name: &str) -> Option<PureFn> {
636 match self.entries.get(name)?.body {
637 FuncBody::Pure(ref func) => Some(Arc::clone(func)),
638 FuncBody::Both { ref pure, .. } => Some(Arc::clone(pure)),
639 _ => None,
640 }
641 }
642
643 pub(super) fn pure_shared(&self) -> Arc<PureTable> {
647 Arc::clone(&self.pure_shared)
648 }
649
650 pub(super) fn all_metas(&self) -> Vec<FuncMeta> {
653 self.entries_metas()
654 }
655
656 fn clone_ctx_fn(&self, name: &str) -> Option<NativeFn<P>> {
661 match self.entries.get(name)?.body {
662 FuncBody::Ctx(ref func) => Some(Arc::clone(func)),
663 FuncBody::Both { ref ctx, .. } => Some(Arc::clone(ctx)),
664 _ => None,
665 }
666 }
667
668 fn meta(&self, name: &str) -> Option<FuncMeta> {
669 self.entries.get(name).map(|entry| entry.meta.clone())
670 }
671
672 fn native_metas(&self) -> Vec<FuncMeta> {
673 let mut out: Vec<FuncMeta> = Vec::new();
674 for entry in self.entries.values() {
675 if !matches!(entry.body, FuncBody::Script(_)) {
676 out.push(entry.meta.clone());
677 }
678 }
679 out.sort_by(|a, b| a.name.cmp(&b.name));
680 out
681 }
682
683 fn entries_metas(&self) -> Vec<FuncMeta> {
686 let mut out: Vec<FuncMeta> = self
687 .entries
688 .values()
689 .map(|entry| entry.meta.clone())
690 .collect();
691 out.sort_by(|a, b| a.name.cmp(&b.name));
692 out
693 }
694
695 pub fn set_script_docs(&mut self, docs: &HashMap<String, (String, String)>) {
698 for (base, pair) in docs {
699 self.script_docs
700 .insert(qualify(SCRIPT_MODULE_NAME, base), pair.clone());
701 }
702 }
703
704 pub fn script_doc_for(&self, qualified: &str) -> Option<(String, String)> {
706 self.script_docs.get(qualified).cloned()
707 }
708
709 pub fn exported_metas(&self, exports: &[String]) -> anyhow::Result<Vec<FuncMeta>> {
712 let mut out = Vec::with_capacity(exports.len());
713 for name in exports {
714 let qualified = match name.split_once("::") {
718 None => qualify(SCRIPT_MODULE_NAME, name),
719 Some(_) => name.clone(),
720 };
721 match self.entries.get(&qualified) {
722 Some(entry) => out.push(entry.meta.clone()),
723 None => anyhow::bail!(
724 "EXPORT `{name}` matches no defined script function or known host function"
725 ),
726 }
727 }
728 Ok(out)
729 }
730}
731
732impl<P: ProcessManager> Clone for FunctionRegistry<P> {
733 fn clone(&self) -> Self {
734 Self {
735 entries: self.entries.clone(),
736 scopes: self.scopes.clone(),
737 pure_shared: Arc::clone(&self.pure_shared),
738 script_docs: self.script_docs.clone(),
739 }
740 }
741}
742
743pub fn builtin_function_names() -> HashSet<String> {
750 let mut names = FunctionRegistry::<DefaultProcessManager>::with_builtins().keys();
751 names.insert(KEYWORD_INSPECT.to_string());
752 names
753}
754
755pub fn builtin_function_metas() -> Vec<FuncMeta> {
759 FunctionRegistry::<DefaultProcessManager>::with_builtins().native_metas()
760}
761
762pub fn std_module_table() -> oxdock_parser::ModuleTable {
767 let functions: HashSet<String> = builtin_function_metas()
769 .into_iter()
770 .map(|meta| base_name(&meta.name).to_string())
771 .collect();
772 oxdock_parser::ModuleTable {
773 modules: HashMap::from([(
774 STD_MODULE_NAME.to_string(),
775 Some(oxdock_parser::ModuleFuncs { functions }),
776 )]),
777 }
778}
779
780#[oxdock_func(pure, returns = TypeTag::Int)]
793#[example(
794 name = "convert",
795 code = r###"
796 IMPORT [STD]
797 LET $n: INT = INT("42")
798 ASSERT_EQ $n 42
799 LET $flag: INT = INT(true)
800 ASSERT_EQ $flag 1
801 "###
802)]
803fn int(
804 #[union(Int, Float, String, Bool)]
806 val: Value,
807) -> Result<Value> {
808 super::args::int_from_value(val)
809}
810
811#[oxdock_func(pure, returns = TypeTag::Float)]
816#[example(
817 name = "convert",
818 code = r###"
819 IMPORT [STD]
820 LET $f: FLOAT = FLOAT("1.5")
821 ASSERT_EQ $f 1.5
822 LET $whole: FLOAT = FLOAT(2)
823 ASSERT_EQ $whole 2.0
824 "###
825)]
826fn float(
827 #[union(Float, Int, String)]
829 val: Value,
830) -> Result<Value> {
831 super::args::float_from_value(val)
832}
833
834#[oxdock_func(pure, returns = TypeTag::String)]
839#[example(
840 name = "format and round-trip",
841 code = r###"
842 # Byte counts render in the largest exact unit.
843 IMPORT [STD]
844 LET $pretty: STRING = FORMAT_BYTE_COUNT(1_048_576)
845 ASSERT_EQ $pretty "1MiB"
846
847 # The pair round-trips through the parser.
848 LET $back: INT = PARSE_BYTE_COUNT($pretty)
849 ASSERT_EQ $back 1_048_576
850 "###
851)]
852fn format_byte_count(
853 bytes: i64,
855) -> Result<Value> {
856 if bytes < 0 {
857 return Err(anyhow::anyhow!(
858 "FORMAT_BYTE_COUNT needs a non-negative byte count, got {bytes}"
859 ));
860 }
861 Ok(Value::string(oxdock_parser::command::format_byte_count(
862 bytes as u64,
863 )))
864}
865
866#[oxdock_func(pure, returns = TypeTag::Int)]
901#[example(
902 name = "parse",
903 code = r###"
904 IMPORT [STD]
905 LET $n: INT = PARSE_BYTE_COUNT("10KB")
906 ASSERT_EQ $n 10_000
907 LET $identity: INT = PARSE_BYTE_COUNT(512)
908 ASSERT_EQ $identity 512
909 "###
910)]
911fn parse_byte_count(
912 #[union(Int, Float, String)]
914 text: Value,
915) -> Result<Value> {
916 if let Some(n) = text.as_i64() {
917 if n < 0 {
918 return Err(anyhow::anyhow!(
919 "PARSE_BYTE_COUNT needs a non-negative byte count, got {n}"
920 ));
921 }
922 return Ok(Value::int(n));
923 }
924 if let Some(f) = text.as_f64() {
925 if f.is_finite() && f.fract() == 0.0 && f >= 0.0 && f <= i64::MAX as f64 {
926 return Ok(Value::int(f as i64));
927 }
928 return Err(anyhow::anyhow!(
929 "PARSE_BYTE_COUNT needs an integral byte count, got {f:?}"
930 ));
931 }
932 let Some(s) = text.as_str() else {
933 return Err(anyhow::anyhow!(
934 "PARSE_BYTE_COUNT needs a token or number, found {text:?}"
935 ));
936 };
937 let n = oxdock_parser::command::parse_byte_count(s)?;
938 let n = i64::try_from(n)
939 .map_err(|_| anyhow::anyhow!("PARSE_BYTE_COUNT out of INT range: {s:?}"))?;
940 Ok(Value::int(n))
941}
942
943#[oxdock_func(pure, returns = TypeTag::String)]
948#[example(
949 name = "format and round-trip",
950 code = r###"
951 # Durations render in the largest exact unit.
952 IMPORT [STD]
953 LET $pretty: STRING = FORMAT_DURATION(90_000)
954 ASSERT_EQ $pretty "90s"
955
956 # The pair round-trips through the parser.
957 LET $back: INT = PARSE_DURATION($pretty)
958 ASSERT_EQ $back 90_000
959 "###
960)]
961fn format_duration(
962 millis: i64,
964) -> Result<Value> {
965 if millis < 0 {
966 return Err(anyhow::anyhow!(
967 "FORMAT_DURATION needs non-negative milliseconds, got {millis}"
968 ));
969 }
970 Ok(Value::string(oxdock_parser::command::format_duration(
971 &std::time::Duration::from_millis(millis as u64),
972 )))
973}
974
975#[oxdock_func(pure, returns = TypeTag::Int)]
981#[example(
982 name = "parse",
983 code = r###"
984 # A bare number means seconds, like TIMEOUT.
985 IMPORT [STD]
986 LET $ms: INT = PARSE_DURATION("2m")
987 ASSERT_EQ $ms 120_000
988
989 # Milliseconds stay exact.
990 LET $exact: INT = PARSE_DURATION("1500ms")
991 ASSERT_EQ $exact 1_500
992
993 # One optional space separates number from unit.
994 LET $spaced: INT = PARSE_DURATION("1 h")
995 ASSERT_EQ $spaced 3_600_000
996 "###
997)]
998fn parse_duration(
999 text: String,
1001) -> Result<Value> {
1002 let duration = oxdock_parser::command::parse_duration(&text)?;
1003 let millis = i64::try_from(duration.as_millis())
1004 .map_err(|_| anyhow::anyhow!("PARSE_DURATION out of INT range: {text:?}"))?;
1005 Ok(Value::int(millis))
1006}
1007
1008#[oxdock_func(rpn, returns = TypeTag::ListOf(std::sync::Arc::new(TypeTag::String)))]
1013#[example(
1014 name = "match",
1015 code = r###"
1016 IMPORT [STD]
1017 WRITE "notes-a.md" "a"
1018 WRITE "notes-b.md" "b"
1019 WRITE "other.txt" "c"
1020 LET $found: LIST<STRING> = GLOB("notes-*.md")
1021 ASSERT_EQ $found.0 "notes-a.md"
1022 ASSERT_EQ $found.1 "notes-b.md"
1023 "###
1024)]
1025fn glob<P: ProcessManager>(
1026 cx: &mut StepCtx<P>,
1027 #[union(String, Path)]
1029 pattern: Value,
1030) -> Result<Value> {
1031 let text = super::args::string_or_path_text(&pattern)?;
1032 super::args::glob_from_value(&[Value::string(text)], cx)
1033}
1034
1035#[oxdock_func(rpn, returns = TypeTag::MapOf(std::sync::Arc::new(TypeTag::Any)))]
1040#[example(
1041 name = "load",
1042 code = r###"
1043 IMPORT [STD]
1044 WRITE "cfg.toml" "title = \"demo\""
1045 LET $cfg: MAP<ANY> = LOAD_TOML("cfg.toml")
1046 ASSERT_EQ $cfg.title "demo"
1047 "###
1048)]
1049fn load_toml<P: ProcessManager>(
1050 cx: &mut StepCtx<P>,
1051 #[union(String, Path)]
1053 path: Value,
1054) -> Result<Value> {
1055 let text = super::args::string_or_path_text(&path)?;
1056 super::args::load_toml_from_value(&[Value::string(text)], cx)
1057}
1058
1059#[oxdock_func(rpn, returns = TypeTag::Any)]
1067#[example(
1068 name = "load",
1069 code = r###"
1070 IMPORT [STD]
1071 WRITE "data.json" "{\"a\": 1}"
1072 LET $doc: MAP<ANY> = LOAD_JSON("data.json")
1073 ASSERT_EQ $doc.a 1
1074 "###
1075)]
1076fn load_json<P: ProcessManager>(
1077 cx: &mut StepCtx<P>,
1078 #[union(String, Path)]
1080 path: Value,
1081) -> Result<Value> {
1082 let text = super::args::string_or_path_text(&path)?;
1083 super::args::load_json_from_value(&[Value::string(text)], cx)
1084}
1085
1086#[oxdock_func(pure, returns = TypeTag::MapOf(std::sync::Arc::new(TypeTag::Any)))]
1092#[example(
1093 name = "parse",
1094 code = r###"
1095 IMPORT [STD]
1096 LET $doc: MAP<ANY> = PARSE_TOML("title = \"demo\"")
1097 ASSERT_EQ $doc.title "demo"
1098 "###
1099)]
1100fn parse_toml(
1101 text: String,
1103) -> Result<Value> {
1104 super::args::parse_toml_from_value(Value::string(text))
1105}
1106
1107#[oxdock_func(pure, returns = TypeTag::Any)]
1116#[example(
1117 name = "parse",
1118 code = r###"
1119 # Parse in-memory JSON text with the same conversion as file loading.
1120 IMPORT [STD]
1121 LET $body: STRING = "{\"a\": 1}"
1122 LET $doc: ANY = PARSE_JSON($body)
1123 ASSERT_EQ $doc.a 1
1124
1125 # Top-level arrays parse to LIST, which is why the return is ANY.
1126 LET $items: LIST<ANY> = PARSE_JSON("[1, 2]")
1127 ASSERT_EQ $items.0 1
1128 ASSERT_EQ $items.1 2
1129 "###
1130)]
1131fn parse_json(
1132 text: String,
1134) -> Result<Value> {
1135 super::args::parse_json_from_value(Value::string(text))
1136}
1137
1138#[oxdock_func(returns = TypeTag::String)]
1144#[example(
1145 name = "describe",
1146 code = r###"
1147 IMPORT [STD]
1148 WRITE "entry.txt" "words"
1149 LET $kind: STRING = PATH_TYPE("entry.txt")
1150 ASSERT_EQ $kind "file"
1151 LET $missing: STRING = PATH_TYPE("no-such-entry.txt")
1152 ASSERT_EQ $missing "absent"
1153 "###
1154)]
1155fn path_type<P: ProcessManager>(
1156 cx: &mut StepCtx<P>,
1157 #[union(String, Path)]
1159 path: Value,
1160) -> Result<Value> {
1161 let text = super::args::string_or_path_text(&path)?;
1162 super::args::path_type_from_value(&[Value::string(text)], cx)
1163}
1164
1165#[oxdock_func(returns = TypeTag::Bool)]
1174#[example(
1175 name = "probe",
1176 code = r###"
1177 # An absent nested path is writable when its ancestor is.
1178 IMPORT [STD]
1179 LET $fresh: BOOL = PATH_WRITABLE("probe-check/nested/file.txt")
1180 ASSERT_EQ $fresh true
1181
1182 # The empty string never aliases the working directory.
1183 LET $empty: BOOL = PATH_WRITABLE("")
1184 ASSERT_EQ $empty false
1185 "###
1186)]
1187fn path_writable<P: ProcessManager>(
1188 cx: &mut StepCtx<P>,
1189 #[union(String, Path)]
1191 path: Value,
1192) -> Result<Value> {
1193 let text = super::args::string_or_path_text(&path)?;
1194 super::args::path_writable_from_value(&[Value::string(text)], cx)
1195}
1196
1197#[oxdock_func(returns = TypeTag::Bool)]
1210#[example(
1211 name = "probe",
1212 code = r###"
1213 # Missing tools read false instead of failing the run.
1214 IMPORT [STD]
1215 LET $missing: BOOL = IS_EXEC("no-such-tool-xyz")
1216 ASSERT_EQ $missing false
1217
1218 # Plain files are not executable on any platform.
1219 WRITE tool.txt payload
1220 LET $plain: BOOL = IS_EXEC("tool.txt")
1221 ASSERT_EQ $plain false
1222 "###
1223)]
1224fn is_exec<P: ProcessManager>(
1225 cx: &mut StepCtx<P>,
1226 #[union(String, Path)]
1228 name: Value,
1229) -> Result<Value> {
1230 let text = super::args::string_or_path_text(&name)?;
1231 super::args::is_exec_from_value(&[Value::string(text)], cx)
1232}
1233
1234#[oxdock_func(pure, returns = TypeTag::Bool)]
1240#[example(
1241 name = "probe",
1242 code = r###"
1243 IMPORT [STD]
1244 LET $m: MAP<ANY> = PARSE_JSON("{\"a\": 1}")
1245 LET $hit: BOOL = HAS_KEY($m, "a")
1246 ASSERT_EQ $hit true
1247 LET $miss: BOOL = HAS_KEY($m, "b")
1248 ASSERT_EQ $miss false
1249 "###
1250)]
1251fn has_key(
1252 map: BTreeMap<String, Value>,
1254 key: String,
1256) -> Result<Value> {
1257 super::args::has_key_from_value(Value::map(map), &key)
1258}
1259
1260#[oxdock_func(pure, returns = TypeTag::MapOf(std::sync::Arc::new(TypeTag::Any)))]
1266#[example(
1267 name = "insert",
1268 code = r###"
1269 IMPORT [STD]
1270 LET $m: MAP<ANY> = MAP_SET({seed: 0}, "a", 1)
1271 ASSERT_EQ $m.a 1
1272 "###
1273)]
1274fn map_set(
1275 map: BTreeMap<String, Value>,
1277 key: String,
1279 value: Value,
1281) -> Result<Value> {
1282 super::args::map_set_from_value(Value::map(map), key, value)
1283}
1284
1285#[oxdock_func(returns = TypeTag::Float, summary = "Draw a random FLOAT uniformly from [0, 1), optionally seeded.")]
1293#[example(
1294 name = "seeded draw",
1295 code = r###"
1296 # A seed draws the same value on every run.
1297 IMPORT [STD]
1298 LET $one: FLOAT = RAND({seed: 7})
1299 LET $two: FLOAT = RAND({seed: 7})
1300 ASSERT_EQ $one $two
1301 "###
1302)]
1303#[example(
1304 name = "unseeded draw",
1305 code = r###"
1306 # Scale a unit draw into a backoff delay between 1 and 11 seconds.
1307 IMPORT [STD]
1308 LET $draw: FLOAT = RAND()
1309 LET $delay: FLOAT = 1.0 + $draw * 10.0
1310 IF $delay < 1.0 {
1311 EXIT 1
1312 }
1313 IF $delay >= 11.0 {
1314 EXIT 1
1315 }
1316 ECHO "retrying in {{ $delay }}s"
1317 "###
1318)]
1319fn rand<P: ProcessManager>(
1320 cx: &mut StepCtx<P>,
1321 #[options("seed?: INT")]
1323 #[optional]
1324 options: BTreeMap<String, Value>,
1325) -> Result<Value> {
1326 let _ = cx;
1327 let seed = options
1330 .get("seed")
1331 .map(|value| value.as_i64().expect("check_options verified INT"));
1332 super::args::rand_float_from_value(seed)
1333}
1334
1335#[oxdock_func(pure, returns = TypeTag::String)]
1341#[example(
1342 name = "encode",
1343 code = r###"
1344 # Encode text to standard base64.
1345 IMPORT [STD]
1346 LET $encoded: STRING = BASE64_ENCODE("hello")
1347 ASSERT_EQ $encoded "aGVsbG8="
1348 "###
1349)]
1350fn base64_encode(
1351 text: String,
1353) -> Result<Value> {
1354 super::args::base64_encode_from_value(Value::string(text))
1355}
1356
1357#[oxdock_func(pure, returns = TypeTag::String)]
1364#[example(
1365 name = "decode",
1366 code = r###"
1367 # Decode standard base64 back to text.
1368 IMPORT [STD]
1369 LET $decoded: STRING = BASE64_DECODE("aGVsbG8=")
1370 ASSERT_EQ $decoded "hello"
1371 "###
1372)]
1373fn base64_decode(
1374 text: String,
1376) -> Result<Value> {
1377 super::args::base64_decode_from_value(Value::string(text))
1378}
1379
1380#[oxdock_func(pure, returns = TypeTag::String)]
1387#[example(
1388 name = "encode",
1389 code = r###"
1390 IMPORT [STD]
1391 LET $json: STRING = TO_JSON({a: 1})
1392 ASSERT_EQ $json "{\"a\":1}\n"
1393 "###
1394)]
1395fn to_json(
1396 #[union(String, Int, Float, Bool, List, Map)]
1398 value: Value,
1399) -> Result<Value> {
1400 super::args::to_json_from_value(value)
1401}
1402
1403#[oxdock_func(pure, returns = TypeTag::String)]
1411#[example(
1412 name = "name the word",
1413 code = r###"
1414 IMPORT [STD]
1415 LET $word: STRING = TYPE_OF(42)
1416 ASSERT_EQ $word "INT"
1417 "###
1418)]
1419fn type_of(
1420 value: Value,
1422) -> Result<Value> {
1423 super::args::type_of_from_value(value)
1424}
1425
1426#[oxdock_func(pure, returns = TypeTag::MapOf(std::sync::Arc::new(TypeTag::Any)))]
1434#[example(
1435 name = "merge",
1436 code = r###"
1437 IMPORT [STD]
1438 LET $m: MAP<ANY> = MERGE_MAPS([{a: 1}, {b: 2}], "overwrite")
1439 ASSERT_EQ $m.a 1
1440 ASSERT_EQ $m.b 2
1441 "###
1442)]
1443fn merge_maps(
1444 maps: Vec<BTreeMap<String, Value>>,
1446 #[values("fail_on_duplicate", "overwrite")]
1448 policy: String,
1449) -> Result<Value> {
1450 super::args::merge_maps_from_value(
1451 Value::list(maps.into_iter().map(Value::map).collect()),
1452 policy,
1453 )
1454}
1455
1456#[oxdock_func(pure, returns = TypeTag::String)]
1461#[example(
1462 name = "report",
1463 code = r###"
1464 # The engine reports its own build version as a dotted string.
1465 IMPORT [STD]
1466 LET $v: STRING = VERSION()
1467 ASSERT_CONTAINS $v "."
1468 "###
1469)]
1470fn version() -> Result<Value> {
1471 Ok(Value::string(env!("CARGO_PKG_VERSION").to_string()))
1472}
1473
1474#[oxdock_func(returns = TypeTag::ListOf(std::sync::Arc::new(TypeTag::String)))]
1479#[example(
1480 name = "list",
1481 code = r###"
1482 IMPORT [STD]
1483 LET $names: LIST<STRING> = FUNCTIONS()
1484 ASSERT_CONTAINS $names "STD::INT"
1485 "###
1486)]
1487fn functions<P: ProcessManager>(cx: &mut StepCtx<P>) -> Result<Value> {
1488 let mut names: Vec<String> = cx
1489 .state
1490 .list_functions()
1491 .into_iter()
1492 .map(|meta| meta.name)
1493 .collect();
1494 names.sort();
1495 names.dedup();
1496 Ok(Value::list(names.into_iter().map(Value::string).collect()))
1497}
1498
1499#[oxdock_func(
1514 returns = TypeTag::Record(std::sync::Arc::from([Field {
1515 name: "name".to_string(),
1516 ty: TypeTag::String,
1517 docs: "Qualified function name.",
1518 optional: false,
1519 }, Field {
1520 name: "module".to_string(),
1521 ty: TypeTag::String,
1522 docs: "Owning module.",
1523 optional: false,
1524 }, Field {
1525 name: "kind".to_string(),
1526 ty: TypeTag::String,
1527 docs: "Origin label (`host` or `script`).",
1528 optional: false,
1529 }, Field {
1530 name: "params".to_string(),
1531 ty: TypeTag::ListOf(std::sync::Arc::new(TypeTag::MapOf(std::sync::Arc::new(
1532 TypeTag::Any,
1533 )))),
1534 docs: "Parameter entries (empty for parameterless functions).",
1535 optional: false,
1536 }, Field {
1537 name: "returns".to_string(),
1538 ty: TypeTag::String,
1539 docs: "Structural return shape (empty when untagged).",
1540 optional: false,
1541 }, Field {
1542 name: "rpn".to_string(),
1543 ty: TypeTag::Bool,
1544 docs: "True when callable in RPN position.",
1545 optional: false,
1546 }, Field {
1547 name: "summary".to_string(),
1548 ty: TypeTag::String,
1549 docs: "One-line description.",
1550 optional: false,
1551 }]))
1552 summary = "Describe one function by qualified name."
1553)]
1554#[example(
1555 name = "describe",
1556 code = r###"
1557 IMPORT [STD]
1558 LET $info: MAP<ANY> = DESCRIBE("STD::INT")
1559 ASSERT_EQ $info.name "STD::INT"
1560 ASSERT_EQ $info.returns "INT"
1561 "###
1562)]
1563fn describe<P: ProcessManager>(
1564 cx: &mut StepCtx<P>,
1565 name: String,
1567) -> Result<Value> {
1568 if split_qualified(&name).is_none() && name != KEYWORD_INSPECT {
1569 anyhow::bail!(
1570 "unknown function `{name}`: DESCRIBE requires a qualified name (e.g. `STD::{name}`)"
1571 );
1572 }
1573 cx.state
1574 .describe_function(&name)
1575 .ok_or_else(|| anyhow::anyhow!("unknown function {name}"))
1576}
1577
1578#[oxdock_func(returns = TypeTag::ListOf(std::sync::Arc::new(TypeTag::String)))]
1584#[example(
1585 name = "list",
1586 code = r###"
1587 IMPORT [STD]
1588 LET $names: LIST<STRING> = TYPES()
1589 ASSERT_CONTAINS $names "STRING"
1590 "###
1591)]
1592fn types<P: ProcessManager>(cx: &mut StepCtx<P>) -> Result<Value> {
1593 Ok(Value::list(
1594 cx.state
1595 .type_names()
1596 .into_iter()
1597 .map(Value::string)
1598 .collect(),
1599 ))
1600}
1601
1602#[oxdock_func(returns = TypeTag::Record(std::sync::Arc::from([Field {
1608 name: "name".to_string(),
1609 ty: TypeTag::String,
1610 docs: "Queried type name.",
1611 optional: false,
1612}, Field {
1613 name: "summary".to_string(),
1614 ty: TypeTag::String,
1615 docs: "One-line description.",
1616 optional: false,
1617}, Field {
1618 name: "docs".to_string(),
1619 ty: TypeTag::String,
1620 docs: "Full documentation text.",
1621 optional: false,
1622}])))]
1623#[example(
1624 name = "describe",
1625 code = r###"
1626 IMPORT [STD]
1627 LET $info: MAP<ANY> = TYPE_DESCRIBE("STRING")
1628 ASSERT_EQ $info.name "STRING"
1629 "###
1630)]
1631fn type_describe<P: ProcessManager>(
1632 cx: &mut StepCtx<P>,
1633 name: String,
1635) -> Result<Value> {
1636 if let Some(descriptor) = cx.state.describe_type(&name) {
1637 let mut map = BTreeMap::new();
1638 map.insert(
1639 "name".to_string(),
1640 Value::string(descriptor.name.to_string()),
1641 );
1642 map.insert(
1643 "summary".to_string(),
1644 Value::string(descriptor.summary.to_string()),
1645 );
1646 map.insert(
1647 "docs".to_string(),
1648 Value::string(descriptor.docs.to_string()),
1649 );
1650 return Ok(Value::map(map));
1651 }
1652 if let Some(target) = cx.state.alias_target(&name) {
1655 let mut map = BTreeMap::new();
1656 map.insert("name".to_string(), Value::string(name.clone()));
1657 map.insert(
1658 "summary".to_string(),
1659 Value::string(format!("Script type alias for {target}.")),
1660 );
1661 map.insert(
1662 "docs".to_string(),
1663 Value::string(format!(
1664 "Declared with TYPE {name} = {target}. The alias expands structurally at every declaration."
1665 )),
1666 );
1667 return Ok(Value::map(map));
1668 }
1669 Err(anyhow::anyhow!("unknown type {name}"))
1670}
1671
1672#[oxdock_func(returns = TypeTag::Bool)]
1686#[example(
1687 name = "null stdin",
1688 code = r###"
1689 # A null stdin is never a terminal, in every harness.
1690 IMPORT [STD]
1691 LET $term: BOOL = IS_TERMINAL("stdin")
1692 ASSERT_EQ $term false
1693 "###
1694)]
1695fn is_terminal<P: ProcessManager>(
1696 cx: &mut StepCtx<P>,
1697 #[values("stdin", "stdout", "stderr")]
1699 stream_name: String,
1700) -> Result<Value> {
1701 use std::io::IsTerminal;
1702 let terminal = match stream_name.as_str() {
1703 "stdin" => {
1704 if cx.stdin_pipe.is_some() {
1709 false
1710 } else {
1711 match &cx.stdin {
1712 CommandStdin::Null => false,
1713 #[cfg(not(miri))]
1714 CommandStdin::OsPipe(_) => false,
1715 CommandStdin::Stream(_) => false,
1716 CommandStdin::Inherit => std::io::stdin().is_terminal(),
1717 }
1718 }
1719 }
1720 "stdout" => {
1721 if cx.out_pipe.is_some() {
1722 false
1724 } else if cx.state.io.stdout().is_some() {
1725 false
1728 } else {
1729 match &cx.out {
1730 None => std::io::stdout().is_terminal(),
1732 #[cfg(not(miri))]
1734 Some(StreamHandle::Os(_)) => false,
1735 Some(StreamHandle::Stream(_)) => std::io::stdout().is_terminal(),
1745 }
1746 }
1747 }
1748 "stderr" => {
1749 if cx.state.io.stderr().is_some() {
1750 false
1752 } else {
1753 match &cx.err {
1754 None => std::io::stderr().is_terminal(),
1756 #[cfg(not(miri))]
1758 Some(StreamHandle::Os(_)) => false,
1759 Some(StreamHandle::Stream(_)) => false,
1762 }
1763 }
1764 }
1765 _ => anyhow::bail!(
1766 "IS_TERMINAL expects \"stdin\", \"stdout\", or \"stderr\", got {stream_name:?}"
1771 ),
1772 };
1773 Ok(Value::bool(terminal))
1774}
1775
1776#[oxdock_func(returns = TypeTag::Semaphore)]
1784#[example(
1785 name = "mint",
1786 code = r###"
1787 # Mint a semaphore admitting at most two holders.
1788 IMPORT [STD]
1789 LET $sem: SEMAPHORE = SEMAPHORE_NEW(2)
1790
1791 # A fresh semaphore reports its full cap as available.
1792 LET $free: INT = SEMAPHORE_AVAILABLE($sem)
1793 ASSERT_EQ $free 2
1794 "###
1795)]
1796fn semaphore_new<P: ProcessManager>(
1797 cx: &mut StepCtx<P>,
1798 max: i64,
1800) -> Result<Value> {
1801 let _ = cx;
1802 if max <= 0 {
1803 return Err(anyhow::anyhow!(
1804 "SEMAPHORE_NEW() requires a positive max, got {max}"
1805 ));
1806 }
1807 Ok(Value::semaphore(max as usize))
1808}
1809
1810#[oxdock_func(returns = TypeTag::Record(std::sync::Arc::from([Field {
1819 name: "held".to_string(),
1820 ty: TypeTag::Bool,
1821 docs: "`true` with the permit under `permit`, `false` with no `permit` key.",
1822 optional: false,
1823}, Field {
1824 name: "permit".to_string(),
1825 ty: TypeTag::Permit,
1826 docs: "Permit handle; read only when `held`.",
1827 optional: true,
1828}])))]
1829#[example(
1830 name = "acquire",
1831 code = r###"
1832 # First acquire holds with a permit to bind.
1833 IMPORT [STD]
1834 LET $sem: SEMAPHORE = SEMAPHORE_NEW(1)
1835 LET $first: MAP<held: BOOL, permit?: PERMIT> = SEMAPHORE_TRY_ACQUIRE($sem)
1836 ASSERT_EQ $first.held true
1837 LET $permit: PERMIT = $first.permit
1838
1839 # A capped semaphore answers held false with no permit key.
1840 LET $second: MAP<held: BOOL, permit?: PERMIT> = SEMAPHORE_TRY_ACQUIRE($sem)
1841 ASSERT_EQ $second.held false
1842 LET $has_permit: BOOL = HAS_KEY($second, "permit")
1843 ASSERT_EQ $has_permit false
1844 "###
1845)]
1846fn semaphore_try_acquire<P: ProcessManager>(
1847 cx: &mut StepCtx<P>,
1848 sem: Arc<SemaphoreState>,
1850) -> Result<Value> {
1851 let _ = cx;
1852 let mut map = BTreeMap::new();
1853 if sem.try_acquire() {
1854 map.insert("held".to_string(), Value::bool(true));
1855 map.insert("permit".to_string(), Value::permit(&sem));
1856 } else {
1857 map.insert("held".to_string(), Value::bool(false));
1858 }
1859 Ok(Value::map(map))
1860}
1861
1862#[oxdock_func(pure, returns = TypeTag::Int)]
1869#[example(
1870 name = "readout",
1871 code = r###"
1872 # Hold one permit on a cap of two.
1873 IMPORT [STD]
1874 LET $sem: SEMAPHORE = SEMAPHORE_NEW(2)
1875 LET $acq: MAP<held: BOOL, permit?: PERMIT> = SEMAPHORE_TRY_ACQUIRE($sem)
1876 ASSERT_EQ $acq.held true
1877
1878 # One held permit leaves exactly one free.
1879 LET $free: INT = SEMAPHORE_AVAILABLE($sem)
1880 ASSERT_EQ $free 1
1881 "###
1882)]
1883fn semaphore_available(
1884 sem: Arc<SemaphoreState>,
1886) -> Result<Value> {
1887 Ok(Value::int(sem.available() as i64))
1888}
1889
1890#[oxdock_func(
1899 rpn,
1900 returns = TypeTag::union(vec![TypeTag::String, TypeTag::Pipe]),
1901 template = text_trim_string
1902)]
1903#[example(
1904 name = "trim",
1905 code = r###"
1906 # Leading and trailing whitespace falls away.
1907 IMPORT [STD]
1908 LET $clean: STRING = TEXT_TRIM(" hello ")
1909 ASSERT_EQ $clean "hello"
1910 "###
1911)]
1912#[example(
1913 name = "trim pipe mirrors",
1914 code = r###"
1915 # Pipe input mints pipe output with the same transform.
1916 IMPORT [STD]
1917 LET $cap: PIPE
1918 WITH_IO [stdout=$cap] {
1919 ECHO " hello "
1920 }
1921 LET $out: PIPE = TEXT_TRIM($cap)
1922 WITH_IO [stdin=$out] READ_LINE $line
1923 ASSERT_EQ $line "hello"
1924 "###
1925)]
1926#[example(
1927 name = "trim template",
1928 code = r###"
1929 # String inputs run inside placeholders too.
1930 IMPORT [STD]
1931 LET $msg: STRING = 'clean:{{ STD::TEXT_TRIM(" hello ") }}'
1932 ASSERT_EQ $msg "clean:hello"
1933 "###
1934)]
1935#[example(
1936 name = "trim file template",
1937 code = r###"
1938 # EXPAND templates resolve the same registry.
1939 IMPORT [STD]
1940 WRITE "tpl.txt" "clean:\{{ STD::TEXT_TRIM(\" hello \") }}"
1941 LET $out: STRING = EXPAND "tpl.txt"
1942 ASSERT_EQ $out "clean:hello"
1943 "###
1944)]
1945fn text_trim<P: ProcessManager>(
1946 cx: &mut StepCtx<P>,
1947 #[union(String, Pipe)]
1949 text: Value,
1950) -> Result<Value> {
1951 super::args::mirror_stream(cx, "TEXT_TRIM", &text, super::args::TextPump::Trim)
1952}
1953
1954fn text_trim_string(text: Value) -> Result<Value> {
1957 super::args::mirror_string("TEXT_TRIM", &text, super::args::TextPump::Trim)
1958}
1959
1960#[oxdock_func(
1969 rpn,
1970 returns = TypeTag::union(vec![TypeTag::String, TypeTag::Pipe]),
1971 template = text_trim_prefix_string
1972)]
1973#[example(
1974 name = "strip prefix",
1975 code = r###"
1976 # A present prefix falls away; absence returns the input unchanged.
1977 IMPORT [STD]
1978 LET $bare: STRING = TEXT_TRIM_PREFIX("v1.2.3", "v")
1979 ASSERT_EQ $bare "1.2.3"
1980
1981 # Missing prefixes pass through untouched.
1982 LET $same: STRING = TEXT_TRIM_PREFIX("1.2.3", "v")
1983 ASSERT_EQ $same "1.2.3"
1984 "###
1985)]
1986#[example(
1987 name = "strip prefix pipe mirrors",
1988 code = r###"
1989 # Pipe input mints pipe output with the same strip.
1990 IMPORT [STD]
1991 LET $cap: PIPE
1992 WITH_IO [stdout=$cap] {
1993 ECHO "v1.2.3"
1994 }
1995 LET $trimmed: PIPE = TEXT_TRIM($cap)
1996 LET $out: PIPE = TEXT_TRIM_PREFIX($trimmed, "v")
1997 WITH_IO [stdin=$out] READ_LINE $line
1998 ASSERT_EQ $line "1.2.3"
1999 "###
2000)]
2001#[example(
2002 name = "strip prefix template",
2003 code = r###"
2004 # String inputs run inside placeholders too.
2005 IMPORT [STD]
2006 LET $msg: STRING = 'bare:{{ STD::TEXT_TRIM_PREFIX("v1.2.3", "v") }}'
2007 ASSERT_EQ $msg "bare:1.2.3"
2008 "###
2009)]
2010fn text_trim_prefix<P: ProcessManager>(
2011 cx: &mut StepCtx<P>,
2012 #[union(String, Pipe)]
2014 text: Value,
2015 prefix: String,
2017) -> Result<Value> {
2018 super::args::mirror_stream(
2019 cx,
2020 "TEXT_TRIM_PREFIX",
2021 &text,
2022 super::args::TextPump::TrimPrefix(prefix),
2023 )
2024}
2025
2026fn text_trim_prefix_string(text: Value, prefix: String) -> Result<Value> {
2029 super::args::mirror_string(
2030 "TEXT_TRIM_PREFIX",
2031 &text,
2032 super::args::TextPump::TrimPrefix(prefix),
2033 )
2034}
2035
2036#[oxdock_func(
2043 rpn,
2044 returns = TypeTag::union(vec![TypeTag::String, TypeTag::Pipe]),
2045 template = text_trim_suffix_string
2046)]
2047#[example(
2048 name = "strip suffix",
2049 code = r###"
2050 # A present suffix falls away; absence returns the input unchanged.
2051 IMPORT [STD]
2052 LET $bare: STRING = TEXT_TRIM_SUFFIX("archive.tar.gz", ".gz")
2053 ASSERT_EQ $bare "archive.tar"
2054
2055 # Missing suffixes pass through untouched.
2056 LET $same: STRING = TEXT_TRIM_SUFFIX("archive.tar", ".gz")
2057 ASSERT_EQ $same "archive.tar"
2058 "###
2059)]
2060#[example(
2061 name = "strip suffix pipe mirrors",
2062 code = r###"
2063 # Pipe input mints pipe output with the same strip.
2064 IMPORT [STD]
2065 LET $cap: PIPE
2066 WITH_IO [stdout=$cap] {
2067 ECHO "archive.tar.gz"
2068 }
2069 LET $trimmed: PIPE = TEXT_TRIM($cap)
2070 LET $out: PIPE = TEXT_TRIM_SUFFIX($trimmed, ".gz")
2071 WITH_IO [stdin=$out] READ_LINE $line
2072 ASSERT_EQ $line "archive.tar"
2073 "###
2074)]
2075#[example(
2076 name = "strip suffix template",
2077 code = r###"
2078 # String inputs run inside placeholders too.
2079 IMPORT [STD]
2080 LET $msg: STRING = 'bare:{{ STD::TEXT_TRIM_SUFFIX("archive.tar.gz", ".gz") }}'
2081 ASSERT_EQ $msg "bare:archive.tar"
2082 "###
2083)]
2084fn text_trim_suffix<P: ProcessManager>(
2085 cx: &mut StepCtx<P>,
2086 #[union(String, Pipe)]
2088 text: Value,
2089 suffix: String,
2091) -> Result<Value> {
2092 super::args::mirror_stream(
2093 cx,
2094 "TEXT_TRIM_SUFFIX",
2095 &text,
2096 super::args::TextPump::TrimSuffix(suffix),
2097 )
2098}
2099
2100fn text_trim_suffix_string(text: Value, suffix: String) -> Result<Value> {
2103 super::args::mirror_string(
2104 "TEXT_TRIM_SUFFIX",
2105 &text,
2106 super::args::TextPump::TrimSuffix(suffix),
2107 )
2108}
2109
2110#[oxdock_func(
2117 rpn,
2118 returns = TypeTag::union(vec![TypeTag::String, TypeTag::Pipe]),
2119 template = text_to_upper_string
2120)]
2121#[example(
2122 name = "uppercase",
2123 code = r###"
2124 # Text folds to uppercase.
2125 IMPORT [STD]
2126 LET $loud: STRING = TEXT_TO_UPPER("hello")
2127 ASSERT_EQ $loud "HELLO"
2128 "###
2129)]
2130#[example(
2131 name = "uppercase pipe mirrors",
2132 code = r###"
2133 # Pipe input mints pipe output with the same fold.
2134 IMPORT [STD]
2135 LET $cap: PIPE
2136 WITH_IO [stdout=$cap] {
2137 ECHO "hello"
2138 }
2139 LET $out: PIPE = TEXT_TO_UPPER($cap)
2140 WITH_IO [stdin=$out] READ_LINE $line
2141 ASSERT_EQ $line "HELLO"
2142 "###
2143)]
2144#[example(
2145 name = "uppercase template",
2146 code = r###"
2147 # String inputs run inside placeholders too.
2148 IMPORT [STD]
2149 LET $msg: STRING = 'loud:{{ STD::TEXT_TO_UPPER("hello") }}'
2150 ASSERT_EQ $msg "loud:HELLO"
2151 "###
2152)]
2153fn text_to_upper<P: ProcessManager>(
2154 cx: &mut StepCtx<P>,
2155 #[union(String, Pipe)]
2157 text: Value,
2158) -> Result<Value> {
2159 super::args::mirror_stream(cx, "TEXT_TO_UPPER", &text, super::args::TextPump::ToUpper)
2160}
2161
2162fn text_to_upper_string(text: Value) -> Result<Value> {
2165 super::args::mirror_string("TEXT_TO_UPPER", &text, super::args::TextPump::ToUpper)
2166}
2167
2168#[oxdock_func(
2175 rpn,
2176 returns = TypeTag::union(vec![TypeTag::String, TypeTag::Pipe]),
2177 template = text_to_lower_string
2178)]
2179#[example(
2180 name = "lowercase",
2181 code = r###"
2182 # Text folds to lowercase.
2183 IMPORT [STD]
2184 LET $quiet: STRING = TEXT_TO_LOWER("HELLO")
2185 ASSERT_EQ $quiet "hello"
2186 "###
2187)]
2188#[example(
2189 name = "lowercase pipe mirrors",
2190 code = r###"
2191 # Pipe input mints pipe output with the same fold.
2192 IMPORT [STD]
2193 LET $cap: PIPE
2194 WITH_IO [stdout=$cap] {
2195 ECHO "HELLO"
2196 }
2197 LET $out: PIPE = TEXT_TO_LOWER($cap)
2198 WITH_IO [stdin=$out] READ_LINE $line
2199 ASSERT_EQ $line "hello"
2200 "###
2201)]
2202#[example(
2203 name = "lowercase template",
2204 code = r###"
2205 # String inputs run inside placeholders too.
2206 IMPORT [STD]
2207 LET $msg: STRING = 'quiet:{{ STD::TEXT_TO_LOWER("HELLO") }}'
2208 ASSERT_EQ $msg "quiet:hello"
2209 "###
2210)]
2211fn text_to_lower<P: ProcessManager>(
2212 cx: &mut StepCtx<P>,
2213 #[union(String, Pipe)]
2215 text: Value,
2216) -> Result<Value> {
2217 super::args::mirror_stream(cx, "TEXT_TO_LOWER", &text, super::args::TextPump::ToLower)
2218}
2219
2220fn text_to_lower_string(text: Value) -> Result<Value> {
2223 super::args::mirror_string("TEXT_TO_LOWER", &text, super::args::TextPump::ToLower)
2224}
2225
2226#[oxdock_func(
2237 rpn,
2238 returns = TypeTag::union(vec![TypeTag::String, TypeTag::Pipe]),
2239 template = text_replace_string
2240)]
2241#[example(
2242 name = "replace",
2243 code = r###"
2244 # Every literal occurrence rewrites in place.
2245 IMPORT [STD]
2246 LET $fixed: STRING = TEXT_REPLACE("hello world", "world", "there")
2247 ASSERT_EQ $fixed "hello there"
2248 "###
2249)]
2250#[example(
2251 name = "replace pipe mirrors",
2252 code = r###"
2253 # Pipe input mints pipe output with the same rewrite.
2254 IMPORT [STD]
2255 LET $cap: PIPE
2256 WITH_IO [stdout=$cap] {
2257 ECHO "hello world"
2258 }
2259 LET $trimmed: PIPE = TEXT_TRIM($cap)
2260 LET $out: PIPE = TEXT_REPLACE($trimmed, "world", "there")
2261 WITH_IO [stdin=$out] READ_LINE $line
2262 ASSERT_EQ $line "hello there"
2263 "###
2264)]
2265#[example(
2266 name = "replace template",
2267 code = r###"
2268 # String inputs run inside placeholders too.
2269 IMPORT [STD]
2270 LET $msg: STRING = 'fixed:{{ STD::TEXT_REPLACE("hello world", "world", "there") }}'
2271 ASSERT_EQ $msg "fixed:hello there"
2272 "###
2273)]
2274fn text_replace<P: ProcessManager>(
2275 cx: &mut StepCtx<P>,
2276 #[union(String, Pipe)]
2278 text: Value,
2279 from: String,
2281 to: String,
2283) -> Result<Value> {
2284 super::args::mirror_stream(
2285 cx,
2286 "TEXT_REPLACE",
2287 &text,
2288 super::args::TextPump::ReplaceLiteral { from, to },
2289 )
2290}
2291
2292fn text_replace_string(text: Value, from: String, to: String) -> Result<Value> {
2295 super::args::mirror_string(
2296 "TEXT_REPLACE",
2297 &text,
2298 super::args::TextPump::ReplaceLiteral { from, to },
2299 )
2300}
2301
2302#[oxdock_func(
2314 rpn,
2315 returns = TypeTag::union(vec![TypeTag::String, TypeTag::Pipe]),
2316 template = text_replace_regex_string
2317)]
2318#[example(
2319 name = "replace with captures",
2320 code = r###"
2321 # Capture groups expand in the replacement.
2322 IMPORT [STD]
2323 LET $swapped: STRING = TEXT_REPLACE_REGEX("2026-10-13", "(\\d+)-(\\d+)-(\\d+)", "$3/$2/$1")
2324 ASSERT_EQ $swapped "13/10/2026"
2325 "###
2326)]
2327#[example(
2328 name = "replace regex pipe mirrors",
2329 code = r###"
2330 # Pipe input mints pipe output with the same rewrite.
2331 IMPORT [STD]
2332 LET $cap: PIPE
2333 WITH_IO [stdout=$cap] {
2334 ECHO "2026-10-13"
2335 }
2336 LET $trimmed: PIPE = TEXT_TRIM($cap)
2337 LET $out: PIPE = TEXT_REPLACE_REGEX($trimmed, "(\\d+)-(\\d+)-(\\d+)", "$3/$2/$1")
2338 WITH_IO [stdin=$out] READ_LINE $line
2339 ASSERT_EQ $line "13/10/2026"
2340 "###
2341)]
2342#[example(
2343 name = "replace regex template",
2344 code = r###"
2345 # String inputs run inside placeholders too.
2346 IMPORT [STD]
2347 LET $msg: STRING = 'swapped:{{ STD::TEXT_REPLACE_REGEX("2026-10-13", "(\\d+)-(\\d+)-(\\d+)", "$3/$2/$1") }}'
2348 ASSERT_EQ $msg "swapped:13/10/2026"
2349 "###
2350)]
2351fn text_replace_regex<P: ProcessManager>(
2352 cx: &mut StepCtx<P>,
2353 #[union(String, Pipe)]
2355 text: Value,
2356 pattern: String,
2358 replacement: String,
2360) -> Result<Value> {
2361 if let Some(s) = text.as_str() {
2362 let out =
2363 super::args::text_replace_regex_str(s, &pattern, &replacement, "TEXT_REPLACE_REGEX")?;
2364 return Ok(Value::string(out));
2365 }
2366 let content = super::args::read_pipe_eager(cx, "TEXT_REPLACE_REGEX", &text)?;
2367 let out = super::args::text_replace_regex_str(
2368 &content,
2369 &pattern,
2370 &replacement,
2371 "TEXT_REPLACE_REGEX",
2372 )?;
2373 super::args::write_completed_pipe(cx, "TEXT_REPLACE_REGEX", out)
2374}
2375
2376fn text_replace_regex_string(text: Value, pattern: String, replacement: String) -> Result<Value> {
2379 let Some(s) = text.as_str() else {
2380 return Err(super::args::pipe_needs_step_io("TEXT_REPLACE_REGEX"));
2381 };
2382 let out = super::args::text_replace_regex_str(s, &pattern, &replacement, "TEXT_REPLACE_REGEX")?;
2383 Ok(Value::string(out))
2384}
2385
2386#[oxdock_func(pure, returns = TypeTag::ListOf(std::sync::Arc::new(TypeTag::String)))]
2394#[example(
2395 name = "split",
2396 code = r###"
2397 # Delimiters split into list items.
2398 IMPORT [STD]
2399 LET $parts: LIST<STRING> = TEXT_SPLIT("a,b,c", ",")
2400 ASSERT_EQ $parts.0 "a"
2401 ASSERT_EQ $parts.1 "b"
2402 ASSERT_EQ $parts.2 "c"
2403 "###
2404)]
2405fn text_split(
2406 text: String,
2408 delimiter: String,
2410) -> Result<Value> {
2411 Ok(super::args::text_list_value(super::args::text_split_str(
2412 &text, &delimiter,
2413 )))
2414}
2415
2416#[oxdock_func(pure, returns = TypeTag::String)]
2419#[example(
2420 name = "join",
2421 code = r###"
2422 # List items join with the separator between them.
2423 IMPORT [STD]
2424 LET $joined: STRING = TEXT_JOIN(["a", "b", "c"], ",")
2425 ASSERT_EQ $joined "a,b,c"
2426 "###
2427)]
2428fn text_join(
2429 elements: Vec<String>,
2431 delimiter: String,
2433) -> Result<Value> {
2434 Ok(Value::string(elements.join(delimiter.as_str())))
2435}
2436
2437#[oxdock_func(pure, returns = TypeTag::ListOf(std::sync::Arc::new(TypeTag::String)))]
2449#[example(
2450 name = "split args",
2451 code = r###"
2452 # Quoted segments stay one word.
2453 IMPORT [STD]
2454 LET $argv: LIST<STRING> = SHELL_SPLIT_ARGS("gh issue comment 153 --body-file notes.md")
2455 ASSERT_EQ $argv.0 "gh"
2456 ASSERT_EQ $argv.3 "153"
2457 ASSERT_EQ $argv.5 "notes.md"
2458
2459 # Quotes and escapes parse the shell way.
2460 LET $quoted: LIST<STRING> = SHELL_SPLIT_ARGS("say \"hi there\" 'a b'")
2461 ASSERT_EQ $quoted.0 "say"
2462 ASSERT_EQ $quoted.1 "hi there"
2463 ASSERT_EQ $quoted.2 "a b"
2464 "###
2465)]
2466fn shell_split_args(
2467 command: String,
2469) -> Result<Value> {
2470 match shell_words::split(&command) {
2471 Ok(words) => Ok(super::args::text_list_value(words)),
2472 Err(err) => anyhow::bail!("SHELL_SPLIT_ARGS: {err}"),
2473 }
2474}
2475
2476#[oxdock_func(pure, returns = TypeTag::String)]
2484#[example(
2485 name = "join args",
2486 code = r###"
2487 # Plain words join with spaces and no quoting.
2488 IMPORT [STD]
2489 LET $plain: STRING = SHELL_JOIN_ARGS(["gh", "issue", "list"])
2490 ASSERT_EQ $plain "gh issue list"
2491
2492 # Words with spaces quote, and the round trip is exact.
2493 LET $words: LIST<STRING> = ["say", "hi there", "a'b"]
2494 LET $joined: STRING = SHELL_JOIN_ARGS($words)
2495 LET $back: LIST<STRING> = SHELL_SPLIT_ARGS($joined)
2496 ASSERT_EQ $back.0 "say"
2497 ASSERT_EQ $back.1 "hi there"
2498 ASSERT_EQ $back.2 "a'b"
2499 "###
2500)]
2501fn shell_join_args(
2502 words: Vec<String>,
2504) -> Result<Value> {
2505 Ok(Value::string(shell_words::join(&words)))
2506}
2507
2508#[oxdock_func(pure, returns = TypeTag::ListOf(std::sync::Arc::new(TypeTag::String)))]
2516#[example(
2517 name = "lines",
2518 code = r###"
2519 # Newlines split into line items.
2520 IMPORT [STD]
2521 LET $lines: LIST<STRING> = TEXT_LINES("one\ntwo\nthree")
2522 ASSERT_EQ $lines.0 "one"
2523 ASSERT_EQ $lines.1 "two"
2524 ASSERT_EQ $lines.2 "three"
2525
2526 # Windows endings split the same way after normalization.
2527 LET $crlf: LIST<STRING> = TEXT_LINES("one\r\ntwo\r\nthree")
2528 ASSERT_EQ $crlf.0 "one"
2529 ASSERT_EQ $crlf.1 "two"
2530 ASSERT_EQ $crlf.2 "three"
2531
2532 # Old Mac endings split too, and mixed endings split together because the input normalizes to LF before splitting.
2533 LET $mixed: LIST<STRING> = TEXT_LINES("a\r\nb\nc\rd")
2534 ASSERT_EQ $mixed.0 "a"
2535 ASSERT_EQ $mixed.1 "b"
2536 ASSERT_EQ $mixed.2 "c"
2537 ASSERT_EQ $mixed.3 "d"
2538 "###
2539)]
2540fn text_lines(
2541 text: String,
2543) -> Result<Value> {
2544 Ok(super::args::text_list_value(super::args::text_lines_str(
2545 &text,
2546 )))
2547}
2548
2549#[oxdock_func(pure, returns = TypeTag::ListOf(std::sync::Arc::new(TypeTag::String)))]
2555#[example(
2556 name = "fields",
2557 code = r###"
2558 # Runs of whitespace separate fields; empties never appear.
2559 IMPORT [STD]
2560 LET $fields: LIST<STRING> = TEXT_FIELDS(" abc def ")
2561 ASSERT_EQ $fields.0 "abc"
2562 ASSERT_EQ $fields.1 "def"
2563 "###
2564)]
2565fn text_fields(
2566 text: String,
2568) -> Result<Value> {
2569 Ok(super::args::text_list_value(super::args::text_fields_str(
2570 &text,
2571 )))
2572}
2573
2574#[oxdock_func(pure, returns = TypeTag::ListOf(std::sync::Arc::new(TypeTag::String)))]
2583#[example(
2584 name = "line range",
2585 code = r###"
2586 # Lines 2 through 3 come back as a list, 1-based inclusive.
2587 IMPORT [STD]
2588 LET $window: LIST<STRING> = TEXT_LINES_RANGE("one\ntwo\nthree\nfour", 2, 3)
2589 ASSERT_EQ $window.0 "two"
2590 ASSERT_EQ $window.1 "three"
2591
2592 # Ranges past the end clamp instead of failing.
2593 LET $tail: LIST<STRING> = TEXT_LINES_RANGE("one\ntwo", 2, 9)
2594 ASSERT_EQ $tail.0 "two"
2595 "###
2596)]
2597fn text_lines_range(
2598 text: String,
2600 from: i64,
2602 to: i64,
2604) -> Result<Value> {
2605 Ok(super::args::text_list_value(
2606 super::args::text_lines_range_str(&text, from, to, "TEXT_LINES_RANGE")?,
2607 ))
2608}
2609
2610#[oxdock_func(pure, returns = TypeTag::Bool)]
2618#[example(
2619 name = "match",
2620 code = r###"
2621 # Regex matches report true; misses report false.
2622 IMPORT [STD]
2623 LET $hit: BOOL = TEXT_MATCH("abc123", "\\d+")
2624 ASSERT_EQ $hit true
2625
2626 # A miss is false, not a failure.
2627 LET $miss: BOOL = TEXT_MATCH("abc", "^\\d+$")
2628 ASSERT_EQ $miss false
2629 "###
2630)]
2631fn text_match(
2632 text: String,
2634 pattern: String,
2636) -> Result<Value> {
2637 let re = super::args::text_compile_pattern("TEXT_MATCH", &pattern)?;
2638 Ok(Value::bool(re.is_match(&text)))
2639}
2640
2641#[oxdock_func(pure, returns = TypeTag::ListOf(std::sync::Arc::new(TypeTag::String)))]
2650#[example(
2651 name = "extract",
2652 code = r###"
2653 # Index zero is the full match; groups follow in order.
2654 IMPORT [STD]
2655 LET $caps: LIST<STRING> = TEXT_EXTRACT("abc123", "([a-z]+)(\\d+)")
2656 ASSERT_EQ $caps.0 "abc123"
2657 ASSERT_EQ $caps.1 "abc"
2658 ASSERT_EQ $caps.2 "123"
2659 "###
2660)]
2661fn text_extract(
2662 text: String,
2664 pattern: String,
2666) -> Result<Value> {
2667 let groups = super::args::text_extract_str(&text, &pattern, "TEXT_EXTRACT")?;
2668 Ok(super::args::text_list_value(groups))
2669}
2670
2671#[oxdock_func(pure, returns = TypeTag::Bool)]
2678#[example(
2679 name = "starts with",
2680 code = r###"
2681 # Present prefixes report true; misses report false.
2682 IMPORT [STD]
2683 LET $hit: BOOL = TEXT_STARTS_WITH("linux-musl-x64", "linux")
2684 ASSERT_EQ $hit true
2685
2686 # A miss is false, not a failure.
2687 LET $miss: BOOL = TEXT_STARTS_WITH("macos-arm", "linux")
2688 ASSERT_EQ $miss false
2689 "###
2690)]
2691fn text_starts_with(
2692 text: String,
2694 prefix: String,
2696) -> Result<Value> {
2697 Ok(Value::bool(text.starts_with(prefix.as_str())))
2698}
2699
2700#[oxdock_func(pure, returns = TypeTag::Bool)]
2707#[example(
2708 name = "ends with",
2709 code = r###"
2710 # Present suffixes report true; misses report false.
2711 IMPORT [STD]
2712 LET $hit: BOOL = TEXT_ENDS_WITH("x86_64-linux-musl", "linux-musl")
2713 ASSERT_EQ $hit true
2714
2715 # A miss is false, not a failure.
2716 LET $miss: BOOL = TEXT_ENDS_WITH("x86_64-linux-gnu", "linux-musl")
2717 ASSERT_EQ $miss false
2718 "###
2719)]
2720fn text_ends_with(
2721 text: String,
2723 suffix: String,
2725) -> Result<Value> {
2726 Ok(Value::bool(text.ends_with(suffix.as_str())))
2727}
2728
2729#[oxdock_func(pure, returns = TypeTag::Bool)]
2736#[example(
2737 name = "contains",
2738 code = r###"
2739 # Present needles report true; misses report false.
2740 IMPORT [STD]
2741 LET $hit: BOOL = TEXT_CONTAINS("x86_64-linux-musl", "musl")
2742 ASSERT_EQ $hit true
2743
2744 # A miss is false, not a failure.
2745 LET $miss: BOOL = TEXT_CONTAINS("x86_64-linux-gnu", "musl")
2746 ASSERT_EQ $miss false
2747 "###
2748)]
2749fn text_contains(
2750 text: String,
2752 needle: String,
2754) -> Result<Value> {
2755 Ok(Value::bool(text.contains(needle.as_str())))
2756}
2757
2758#[oxdock_func(pure, returns = TypeTag::Int)]
2765#[example(
2766 name = "length",
2767 code = r###"
2768 # Plain text counts one per character.
2769 IMPORT [STD]
2770 LET $n: INT = TEXT_LENGTH("hello")
2771 ASSERT_EQ $n 5
2772
2773 # Multibyte characters count once each, not per byte.
2774 LET $wide: INT = TEXT_LENGTH("héllo")
2775 ASSERT_EQ $wide 5
2776 "###
2777)]
2778fn text_length(
2779 text: String,
2781) -> Result<Value> {
2782 Ok(Value::int(text.chars().count() as i64))
2783}
2784
2785#[oxdock_func(pure, returns = TypeTag::Int)]
2793#[example(
2794 name = "count",
2795 code = r###"
2796 # Every non-overlapping occurrence counts once.
2797 IMPORT [STD]
2798 LET $n: INT = TEXT_COUNT("hello world", "o")
2799 ASSERT_EQ $n 2
2800
2801 # Overlapping candidates never double count.
2802 LET $once: INT = TEXT_COUNT("aaa", "aa")
2803 ASSERT_EQ $once 1
2804 "###
2805)]
2806fn text_count(
2807 text: String,
2809 needle: String,
2811) -> Result<Value> {
2812 let n = super::args::text_count_str(&text, &needle, "TEXT_COUNT")?;
2813 Ok(Value::int(n))
2814}
2815
2816#[oxdock_func(pure, returns = TypeTag::Int)]
2826#[example(
2827 name = "count matches",
2828 code = r###"
2829 # One line matches once no matter how many times it hits.
2830 IMPORT [STD]
2831 LET $n: INT = TEXT_COUNT_MATCHES("test a: test\ntest b: nope\ntest c: test", ": test")
2832 ASSERT_EQ $n 2
2833
2834 # A miss binds zero, never an error.
2835 LET $none: INT = TEXT_COUNT_MATCHES("test b: nope", ": test$")
2836 ASSERT_EQ $none 0
2837 "###
2838)]
2839fn text_count_matches(
2840 text: String,
2842 pattern: String,
2844) -> Result<Value> {
2845 let n = super::args::text_count_matches_str(&text, &pattern, "TEXT_COUNT_MATCHES")?;
2846 Ok(Value::int(n))
2847}
2848
2849#[oxdock_func(pure, returns = TypeTag::ListOf(std::sync::Arc::new(TypeTag::String)))]
2862#[example(
2863 name = "grep",
2864 code = r###"
2865 # Matching lines come back as a list, in order.
2866 IMPORT [STD]
2867 LET $hits: LIST<STRING> = TEXT_GREP("one\ntwo\none more", "^one")
2868 ASSERT_EQ $hits.0 "one"
2869 ASSERT_EQ $hits.1 "one more"
2870
2871 # A miss binds an empty list, never an error.
2872 LET $miss: LIST<STRING> = TEXT_GREP("one\ntwo", "^z")
2873 LET $joined: STRING = TEXT_JOIN($miss, ",")
2874 ASSERT_EQ $joined ""
2875
2876 # The (?i) flag ignores case, so uppercase lines match too.
2877 LET $folded: LIST<STRING> = TEXT_GREP("One\ntwo\nONE more", "(?i)^one")
2878 ASSERT_EQ $folded.0 "One"
2879 ASSERT_EQ $folded.1 "ONE more"
2880 "###
2881)]
2882#[example(
2883 name = "grep invert",
2884 code = r###"
2885 # The invert option keeps every non-matching line instead.
2886 IMPORT [STD]
2887 LET $kept: LIST<STRING> = TEXT_GREP("one\ntwo\none more", "^one", {invert: true})
2888 ASSERT_EQ $kept.0 "two"
2889
2890 # A pattern matching every line binds an empty list, never an error.
2891 LET $none: LIST<STRING> = TEXT_GREP("one\ntwo", "^", {invert: true})
2892 LET $joined: STRING = TEXT_JOIN($none, ",")
2893 ASSERT_EQ $joined ""
2894
2895 # Options ride into placeholders as MAP literals. Placeholder
2896 # strings unescape only backslash and quote, so multiline text
2897 # arrives through a variable.
2898 LET $two_lines: STRING = "one\ntwo"
2899 LET $msg: STRING = 'kept:{{ STD::TEXT_GREP($two_lines, "^one", {invert: true}) }}'
2900 ASSERT_EQ $msg "kept:two"
2901 "###
2902)]
2903fn text_grep(
2904 text: String,
2906 pattern: String,
2908 #[options("invert?: BOOL")]
2910 #[optional]
2911 options: BTreeMap<String, Value>,
2912) -> Result<Value> {
2913 let invert = super::args::text_invert_flag(&options);
2916 Ok(super::args::text_list_value(super::args::text_grep_str(
2917 &text,
2918 &pattern,
2919 invert,
2920 "TEXT_GREP",
2921 )?))
2922}
2923
2924#[oxdock_func(returns = TypeTag::Bool)]
2935#[example(
2936 name = "drain to end",
2937 code = r###"
2938 # Capture two lines, then drain to end of stream with no sentinel line.
2939 IMPORT [STD]
2940 LET $cap: PIPE
2941 WITH_IO [stdout=$cap] {
2942 ECHO "one"
2943 ECHO "two"
2944 }
2945
2946 # The loop exits on close, and the count proves both lines drained.
2947 LET $n: INT = 0
2948 WHILE !EOF($cap) {
2949 WITH_IO [stdin=$cap] READ_LINE $line
2950 $n = $n + 1
2951 }
2952 ASSERT_EQ $n 2
2953 "###
2954)]
2955fn eof<P: ProcessManager>(
2956 cx: &mut StepCtx<P>,
2957 pipe: PipeHandle,
2959) -> Result<Value> {
2960 let info = cx.state.io.inspect_pipe(&pipe);
2961 Ok(Value::bool(info.closed && info.buffered == 0))
2962}
2963
2964fn task_poll_result_fields() -> Arc<[Field]> {
2968 Arc::from(vec![
2969 Field {
2970 name: "state".to_string(),
2971 ty: TypeTag::String,
2972 docs: "Task phase: `running` or `finished`.",
2973 optional: false,
2974 },
2975 Field {
2976 name: "ok".to_string(),
2977 ty: TypeTag::Bool,
2978 docs: "True unless the task failed.",
2979 optional: false,
2980 },
2981 Field {
2982 name: "stdout_tail".to_string(),
2983 ty: TypeTag::String,
2984 docs: "Bounded stdout tail, live while running.",
2985 optional: false,
2986 },
2987 Field {
2988 name: "stderr_tail".to_string(),
2989 ty: TypeTag::String,
2990 docs: "Bounded stderr tail, live while running.",
2991 optional: false,
2992 },
2993 Field {
2994 name: "truncated_bytes".to_string(),
2995 ty: TypeTag::Int,
2996 docs: "Dropped head bytes past the per-stream cap.",
2997 optional: false,
2998 },
2999 Field {
3000 name: "exit_code".to_string(),
3001 ty: TypeTag::Int,
3002 docs: "Process exit code, present once finished.",
3003 optional: true,
3004 },
3005 Field {
3006 name: "result".to_string(),
3007 ty: TypeTag::Any,
3008 docs: "Task `RETURN` value, present on clean finish.",
3009 optional: true,
3010 },
3011 Field {
3012 name: "error".to_string(),
3013 ty: TypeTag::String,
3014 docs: "Failure text, present on failed finish.",
3015 optional: true,
3016 },
3017 ])
3018}
3019
3020#[oxdock_func(returns = TypeTag::Record(task_poll_result_fields()))]
3033#[example(
3034 name = "running poll",
3035 code = r###"
3036 # A sleeping task is still running on the first poll.
3037 IMPORT [STD]
3038 LET $t: HANDLE = ASYNC { SLEEP 30s }
3039 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)
3040 ASSERT_EQ $m.state "running"
3041 ASSERT_EQ $m.ok true
3042 # Clean up the sleeper so the run ends promptly.
3043 CANCEL $t
3044 "###
3045)]
3046#[example(
3047 name = "finished poll",
3048 code = r###"
3049 # A finished task reports its value and final tails, then still awaits.
3050 IMPORT [STD]
3051 LET $t: HANDLE = ASYNC { ECHO "hi"; SLEEP 1s; RETURN "done" }
3052 # Do other work while the task runs; poll once it should be done.
3053 SLEEP 2s
3054 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)
3055 ASSERT_EQ $m.state "finished"
3056 ASSERT_EQ $m.result "done"
3057 LET $o: STRING = AWAIT $t
3058 ASSERT_EQ $o "done"
3059 "###
3060)]
3061fn task_poll<P: ProcessManager>(
3062 cx: &mut StepCtx<P>,
3063 task: HandleValue,
3065) -> Result<Value> {
3066 let entry =
3067 super::handlers::resolve_task_entry_by_id(task.0, &format!("TASK_POLL({})", task.0), cx)?;
3068 let obs = entry.observe_completion();
3069 let (stdout_tail, stderr_tail, dropped) = entry.snapshot_tails();
3070 let mut out = BTreeMap::new();
3071 out.insert(
3072 "state".to_string(),
3073 Value::string(if obs.running { "running" } else { "finished" }.to_string()),
3074 );
3075 out.insert("ok".to_string(), Value::bool(obs.ok));
3076 if !obs.running {
3077 out.insert("exit_code".to_string(), Value::int(obs.exit_code));
3078 }
3079 if let Some(result) = obs.result {
3080 out.insert("result".to_string(), result);
3081 }
3082 if !obs.error.is_empty() {
3083 out.insert("error".to_string(), Value::string(obs.error));
3084 }
3085 out.insert("stdout_tail".to_string(), Value::string(stdout_tail));
3086 out.insert("stderr_tail".to_string(), Value::string(stderr_tail));
3087 out.insert(
3088 "truncated_bytes".to_string(),
3089 Value::int(dropped.min(i64::MAX as u64) as i64),
3090 );
3091 Ok(Value::map(out))
3092}
3093
3094fn meta_to_value(meta: &FuncMeta) -> Value {
3095 let mut map = BTreeMap::new();
3096 map.insert("name".to_string(), Value::string(meta.name.clone()));
3097 map.insert("module".to_string(), Value::string(meta.module.clone()));
3098 map.insert(
3099 "kind".to_string(),
3100 Value::string(meta.kind.label().to_string()),
3101 );
3102 let params = match &meta.params {
3103 Some(params) => Value::list(
3104 params
3105 .iter()
3106 .map(|p| {
3107 let mut entry = BTreeMap::new();
3108 entry.insert("name".to_string(), Value::string(p.name.clone()));
3109 entry.insert(
3110 "param_type".to_string(),
3111 Value::string(
3112 p.param_type
3113 .as_ref()
3114 .map(render_structural)
3115 .unwrap_or_default(),
3116 ),
3117 );
3118 entry.insert(
3119 "allowed".to_string(),
3120 Value::string(
3121 p.allowed
3122 .map(|values| values.join(", "))
3123 .unwrap_or_default(),
3124 ),
3125 );
3126 entry.insert("docs".to_string(), Value::string(String::new()));
3127 entry.insert("optional".to_string(), Value::bool(p.optional));
3128 entry.insert(
3129 "options".to_string(),
3130 match p.options {
3131 Some(keys) => Value::list(
3132 keys.iter()
3133 .map(|key| {
3134 let mut option = BTreeMap::new();
3135 option.insert(
3136 "name".to_string(),
3137 Value::string(key.name.to_string()),
3138 );
3139 option.insert(
3140 "value_type".to_string(),
3141 Value::string(render_structural(&key.value)),
3142 );
3143 option.insert(
3144 "required".to_string(),
3145 Value::bool(key.required),
3146 );
3147 option.insert(
3148 "default".to_string(),
3149 Value::string(
3150 key.default.unwrap_or_default().to_string(),
3151 ),
3152 );
3153 Value::map(option)
3154 })
3155 .collect(),
3156 ),
3157 None => Value::string(String::new()),
3158 },
3159 );
3160 Value::map(entry)
3161 })
3162 .collect(),
3163 ),
3164 None => Value::list(Vec::new()),
3168 };
3169 map.insert("params".to_string(), params);
3170 map.insert(
3171 "returns".to_string(),
3172 Value::string(
3173 meta.returns
3174 .as_ref()
3175 .map(render_structural)
3176 .unwrap_or_default(),
3177 ),
3178 );
3179 map.insert("rpn".to_string(), Value::bool(meta.rpn));
3180 map.insert(
3181 "summary".to_string(),
3182 Value::string(meta.summary.to_string()),
3183 );
3184 Value::map(map)
3185}
3186
3187#[derive(Debug, Clone)]
3191pub struct RecordSchema {
3192 pub name: &'static str,
3193 pub fields: std::sync::Arc<[Field]>,
3194}
3195
3196#[derive(Clone)]
3200pub struct HostModule<P: ProcessManager> {
3201 pub name: String,
3202 pub funcs: Vec<HostRegistration<P>>,
3203 pub types: Vec<&'static TypeDescriptor>,
3204 pub record_schemas: Vec<RecordSchema>,
3205 pub states: Vec<ModuleState>,
3212}
3213
3214#[derive(Clone)]
3218pub struct ModuleState {
3219 id: std::any::TypeId,
3220 state: std::sync::Arc<dyn std::any::Any + Send + Sync>,
3221}
3222
3223pub type PreRunInspector = dyn Fn(&[Step]) -> Result<()> + Send + Sync;
3227
3228#[derive(Clone)]
3234pub struct PreRunCheck {
3235 check: Arc<PreRunInspector>,
3236}
3237
3238impl PreRunCheck {
3239 pub fn new(check: impl Fn(&[Step]) -> Result<()> + Send + Sync + 'static) -> Self {
3241 Self {
3242 check: Arc::new(check),
3243 }
3244 }
3245
3246 pub fn run(&self, steps: &[Step]) -> Result<()> {
3248 (self.check)(steps)
3249 }
3250}
3251
3252impl<P: ProcessManager> HostModule<P> {
3253 pub fn with_state<T: Send + Sync + 'static>(mut self, state: std::sync::Arc<T>) -> Self {
3256 self.states.push(ModuleState {
3257 id: std::any::TypeId::of::<T>(),
3258 state,
3259 });
3260 self
3261 }
3262
3263 pub fn check_pre_run(&self, steps: &[Step]) -> Result<()> {
3267 for state in &self.states {
3268 if let Some(check) = state.state.downcast_ref::<PreRunCheck>() {
3269 check.run(steps)?;
3270 }
3271 }
3272 Ok(())
3273 }
3274}
3275
3276impl<P: ProcessManager> ExecState<P> {
3277 pub fn register_module(&mut self, module: HostModule<P>) {
3280 for registration in module.funcs {
3281 match registration {
3282 HostRegistration::Stateful { name, meta, func } => {
3283 self.functions.register_host(&module.name, name, meta, func);
3284 }
3285 HostRegistration::Pure { name, meta, func } => {
3286 self.functions
3287 .register_pure_host(&module.name, name, meta, func);
3288 }
3289 HostRegistration::Both {
3290 name,
3291 meta,
3292 func,
3293 template,
3294 } => {
3295 self.functions
3296 .register_both_host(&module.name, name, meta, func, template);
3297 }
3298 }
3299 }
3300 for descriptor in module.types {
3301 self.register_type(descriptor);
3302 }
3303 for schema in module.record_schemas {
3304 self.register_record_schema(schema.name, schema.fields);
3305 }
3306 for state in module.states {
3307 self.module_states
3308 .insert((module.name.clone(), state.id), state.state);
3309 }
3310 }
3311
3312 pub fn list_functions(&self) -> Vec<FuncMeta> {
3314 let mut out: Vec<FuncMeta> = self.functions.entries_metas().into_iter().collect();
3315 if !out.iter().any(|m| m.name == KEYWORD_INSPECT) {
3317 out.push(FuncMeta {
3318 name: KEYWORD_INSPECT.to_string(),
3319 module: STD_MODULE_NAME.to_string(),
3320 kind: FuncKind::HostCtx,
3321 params: None,
3322 returns: Some(TypeTag::Map),
3323 rpn: false,
3324 summary: "Inspect a variable binding.",
3325 docs: "INSPECT($var): dedicated AST node taking a variable, not a value.",
3326 examples: &[],
3327 });
3328 }
3329 out.sort_by(|a, b| a.name.cmp(&b.name));
3330 out
3331 }
3332
3333 pub fn describe_function(&self, name: &str) -> Option<Value> {
3335 if let Some(meta) = self.functions.meta(name) {
3336 return Some(meta_to_value(&meta));
3337 }
3338 if name == KEYWORD_INSPECT {
3340 return Some(meta_to_value(&FuncMeta {
3341 name: KEYWORD_INSPECT.to_string(),
3342 module: STD_MODULE_NAME.to_string(),
3343 kind: FuncKind::HostCtx,
3344 params: None,
3345 returns: Some(TypeTag::Map),
3346 rpn: false,
3347 summary: "Inspect a variable binding.",
3348 docs: "INSPECT($var): dedicated AST node taking a variable, not a value.",
3349 examples: &[],
3350 }));
3351 }
3352 None
3353 }
3354
3355 pub(super) fn clone_native_pure(&self, name: &str) -> Option<PureFn> {
3356 self.functions.clone_pure_fn(name)
3357 }
3358
3359 pub fn pure_function_table(&self) -> Arc<PureTable> {
3364 self.functions.pure_shared()
3365 }
3366
3367 pub(super) fn clone_native_ctx(&self, name: &str) -> Option<NativeFn<P>> {
3368 self.functions.clone_ctx_fn(name)
3369 }
3370
3371 pub(super) fn native_meta(&self, name: &str) -> Option<FuncMeta> {
3372 self.functions.meta(name)
3373 }
3374}
3375
3376#[cfg(test)]
3377mod tests {
3378 use super::*;
3379
3380 #[test]
3381 fn describe_entry_renders_union_spellings() {
3382 let union = oxdock_parser::union_tag!(String, Pipe);
3388 let meta = FuncMeta {
3389 name: "T::F".to_string(),
3390 module: "T".to_string(),
3391 kind: FuncKind::HostPure,
3392 params: Some(vec![FuncParam {
3393 name: "text".to_string(),
3394 param_type: Some(union.clone()),
3395 allowed: None,
3396 docs: "",
3397 options: None,
3398 optional: false,
3399 }]),
3400 returns: Some(union),
3401 rpn: false,
3402 summary: "test-only",
3403 docs: "test-only",
3404 examples: &[],
3405 };
3406 let value = meta_to_value(&meta);
3407 let map = value.as_map().expect("describe value is a map");
3408 let params = map
3409 .get("params")
3410 .expect("params key")
3411 .as_list()
3412 .expect("params is a list");
3413 let first = params[0].as_map().expect("entry is a map");
3414 assert_eq!(
3415 first.get("param_type").and_then(Value::as_str),
3416 Some("STRING|PIPE"),
3417 "param renders the set"
3418 );
3419 assert_eq!(
3420 map.get("returns").and_then(Value::as_str),
3421 Some("STRING|PIPE"),
3422 "returns render the set"
3423 );
3424 }
3425
3426 #[test]
3427 fn describe_entry_carries_optional_flag() {
3428 let meta = FuncMeta {
3432 name: "T::F".to_string(),
3433 module: "T".to_string(),
3434 kind: FuncKind::HostPure,
3435 params: Some(vec![
3436 FuncParam {
3437 name: "url".to_string(),
3438 param_type: Some(TypeTag::String),
3439 allowed: None,
3440 docs: "",
3441 options: None,
3442 optional: false,
3443 },
3444 FuncParam {
3445 name: "options".to_string(),
3446 param_type: Some(TypeTag::Map),
3447 allowed: None,
3448 docs: "",
3449 options: None,
3450 optional: true,
3451 },
3452 ]),
3453 returns: Some(TypeTag::String),
3454 rpn: false,
3455 summary: "test-only",
3456 docs: "test-only",
3457 examples: &[],
3458 };
3459 let value = meta_to_value(&meta);
3460 let map = value.as_map().expect("describe value is a map");
3461 let params = map
3462 .get("params")
3463 .expect("params key")
3464 .as_list()
3465 .expect("params is a list");
3466 assert_eq!(params.len(), 2);
3467 let first = params[0].as_map().expect("entry is a map");
3468 let second = params[1].as_map().expect("entry is a map");
3469 assert_eq!(
3470 first.get("optional").and_then(Value::as_bool),
3471 Some(false),
3472 "required param must read false"
3473 );
3474 assert_eq!(
3475 second.get("optional").and_then(Value::as_bool),
3476 Some(true),
3477 "omittable param must read true"
3478 );
3479 }
3480
3481 #[test]
3482 fn template_twins_mirror_string_paths_and_refuse_pipes() {
3483 let pipe = Value::pipe_fresh();
3489 type TwinCase = (&'static str, Box<dyn Fn() -> Result<Value>>);
3490 let cases: Vec<TwinCase> = vec![
3491 (
3492 "TEXT_TRIM",
3493 Box::new(|| text_trim_string(Value::string(" hello ".to_string()))),
3494 ),
3495 (
3496 "TEXT_TRIM_PREFIX",
3497 Box::new(|| {
3498 text_trim_prefix_string(Value::string("v1".to_string()), "v".to_string())
3499 }),
3500 ),
3501 (
3502 "TEXT_TRIM_SUFFIX",
3503 Box::new(|| {
3504 text_trim_suffix_string(Value::string("a.gz".to_string()), "x".to_string())
3505 }),
3506 ),
3507 (
3508 "TEXT_TO_UPPER",
3509 Box::new(|| text_to_upper_string(Value::string("hi".to_string()))),
3510 ),
3511 (
3512 "TEXT_TO_LOWER",
3513 Box::new(|| text_to_lower_string(Value::string("HI".to_string()))),
3514 ),
3515 (
3516 "TEXT_REPLACE",
3517 Box::new(|| {
3518 text_replace_string(
3519 Value::string("ab".to_string()),
3520 "b".to_string(),
3521 "c".to_string(),
3522 )
3523 }),
3524 ),
3525 (
3526 "TEXT_REPLACE_REGEX",
3527 Box::new(|| {
3528 text_replace_regex_string(
3529 Value::string("ab".to_string()),
3530 "b".to_string(),
3531 "c".to_string(),
3532 )
3533 }),
3534 ),
3535 ];
3536 assert_eq!(cases.len(), 7, "every mirror op needs a twin row");
3537 for (name, run) in &cases {
3538 let value = run().unwrap_or_else(|e| panic!("{name} twin must answer strings: {e:#}"));
3539 assert!(
3540 value.as_str().is_some(),
3541 "{name} twin must answer STRING, got {}",
3542 value.type_name()
3543 );
3544 }
3545 assert_eq!(
3546 text_trim_string(Value::string(" hello ".to_string()))
3547 .expect("trim twin")
3548 .as_str(),
3549 Some("hello")
3550 );
3551 let pipe_cases: Vec<(&str, Result<Value>)> = vec![
3553 ("TEXT_TRIM", text_trim_string(pipe.clone())),
3554 (
3555 "TEXT_TRIM_PREFIX",
3556 text_trim_prefix_string(pipe.clone(), "v".to_string()),
3557 ),
3558 (
3559 "TEXT_TRIM_SUFFIX",
3560 text_trim_suffix_string(pipe.clone(), ".gz".to_string()),
3561 ),
3562 ("TEXT_TO_UPPER", text_to_upper_string(pipe.clone())),
3563 ("TEXT_TO_LOWER", text_to_lower_string(pipe.clone())),
3564 (
3565 "TEXT_REPLACE",
3566 text_replace_string(pipe.clone(), "a".to_string(), "b".to_string()),
3567 ),
3568 (
3569 "TEXT_REPLACE_REGEX",
3570 text_replace_regex_string(pipe.clone(), "a".to_string(), "b".to_string()),
3571 ),
3572 ];
3573 for (name, result) in pipe_cases {
3574 let err = result.expect_err(&format!("{name} twin must refuse PIPE"));
3575 assert!(
3576 format!("{err:#}").contains("step IO"),
3577 "{name} refusal names the missing context: {err:#}"
3578 );
3579 }
3580 }
3581
3582 #[test]
3583 fn shell_words_join_split_round_trip() {
3584 let words = vec![
3588 "gh".to_string(),
3589 "issue".to_string(),
3590 "comment".to_string(),
3591 "with spaces".to_string(),
3592 "it's".to_string(),
3593 "say \"hi\"".to_string(),
3594 "$HOME".to_string(),
3595 "$(whoami)".to_string(),
3596 "C:\\path\\to".to_string(),
3597 "naïve café".to_string(),
3598 "".to_string(),
3599 ];
3600 let joined = shell_words::join(&words);
3601 let back = shell_words::split(&joined).expect("join output must parse");
3602 assert_eq!(back, words);
3603 assert!(shell_words::split("unbalanced \"quote").is_err());
3604 }
3605}