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, GuardExpr, KEYWORD_INSPECT, SCRIPT_MODULE_NAME, STD_MODULE_NAME, SemaphoreState, Step,
9 TypeTag, Value, base_name, guards_overlap, 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
31pub(super) fn file_func_key(defining_file: &str, name: &str) -> String {
35 qualify(defining_file, name)
36}
37
38pub(super) fn ambiguous_alias_message(alias: &str, name: &str, files: &HashSet<String>) -> String {
41 let mut files: Vec<&str> = files.iter().map(|file| file.as_str()).collect();
42 files.sort();
43 format!(
44 "function `{alias}::{name}` is ambiguous: alias `{alias}` is imported from multiple files ({})",
45 files.join(", ")
46 )
47}
48
49pub(super) enum AliasResolution {
55 Global,
57 Canonical(String),
59 Unknown,
61 Ambiguous {
64 alias: String,
65 base: String,
66 files: HashSet<String>,
67 },
68 Any {
75 base: String,
76 files: HashSet<String>,
77 has_host: bool,
78 },
79}
80
81pub(super) type AliasTargets = HashMap<String, Vec<(Option<String>, Option<GuardExpr>)>>;
88
89pub(super) fn classify_alias_call(
95 unit_targets: &AliasTargets,
96 name: &str,
97 exists: &dyn Fn(&str) -> bool,
98) -> AliasResolution {
99 let Some((alias, base)) = name.split_once("::") else {
100 return AliasResolution::Global;
101 };
102 if alias == SCRIPT_MODULE_NAME {
103 return AliasResolution::Global;
104 }
105 let Some(entries) = unit_targets.get(alias) else {
106 return AliasResolution::Global;
107 };
108 if entries.is_empty() {
109 return AliasResolution::Unknown;
110 }
111 let mut files: Vec<(&str, Vec<Option<&GuardExpr>>)> = Vec::new();
114 let mut host_guards: Vec<Option<&GuardExpr>> = Vec::new();
115 for (file, guard) in entries {
116 match file {
117 Some(path) => match files.iter_mut().find(|(known, _)| *known == path) {
118 Some((_, guards)) => guards.push(guard.as_ref()),
119 None => files.push((path, vec![guard.as_ref()])),
120 },
121 None => host_guards.push(guard.as_ref()),
122 }
123 }
124 if files.is_empty() {
125 return AliasResolution::Unknown;
126 }
127 let overlaps = |left: &[Option<&GuardExpr>], right: &[Option<&GuardExpr>]| {
128 left.iter()
129 .any(|a| right.iter().any(|b| guards_overlap(*a, *b)))
130 };
131 if files.len() == 1 {
132 let disjoint_host = host_guards
136 .iter()
137 .any(|host| !overlaps(&files[0].1, &[*host]));
138 if !disjoint_host {
139 return AliasResolution::Canonical(file_func_key(files[0].0, base));
140 }
141 let mut all = HashSet::new();
142 all.insert(files[0].0.to_string());
143 return AliasResolution::Any {
144 base: base.to_string(),
145 files: all,
146 has_host: true,
147 };
148 }
149 let mut ambiguous = HashSet::new();
150 for (i, (file, guards)) in files.iter().enumerate() {
151 for (other, other_guards) in files.iter().skip(i + 1) {
152 if overlaps(guards, other_guards)
153 && (exists(&file_func_key(file, base)) || exists(&file_func_key(other, base)))
154 {
155 ambiguous.insert((*file).to_string());
156 ambiguous.insert((*other).to_string());
157 }
158 }
159 }
160 if !ambiguous.is_empty() {
161 return AliasResolution::Ambiguous {
162 alias: alias.to_string(),
163 base: base.to_string(),
164 files: ambiguous,
165 };
166 }
167 let all: HashSet<String> = files.iter().map(|(file, _)| (*file).to_string()).collect();
168 if all.iter().any(|file| exists(&file_func_key(file, base))) {
169 return AliasResolution::Any {
170 base: base.to_string(),
171 files: all,
172 has_host: !host_guards.is_empty(),
173 };
174 }
175 AliasResolution::Unknown
176}
177
178pub(super) fn disjoint_template_script_visible(
186 base: &str,
187 files: &HashSet<String>,
188 has_host: bool,
189 exists: &dyn Fn(&str) -> bool,
190) -> bool {
191 !has_host && !files.is_empty() && files.iter().all(|file| exists(&file_func_key(file, base)))
192}
193
194pub(super) fn disjoint_alias_placeholder_miss(
201 module: &str,
202 name: &str,
203 base: &str,
204 files: &HashSet<String>,
205 has_host: bool,
206 is_script: &dyn Fn(&str) -> bool,
207) -> String {
208 let script = disjoint_template_script_visible(base, files, has_host, is_script);
209 describe_placeholder_miss(module, name, script, false, !script)
210 .expect("disjoint miss always renders")
211}
212
213pub(super) fn spellings_for_defining_file(
220 unit_targets: &AliasTargets,
221 defining: &str,
222 base: &str,
223 is_script: &dyn Fn(&str) -> bool,
224) -> (Vec<String>, Vec<(String, HashSet<String>)>) {
225 let mut direct = Vec::new();
226 let mut ambiguous = Vec::new();
227 for (alias, files) in unit_targets {
228 if !files
229 .iter()
230 .any(|(file, _)| file.as_deref() == Some(defining))
231 {
232 continue;
233 }
234 let spelling = qualify(alias, base);
235 match classify_alias_call(unit_targets, &spelling, &|key| {
236 key == file_func_key(defining, base)
237 }) {
238 AliasResolution::Canonical(_) => direct.push(spelling),
239 AliasResolution::Ambiguous { files, .. } => {
240 ambiguous.push((spelling, files));
241 }
242 AliasResolution::Any {
243 base,
244 files,
245 has_host,
246 } => {
247 if disjoint_template_script_visible(&base, &files, has_host, is_script) {
248 direct.push(spelling);
249 }
250 }
251 AliasResolution::Global | AliasResolution::Unknown => {}
252 }
253 }
254 (direct, ambiguous)
255}
256
257impl FuncKind {
258 pub fn label(&self) -> &'static str {
259 match self {
260 FuncKind::Script => "script",
261 FuncKind::HostCtx | FuncKind::HostPure => "host",
262 }
263 }
264}
265
266#[derive(Debug, Clone)]
284pub struct FuncParam {
285 pub name: String,
286 pub param_type: Option<TypeTag>,
287 pub allowed: Option<&'static [&'static str]>,
288 pub docs: &'static str,
289 pub options: Option<&'static [ParamOption]>,
290 pub optional: bool,
291}
292
293pub fn required_arity(params: &[FuncParam]) -> usize {
298 params
299 .iter()
300 .rev()
301 .take_while(|param| param.optional)
302 .fold(params.len(), |count, _| count - 1)
303}
304
305pub fn fill_optional_args(params: &[FuncParam], mut values: Vec<Value>) -> Vec<Value> {
310 assert!(
311 values.len() <= params.len(),
312 "arity gate must run before fill_optional_args"
313 );
314 assert!(
315 values.len() >= required_arity(params),
316 "arity gate must run before fill_optional_args"
317 );
318 while values.len() < params.len() {
319 values.push(Value::map(BTreeMap::new()));
320 }
321 values
322}
323
324#[derive(Debug, Clone)]
331pub struct ParamOption {
332 pub name: &'static str,
333 pub value: TypeTag,
334 pub required: bool,
335 pub default: Option<&'static str>,
336}
337
338#[derive(Debug, Clone)]
344pub struct FuncMeta {
345 pub name: String,
346 pub module: String,
350 pub kind: FuncKind,
351 pub params: Option<Vec<FuncParam>>,
352 pub returns: Option<TypeTag>,
353 pub rpn: bool,
354 pub summary: &'static str,
355 pub docs: &'static str,
356 pub examples: &'static [crate::Example],
362}
363
364pub type PureFn = Arc<dyn Fn(Vec<Value>) -> Result<Value> + Send + Sync>;
367
368pub type NativeFn<P> = Arc<dyn Fn(&mut StepCtx<P>, Vec<Value>) -> Result<Value> + Send + Sync>;
370
371pub trait OxDockFn<P: ProcessManager> {
375 fn registration() -> HostRegistration<P>;
378}
379
380pub enum HostRegistration<P: ProcessManager> {
389 Stateful {
390 name: String,
391 meta: FuncMeta,
392 func: NativeFn<P>,
393 },
394 Pure {
395 name: String,
396 meta: FuncMeta,
397 func: PureFn,
398 },
399 Both {
400 name: String,
401 meta: FuncMeta,
402 func: NativeFn<P>,
403 template: PureFn,
404 },
405}
406
407impl<P: ProcessManager> Clone for HostRegistration<P> {
410 fn clone(&self) -> Self {
411 match self {
412 HostRegistration::Stateful { name, meta, func } => HostRegistration::Stateful {
413 name: name.clone(),
414 meta: meta.clone(),
415 func: Arc::clone(func),
416 },
417 HostRegistration::Pure { name, meta, func } => HostRegistration::Pure {
418 name: name.clone(),
419 meta: meta.clone(),
420 func: Arc::clone(func),
421 },
422 HostRegistration::Both {
423 name,
424 meta,
425 func,
426 template,
427 } => HostRegistration::Both {
428 name: name.clone(),
429 meta: meta.clone(),
430 func: Arc::clone(func),
431 template: Arc::clone(template),
432 },
433 }
434 }
435}
436
437impl<P: ProcessManager> HostRegistration<P> {
438 pub fn meta(&self) -> &FuncMeta {
441 match self {
442 HostRegistration::Stateful { meta, .. } => meta,
443 HostRegistration::Pure { meta, .. } => meta,
444 HostRegistration::Both { meta, .. } => meta,
445 }
446 }
447}
448
449#[derive(Debug, Clone)]
455pub(super) struct FuncDefData {
456 pub(super) params: Vec<(String, TypeTag, bool)>,
457 pub(super) return_type: TypeTag,
458 pub(super) return_spelling: String,
459 pub(super) is_async: bool,
460 pub(super) body: Vec<Step>,
461 pub(super) module: Option<String>,
466}
467
468pub fn optional_zero_value(tag: &TypeTag) -> Result<Value> {
476 match tag {
477 TypeTag::Bool => Ok(Value::bool(false)),
478 TypeTag::String | TypeTag::Any => Ok(Value::string(String::new())),
479 TypeTag::Int => Ok(Value::int(0)),
480 TypeTag::Float => Ok(Value::float(0.0)),
481 TypeTag::List | TypeTag::ListOf(_) => Ok(Value::list(Vec::new())),
482 TypeTag::Map | TypeTag::MapOf(_) => Ok(Value::map(BTreeMap::new())),
483 TypeTag::Record(fields)
484 if fields
485 .iter()
486 .all(|field| field.optional || field.default.is_some()) =>
487 {
488 Ok(Value::map(BTreeMap::new()))
489 }
490 other => anyhow::bail!(
491 "no zero value for {}; omit the `?` or pass the argument explicitly",
492 oxdock_parser::render_structural(other)
493 ),
494 }
495}
496
497pub fn resolve_script_params<P: ProcessManager>(
503 state: &ExecState<P>,
504 func_name: &str,
505 params: &[(String, String, bool)],
506) -> Result<Vec<(String, TypeTag, bool)>> {
507 let mut resolved = Vec::with_capacity(params.len());
508 for (pname, ptype, optional) in params {
509 let clean = pname.trim_start_matches('$').to_string();
510 let tag = state
511 .resolve_tag(ptype)
512 .map_err(|err| anyhow::anyhow!("function `{func_name}`: {err:#}"))?;
513 state.check_declaration_tag(&format!("function `{func_name}` param `${clean}`"), &tag)?;
514 if *optional {
515 optional_zero_value(&tag).map(|_| ()).map_err(|err| {
516 anyhow::anyhow!("function `{func_name}` optional param `${clean}`: {err:#}")
517 })?;
518 }
519 resolved.push((clean, tag, *optional));
520 }
521 Ok(resolved)
522}
523
524pub fn check_script_param_tags(func_name: &str, params: &[(String, TypeTag, bool)]) -> Result<()> {
527 for (pname, tag, optional) in params {
528 if *optional {
529 optional_zero_value(tag).map(|_| ()).map_err(|err| {
530 anyhow::anyhow!("function `{func_name}` optional param `${pname}`: {err:#}")
531 })?;
532 }
533 }
534 Ok(())
535}
536
537pub(super) enum FuncBody<P: ProcessManager> {
542 Script(FuncDefData),
543 Pure(PureFn),
544 Ctx(NativeFn<P>),
545 Both { pure: PureFn, ctx: NativeFn<P> },
546}
547
548impl<P: ProcessManager> Clone for FuncBody<P> {
550 fn clone(&self) -> Self {
551 match self {
552 FuncBody::Script(def) => FuncBody::Script(def.clone()),
553 FuncBody::Pure(func) => FuncBody::Pure(Arc::clone(func)),
554 FuncBody::Ctx(func) => FuncBody::Ctx(Arc::clone(func)),
555 FuncBody::Both { pure, ctx } => FuncBody::Both {
556 pure: Arc::clone(pure),
557 ctx: Arc::clone(ctx),
558 },
559 }
560 }
561}
562
563pub(super) struct FuncEntry<P: ProcessManager> {
567 pub(super) meta: FuncMeta,
568 pub(super) body: FuncBody<P>,
569}
570
571impl<P: ProcessManager> Clone for FuncEntry<P> {
573 fn clone(&self) -> Self {
574 Self {
575 meta: self.meta.clone(),
576 body: self.body.clone(),
577 }
578 }
579}
580
581struct ScopeFrame<P: ProcessManager> {
584 defined: HashSet<String>,
585 shadowed: Vec<(String, FuncEntry<P>)>,
586}
587
588impl<P: ProcessManager> Clone for ScopeFrame<P> {
590 fn clone(&self) -> Self {
591 Self {
592 defined: self.defined.clone(),
593 shadowed: self.shadowed.clone(),
594 }
595 }
596}
597
598pub type PureTable = HashMap<String, HashMap<String, PureFn>>;
608
609pub fn placeholder_resolver(table: Arc<PureTable>) -> oxdock_process::PlaceholderCall {
618 Arc::new(move |module, func, args| {
619 let callee = table
620 .get(module)
621 .and_then(|entries| entries.get(func))
622 .ok_or_else(|| {
623 let mut known: Vec<String> = table
624 .iter()
625 .flat_map(|(m, entries)| entries.keys().map(move |f| format!("{m}::{f}")))
626 .collect();
627 known.sort();
628 anyhow::anyhow!(
629 "unknown placeholder function '{module}::{func}'; known functions: {}",
630 known.join(", ")
631 )
632 })?;
633 callee(args)
634 })
635}
636
637pub(super) fn describe_placeholder_miss(
644 module: &str,
645 name: &str,
646 is_script: bool,
647 is_stateful: bool,
648 alias_known: bool,
649) -> Option<String> {
650 let qualified = qualify(module, name);
651 if is_script {
652 let call = if module == SCRIPT_MODULE_NAME {
653 format!("{name}(...)")
654 } else {
655 format!("{qualified}(...)")
656 };
657 return Some(format!(
658 "placeholder function '{qualified}' is a script function and cannot run in {{{{ }}}}; bind the result first with LET $v = {call} then interpolate {{{{ $v }}}}"
659 ));
660 }
661 if is_stateful {
662 return Some(format!(
663 "placeholder function '{qualified}' is stateful and cannot run in {{{{ }}}}; capture it first with LET then interpolate {{{{ $v }}}}"
664 ));
665 }
666 if alias_known {
667 return Some(format!(
668 "placeholder function '{qualified}': no function '{name}' under file alias '{module}'; check the file's EXPORT list and the IMPORT harvest, or bind a known function first with LET then interpolate {{{{ $v }}}}"
669 ));
670 }
671 None
672}
673
674pub(super) struct PlaceholderClasses {
677 pub script: HashSet<String>,
678 pub stateful: HashSet<String>,
679 pub aliases: HashSet<String>,
680 pub ambiguous: HashMap<String, HashSet<String>>,
682}
683
684impl PlaceholderClasses {
685 pub(super) fn describe(&self, module: &str, name: &str) -> Option<String> {
686 let qualified = qualify(module, name);
687 if let Some(files) = self.ambiguous.get(&qualified) {
688 return Some(ambiguous_alias_message(module, name, files));
689 }
690 describe_placeholder_miss(
691 module,
692 name,
693 self.script.contains(&qualified),
694 self.stateful.contains(&qualified),
695 self.aliases.contains(module),
696 )
697 }
698}
699
700pub struct FunctionRegistry<P: ProcessManager> {
701 entries: HashMap<String, FuncEntry<P>>,
702 scopes: Vec<ScopeFrame<P>>,
703 pure_shared: Arc<PureTable>,
704 script_docs: HashMap<String, (String, String)>,
708}
709
710impl<P: ProcessManager> FunctionRegistry<P> {
711 pub(super) fn with_builtins() -> Self {
712 let mut reg = Self {
713 entries: HashMap::new(),
714 pure_shared: Arc::new(HashMap::new()),
715 script_docs: HashMap::new(),
716 scopes: vec![ScopeFrame {
717 defined: HashSet::new(),
718 shadowed: Vec::new(),
719 }],
720 };
721 for host in Self::builtin_registrations() {
725 match host {
726 HostRegistration::Stateful { name, meta, func } => {
727 reg.insert_qualified(STD_MODULE_NAME, name, meta, FuncBody::Ctx(func));
728 }
729 HostRegistration::Pure { name, meta, func } => {
730 reg.insert_qualified(STD_MODULE_NAME, name, meta, FuncBody::Pure(func));
731 }
732 HostRegistration::Both {
733 name,
734 meta,
735 func,
736 template,
737 } => {
738 reg.insert_qualified(
739 STD_MODULE_NAME,
740 name,
741 meta,
742 FuncBody::Both {
743 pure: template,
744 ctx: func,
745 },
746 );
747 }
748 }
749 }
750 reg
751 }
752
753 pub(super) fn builtin_registrations() -> Vec<HostRegistration<P>> {
758 vec![
759 Int::registration(),
760 Float::registration(),
761 BoolConvert::registration(),
762 BoolOr::registration(),
763 FormatByteCount::registration(),
764 ParseByteCount::registration(),
765 FormatDuration::registration(),
766 ParseDuration::registration(),
767 Types::registration(),
768 TypeDescribe::registration(),
769 Glob::registration(),
770 LoadToml::registration(),
771 LoadJson::registration(),
772 HashSha256::registration(),
773 Cwd::registration(),
774 ParseToml::registration(),
775 ParseJson::registration(),
776 PathType::registration(),
777 PathWritable::registration(),
778 IsExec::registration(),
779 HasKey::registration(),
780 Get::registration(),
781 MapSet::registration(),
782 MergeMaps::registration(),
783 Base64Encode::registration(),
784 Base64Decode::registration(),
785 Rand::registration(),
786 ToJson::registration(),
787 TypeOf::registration(),
788 Functions::registration(),
789 Describe::registration(),
790 IsMain::registration(),
791 IsTerminal::registration(),
792 Eof::registration(),
793 TaskPoll::registration(),
794 Version::registration(),
795 Interpreter::registration(),
796 Argv::registration(),
797 ParseArgs::registration(),
798 ParseFlags::registration(),
799 ParsePositionals::registration(),
800 TextTrim::registration(),
801 TextTrimPrefix::registration(),
802 TextTrimSuffix::registration(),
803 PathJoin::registration(),
804 TextToUpper::registration(),
805 TextToLower::registration(),
806 TextReplace::registration(),
807 TextReplaceRegex::registration(),
808 TextSplit::registration(),
809 TextJoin::registration(),
810 TextLines::registration(),
811 TextFields::registration(),
812 TextMatch::registration(),
813 TextExtract::registration(),
814 TextStartsWith::registration(),
815 TextEndsWith::registration(),
816 TextContains::registration(),
817 Len::registration(),
818 TextCount::registration(),
819 TextCountMatches::registration(),
820 TextGrep::registration(),
821 TextLinesRange::registration(),
822 SemaphoreNew::registration(),
823 SemaphoreTryAcquire::registration(),
824 SemaphoreAvailable::registration(),
825 ShellSplitArgs::registration(),
826 ShellJoinArgs::registration(),
827 ]
828 }
829
830 pub(super) fn keys(&self) -> HashSet<String> {
833 self.entries.keys().cloned().collect()
834 }
835
836 pub(super) fn get(&self, name: &str) -> Option<FuncEntry<P>> {
838 self.entries.get(name).cloned()
839 }
840
841 pub(super) fn describe_unit_placeholder_miss(
847 &self,
848 unit_targets: &AliasTargets,
849 module: &str,
850 name: &str,
851 ) -> Option<String> {
852 let qualified = qualify(module, name);
853 match classify_alias_call(unit_targets, &qualified, &|key| {
858 self.entries.contains_key(key)
859 }) {
860 AliasResolution::Canonical(canonical) => {
861 if let Some(entry) = self.entries.get(&canonical) {
862 if let Some(miss) = Self::placeholder_miss_for_body(module, name, &entry.body) {
863 return Some(miss);
864 }
865 None
866 } else {
867 describe_placeholder_miss(module, name, false, false, true)
868 }
869 }
870 AliasResolution::Global => {
871 if let Some(entry) = self.entries.get(&qualified) {
872 if let Some(miss) = Self::placeholder_miss_for_body(module, name, &entry.body) {
876 return Some(miss);
877 }
878 }
879 None
880 }
881 AliasResolution::Ambiguous { files, .. } => {
882 Some(ambiguous_alias_message(module, name, &files))
883 }
884 AliasResolution::Unknown => describe_placeholder_miss(module, name, false, false, true),
885 AliasResolution::Any {
891 base,
892 files,
893 has_host,
894 } => Some(disjoint_alias_placeholder_miss(
895 module,
896 name,
897 &base,
898 &files,
899 has_host,
900 &|key| matches!(self.entries.get(key), Some(entry) if matches!(entry.body, FuncBody::Script(_))),
901 )),
902 }
903 }
904
905 fn placeholder_miss_for_body(module: &str, name: &str, body: &FuncBody<P>) -> Option<String> {
909 match body {
910 FuncBody::Script(_) => describe_placeholder_miss(module, name, true, false, false),
911 FuncBody::Ctx(_) => describe_placeholder_miss(module, name, false, true, false),
912 FuncBody::Pure(_) | FuncBody::Both { .. } => None,
913 }
914 }
915
916 pub(super) fn placeholder_snapshot(&self, unit_targets: &AliasTargets) -> PlaceholderClasses {
920 let mut script = HashSet::new();
921 let mut stateful = HashSet::new();
922 let mut ambiguous: HashMap<String, HashSet<String>> = HashMap::new();
923 for (key, entry) in self.entries.iter() {
924 let Some((module, base)) = split_qualified(key) else {
925 continue;
926 };
927 match &entry.body {
928 FuncBody::Script(def) => {
929 if module == SCRIPT_MODULE_NAME {
930 script.insert(key.clone());
932 continue;
933 }
934 let defining = def.module.as_deref().unwrap_or(module);
942 let (direct, ambiguous_here) = spellings_for_defining_file(
943 unit_targets,
944 defining,
945 base,
946 &|key| matches!(self.entries.get(key), Some(entry) if matches!(entry.body, FuncBody::Script(_))),
947 );
948 script.extend(direct);
949 for (spelling, files) in ambiguous_here {
950 ambiguous.entry(spelling).or_default().extend(files);
951 }
952 }
953 FuncBody::Ctx(_) => {
954 stateful.insert(key.clone());
955 }
956 FuncBody::Pure(_) | FuncBody::Both { .. } => {}
957 }
958 }
959 let aliases = unit_targets.keys().cloned().collect();
960 PlaceholderClasses {
961 script,
962 stateful,
963 aliases,
964 ambiguous,
965 }
966 }
967
968 fn insert_native(&mut self, name: String, meta: FuncMeta, body: FuncBody<P>) {
969 self.entries.insert(name, FuncEntry { meta, body });
970 self.rebuild_pure_shared();
971 }
972
973 fn rebuild_pure_shared(&mut self) {
979 let mut table: PureTable = HashMap::new();
980 for (name, entry) in &self.entries {
981 let func = match &entry.body {
982 FuncBody::Pure(func) => func,
983 FuncBody::Both { pure, .. } => pure,
984 FuncBody::Script(_) | FuncBody::Ctx(_) => continue,
985 };
986 if let Some((module, base)) = split_qualified(name) {
987 table
988 .entry(module.to_string())
989 .or_default()
990 .insert(base.to_string(), Arc::clone(func));
991 }
992 }
993 self.pure_shared = Arc::new(table);
994 }
995
996 fn insert_qualified(
1000 &mut self,
1001 module: &str,
1002 base: String,
1003 mut meta: FuncMeta,
1004 body: FuncBody<P>,
1005 ) {
1006 meta.name = qualify(module, &base);
1007 meta.module = module.to_string();
1008 if self.entries.contains_key(&meta.name) {
1013 panic!("duplicate function registration `{}`", meta.name);
1014 }
1015 self.insert_native(meta.name.clone(), meta, body);
1016 }
1017
1018 pub(super) fn register_host(
1019 &mut self,
1020 module: &str,
1021 name: String,
1022 mut meta: FuncMeta,
1023 func: NativeFn<P>,
1024 ) {
1025 meta.kind = FuncKind::HostCtx;
1026 self.insert_qualified(module, name, meta, FuncBody::Ctx(func));
1027 }
1028
1029 pub(super) fn register_pure_host(
1030 &mut self,
1031 module: &str,
1032 name: String,
1033 mut meta: FuncMeta,
1034 func: PureFn,
1035 ) {
1036 meta.kind = FuncKind::HostPure;
1037 self.insert_qualified(module, name, meta, FuncBody::Pure(func));
1038 }
1039
1040 pub(super) fn register_both_host(
1041 &mut self,
1042 module: &str,
1043 name: String,
1044 mut meta: FuncMeta,
1045 func: NativeFn<P>,
1046 template: PureFn,
1047 ) {
1048 meta.kind = FuncKind::HostCtx;
1049 self.insert_qualified(
1050 module,
1051 name,
1052 meta,
1053 FuncBody::Both {
1054 pure: template,
1055 ctx: func,
1056 },
1057 );
1058 }
1059
1060 #[allow(clippy::too_many_arguments)]
1065 pub(super) fn define_script(
1066 &mut self,
1067 name: &str,
1068 params: &[(String, TypeTag, bool)],
1069 return_type: TypeTag,
1070 return_spelling: &str,
1071 is_async: bool,
1072 body: &[Step],
1073 module: Option<&str>,
1074 ) -> Result<()> {
1075 let qualified = qualify(SCRIPT_MODULE_NAME, name);
1076 let shadowable = matches!(
1077 self.entries.get(&qualified).map(|entry| &entry.body),
1078 Some(FuncBody::Script(_))
1079 );
1080 let reserved = self.entries.iter().any(|(key, entry)| {
1085 split_qualified(key).is_some_and(|(_, base)| base == name)
1086 && !matches!(entry.body, FuncBody::Script(_))
1087 });
1088 if reserved && !shadowable {
1089 anyhow::bail!("cannot shadow reserved function `{name}`");
1090 }
1091 if self
1092 .scopes
1093 .last()
1094 .is_some_and(|frame| frame.defined.contains(&qualified))
1095 {
1096 anyhow::bail!("duplicate function `{name}` in same scope");
1097 }
1098 check_script_param_tags(name, params)?;
1099 let old = self.entries.insert(
1100 qualified.clone(),
1101 FuncEntry {
1102 meta: FuncMeta {
1103 name: qualified.clone(),
1104 module: SCRIPT_MODULE_NAME.to_string(),
1105 kind: FuncKind::Script,
1106 params: Some(
1107 params
1108 .iter()
1109 .map(|(pname, param_type, optional)| {
1110 Ok(FuncParam {
1111 name: pname.clone(),
1112 param_type: Some(param_type.clone()),
1113 allowed: None,
1114 docs: "",
1117 options: None,
1118 optional: *optional,
1119 })
1120 })
1121 .collect::<Result<_>>()?,
1122 ),
1123 returns: Some(return_type.clone()),
1124 rpn: false,
1125 summary: "DSL-defined function.",
1126 docs: "Defined via FUNC in script.",
1127 examples: &[],
1128 },
1129 body: FuncBody::Script(FuncDefData {
1130 params: params.to_vec(),
1131 return_type,
1132 return_spelling: return_spelling.to_string(),
1133 is_async,
1134 body: body.to_vec(),
1135 module: module.map(|m| m.to_string()),
1136 }),
1137 },
1138 );
1139 if let Some(frame) = self.scopes.last_mut() {
1140 frame.defined.insert(qualified.clone());
1141 if let Some(old) = old {
1142 frame.shadowed.push((qualified, old));
1143 }
1144 }
1145 Ok(())
1146 }
1147
1148 #[allow(clippy::too_many_arguments)]
1154 pub(super) fn define_file_func(
1155 &mut self,
1156 name: &str,
1157 params: &[(String, TypeTag, bool)],
1158 return_type: TypeTag,
1159 return_spelling: &str,
1160 is_async: bool,
1161 body: &[Step],
1162 defining: &str,
1163 ) -> Result<()> {
1164 let qualified = file_func_key(defining, name);
1168 let shadowable = matches!(
1169 self.entries.get(&qualified).map(|entry| &entry.body),
1170 Some(FuncBody::Script(_))
1171 );
1172 let reserved = self.entries.iter().any(|(key, entry)| {
1176 split_qualified(key).is_some_and(|(_, base)| base == name)
1177 && !matches!(entry.body, FuncBody::Script(_))
1178 });
1179 if reserved && !shadowable {
1180 anyhow::bail!("cannot shadow reserved function `{name}`");
1181 }
1182 let frame_idx = 0;
1186 if self
1187 .scopes
1188 .get(frame_idx)
1189 .is_some_and(|frame| frame.defined.contains(&qualified))
1190 {
1191 anyhow::bail!("duplicate function `{name}` in same scope");
1192 }
1193 check_script_param_tags(name, params)?;
1194 let old = self.entries.insert(
1195 qualified.clone(),
1196 FuncEntry {
1197 meta: FuncMeta {
1198 name: qualified.clone(),
1199 module: defining.to_string(),
1200 kind: FuncKind::Script,
1201 params: Some(
1202 params
1203 .iter()
1204 .map(|(pname, param_type, optional)| {
1205 Ok(FuncParam {
1206 name: pname.clone(),
1207 param_type: Some(param_type.clone()),
1208 allowed: None,
1209 docs: "",
1210 options: None,
1211 optional: *optional,
1212 })
1213 })
1214 .collect::<Result<_>>()?,
1215 ),
1216 returns: Some(return_type.clone()),
1217 rpn: false,
1218 summary: "DSL-defined function.",
1219 docs: "Defined via FUNC in an imported script.",
1220 examples: &[],
1221 },
1222 body: FuncBody::Script(FuncDefData {
1223 params: params.to_vec(),
1224 return_type,
1225 return_spelling: return_spelling.to_string(),
1226 is_async,
1227 body: body.to_vec(),
1228 module: Some(defining.to_string()),
1229 }),
1230 },
1231 );
1232 if let Some(frame) = self.scopes.get_mut(frame_idx) {
1233 frame.defined.insert(qualified.clone());
1234 if let Some(old) = old {
1235 frame.shadowed.push((qualified, old));
1236 }
1237 }
1238 Ok(())
1239 }
1240
1241 pub(super) fn push_scope(&mut self) {
1244 self.scopes.push(ScopeFrame {
1245 defined: HashSet::new(),
1246 shadowed: Vec::new(),
1247 });
1248 }
1249
1250 pub(super) fn pop_scope(&mut self) {
1253 let Some(frame) = self.scopes.pop() else {
1254 return;
1255 };
1256 for name in frame.defined {
1257 self.entries.remove(&name);
1258 }
1259 for (name, old) in frame.shadowed {
1260 self.entries.insert(name, old);
1261 }
1262 }
1263
1264 pub(super) fn contains_script(&self, name: &str) -> bool {
1269 matches!(
1270 self.entries.get(name).map(|entry| &entry.body),
1271 Some(FuncBody::Script(_))
1272 )
1273 }
1274
1275 pub(super) fn resolve_file_call_key(
1278 &self,
1279 unit_targets: &AliasTargets,
1280 name: &str,
1281 ) -> Result<Option<String>> {
1282 match classify_alias_call(unit_targets, name, &|key| self.entries.contains_key(key)) {
1283 AliasResolution::Global | AliasResolution::Unknown | AliasResolution::Any { .. } => {
1284 Ok(None)
1285 }
1286 AliasResolution::Canonical(key) => Ok(Some(key)),
1287 AliasResolution::Ambiguous { alias, base, files } => Err(anyhow::anyhow!(
1288 "{}",
1289 ambiguous_alias_message(&alias, &base, &files)
1290 )),
1291 }
1292 }
1293
1294 fn clone_pure_fn(&self, name: &str) -> Option<PureFn> {
1298 match self.entries.get(name)?.body {
1299 FuncBody::Pure(ref func) => Some(Arc::clone(func)),
1300 FuncBody::Both { ref pure, .. } => Some(Arc::clone(pure)),
1301 _ => None,
1302 }
1303 }
1304
1305 pub(super) fn pure_shared(&self) -> Arc<PureTable> {
1309 Arc::clone(&self.pure_shared)
1310 }
1311
1312 pub(super) fn all_metas(&self) -> Vec<FuncMeta> {
1315 self.entries_metas()
1316 }
1317
1318 fn clone_ctx_fn(&self, name: &str) -> Option<NativeFn<P>> {
1323 match self.entries.get(name)?.body {
1324 FuncBody::Ctx(ref func) => Some(Arc::clone(func)),
1325 FuncBody::Both { ref ctx, .. } => Some(Arc::clone(ctx)),
1326 _ => None,
1327 }
1328 }
1329
1330 fn meta(&self, name: &str) -> Option<FuncMeta> {
1331 self.entries.get(name).map(|entry| entry.meta.clone())
1332 }
1333
1334 fn native_metas(&self) -> Vec<FuncMeta> {
1335 let mut out: Vec<FuncMeta> = Vec::new();
1336 for entry in self.entries.values() {
1337 if !matches!(entry.body, FuncBody::Script(_)) {
1338 out.push(entry.meta.clone());
1339 }
1340 }
1341 out.sort_by(|a, b| a.name.cmp(&b.name));
1342 out
1343 }
1344
1345 pub(super) fn pure_metas(&self) -> Vec<FuncMeta> {
1350 let mut out: Vec<FuncMeta> = Vec::new();
1351 for entry in self.entries.values() {
1352 if matches!(entry.body, FuncBody::Pure(_) | FuncBody::Both { .. }) {
1353 out.push(entry.meta.clone());
1354 }
1355 }
1356 out.sort_by(|a, b| a.name.cmp(&b.name));
1357 out
1358 }
1359
1360 fn entries_metas(&self) -> Vec<FuncMeta> {
1363 let mut out: Vec<FuncMeta> = self
1364 .entries
1365 .values()
1366 .map(|entry| entry.meta.clone())
1367 .collect();
1368 out.sort_by(|a, b| a.name.cmp(&b.name));
1369 out
1370 }
1371
1372 pub fn set_script_docs(&mut self, docs: &HashMap<String, (String, String)>) {
1375 for (base, pair) in docs {
1376 self.script_docs
1377 .insert(qualify(SCRIPT_MODULE_NAME, base), pair.clone());
1378 }
1379 }
1380
1381 pub fn script_doc_for(&self, qualified: &str) -> Option<(String, String)> {
1383 self.script_docs.get(qualified).cloned()
1384 }
1385
1386 pub fn exported_metas(
1391 &self,
1392 func_exports: &[String],
1393 unit_targets: &AliasTargets,
1394 ) -> anyhow::Result<Vec<FuncMeta>> {
1395 let mut out = Vec::with_capacity(func_exports.len());
1396 for name in func_exports {
1397 let qualified = match split_qualified(name) {
1401 None => qualify(SCRIPT_MODULE_NAME, name),
1402 Some(_) => name.clone(),
1403 };
1404 let lookup = self
1405 .resolve_file_call_key(unit_targets, &qualified)?
1406 .unwrap_or_else(|| qualified.clone());
1407 if let Some(entry) = self.entries.get(&lookup) {
1408 let mut meta = entry.meta.clone();
1409 if lookup != qualified {
1410 meta.name = name.clone();
1411 }
1412 out.push(meta);
1413 continue;
1414 }
1415 anyhow::bail!(
1416 "EXPORT `{name}` matches no defined script function or known host function"
1417 );
1418 }
1419 Ok(out)
1420 }
1421}
1422
1423impl<P: ProcessManager> Clone for FunctionRegistry<P> {
1424 fn clone(&self) -> Self {
1425 Self {
1426 entries: self.entries.clone(),
1427 scopes: self.scopes.clone(),
1428 pure_shared: Arc::clone(&self.pure_shared),
1429 script_docs: self.script_docs.clone(),
1430 }
1431 }
1432}
1433
1434pub fn builtin_function_names() -> HashSet<String> {
1441 let mut names = FunctionRegistry::<DefaultProcessManager>::with_builtins().keys();
1442 names.insert(KEYWORD_INSPECT.to_string());
1443 names
1444}
1445
1446pub fn builtin_function_metas() -> Vec<FuncMeta> {
1450 FunctionRegistry::<DefaultProcessManager>::with_builtins().native_metas()
1451}
1452
1453pub fn std_module_table() -> oxdock_parser::ModuleTable {
1458 let func_names: HashSet<String> = builtin_function_metas()
1460 .into_iter()
1461 .map(|meta| base_name(&meta.name).to_string())
1462 .collect();
1463 oxdock_parser::ModuleTable {
1464 modules: HashMap::from([(
1465 STD_MODULE_NAME.to_string(),
1466 Some(oxdock_parser::ModuleFuncs { func_names }),
1467 )]),
1468 }
1469}
1470
1471#[oxdock_func(pure, returns = TypeTag::Int)]
1484#[example(
1485 name = "convert",
1486 code = r###"
1487 IMPORT [STD]
1488 LET $n: INT = INT("42")
1489 ASSERT_EQ $n 42
1490 LET $flag: INT = INT(true)
1491 ASSERT_EQ $flag 1
1492 "###
1493)]
1494fn int(
1495 #[union(Int, Float, String, Bool)]
1497 val: Value,
1498) -> Result<Value> {
1499 super::args::int_from_value(val)
1500}
1501
1502#[oxdock_func(pure, returns = TypeTag::Float)]
1507#[example(
1508 name = "convert",
1509 code = r###"
1510 IMPORT [STD]
1511 LET $f: FLOAT = FLOAT("1.5")
1512 ASSERT_EQ $f 1.5
1513 LET $whole: FLOAT = FLOAT(2)
1514 ASSERT_EQ $whole 2.0
1515 "###
1516)]
1517fn float(
1518 #[union(Float, Int, String)]
1520 val: Value,
1521) -> Result<Value> {
1522 super::args::float_from_value(val)
1523}
1524
1525#[oxdock_func(pure, returns = TypeTag::String)]
1530#[example(
1531 name = "format and round-trip",
1532 code = r###"
1533 # Byte counts render in the largest exact unit.
1534 IMPORT [STD]
1535 LET $pretty: STRING = FORMAT_BYTE_COUNT(1_048_576)
1536 ASSERT_EQ $pretty "1MiB"
1537
1538 # The pair round-trips through the parser.
1539 LET $back: INT = PARSE_BYTE_COUNT($pretty)
1540 ASSERT_EQ $back 1_048_576
1541 "###
1542)]
1543fn format_byte_count(
1544 bytes: i64,
1546) -> Result<Value> {
1547 if bytes < 0 {
1548 return Err(anyhow::anyhow!(
1549 "FORMAT_BYTE_COUNT needs a non-negative byte count, got {bytes}"
1550 ));
1551 }
1552 Ok(Value::string(oxdock_parser::command::format_byte_count(
1553 bytes as u64,
1554 )))
1555}
1556
1557#[oxdock_func(pure, returns = TypeTag::Int)]
1592#[example(
1593 name = "parse",
1594 code = r###"
1595 IMPORT [STD]
1596 LET $n: INT = PARSE_BYTE_COUNT("10KB")
1597 ASSERT_EQ $n 10_000
1598 LET $identity: INT = PARSE_BYTE_COUNT(512)
1599 ASSERT_EQ $identity 512
1600 "###
1601)]
1602fn parse_byte_count(
1603 #[union(Int, Float, String)]
1605 text: Value,
1606) -> Result<Value> {
1607 if let Some(n) = text.as_i64() {
1608 if n < 0 {
1609 return Err(anyhow::anyhow!(
1610 "PARSE_BYTE_COUNT needs a non-negative byte count, got {n}"
1611 ));
1612 }
1613 return Ok(Value::int(n));
1614 }
1615 if let Some(f) = text.as_f64() {
1616 if f.is_finite() && f.fract() == 0.0 && f >= 0.0 && f <= i64::MAX as f64 {
1617 return Ok(Value::int(f as i64));
1618 }
1619 return Err(anyhow::anyhow!(
1620 "PARSE_BYTE_COUNT needs an integral byte count, got {f:?}"
1621 ));
1622 }
1623 let Some(s) = text.as_str() else {
1624 return Err(anyhow::anyhow!(
1625 "PARSE_BYTE_COUNT needs a token or number, found {text:?}"
1626 ));
1627 };
1628 let n = oxdock_parser::command::parse_byte_count(s)?;
1629 let n = i64::try_from(n)
1630 .map_err(|_| anyhow::anyhow!("PARSE_BYTE_COUNT out of INT range: {s:?}"))?;
1631 Ok(Value::int(n))
1632}
1633
1634#[oxdock_func(pure, returns = TypeTag::String)]
1639#[example(
1640 name = "format and round-trip",
1641 code = r###"
1642 # Durations render in the largest exact unit.
1643 IMPORT [STD]
1644 LET $pretty: STRING = FORMAT_DURATION(90_000)
1645 ASSERT_EQ $pretty "90s"
1646
1647 # The pair round-trips through the parser.
1648 LET $back: INT = PARSE_DURATION($pretty)
1649 ASSERT_EQ $back 90_000
1650 "###
1651)]
1652fn format_duration(
1653 millis: i64,
1655) -> Result<Value> {
1656 if millis < 0 {
1657 return Err(anyhow::anyhow!(
1658 "FORMAT_DURATION needs non-negative milliseconds, got {millis}"
1659 ));
1660 }
1661 Ok(Value::string(oxdock_parser::command::format_duration(
1662 &std::time::Duration::from_millis(millis as u64),
1663 )))
1664}
1665
1666#[oxdock_func(pure, returns = TypeTag::Int)]
1672#[example(
1673 name = "parse",
1674 code = r###"
1675 # A bare number means seconds, like TIMEOUT.
1676 IMPORT [STD]
1677 LET $ms: INT = PARSE_DURATION("2m")
1678 ASSERT_EQ $ms 120_000
1679
1680 # Milliseconds stay exact.
1681 LET $exact: INT = PARSE_DURATION("1500ms")
1682 ASSERT_EQ $exact 1_500
1683
1684 # One optional space separates number from unit.
1685 LET $spaced: INT = PARSE_DURATION("1 h")
1686 ASSERT_EQ $spaced 3_600_000
1687 "###
1688)]
1689fn parse_duration(
1690 text: String,
1692) -> Result<Value> {
1693 let duration = oxdock_parser::command::parse_duration(&text)?;
1694 let millis = i64::try_from(duration.as_millis())
1695 .map_err(|_| anyhow::anyhow!("PARSE_DURATION out of INT range: {text:?}"))?;
1696 Ok(Value::int(millis))
1697}
1698
1699#[oxdock_func(rpn, returns = TypeTag::ListOf(std::sync::Arc::new(TypeTag::String)))]
1704#[example(
1705 name = "match",
1706 code = r###"
1707 IMPORT [STD]
1708 WRITE "notes-a.md" "a"
1709 WRITE "notes-b.md" "b"
1710 WRITE "other.txt" "c"
1711 LET $found: LIST<STRING> = GLOB("notes-*.md")
1712 ASSERT_EQ $found.0 "notes-a.md"
1713 ASSERT_EQ $found.1 "notes-b.md"
1714 "###
1715)]
1716fn glob<P: ProcessManager>(
1717 cx: &mut StepCtx<P>,
1718 #[union(String, Path)]
1720 pattern: Value,
1721) -> Result<Value> {
1722 let text = super::args::string_or_path_text(&pattern)?;
1723 super::args::glob_from_value(&[Value::string(text)], cx)
1724}
1725
1726#[oxdock_func(rpn, returns = TypeTag::MapOf(std::sync::Arc::new(TypeTag::Any)))]
1731#[example(
1732 name = "load",
1733 code = r###"
1734 IMPORT [STD]
1735 WRITE "cfg.toml" "title = \"demo\""
1736 LET $cfg: MAP<ANY> = LOAD_TOML("cfg.toml")
1737 ASSERT_EQ $cfg.title "demo"
1738 "###
1739)]
1740fn load_toml<P: ProcessManager>(
1741 cx: &mut StepCtx<P>,
1742 #[union(String, Path)]
1744 path: Value,
1745) -> Result<Value> {
1746 let text = super::args::string_or_path_text(&path)?;
1747 super::args::load_toml_from_value(&[Value::string(text)], cx)
1748}
1749
1750#[oxdock_func(rpn, returns = TypeTag::Any)]
1758#[example(
1759 name = "load",
1760 code = r###"
1761 IMPORT [STD]
1762 WRITE "data.json" "{\"a\": 1}"
1763 LET $doc: MAP<ANY> = LOAD_JSON("data.json")
1764 ASSERT_EQ $doc.a 1
1765 "###
1766)]
1767fn load_json<P: ProcessManager>(
1768 cx: &mut StepCtx<P>,
1769 #[union(String, Path)]
1771 path: Value,
1772) -> Result<Value> {
1773 let text = super::args::string_or_path_text(&path)?;
1774 super::args::load_json_from_value(&[Value::string(text)], cx)
1775}
1776
1777#[oxdock_func(rpn, returns = TypeTag::String)]
1787#[example(
1788 name = "hash",
1789 code = r###"
1790 IMPORT [STD]
1791 WRITE payload.txt hello
1792 LET $digest: STRING = HASH_SHA256("payload.txt")
1793 ASSERT_EQ $digest "2cf24dba5fb0a30e26e83b2ac5b9e29e1b161e5c1fa7425e73043362938b9824"
1794 "###
1795)]
1796fn hash_sha256<P: ProcessManager>(
1797 cx: &mut StepCtx<P>,
1798 #[union(String, Path)]
1800 path: Value,
1801) -> Result<Value> {
1802 use sha2::Digest;
1803
1804 let text = super::args::string_or_path_text(&path)?;
1805 let target = cx.state.fs.resolve_read(&cx.state.cwd, &text)?;
1806 let mut hasher = sha2::Sha256::new();
1807 super::fs_ops::hash_path(cx.state.fs.as_ref(), &target, "", &mut hasher)?;
1808 let digest = hasher.finalize();
1809 let bytes: &[u8] = digest.as_ref();
1810 Ok(Value::string(oxdock_utils::hex_encode(bytes)))
1811}
1812
1813#[oxdock_func(rpn, returns = TypeTag::String)]
1824#[example(
1825 name = "cwd",
1826 code = r###"
1827 IMPORT [STD]
1828 WORKDIR sub
1829 LET $c: STRING = CWD()
1830 ASSERT_CONTAINS $c "sub"
1831 "###
1832)]
1833fn cwd<P: ProcessManager>(cx: &mut StepCtx<P>) -> Result<Value> {
1834 if cx.state.fs.is_snapshot_pending() {
1835 return Ok(Value::string(super::SNAPSHOT_PENDING_DISPLAY.to_string()));
1836 }
1837 let concrete = cx.state.fs.concretize_cwd(&cx.state.cwd);
1838 let real = super::fs_ops::canonical_cwd(cx.state.fs.as_ref(), &concrete)?;
1839 Ok(Value::string(real))
1840}
1841
1842#[oxdock_func(pure, returns = TypeTag::MapOf(std::sync::Arc::new(TypeTag::Any)))]
1848#[example(
1849 name = "parse",
1850 code = r###"
1851 IMPORT [STD]
1852 LET $doc: MAP<ANY> = PARSE_TOML("title = \"demo\"")
1853 ASSERT_EQ $doc.title "demo"
1854 "###
1855)]
1856fn parse_toml(
1857 text: String,
1859) -> Result<Value> {
1860 super::args::parse_toml_from_value(Value::string(text))
1861}
1862
1863#[oxdock_func(pure, returns = TypeTag::Any)]
1872#[example(
1873 name = "parse",
1874 code = r###"
1875 # Parse in-memory JSON text with the same conversion as file loading.
1876 IMPORT [STD]
1877 LET $body: STRING = "{\"a\": 1}"
1878 LET $doc: ANY = PARSE_JSON($body)
1879 ASSERT_EQ $doc.a 1
1880
1881 # Top-level arrays parse to LIST, which is why the return is ANY.
1882 LET $items: LIST<ANY> = PARSE_JSON("[1, 2]")
1883 ASSERT_EQ $items.0 1
1884 ASSERT_EQ $items.1 2
1885 "###
1886)]
1887fn parse_json(
1888 text: String,
1890) -> Result<Value> {
1891 super::args::parse_json_from_value(Value::string(text))
1892}
1893
1894#[oxdock_func(returns = TypeTag::String)]
1900#[example(
1901 name = "describe",
1902 code = r###"
1903 IMPORT [STD]
1904 WRITE "entry.txt" "words"
1905 LET $kind: STRING = PATH_TYPE("entry.txt")
1906 ASSERT_EQ $kind "file"
1907 LET $missing: STRING = PATH_TYPE("no-such-entry.txt")
1908 ASSERT_EQ $missing "absent"
1909 "###
1910)]
1911fn path_type<P: ProcessManager>(
1912 cx: &mut StepCtx<P>,
1913 #[union(String, Path)]
1915 path: Value,
1916) -> Result<Value> {
1917 let text = super::args::string_or_path_text(&path)?;
1918 super::args::path_type_from_value(&[Value::string(text)], cx)
1919}
1920
1921#[oxdock_func(returns = TypeTag::Bool)]
1930#[example(
1931 name = "probe",
1932 code = r###"
1933 # An absent nested path is writable when its ancestor is.
1934 IMPORT [STD]
1935 LET $fresh: BOOL = PATH_WRITABLE("probe-check/nested/file.txt")
1936 ASSERT_EQ $fresh true
1937
1938 # The empty string never aliases the working directory.
1939 LET $empty: BOOL = PATH_WRITABLE("")
1940 ASSERT_EQ $empty false
1941 "###
1942)]
1943fn path_writable<P: ProcessManager>(
1944 cx: &mut StepCtx<P>,
1945 #[union(String, Path)]
1947 path: Value,
1948) -> Result<Value> {
1949 let text = super::args::string_or_path_text(&path)?;
1950 super::args::path_writable_from_value(&[Value::string(text)], cx)
1951}
1952
1953#[oxdock_func(returns = TypeTag::Bool)]
1966#[example(
1967 name = "probe",
1968 code = r###"
1969 # Missing tools read false instead of failing the run.
1970 IMPORT [STD]
1971 LET $missing: BOOL = IS_EXEC("no-such-tool-xyz")
1972 ASSERT_EQ $missing false
1973
1974 # Plain files are not executable on any platform.
1975 WRITE tool.txt payload
1976 LET $plain: BOOL = IS_EXEC("tool.txt")
1977 ASSERT_EQ $plain false
1978 "###
1979)]
1980fn is_exec<P: ProcessManager>(
1981 cx: &mut StepCtx<P>,
1982 #[union(String, Path)]
1984 name: Value,
1985) -> Result<Value> {
1986 let text = super::args::string_or_path_text(&name)?;
1987 super::args::is_exec_from_value(&[Value::string(text)], cx)
1988}
1989
1990#[oxdock_func(pure, returns = TypeTag::Bool)]
1996#[example(
1997 name = "probe",
1998 code = r###"
1999 IMPORT [STD]
2000 LET $m: MAP<ANY> = PARSE_JSON("{\"a\": 1}")
2001 LET $hit: BOOL = HAS_KEY($m, "a")
2002 ASSERT_EQ $hit true
2003 LET $miss: BOOL = HAS_KEY($m, "b")
2004 ASSERT_EQ $miss false
2005 "###
2006)]
2007fn has_key(
2008 map: BTreeMap<String, Value>,
2010 key: String,
2012) -> Result<Value> {
2013 super::args::has_key_from_value(Value::map(map), &key)
2014}
2015
2016#[oxdock_func(pure, returns = TypeTag::Any)]
2022#[example(
2023 name = "present and absent",
2024 code = r###"
2025 IMPORT [STD]
2026 LET $m: MAP<ANY> = PARSE_JSON("{\"a\": 1}")
2027 LET $hit: INT = GET($m, "a", 0)
2028 ASSERT_EQ $hit 1
2029 LET $miss: INT = GET($m, "b", 0)
2030 ASSERT_EQ $miss 0
2031 "###
2032)]
2033fn get(
2034 map: BTreeMap<String, Value>,
2036 key: String,
2038 default: Value,
2040) -> Result<Value> {
2041 Ok(map.get(&key).cloned().unwrap_or(default))
2042}
2043
2044#[oxdock_func(pure, returns = TypeTag::MapOf(std::sync::Arc::new(TypeTag::Any)))]
2050#[example(
2051 name = "insert",
2052 code = r###"
2053 IMPORT [STD]
2054 LET $m: MAP<ANY> = MAP_SET({seed: 0}, "a", 1)
2055 ASSERT_EQ $m.a 1
2056 "###
2057)]
2058fn map_set(
2059 map: BTreeMap<String, Value>,
2061 key: String,
2063 value: Value,
2065) -> Result<Value> {
2066 super::args::map_set_from_value(Value::map(map), key, value)
2067}
2068
2069#[oxdock_func(returns = TypeTag::Float, summary = "Draw a random FLOAT uniformly from [0, 1), optionally seeded.")]
2077#[example(
2078 name = "seeded draw",
2079 code = r###"
2080 # A seed draws the same value on every run.
2081 IMPORT [STD]
2082 LET $one: FLOAT = RAND({seed: 7})
2083 LET $two: FLOAT = RAND({seed: 7})
2084 ASSERT_EQ $one $two
2085 "###
2086)]
2087#[example(
2088 name = "unseeded draw",
2089 code = r###"
2090 # Scale a unit draw into a backoff delay between 1 and 11 seconds.
2091 IMPORT [STD]
2092 LET $draw: FLOAT = RAND()
2093 LET $delay: FLOAT = 1.0 + $draw * 10.0
2094 IF $delay < 1.0 {
2095 EXIT 1
2096 }
2097 IF $delay >= 11.0 {
2098 EXIT 1
2099 }
2100 ECHO "retrying in {{ $delay }}s"
2101 "###
2102)]
2103fn rand<P: ProcessManager>(
2104 cx: &mut StepCtx<P>,
2105 #[options("seed?: INT")]
2107 #[optional]
2108 options: BTreeMap<String, Value>,
2109) -> Result<Value> {
2110 let _ = cx;
2111 let seed = options
2114 .get("seed")
2115 .map(|value| value.as_i64().expect("check_options verified INT"));
2116 super::args::rand_float_from_value(seed)
2117}
2118
2119#[oxdock_func(pure, returns = TypeTag::String)]
2125#[example(
2126 name = "encode",
2127 code = r###"
2128 # Encode text to standard base64.
2129 IMPORT [STD]
2130 LET $encoded: STRING = BASE64_ENCODE("hello")
2131 ASSERT_EQ $encoded "aGVsbG8="
2132 "###
2133)]
2134fn base64_encode(
2135 text: String,
2137) -> Result<Value> {
2138 super::args::base64_encode_from_value(Value::string(text))
2139}
2140
2141#[oxdock_func(pure, returns = TypeTag::String)]
2148#[example(
2149 name = "decode",
2150 code = r###"
2151 # Decode standard base64 back to text.
2152 IMPORT [STD]
2153 LET $decoded: STRING = BASE64_DECODE("aGVsbG8=")
2154 ASSERT_EQ $decoded "hello"
2155 "###
2156)]
2157fn base64_decode(
2158 text: String,
2160) -> Result<Value> {
2161 super::args::base64_decode_from_value(Value::string(text))
2162}
2163
2164#[oxdock_func(pure, returns = TypeTag::String)]
2171#[example(
2172 name = "encode",
2173 code = r###"
2174 IMPORT [STD]
2175 LET $json: STRING = TO_JSON({a: 1})
2176 ASSERT_EQ $json "{\"a\":1}\n"
2177 "###
2178)]
2179fn to_json(
2180 #[union(String, Int, Float, Bool, List, Map)]
2182 value: Value,
2183) -> Result<Value> {
2184 super::args::to_json_from_value(value)
2185}
2186
2187#[oxdock_func(pure, returns = TypeTag::String)]
2195#[example(
2196 name = "name the word",
2197 code = r###"
2198 IMPORT [STD]
2199 LET $word: STRING = TYPE_OF(42)
2200 ASSERT_EQ $word "INT"
2201 "###
2202)]
2203fn type_of(
2204 value: Value,
2206) -> Result<Value> {
2207 super::args::type_of_from_value(value)
2208}
2209
2210#[oxdock_func(pure, returns = TypeTag::MapOf(std::sync::Arc::new(TypeTag::Any)))]
2218#[example(
2219 name = "merge",
2220 code = r###"
2221 IMPORT [STD]
2222 LET $m: MAP<ANY> = MERGE_MAPS([{a: 1}, {b: 2}], "overwrite")
2223 ASSERT_EQ $m.a 1
2224 ASSERT_EQ $m.b 2
2225 "###
2226)]
2227fn merge_maps(
2228 maps: Vec<BTreeMap<String, Value>>,
2230 #[values("fail_on_duplicate", "overwrite")]
2232 policy: String,
2233) -> Result<Value> {
2234 super::args::merge_maps_from_value(
2235 Value::list(maps.into_iter().map(Value::map).collect()),
2236 policy,
2237 )
2238}
2239
2240#[oxdock_func(pure, returns = TypeTag::String)]
2245#[example(
2246 name = "report",
2247 code = r###"
2248 # The engine reports its own build version as a dotted string.
2249 IMPORT [STD]
2250 LET $v: STRING = VERSION()
2251 ASSERT_CONTAINS $v "."
2252 "###
2253)]
2254fn version() -> Result<Value> {
2255 Ok(Value::string(env!("CARGO_PKG_VERSION").to_string()))
2256}
2257
2258#[oxdock_func(returns = TypeTag::ListOf(std::sync::Arc::new(TypeTag::String)))]
2263#[example(
2264 name = "list",
2265 code = r###"
2266 IMPORT [STD]
2267 LET $names: LIST<STRING> = FUNCTIONS()
2268 ASSERT_CONTAINS $names "STD::INT"
2269 "###
2270)]
2271fn functions<P: ProcessManager>(cx: &mut StepCtx<P>) -> Result<Value> {
2272 let mut names: Vec<String> = cx
2273 .state
2274 .list_functions()
2275 .into_iter()
2276 .map(|meta| meta.name)
2277 .collect();
2278 names.sort();
2279 names.dedup();
2280 Ok(Value::list(names.into_iter().map(Value::string).collect()))
2281}
2282
2283#[oxdock_func(returns = TypeTag::ListOf(std::sync::Arc::new(TypeTag::String)))]
2290#[example(
2291 name = "empty",
2292 code = r###"
2293 # With no staged args the list is empty.
2294 IMPORT [STD]
2295 LET $args: LIST<STRING> = ARGV()
2296 LET $n: INT = LEN($args)
2297 ASSERT_EQ $n 0
2298 "###
2299)]
2300fn argv<P: ProcessManager>(cx: &mut StepCtx<P>) -> Result<Value> {
2301 Ok(Value::list(
2302 cx.state
2303 .io
2304 .script_args()
2305 .iter()
2306 .cloned()
2307 .map(Value::string)
2308 .collect(),
2309 ))
2310}
2311
2312pub struct ParseArgs;
2332
2333impl<P: ProcessManager> OxDockFn<P> for ParseArgs {
2334 fn registration() -> HostRegistration<P> {
2335 let func: NativeFn<P> = Arc::new(|cx: &mut StepCtx<P>, values: Vec<Value>| {
2336 if values.len() != 1 {
2337 anyhow::bail!("PARSE_ARGS() expects 1 argument, got {}", values.len());
2338 }
2339 let mut iter = values.into_iter();
2340 let args_val = iter.next().expect("arity checked above");
2341 let args = string_list_arg(&args_val, "PARSE_ARGS() argument `$args`")?;
2342 let specs = resolve_flags_specs(cx)?;
2343 let (raw, positionals) = tokenize_raw_args(args)?;
2344 let coerced = coerce_flags(&specs, &raw)?;
2345 let mut out = BTreeMap::new();
2346 out.insert("flags".to_string(), Value::map(coerced));
2347 if !positionals.is_empty() {
2348 out.insert("positionals".to_string(), Value::list(positionals));
2349 }
2350 Ok(Value::map(out))
2351 });
2352 HostRegistration::Stateful {
2353 name: "PARSE_ARGS".to_string(),
2354 meta: FuncMeta {
2355 name: "PARSE_ARGS".to_string(),
2356 module: String::new(),
2357 kind: FuncKind::HostPure,
2358 params: Some(vec![FuncParam {
2359 name: "args".to_string(),
2360 param_type: Some(TypeTag::ListOf(Arc::new(TypeTag::String))),
2361 allowed: None,
2362 docs: "Argv tail to parse, usually from `STD::ARGV()`.",
2363 options: None,
2364 optional: false,
2365 }]),
2366 returns: Some(TypeTag::Record(Arc::from([
2367 Field {
2368 name: "flags".to_string(),
2369 ty: TypeTag::Map,
2370 docs: "Flags coerced to `TYPE FLAGS`.",
2371 optional: false,
2372 default: None,
2373 },
2374 Field {
2375 name: "positionals".to_string(),
2376 ty: TypeTag::ListOf(Arc::new(TypeTag::String)),
2377 docs: "Trailing values and entries after the first double dash. Omitted when empty.",
2378 optional: true,
2379 default: None,
2380 },
2381 ]))),
2382 rpn: true,
2383 summary: "Parse an argv tail against TYPE FLAGS.",
2384 docs: "Consumes a `LIST<STRING>` with the `lexopt` tokenizer and coerces flags through `TYPE FLAGS`. See the function reference for the coercion and omission rules.",
2385 examples: &[
2386 crate::Example {
2387 name: "flags and positionals",
2388 fence_meta: None,
2389 code: indoc::indoc! {r#"
2390 IMPORT [STD]
2391 # One schema TYPE drives coercion; the pair binds both slots.
2392 TYPE FLAGS = MAP<model: STRING, verbose?: BOOL>
2393 TYPE POSITIONS = LIST<STRING>
2394 TYPE PARSED = MAP<flags: FLAGS, positionals?: POSITIONS>
2395 LET $parsed: PARSED = PARSE_ARGS(["--model=gpt-4", "--verbose", "serve"])
2396 LET $flags: FLAGS = $parsed.flags
2397 ASSERT_EQ $flags.model "gpt-4"
2398 ASSERT_EQ $flags.verbose true
2399 ASSERT_EQ $parsed.positionals.0 "serve"
2400 "#},
2401 },
2402 crate::Example {
2403 name: "optional stays absent",
2404 fence_meta: None,
2405 code: indoc::indoc! {r#"
2406 IMPORT [STD]
2407 # Absent optionals stay absent; read them with a typed GET default.
2408 TYPE FLAGS = MAP<model: STRING, propose?: BOOL>
2409 TYPE POSITIONS = LIST<STRING>
2410 TYPE PARSED = MAP<flags: FLAGS, positionals?: POSITIONS>
2411 LET $parsed: PARSED = PARSE_ARGS(["--model=x"])
2412 LET $flags: FLAGS = $parsed.flags
2413 LET $propose: BOOL = GET($flags, "propose", false)
2414 ASSERT_EQ $propose false
2415 "#},
2416 },
2417 crate::Example {
2418 name: "flags only omits positionals",
2419 fence_meta: None,
2420 code: indoc::indoc! {r#"
2421 IMPORT [STD]
2422 # Empty positionals are omitted, so a flags only shape binds clean.
2423 TYPE FLAGS = MAP<model: STRING>
2424 TYPE PARSED = MAP<flags: FLAGS>
2425 LET $parsed: PARSED = PARSE_ARGS(["--model=x"])
2426 LET $flags: FLAGS = $parsed.flags
2427 ASSERT_EQ $flags.model "x"
2428 "#},
2429 },
2430 crate::Example {
2431 name: "literal defaults",
2432 fence_meta: None,
2433 code: indoc::indoc! {r#"
2434 IMPORT [STD]
2435 # Defaults are literals only: INT, FLOAT, BOOL,
2436 # and double-quoted STRING fill absent flags.
2437 TYPE FLAGS = MAP<retries: INT = 2, ratio: FLOAT = 2.5, verbose: BOOL = true, model: STRING = "gpt-4">
2438 TYPE PARSED = MAP<flags: FLAGS>
2439 LET $parsed: PARSED = PARSE_ARGS([])
2440 LET $flags: FLAGS = $parsed.flags
2441 ASSERT_EQ $flags.retries 2
2442 ASSERT_EQ $flags.verbose true
2443 ASSERT_EQ $flags.model "gpt-4"
2444 LET $ratio_ok: BOOL = $flags.ratio == 2.5
2445 ASSERT_EQ $ratio_ok true
2446 "#},
2447 },
2448 crate::Example {
2449 name: "variable default fails",
2450 fence_meta: Some("expect_error:\"expected default literal\""),
2451 code: indoc::indoc! {r#"
2452 IMPORT [STD]
2453 # Defaults are literals: a variable in place
2454 # of a literal fails instead of evaluating.
2455 TYPE FLAGS = MAP<n: INT = $x>
2456 TYPE PARSED = MAP<flags: FLAGS>
2457 LET $p: PARSED = PARSE_ARGS([])
2458 "#},
2459 },
2460 crate::Example {
2461 name: "missing required",
2462 fence_meta: Some("expect_error:\"missing required flag\""),
2463 code: indoc::indoc! {r#"
2464 IMPORT [STD]
2465 # Absent required flags fail naming the flag.
2466 TYPE FLAGS = MAP<model: STRING>
2467 TYPE PARSED = MAP<flags: FLAGS>
2468 LET $parsed: PARSED = PARSE_ARGS([])
2469 "#},
2470 },
2471 crate::Example {
2472 name: "unknown flag",
2473 fence_meta: Some("expect_error:\"unknown flag\""),
2474 code: indoc::indoc! {r#"
2475 IMPORT [STD]
2476 # Undeclared flags fail instead of passing through.
2477 TYPE FLAGS = MAP<model: STRING>
2478 TYPE PARSED = MAP<flags: FLAGS>
2479 LET $parsed: PARSED = PARSE_ARGS(["--model=x", "--nope=1"])
2480 "#},
2481 },
2482 ],
2483 },
2484 func,
2485 }
2486 }
2487}
2488
2489#[derive(Debug, Clone, Copy, PartialEq, Eq)]
2493enum CliType {
2494 String,
2495 Bool,
2496 Int,
2497 Float,
2498}
2499
2500fn coerce_cli_flag(target: CliType, flag: &str, raw: Value) -> Result<Value> {
2505 match target {
2506 CliType::Bool => {
2507 if let Some(b) = raw.as_bool() {
2508 return Ok(Value::bool(b));
2509 }
2510 if let Some(s) = raw.as_str() {
2511 match super::args::parse_bool_str(s) {
2512 Some(b) => return Ok(Value::bool(b)),
2513 None => anyhow::bail!(
2514 "PARSE_ARGS flag --{flag} expects BOOL (true/false, 1/0, yes/no, on/off), got {s:?}"
2515 ),
2516 }
2517 }
2518 anyhow::bail!(
2519 "PARSE_ARGS flag --{flag} expects BOOL, got {}",
2520 raw.type_name()
2521 )
2522 }
2523 CliType::String => {
2524 if let Some(s) = raw.as_str() {
2525 return Ok(Value::string(s.to_string()));
2526 }
2527 anyhow::bail!("PARSE_ARGS flag --{flag} needs a value: use --{flag}=<value>");
2528 }
2529 CliType::Int => {
2530 if raw.as_bool().is_some() {
2531 anyhow::bail!("PARSE_ARGS flag --{flag} needs a value: use --{flag}=<value>");
2532 }
2533 super::args::int_from_value(raw)
2534 .map_err(|_| anyhow::anyhow!("PARSE_ARGS flag --{flag} expects INT"))
2535 }
2536 CliType::Float => {
2537 if raw.as_bool().is_some() {
2538 anyhow::bail!("PARSE_ARGS flag --{flag} needs a value: use --{flag}=<value>");
2539 }
2540 super::args::float_from_value(raw)
2541 .map_err(|_| anyhow::anyhow!("PARSE_ARGS flag --{flag} expects FLOAT"))
2542 }
2543 }
2544}
2545
2546type CliSpecs = BTreeMap<String, (CliType, bool, Option<Value>)>;
2550
2551fn string_list_arg(val: &Value, what: &str) -> Result<Vec<String>> {
2554 crate::check_value_at(&TypeTag::ListOf(Arc::new(TypeTag::String)), val, what)?;
2555 Ok(val
2556 .as_list()
2557 .expect("check_value_at enforces LIST")
2558 .iter()
2559 .map(|v| {
2560 v.as_str()
2561 .expect("check_value_at enforces STRING")
2562 .to_string()
2563 })
2564 .collect())
2565}
2566
2567fn tokenize_raw_args(args: Vec<String>) -> Result<(BTreeMap<String, Value>, Vec<Value>)> {
2571 use lexopt::Arg::{Long, Short, Value as ArgValue};
2572 let mut parser = lexopt::Parser::from_args(args);
2573 let mut flags: BTreeMap<String, Value> = BTreeMap::new();
2574 let mut positionals: Vec<Value> = Vec::new();
2575 let utf8 = |value: std::ffi::OsString| -> Result<String> {
2576 value
2577 .into_string()
2578 .map_err(|_| anyhow::anyhow!("PARSE_ARGS: argument must be UTF-8"))
2579 };
2580 loop {
2581 match parser.next() {
2582 Ok(None) => break,
2583 Ok(Some(Long(name))) => {
2584 let key = name.to_owned();
2585 if let Some(raw) = parser.optional_value() {
2586 flags.insert(key, Value::string(utf8(raw)?));
2587 } else {
2588 flags.insert(key, Value::bool(true));
2589 }
2590 }
2591 Ok(Some(Short(ch))) => {
2592 flags.insert(ch.to_string(), Value::bool(true));
2593 }
2594 Ok(Some(ArgValue(raw))) => {
2595 positionals.push(Value::string(utf8(raw)?));
2596 }
2597 Err(lexopt::Error::UnexpectedValue { option, value }) => {
2598 let key = option
2599 .strip_prefix("--")
2600 .or_else(|| option.strip_prefix('-'))
2601 .unwrap_or(option.as_str());
2602 flags.insert(key.to_string(), Value::string(utf8(value)?));
2603 }
2604 Err(err) => anyhow::bail!("PARSE_ARGS: {err}"),
2605 }
2606 }
2607 Ok((flags, positionals))
2608}
2609
2610fn coerce_flags(
2615 specs: &CliSpecs,
2616 raw: &BTreeMap<String, Value>,
2617) -> Result<BTreeMap<String, Value>> {
2618 let mut coerced: BTreeMap<String, Value> = BTreeMap::new();
2619 for (flag, (target, required, default)) in specs.iter() {
2620 if flag.is_empty() {
2621 anyhow::bail!("PARSE_ARGS schema flag names must be non-empty");
2622 }
2623 if let Some(raw) = raw.get(flag) {
2624 coerced.insert(flag.clone(), coerce_cli_flag(*target, flag, raw.clone())?);
2625 } else if let Some(d) = default {
2626 coerced.insert(flag.clone(), d.clone());
2627 } else if *required {
2628 anyhow::bail!("PARSE_ARGS missing required flag --{flag}");
2629 }
2630 }
2631 for flag in raw.keys() {
2632 if !specs.contains_key(flag) {
2633 anyhow::bail!("PARSE_ARGS unknown flag --{flag}");
2634 }
2635 }
2636 Ok(coerced)
2637}
2638
2639fn resolve_flags_specs<P: ProcessManager>(cx: &mut StepCtx<P>) -> Result<CliSpecs> {
2645 let name = "FLAGS";
2646 let tag = cx
2647 .state
2648 .resolve_tag(name)
2649 .map_err(|err| anyhow::anyhow!("PARSE_ARGS schema type {name:?}: {err:#}"))?;
2650 let TypeTag::Record(fields) = tag else {
2651 anyhow::bail!("PARSE_ARGS schema type {name:?} must be a MAP shape with scalar fields");
2652 };
2653 let mut specs = BTreeMap::new();
2654 for field in fields.iter() {
2655 let target = match field.ty {
2656 TypeTag::String => CliType::String,
2657 TypeTag::Bool => CliType::Bool,
2658 TypeTag::Int => CliType::Int,
2659 TypeTag::Float => CliType::Float,
2660 _ => anyhow::bail!(
2661 "PARSE_ARGS schema for --{}: type must be one of STRING, BOOL, INT, or FLOAT, got {}",
2662 field.name,
2663 field.ty.name(),
2664 ),
2665 };
2666 specs.insert(
2667 field.name.clone(),
2668 (
2669 target,
2670 !field.optional && field.default.is_none(),
2671 field.default.clone(),
2672 ),
2673 );
2674 }
2675 Ok(specs)
2676}
2677
2678pub struct ParseFlags;
2686
2687impl<P: ProcessManager> OxDockFn<P> for ParseFlags {
2688 fn registration() -> HostRegistration<P> {
2689 let func: NativeFn<P> = Arc::new(|cx: &mut StepCtx<P>, values: Vec<Value>| {
2690 if values.len() != 1 {
2691 anyhow::bail!("PARSE_FLAGS() expects 1 argument, got {}", values.len());
2692 }
2693 let mut iter = values.into_iter();
2694 let args_val = iter.next().expect("arity checked above");
2695 let args = string_list_arg(&args_val, "PARSE_FLAGS() argument `$args`")?;
2696 let specs = resolve_flags_specs(cx)?;
2697 let (raw, positionals) = tokenize_raw_args(args)?;
2698 if !positionals.is_empty() {
2699 let shown: Vec<String> = positionals.iter().map(|pos| pos.to_string()).collect();
2700 anyhow::bail!(
2701 "PARSE_FLAGS() does not accept positional arguments; found {}",
2702 shown.join(", ")
2703 );
2704 }
2705 Ok(Value::map(coerce_flags(&specs, &raw)?))
2706 });
2707 HostRegistration::Stateful {
2708 name: "PARSE_FLAGS".to_string(),
2709 meta: FuncMeta {
2710 name: "PARSE_FLAGS".to_string(),
2711 module: String::new(),
2712 kind: FuncKind::HostPure,
2713 params: Some(vec![FuncParam {
2714 name: "args".to_string(),
2715 param_type: Some(TypeTag::ListOf(Arc::new(TypeTag::String))),
2716 allowed: None,
2717 docs: "Argv tail to parse, usually from `STD::ARGV()`.",
2718 options: None,
2719 optional: false,
2720 }]),
2721 returns: Some(TypeTag::Map),
2722 rpn: true,
2723 summary: "Parse flags against TYPE FLAGS.",
2724 docs: "Consumes a `LIST<STRING>` and coerces flags through `TYPE FLAGS`. Returns the flags `MAP` directly; positional arguments fail.",
2725 examples: &[crate::Example {
2726 name: "flags only",
2727 fence_meta: None,
2728 code: indoc::indoc! {r#"
2729 IMPORT [STD]
2730 # Flags only returns the flags MAP directly.
2731 TYPE FLAGS = MAP<model: STRING, retries: INT = 2>
2732 LET $flags: FLAGS = PARSE_FLAGS(["--model=x"])
2733 ASSERT_EQ $flags.model "x"
2734 ASSERT_EQ $flags.retries 2
2735 "#},
2736 }],
2737 },
2738 func,
2739 }
2740 }
2741}
2742
2743pub struct ParsePositionals;
2748
2749impl<P: ProcessManager> OxDockFn<P> for ParsePositionals {
2750 fn registration() -> HostRegistration<P> {
2751 let func: NativeFn<P> = Arc::new(|_: &mut StepCtx<P>, values: Vec<Value>| {
2752 if values.len() != 1 {
2753 anyhow::bail!(
2754 "PARSE_POSITIONALS() expects 1 argument, got {}",
2755 values.len()
2756 );
2757 }
2758 let mut iter = values.into_iter();
2759 let args_val = iter.next().expect("arity checked above");
2760 let args = string_list_arg(&args_val, "PARSE_POSITIONALS() argument `$args`")?;
2761 let (_raw, positionals) = tokenize_raw_args(args)?;
2762 Ok(Value::list(positionals))
2763 });
2764 HostRegistration::Stateful {
2765 name: "PARSE_POSITIONALS".to_string(),
2766 meta: FuncMeta {
2767 name: "PARSE_POSITIONALS".to_string(),
2768 module: String::new(),
2769 kind: FuncKind::HostPure,
2770 params: Some(vec![FuncParam {
2771 name: "args".to_string(),
2772 param_type: Some(TypeTag::ListOf(Arc::new(TypeTag::String))),
2773 allowed: None,
2774 docs: "Argv tail to parse, usually from `STD::ARGV()`.",
2775 options: None,
2776 optional: false,
2777 }]),
2778 returns: Some(TypeTag::ListOf(Arc::new(TypeTag::String))),
2779 rpn: true,
2780 summary: "Parse positionals in argv order.",
2781 docs: "Consumes a `LIST<STRING>` and returns positionals in argv order with no schema.",
2782 examples: &[crate::Example {
2783 name: "positionals only",
2784 fence_meta: None,
2785 code: indoc::indoc! {r#"
2786 IMPORT [STD]
2787 # No schema needed: positionals are always strings in order.
2788 TYPE POSITIONS = LIST<STRING>
2789 LET $pos: POSITIONS = PARSE_POSITIONALS(["serve", "--", "--not-a-flag"])
2790 ASSERT_EQ $pos.0 "serve"
2791 ASSERT_EQ $pos.1 "--not-a-flag"
2792 "#},
2793 }],
2794 },
2795 func,
2796 }
2797 }
2798}
2799
2800#[oxdock_func(
2815 returns = TypeTag::Record(std::sync::Arc::from([Field {
2816 name: "name".to_string(),
2817 ty: TypeTag::String,
2818 docs: "Qualified function name.",
2819 optional: false,
2820 default: None,
2821 }, Field {
2822 name: "module".to_string(),
2823 ty: TypeTag::String,
2824 docs: "Owning module.",
2825 optional: false,
2826 default: None,
2827 }, Field {
2828 name: "kind".to_string(),
2829 ty: TypeTag::String,
2830 docs: "Origin label (`host` or `script`).",
2831 optional: false,
2832 default: None,
2833 }, Field {
2834 name: "params".to_string(),
2835 ty: TypeTag::ListOf(std::sync::Arc::new(TypeTag::MapOf(std::sync::Arc::new(
2836 TypeTag::Any,
2837 )))),
2838 docs: "Parameter entries (empty for parameterless functions).",
2839 optional: false,
2840 default: None,
2841 }, Field {
2842 name: "returns".to_string(),
2843 ty: TypeTag::String,
2844 docs: "Structural return shape (empty when untagged).",
2845 optional: false,
2846 default: None,
2847 }, Field {
2848 name: "rpn".to_string(),
2849 ty: TypeTag::Bool,
2850 docs: "True when callable in RPN position.",
2851 optional: false,
2852 default: None,
2853 }, Field {
2854 name: "summary".to_string(),
2855 ty: TypeTag::String,
2856 docs: "One-line description.",
2857 optional: false,
2858 default: None,
2859 }]))
2860 summary = "Describe one function by qualified name."
2861)]
2862#[example(
2863 name = "describe",
2864 code = r###"
2865 IMPORT [STD]
2866 LET $info: MAP<ANY> = DESCRIBE("STD::INT")
2867 ASSERT_EQ $info.name "STD::INT"
2868 ASSERT_EQ $info.returns "INT"
2869 "###
2870)]
2871fn describe<P: ProcessManager>(
2872 cx: &mut StepCtx<P>,
2873 name: String,
2875) -> Result<Value> {
2876 if split_qualified(&name).is_none() && name != KEYWORD_INSPECT {
2877 anyhow::bail!(
2878 "unknown function `{name}`: DESCRIBE requires a qualified name (e.g. `STD::{name}`)"
2879 );
2880 }
2881 cx.state
2882 .describe_function(&name)
2883 .ok_or_else(|| anyhow::anyhow!("unknown function {name}"))
2884}
2885
2886#[oxdock_func(returns = TypeTag::ListOf(std::sync::Arc::new(TypeTag::String)))]
2892#[example(
2893 name = "list",
2894 code = r###"
2895 IMPORT [STD]
2896 LET $names: LIST<STRING> = TYPES()
2897 ASSERT_CONTAINS $names "STRING"
2898 "###
2899)]
2900fn types<P: ProcessManager>(cx: &mut StepCtx<P>) -> Result<Value> {
2901 Ok(Value::list(
2902 cx.state
2903 .type_names()
2904 .into_iter()
2905 .map(Value::string)
2906 .collect(),
2907 ))
2908}
2909
2910#[oxdock_func(returns = TypeTag::Record(std::sync::Arc::from([Field {
2916 name: "name".to_string(),
2917 ty: TypeTag::String,
2918 docs: "Queried type name.",
2919 optional: false,
2920 default: None,
2921}, Field {
2922 name: "summary".to_string(),
2923 ty: TypeTag::String,
2924 docs: "One-line description.",
2925 optional: false,
2926 default: None,
2927}, Field {
2928 name: "docs".to_string(),
2929 ty: TypeTag::String,
2930 docs: "Full documentation text.",
2931 optional: false,
2932 default: None,
2933}])))]
2934#[example(
2935 name = "describe",
2936 code = r###"
2937 IMPORT [STD]
2938 LET $info: MAP<ANY> = TYPE_DESCRIBE("STRING")
2939 ASSERT_EQ $info.name "STRING"
2940 "###
2941)]
2942fn type_describe<P: ProcessManager>(
2943 cx: &mut StepCtx<P>,
2944 name: String,
2946) -> Result<Value> {
2947 if let Some(descriptor) = cx.state.describe_type(&name) {
2948 let mut map = BTreeMap::new();
2949 map.insert(
2950 "name".to_string(),
2951 Value::string(descriptor.name.to_string()),
2952 );
2953 map.insert(
2954 "summary".to_string(),
2955 Value::string(descriptor.summary.to_string()),
2956 );
2957 map.insert(
2958 "docs".to_string(),
2959 Value::string(descriptor.docs.to_string()),
2960 );
2961 return Ok(Value::map(map));
2962 }
2963 if let Some(target) = cx.state.alias_target(&name) {
2966 let mut map = BTreeMap::new();
2967 map.insert("name".to_string(), Value::string(name.clone()));
2968 map.insert(
2969 "summary".to_string(),
2970 Value::string(format!("Script type alias for {target}.")),
2971 );
2972 map.insert(
2973 "docs".to_string(),
2974 Value::string(format!(
2975 "Declared with TYPE {name} = {target}. The alias expands structurally at every declaration."
2976 )),
2977 );
2978 return Ok(Value::map(map));
2979 }
2980 Err(anyhow::anyhow!("unknown type {name}"))
2981}
2982
2983#[oxdock_func(returns = TypeTag::String)]
2997#[example(
2998 name = "self",
2999 code = r###"
3000 # The running interpreter resolves to a non-empty path.
3001 IMPORT [STD]
3002 LET $exe: STRING = INTERPRETER()
3003 LET $nonempty: BOOL = $exe != ""
3004 ASSERT_EQ $nonempty true
3005 "###
3006)]
3007#[example(
3008 name = "dynamic assembly",
3009 code = r###"
3010 # Assemble the child script dynamically: the parent interpolates
3011 # its own bindings into the pipe, then runs the interpreter on it.
3012 # Unescaped {{ }} bakes in at render time; \{{ }} stays literal
3013 # so the child expands it with its own bindings.
3014 # The pipe delivers EOF when the producer step ends, so the child
3015 # reads exactly one script.
3016 IMPORT [STD]
3017 LET $exe: STRING = INTERPRETER()
3018 LET $who: STRING = "Ada"
3019 LET $child: PIPE
3020 WITH_IO [stdout=$child] ECHO """
3021 ECHO "hello {{ $who }}!"
3022 LET $who: STRING = "Grace"
3023 ECHO "child sees \{{ $who }}!"
3024 """
3025 LET $out: STRING = WITH_IO [stdin=$child] RUN [$exe]
3026 ASSERT_CONTAINS $out "hello Ada!"
3027 ASSERT_CONTAINS $out "child sees Grace!"
3028 "###
3029)]
3030fn interpreter<P: ProcessManager>(cx: &mut StepCtx<P>) -> Result<Value> {
3031 if let Some(staged) = cx.state.io.interpreter_override() {
3032 return Ok(Value::string(staged));
3033 }
3034 Ok(Value::string(oxdock_process::interpreter_exe()?))
3035}
3036
3037#[oxdock_func(returns = TypeTag::Bool)]
3045#[example(
3046 name = "main",
3047 code = r###"
3048 # Entry top level runs as main.
3049 IMPORT [STD]
3050 LET $m: BOOL = IS_MAIN()
3051 ASSERT_EQ $m true
3052 "###
3053)]
3054#[example(
3055 name = "library doubles as demo",
3056 fence_meta = "roots:unified",
3057 code = r###"
3058 # A library doubles as a runnable demo: guard the demo with
3059 # IF IS_MAIN() so importing it stays side effect free. The
3060 # parent writes both files, then runs each in a fresh
3061 # interpreter: direct execution prints the demo, importing
3062 # it does not. Unified roots: the child inherits one
3063 # workspace, so parent and child see the same files. The
3064 # exact stdout match proves the demo line stays out of the
3065 # importing run.
3066 IMPORT [STD]
3067
3068 # The library under test: demo guarded by IS_MAIN.
3069 WRITE lib.oxfile """
3070 IMPORT [STD]
3071 FUNC GREET($x: STRING): STRING { RETURN "hi \{{ $x }}" }
3072 EXPORT GREET
3073 IF IS_MAIN() {
3074 ECHO "demo: hi Ada"
3075 }
3076 """
3077
3078 # The importer: calls the library, prints only its own line.
3079 WRITE main.oxfile """
3080 IMPORT ["lib.oxfile" AS LIB]
3081 LET $g: STRING = LIB::GREET("Bo")
3082 ECHO "imported: \{{ $g }}"
3083 """
3084
3085 # Direct run executes the demo.
3086 LET $exe: STRING = INTERPRETER()
3087 LET $direct: STRING = RUN [$exe, "lib.oxfile"]
3088 ASSERT_CONTAINS $direct "demo: hi Ada"
3089
3090 # Importing run stays silent apart from its own line.
3091 LET $via: STRING = RUN [$exe, "main.oxfile"]
3092 ASSERT_EQ $via "imported: hi Bo\n"
3093 "###
3094)]
3095fn is_main<P: ProcessManager>(cx: &mut StepCtx<P>) -> Result<Value> {
3096 let main = match cx.state.module_stack.last() {
3097 None | Some(None) => true,
3098 Some(Some(_)) => false,
3099 };
3100 Ok(Value::bool(main))
3101}
3102
3103#[oxdock_func(returns = TypeTag::Bool)]
3117#[example(
3118 name = "null stdin",
3119 code = r###"
3120 # A null stdin is never a terminal, in every harness.
3121 IMPORT [STD]
3122 LET $term: BOOL = IS_TERMINAL("stdin")
3123 ASSERT_EQ $term false
3124 "###
3125)]
3126fn is_terminal<P: ProcessManager>(
3127 cx: &mut StepCtx<P>,
3128 #[values("stdin", "stdout", "stderr")]
3130 stream_name: String,
3131) -> Result<Value> {
3132 use std::io::IsTerminal;
3133 let terminal = match stream_name.as_str() {
3134 "stdin" => {
3135 if cx.stdin_pipe.is_some() {
3140 false
3141 } else {
3142 match &cx.stdin {
3143 CommandStdin::Null => false,
3144 #[cfg(not(miri))]
3145 CommandStdin::OsPipe(_) => false,
3146 CommandStdin::Stream(_) => false,
3147 CommandStdin::Inherit => std::io::stdin().is_terminal(),
3148 }
3149 }
3150 }
3151 "stdout" => {
3152 if cx.out_pipe.is_some() {
3153 false
3155 } else if cx.state.io.stdout().is_some() {
3156 false
3159 } else {
3160 match &cx.out {
3161 None => std::io::stdout().is_terminal(),
3163 #[cfg(not(miri))]
3165 Some(StreamHandle::Os(_)) => false,
3166 Some(StreamHandle::Stream(_)) => std::io::stdout().is_terminal(),
3176 }
3177 }
3178 }
3179 "stderr" => {
3180 if cx.state.io.stderr().is_some() {
3181 false
3183 } else {
3184 match &cx.err {
3185 None => std::io::stderr().is_terminal(),
3187 #[cfg(not(miri))]
3189 Some(StreamHandle::Os(_)) => false,
3190 Some(StreamHandle::Stream(_)) => false,
3193 }
3194 }
3195 }
3196 _ => anyhow::bail!(
3197 "IS_TERMINAL expects \"stdin\", \"stdout\", or \"stderr\", got {stream_name:?}"
3202 ),
3203 };
3204 Ok(Value::bool(terminal))
3205}
3206
3207#[oxdock_func(returns = TypeTag::Semaphore)]
3215#[example(
3216 name = "mint",
3217 code = r###"
3218 # Mint a semaphore admitting at most two holders.
3219 IMPORT [STD]
3220 LET $sem: SEMAPHORE = SEMAPHORE_NEW(2)
3221
3222 # A fresh semaphore reports its full cap as available.
3223 LET $free: INT = SEMAPHORE_AVAILABLE($sem)
3224 ASSERT_EQ $free 2
3225 "###
3226)]
3227fn semaphore_new<P: ProcessManager>(
3228 cx: &mut StepCtx<P>,
3229 max: i64,
3231) -> Result<Value> {
3232 let _ = cx;
3233 if max <= 0 {
3234 return Err(anyhow::anyhow!(
3235 "SEMAPHORE_NEW() requires a positive max, got {max}"
3236 ));
3237 }
3238 Ok(Value::semaphore(max as usize))
3239}
3240
3241#[oxdock_func(returns = TypeTag::Record(std::sync::Arc::from([Field {
3250 name: "held".to_string(),
3251 ty: TypeTag::Bool,
3252 docs: "`true` with the permit under `permit`, `false` with no `permit` key.",
3253 optional: false,
3254 default: None,
3255}, Field {
3256 name: "permit".to_string(),
3257 ty: TypeTag::Permit,
3258 docs: "Permit handle; read only when `held`.",
3259 optional: true,
3260 default: None,
3261}])))]
3262#[example(
3263 name = "acquire",
3264 code = r###"
3265 # First acquire holds with a permit to bind.
3266 IMPORT [STD]
3267 LET $sem: SEMAPHORE = SEMAPHORE_NEW(1)
3268 LET $first: MAP<held: BOOL, permit?: PERMIT> = SEMAPHORE_TRY_ACQUIRE($sem)
3269 ASSERT_EQ $first.held true
3270 LET $permit: PERMIT = $first.permit
3271
3272 # A capped semaphore answers held false with no permit key.
3273 LET $second: MAP<held: BOOL, permit?: PERMIT> = SEMAPHORE_TRY_ACQUIRE($sem)
3274 ASSERT_EQ $second.held false
3275 LET $has_permit: BOOL = HAS_KEY($second, "permit")
3276 ASSERT_EQ $has_permit false
3277 "###
3278)]
3279fn semaphore_try_acquire<P: ProcessManager>(
3280 cx: &mut StepCtx<P>,
3281 sem: Arc<SemaphoreState>,
3283) -> Result<Value> {
3284 let _ = cx;
3285 let mut map = BTreeMap::new();
3286 if sem.try_acquire() {
3287 map.insert("held".to_string(), Value::bool(true));
3288 map.insert("permit".to_string(), Value::permit(&sem));
3289 } else {
3290 map.insert("held".to_string(), Value::bool(false));
3291 }
3292 Ok(Value::map(map))
3293}
3294
3295#[oxdock_func(pure, returns = TypeTag::Int)]
3302#[example(
3303 name = "readout",
3304 code = r###"
3305 # Hold one permit on a cap of two.
3306 IMPORT [STD]
3307 LET $sem: SEMAPHORE = SEMAPHORE_NEW(2)
3308 LET $acq: MAP<held: BOOL, permit?: PERMIT> = SEMAPHORE_TRY_ACQUIRE($sem)
3309 ASSERT_EQ $acq.held true
3310
3311 # One held permit leaves exactly one free.
3312 LET $free: INT = SEMAPHORE_AVAILABLE($sem)
3313 ASSERT_EQ $free 1
3314 "###
3315)]
3316fn semaphore_available(
3317 sem: Arc<SemaphoreState>,
3319) -> Result<Value> {
3320 Ok(Value::int(sem.available() as i64))
3321}
3322
3323#[oxdock_func(
3332 rpn,
3333 returns = TypeTag::union(vec![TypeTag::String, TypeTag::Pipe]),
3334 template = text_trim_string
3335)]
3336#[example(
3337 name = "trim",
3338 code = r###"
3339 # Leading and trailing whitespace falls away.
3340 IMPORT [STD]
3341 LET $clean: STRING = TEXT_TRIM(" hello ")
3342 ASSERT_EQ $clean "hello"
3343 "###
3344)]
3345#[example(
3346 name = "trim pipe mirrors",
3347 code = r###"
3348 # Pipe input mints pipe output with the same transform.
3349 IMPORT [STD]
3350 LET $cap: PIPE
3351 WITH_IO [stdout=$cap] {
3352 ECHO " hello "
3353 }
3354 LET $out: PIPE = TEXT_TRIM($cap)
3355 WITH_IO [stdin=$out] READ_LINE $line
3356 ASSERT_EQ $line "hello"
3357 "###
3358)]
3359#[example(
3360 name = "trim template",
3361 code = r###"
3362 # String inputs run inside placeholders too.
3363 IMPORT [STD]
3364 LET $msg: STRING = 'clean:{{ STD::TEXT_TRIM(" hello ") }}'
3365 ASSERT_EQ $msg "clean:hello"
3366 "###
3367)]
3368#[example(
3369 name = "trim file template",
3370 code = r###"
3371 # EXPAND templates resolve the same registry.
3372 IMPORT [STD]
3373 WRITE "tpl.txt" "clean:\{{ STD::TEXT_TRIM(\" hello \") }}"
3374 LET $out: STRING = EXPAND "tpl.txt"
3375 ASSERT_EQ $out "clean:hello"
3376 "###
3377)]
3378fn text_trim<P: ProcessManager>(
3379 cx: &mut StepCtx<P>,
3380 #[union(String, Pipe)]
3382 text: Value,
3383) -> Result<Value> {
3384 super::args::mirror_stream(cx, "TEXT_TRIM", &text, super::args::TextPump::Trim)
3385}
3386
3387fn text_trim_string(text: Value) -> Result<Value> {
3390 super::args::mirror_string("TEXT_TRIM", &text, super::args::TextPump::Trim)
3391}
3392
3393#[oxdock_func(
3402 rpn,
3403 returns = TypeTag::union(vec![TypeTag::String, TypeTag::Pipe]),
3404 template = text_trim_prefix_string
3405)]
3406#[example(
3407 name = "strip prefix",
3408 code = r###"
3409 # A present prefix falls away; absence returns the input unchanged.
3410 IMPORT [STD]
3411 LET $bare: STRING = TEXT_TRIM_PREFIX("v1.2.3", "v")
3412 ASSERT_EQ $bare "1.2.3"
3413
3414 # Missing prefixes pass through untouched.
3415 LET $same: STRING = TEXT_TRIM_PREFIX("1.2.3", "v")
3416 ASSERT_EQ $same "1.2.3"
3417 "###
3418)]
3419#[example(
3420 name = "strip prefix pipe mirrors",
3421 code = r###"
3422 # Pipe input mints pipe output with the same strip.
3423 IMPORT [STD]
3424 LET $cap: PIPE
3425 WITH_IO [stdout=$cap] {
3426 ECHO "v1.2.3"
3427 }
3428 LET $trimmed: PIPE = TEXT_TRIM($cap)
3429 LET $out: PIPE = TEXT_TRIM_PREFIX($trimmed, "v")
3430 WITH_IO [stdin=$out] READ_LINE $line
3431 ASSERT_EQ $line "1.2.3"
3432 "###
3433)]
3434#[example(
3435 name = "strip prefix template",
3436 code = r###"
3437 # String inputs run inside placeholders too.
3438 IMPORT [STD]
3439 LET $msg: STRING = 'bare:{{ STD::TEXT_TRIM_PREFIX("v1.2.3", "v") }}'
3440 ASSERT_EQ $msg "bare:1.2.3"
3441 "###
3442)]
3443fn text_trim_prefix<P: ProcessManager>(
3444 cx: &mut StepCtx<P>,
3445 #[union(String, Pipe)]
3447 text: Value,
3448 prefix: String,
3450) -> Result<Value> {
3451 super::args::mirror_stream(
3452 cx,
3453 "TEXT_TRIM_PREFIX",
3454 &text,
3455 super::args::TextPump::TrimPrefix(prefix),
3456 )
3457}
3458
3459fn text_trim_prefix_string(text: Value, prefix: String) -> Result<Value> {
3462 super::args::mirror_string(
3463 "TEXT_TRIM_PREFIX",
3464 &text,
3465 super::args::TextPump::TrimPrefix(prefix),
3466 )
3467}
3468
3469#[oxdock_func(
3476 rpn,
3477 returns = TypeTag::union(vec![TypeTag::String, TypeTag::Pipe]),
3478 template = text_trim_suffix_string
3479)]
3480#[example(
3481 name = "strip suffix",
3482 code = r###"
3483 # A present suffix falls away; absence returns the input unchanged.
3484 IMPORT [STD]
3485 LET $bare: STRING = TEXT_TRIM_SUFFIX("archive.tar.gz", ".gz")
3486 ASSERT_EQ $bare "archive.tar"
3487
3488 # Missing suffixes pass through untouched.
3489 LET $same: STRING = TEXT_TRIM_SUFFIX("archive.tar", ".gz")
3490 ASSERT_EQ $same "archive.tar"
3491 "###
3492)]
3493#[example(
3494 name = "strip suffix pipe mirrors",
3495 code = r###"
3496 # Pipe input mints pipe output with the same strip.
3497 IMPORT [STD]
3498 LET $cap: PIPE
3499 WITH_IO [stdout=$cap] {
3500 ECHO "archive.tar.gz"
3501 }
3502 LET $trimmed: PIPE = TEXT_TRIM($cap)
3503 LET $out: PIPE = TEXT_TRIM_SUFFIX($trimmed, ".gz")
3504 WITH_IO [stdin=$out] READ_LINE $line
3505 ASSERT_EQ $line "archive.tar"
3506 "###
3507)]
3508#[example(
3509 name = "strip suffix template",
3510 code = r###"
3511 # String inputs run inside placeholders too.
3512 IMPORT [STD]
3513 LET $msg: STRING = 'bare:{{ STD::TEXT_TRIM_SUFFIX("archive.tar.gz", ".gz") }}'
3514 ASSERT_EQ $msg "bare:archive.tar"
3515 "###
3516)]
3517fn text_trim_suffix<P: ProcessManager>(
3518 cx: &mut StepCtx<P>,
3519 #[union(String, Pipe)]
3521 text: Value,
3522 suffix: String,
3524) -> Result<Value> {
3525 super::args::mirror_stream(
3526 cx,
3527 "TEXT_TRIM_SUFFIX",
3528 &text,
3529 super::args::TextPump::TrimSuffix(suffix),
3530 )
3531}
3532
3533fn text_trim_suffix_string(text: Value, suffix: String) -> Result<Value> {
3536 super::args::mirror_string(
3537 "TEXT_TRIM_SUFFIX",
3538 &text,
3539 super::args::TextPump::TrimSuffix(suffix),
3540 )
3541}
3542
3543#[oxdock_func(returns = TypeTag::String)]
3554#[example(
3555 name = "join path",
3556 code = r###"
3557 # Directory and file stem join with the native separator.
3558 # Source `\\` is one backslash at runtime; `/` works on Windows
3559 # too, native just reads better there.
3560 IMPORT [STD]
3561 LET $p: STRING = PATH_JOIN("some-dir", "some-file")
3562 [family:unix] ASSERT_EQ $p "some-dir/some-file"
3563 [family:windows] ASSERT_EQ $p "some-dir\\some-file"
3564 "###
3565)]
3566fn path_join<P: ProcessManager>(
3567 _cx: &mut StepCtx<P>,
3568 #[union(String, Path)]
3570 dir: Value,
3571 #[union(String, Path)]
3573 name: Value,
3574) -> Result<Value> {
3575 let d = super::args::string_or_path_text(&dir)?;
3576 let n = super::args::string_or_path_text(&name)?;
3577 Ok(Value::string(oxdock_fs::join_native(&d, &n)))
3578}
3579
3580#[oxdock_func(
3587 rpn,
3588 returns = TypeTag::union(vec![TypeTag::String, TypeTag::Pipe]),
3589 template = text_to_upper_string
3590)]
3591#[example(
3592 name = "uppercase",
3593 code = r###"
3594 # Text folds to uppercase.
3595 IMPORT [STD]
3596 LET $loud: STRING = TEXT_TO_UPPER("hello")
3597 ASSERT_EQ $loud "HELLO"
3598 "###
3599)]
3600#[example(
3601 name = "uppercase pipe mirrors",
3602 code = r###"
3603 # Pipe input mints pipe output with the same fold.
3604 IMPORT [STD]
3605 LET $cap: PIPE
3606 WITH_IO [stdout=$cap] {
3607 ECHO "hello"
3608 }
3609 LET $out: PIPE = TEXT_TO_UPPER($cap)
3610 WITH_IO [stdin=$out] READ_LINE $line
3611 ASSERT_EQ $line "HELLO"
3612 "###
3613)]
3614#[example(
3615 name = "uppercase template",
3616 code = r###"
3617 # String inputs run inside placeholders too.
3618 IMPORT [STD]
3619 LET $msg: STRING = 'loud:{{ STD::TEXT_TO_UPPER("hello") }}'
3620 ASSERT_EQ $msg "loud:HELLO"
3621 "###
3622)]
3623fn text_to_upper<P: ProcessManager>(
3624 cx: &mut StepCtx<P>,
3625 #[union(String, Pipe)]
3627 text: Value,
3628) -> Result<Value> {
3629 super::args::mirror_stream(cx, "TEXT_TO_UPPER", &text, super::args::TextPump::ToUpper)
3630}
3631
3632fn text_to_upper_string(text: Value) -> Result<Value> {
3635 super::args::mirror_string("TEXT_TO_UPPER", &text, super::args::TextPump::ToUpper)
3636}
3637
3638#[oxdock_func(
3645 rpn,
3646 returns = TypeTag::union(vec![TypeTag::String, TypeTag::Pipe]),
3647 template = text_to_lower_string
3648)]
3649#[example(
3650 name = "lowercase",
3651 code = r###"
3652 # Text folds to lowercase.
3653 IMPORT [STD]
3654 LET $quiet: STRING = TEXT_TO_LOWER("HELLO")
3655 ASSERT_EQ $quiet "hello"
3656 "###
3657)]
3658#[example(
3659 name = "lowercase pipe mirrors",
3660 code = r###"
3661 # Pipe input mints pipe output with the same fold.
3662 IMPORT [STD]
3663 LET $cap: PIPE
3664 WITH_IO [stdout=$cap] {
3665 ECHO "HELLO"
3666 }
3667 LET $out: PIPE = TEXT_TO_LOWER($cap)
3668 WITH_IO [stdin=$out] READ_LINE $line
3669 ASSERT_EQ $line "hello"
3670 "###
3671)]
3672#[example(
3673 name = "lowercase template",
3674 code = r###"
3675 # String inputs run inside placeholders too.
3676 IMPORT [STD]
3677 LET $msg: STRING = 'quiet:{{ STD::TEXT_TO_LOWER("HELLO") }}'
3678 ASSERT_EQ $msg "quiet:hello"
3679 "###
3680)]
3681fn text_to_lower<P: ProcessManager>(
3682 cx: &mut StepCtx<P>,
3683 #[union(String, Pipe)]
3685 text: Value,
3686) -> Result<Value> {
3687 super::args::mirror_stream(cx, "TEXT_TO_LOWER", &text, super::args::TextPump::ToLower)
3688}
3689
3690fn text_to_lower_string(text: Value) -> Result<Value> {
3693 super::args::mirror_string("TEXT_TO_LOWER", &text, super::args::TextPump::ToLower)
3694}
3695
3696#[oxdock_func(
3707 rpn,
3708 returns = TypeTag::union(vec![TypeTag::String, TypeTag::Pipe]),
3709 template = text_replace_string
3710)]
3711#[example(
3712 name = "replace",
3713 code = r###"
3714 # Every literal occurrence rewrites in place.
3715 IMPORT [STD]
3716 LET $fixed: STRING = TEXT_REPLACE("hello world", "world", "there")
3717 ASSERT_EQ $fixed "hello there"
3718 "###
3719)]
3720#[example(
3721 name = "replace pipe mirrors",
3722 code = r###"
3723 # Pipe input mints pipe output with the same rewrite.
3724 IMPORT [STD]
3725 LET $cap: PIPE
3726 WITH_IO [stdout=$cap] {
3727 ECHO "hello world"
3728 }
3729 LET $trimmed: PIPE = TEXT_TRIM($cap)
3730 LET $out: PIPE = TEXT_REPLACE($trimmed, "world", "there")
3731 WITH_IO [stdin=$out] READ_LINE $line
3732 ASSERT_EQ $line "hello there"
3733 "###
3734)]
3735#[example(
3736 name = "replace template",
3737 code = r###"
3738 # String inputs run inside placeholders too.
3739 IMPORT [STD]
3740 LET $msg: STRING = 'fixed:{{ STD::TEXT_REPLACE("hello world", "world", "there") }}'
3741 ASSERT_EQ $msg "fixed:hello there"
3742 "###
3743)]
3744fn text_replace<P: ProcessManager>(
3745 cx: &mut StepCtx<P>,
3746 #[union(String, Pipe)]
3748 text: Value,
3749 from: String,
3751 to: String,
3753) -> Result<Value> {
3754 super::args::mirror_stream(
3755 cx,
3756 "TEXT_REPLACE",
3757 &text,
3758 super::args::TextPump::ReplaceLiteral { from, to },
3759 )
3760}
3761
3762fn text_replace_string(text: Value, from: String, to: String) -> Result<Value> {
3765 super::args::mirror_string(
3766 "TEXT_REPLACE",
3767 &text,
3768 super::args::TextPump::ReplaceLiteral { from, to },
3769 )
3770}
3771
3772#[oxdock_func(
3784 rpn,
3785 returns = TypeTag::union(vec![TypeTag::String, TypeTag::Pipe]),
3786 template = text_replace_regex_string
3787)]
3788#[example(
3789 name = "replace with captures",
3790 code = r###"
3791 # Capture groups expand in the replacement.
3792 IMPORT [STD]
3793 LET $swapped: STRING = TEXT_REPLACE_REGEX("2026-10-13", "(\\d+)-(\\d+)-(\\d+)", "$3/$2/$1")
3794 ASSERT_EQ $swapped "13/10/2026"
3795 "###
3796)]
3797#[example(
3798 name = "replace regex pipe mirrors",
3799 code = r###"
3800 # Pipe input mints pipe output with the same rewrite.
3801 IMPORT [STD]
3802 LET $cap: PIPE
3803 WITH_IO [stdout=$cap] {
3804 ECHO "2026-10-13"
3805 }
3806 LET $trimmed: PIPE = TEXT_TRIM($cap)
3807 LET $out: PIPE = TEXT_REPLACE_REGEX($trimmed, "(\\d+)-(\\d+)-(\\d+)", "$3/$2/$1")
3808 WITH_IO [stdin=$out] READ_LINE $line
3809 ASSERT_EQ $line "13/10/2026"
3810 "###
3811)]
3812#[example(
3813 name = "replace regex template",
3814 code = r###"
3815 # String inputs run inside placeholders too.
3816 IMPORT [STD]
3817 LET $msg: STRING = 'swapped:{{ STD::TEXT_REPLACE_REGEX("2026-10-13", "(\\d+)-(\\d+)-(\\d+)", "$3/$2/$1") }}'
3818 ASSERT_EQ $msg "swapped:13/10/2026"
3819 "###
3820)]
3821fn text_replace_regex<P: ProcessManager>(
3822 cx: &mut StepCtx<P>,
3823 #[union(String, Pipe)]
3825 text: Value,
3826 pattern: String,
3828 replacement: String,
3830) -> Result<Value> {
3831 if let Some(s) = text.as_str() {
3832 let out =
3833 super::args::text_replace_regex_str(s, &pattern, &replacement, "TEXT_REPLACE_REGEX")?;
3834 return Ok(Value::string(out));
3835 }
3836 let content = super::args::read_pipe_eager(cx, "TEXT_REPLACE_REGEX", &text)?;
3837 let out = super::args::text_replace_regex_str(
3838 &content,
3839 &pattern,
3840 &replacement,
3841 "TEXT_REPLACE_REGEX",
3842 )?;
3843 super::args::write_completed_pipe(cx, "TEXT_REPLACE_REGEX", out)
3844}
3845
3846fn text_replace_regex_string(text: Value, pattern: String, replacement: String) -> Result<Value> {
3849 let Some(s) = text.as_str() else {
3850 return Err(super::args::pipe_needs_step_io("TEXT_REPLACE_REGEX"));
3851 };
3852 let out = super::args::text_replace_regex_str(s, &pattern, &replacement, "TEXT_REPLACE_REGEX")?;
3853 Ok(Value::string(out))
3854}
3855
3856#[oxdock_func(pure, returns = TypeTag::ListOf(std::sync::Arc::new(TypeTag::String)))]
3864#[example(
3865 name = "split",
3866 code = r###"
3867 # Delimiters split into list items.
3868 IMPORT [STD]
3869 LET $parts: LIST<STRING> = TEXT_SPLIT("a,b,c", ",")
3870 ASSERT_EQ $parts.0 "a"
3871 ASSERT_EQ $parts.1 "b"
3872 ASSERT_EQ $parts.2 "c"
3873 "###
3874)]
3875fn text_split(
3876 text: String,
3878 delimiter: String,
3880) -> Result<Value> {
3881 Ok(super::args::text_list_value(super::args::text_split_str(
3882 &text, &delimiter,
3883 )))
3884}
3885
3886#[oxdock_func(pure, returns = TypeTag::String)]
3889#[example(
3890 name = "join",
3891 code = r###"
3892 # List items join with the separator between them.
3893 IMPORT [STD]
3894 LET $joined: STRING = TEXT_JOIN(["a", "b", "c"], ",")
3895 ASSERT_EQ $joined "a,b,c"
3896 "###
3897)]
3898fn text_join(
3899 elements: Vec<String>,
3901 delimiter: String,
3903) -> Result<Value> {
3904 Ok(Value::string(elements.join(delimiter.as_str())))
3905}
3906
3907#[oxdock_func(pure, returns = TypeTag::ListOf(std::sync::Arc::new(TypeTag::String)))]
3919#[example(
3920 name = "split args",
3921 code = r###"
3922 # Quoted segments stay one word.
3923 IMPORT [STD]
3924 LET $argv: LIST<STRING> = SHELL_SPLIT_ARGS("gh issue comment 153 --body-file notes.md")
3925 ASSERT_EQ $argv.0 "gh"
3926 ASSERT_EQ $argv.3 "153"
3927 ASSERT_EQ $argv.5 "notes.md"
3928
3929 # Quotes and escapes parse the shell way.
3930 LET $quoted: LIST<STRING> = SHELL_SPLIT_ARGS("say \"hi there\" 'a b'")
3931 ASSERT_EQ $quoted.0 "say"
3932 ASSERT_EQ $quoted.1 "hi there"
3933 ASSERT_EQ $quoted.2 "a b"
3934 "###
3935)]
3936fn shell_split_args(
3937 command: String,
3939) -> Result<Value> {
3940 match shell_words::split(&command) {
3941 Ok(words) => Ok(super::args::text_list_value(words)),
3942 Err(err) => anyhow::bail!("SHELL_SPLIT_ARGS: {err}"),
3943 }
3944}
3945
3946#[oxdock_func(pure, returns = TypeTag::String)]
3954#[example(
3955 name = "join args",
3956 code = r###"
3957 # Plain words join with spaces and no quoting.
3958 IMPORT [STD]
3959 LET $plain: STRING = SHELL_JOIN_ARGS(["gh", "issue", "list"])
3960 ASSERT_EQ $plain "gh issue list"
3961
3962 # Words with spaces quote, and the round trip is exact.
3963 LET $words: LIST<STRING> = ["say", "hi there", "a'b"]
3964 LET $joined: STRING = SHELL_JOIN_ARGS($words)
3965 LET $back: LIST<STRING> = SHELL_SPLIT_ARGS($joined)
3966 ASSERT_EQ $back.0 "say"
3967 ASSERT_EQ $back.1 "hi there"
3968 ASSERT_EQ $back.2 "a'b"
3969 "###
3970)]
3971fn shell_join_args(
3972 words: Vec<String>,
3974) -> Result<Value> {
3975 Ok(Value::string(shell_words::join(&words)))
3976}
3977
3978#[oxdock_func(pure, returns = TypeTag::ListOf(std::sync::Arc::new(TypeTag::String)))]
3986#[example(
3987 name = "lines",
3988 code = r###"
3989 # Newlines split into line items.
3990 IMPORT [STD]
3991 LET $lines: LIST<STRING> = TEXT_LINES("one\ntwo\nthree")
3992 ASSERT_EQ $lines.0 "one"
3993 ASSERT_EQ $lines.1 "two"
3994 ASSERT_EQ $lines.2 "three"
3995
3996 # Windows endings split the same way after normalization.
3997 LET $crlf: LIST<STRING> = TEXT_LINES("one\r\ntwo\r\nthree")
3998 ASSERT_EQ $crlf.0 "one"
3999 ASSERT_EQ $crlf.1 "two"
4000 ASSERT_EQ $crlf.2 "three"
4001
4002 # Old Mac endings split too, and mixed endings split together because the input normalizes to LF before splitting.
4003 LET $mixed: LIST<STRING> = TEXT_LINES("a\r\nb\nc\rd")
4004 ASSERT_EQ $mixed.0 "a"
4005 ASSERT_EQ $mixed.1 "b"
4006 ASSERT_EQ $mixed.2 "c"
4007 ASSERT_EQ $mixed.3 "d"
4008 "###
4009)]
4010fn text_lines(
4011 text: String,
4013) -> Result<Value> {
4014 Ok(super::args::text_list_value(super::args::text_lines_str(
4015 &text,
4016 )))
4017}
4018
4019#[oxdock_func(pure, returns = TypeTag::ListOf(std::sync::Arc::new(TypeTag::String)))]
4025#[example(
4026 name = "fields",
4027 code = r###"
4028 # Runs of whitespace separate fields; empties never appear.
4029 IMPORT [STD]
4030 LET $fields: LIST<STRING> = TEXT_FIELDS(" abc def ")
4031 ASSERT_EQ $fields.0 "abc"
4032 ASSERT_EQ $fields.1 "def"
4033 "###
4034)]
4035fn text_fields(
4036 text: String,
4038) -> Result<Value> {
4039 Ok(super::args::text_list_value(super::args::text_fields_str(
4040 &text,
4041 )))
4042}
4043
4044#[oxdock_func(pure, returns = TypeTag::ListOf(std::sync::Arc::new(TypeTag::String)))]
4053#[example(
4054 name = "line range",
4055 code = r###"
4056 # Lines 2 through 3 come back as a list, 1-based inclusive.
4057 IMPORT [STD]
4058 LET $window: LIST<STRING> = TEXT_LINES_RANGE("one\ntwo\nthree\nfour", 2, 3)
4059 ASSERT_EQ $window.0 "two"
4060 ASSERT_EQ $window.1 "three"
4061
4062 # Ranges past the end clamp instead of failing.
4063 LET $tail: LIST<STRING> = TEXT_LINES_RANGE("one\ntwo", 2, 9)
4064 ASSERT_EQ $tail.0 "two"
4065 "###
4066)]
4067fn text_lines_range(
4068 text: String,
4070 from: i64,
4072 to: i64,
4074) -> Result<Value> {
4075 Ok(super::args::text_list_value(
4076 super::args::text_lines_range_str(&text, from, to, "TEXT_LINES_RANGE")?,
4077 ))
4078}
4079
4080#[oxdock_func(pure, returns = TypeTag::Bool)]
4088#[example(
4089 name = "match",
4090 code = r###"
4091 # Regex matches report true; misses report false.
4092 IMPORT [STD]
4093 LET $hit: BOOL = TEXT_MATCH("abc123", "\\d+")
4094 ASSERT_EQ $hit true
4095
4096 # A miss is false, not a failure.
4097 LET $miss: BOOL = TEXT_MATCH("abc", "^\\d+$")
4098 ASSERT_EQ $miss false
4099 "###
4100)]
4101fn text_match(
4102 text: String,
4104 pattern: String,
4106) -> Result<Value> {
4107 let re = super::args::text_compile_pattern("TEXT_MATCH", &pattern)?;
4108 Ok(Value::bool(re.is_match(&text)))
4109}
4110
4111#[oxdock_func(pure, name = "BOOL", returns = TypeTag::Bool)]
4120#[example(
4121 name = "convert",
4122 code = r###"
4123 IMPORT [STD]
4124 LET $n: BOOL = BOOL("yes")
4125 ASSERT_EQ $n true
4126 LET $f: BOOL = BOOL("0")
4127 ASSERT_EQ $f false
4128 "###
4129)]
4130fn bool_convert(
4131 #[union(Bool, String)]
4133 val: Value,
4134) -> Result<Value> {
4135 if let Some(b) = val.as_bool() {
4136 return Ok(Value::bool(b));
4137 }
4138 let Some(s) = val.as_str() else {
4139 return Err(anyhow::anyhow!(
4140 "BOOL needs a Bool or String, found {val:?}"
4141 ));
4142 };
4143 match super::args::parse_bool_str(s) {
4144 Some(b) => Ok(Value::bool(b)),
4145 None => anyhow::bail!("BOOL cannot coerce {s:?} to BOOL"),
4146 }
4147}
4148
4149#[oxdock_func(pure, returns = TypeTag::Bool)]
4159#[example(
4160 name = "absent-default",
4161 code = r###"
4162 # Absent names read empty; the default settles the polarity.
4163 IMPORT [STD]
4164 INHERIT_ENV [OXDOCK_TEST_ABSENT_FLAG]
4165 LET $dry: BOOL = BOOL_OR("{{ env:OXDOCK_TEST_ABSENT_FLAG }}", true)
4166 ASSERT_EQ $dry true
4167
4168 # Present values coerce strictly, ignoring the default.
4169 LET $off: BOOL = BOOL_OR("false", true)
4170 ASSERT_EQ $off false
4171 "###
4172)]
4173fn bool_or(
4174 text: String,
4176 default: bool,
4178) -> Result<Value> {
4179 if text.trim().is_empty() {
4180 return Ok(Value::bool(default));
4181 }
4182 match super::args::parse_bool_str(&text) {
4183 Some(b) => Ok(Value::bool(b)),
4184 None => anyhow::bail!("BOOL_OR cannot coerce {text:?} to BOOL"),
4185 }
4186}
4187
4188#[oxdock_func(pure, returns = TypeTag::ListOf(std::sync::Arc::new(TypeTag::String)))]
4197#[example(
4198 name = "extract",
4199 code = r###"
4200 # Index zero is the full match; groups follow in order.
4201 IMPORT [STD]
4202 LET $caps: LIST<STRING> = TEXT_EXTRACT("abc123", "([a-z]+)(\\d+)")
4203 ASSERT_EQ $caps.0 "abc123"
4204 ASSERT_EQ $caps.1 "abc"
4205 ASSERT_EQ $caps.2 "123"
4206 "###
4207)]
4208fn text_extract(
4209 text: String,
4211 pattern: String,
4213) -> Result<Value> {
4214 let groups = super::args::text_extract_str(&text, &pattern, "TEXT_EXTRACT")?;
4215 Ok(super::args::text_list_value(groups))
4216}
4217
4218#[oxdock_func(pure, returns = TypeTag::Bool)]
4225#[example(
4226 name = "starts with",
4227 code = r###"
4228 # Present prefixes report true; misses report false.
4229 IMPORT [STD]
4230 LET $hit: BOOL = TEXT_STARTS_WITH("linux-musl-x64", "linux")
4231 ASSERT_EQ $hit true
4232
4233 # A miss is false, not a failure.
4234 LET $miss: BOOL = TEXT_STARTS_WITH("macos-arm", "linux")
4235 ASSERT_EQ $miss false
4236 "###
4237)]
4238fn text_starts_with(
4239 text: String,
4241 prefix: String,
4243) -> Result<Value> {
4244 Ok(Value::bool(text.starts_with(prefix.as_str())))
4245}
4246
4247#[oxdock_func(pure, returns = TypeTag::Bool)]
4254#[example(
4255 name = "ends with",
4256 code = r###"
4257 # Present suffixes report true; misses report false.
4258 IMPORT [STD]
4259 LET $hit: BOOL = TEXT_ENDS_WITH("x86_64-linux-musl", "linux-musl")
4260 ASSERT_EQ $hit true
4261
4262 # A miss is false, not a failure.
4263 LET $miss: BOOL = TEXT_ENDS_WITH("x86_64-linux-gnu", "linux-musl")
4264 ASSERT_EQ $miss false
4265 "###
4266)]
4267fn text_ends_with(
4268 text: String,
4270 suffix: String,
4272) -> Result<Value> {
4273 Ok(Value::bool(text.ends_with(suffix.as_str())))
4274}
4275
4276#[oxdock_func(pure, returns = TypeTag::Bool)]
4283#[example(
4284 name = "contains",
4285 code = r###"
4286 # Present needles report true; misses report false.
4287 IMPORT [STD]
4288 LET $hit: BOOL = TEXT_CONTAINS("x86_64-linux-musl", "musl")
4289 ASSERT_EQ $hit true
4290
4291 # A miss is false, not a failure.
4292 LET $miss: BOOL = TEXT_CONTAINS("x86_64-linux-gnu", "musl")
4293 ASSERT_EQ $miss false
4294 "###
4295)]
4296fn text_contains(
4297 text: String,
4299 needle: String,
4301) -> Result<Value> {
4302 Ok(Value::bool(text.contains(needle.as_str())))
4303}
4304
4305#[oxdock_func(pure, returns = TypeTag::Int)]
4314#[example(
4315 name = "length",
4316 code = r###"
4317 # Plain text counts one per character.
4318 IMPORT [STD]
4319 LET $n: INT = LEN("hello")
4320 ASSERT_EQ $n 5
4321
4322 # Multibyte characters count once each, not per byte.
4323 LET $wide: INT = LEN("héllo")
4324 ASSERT_EQ $wide 5
4325
4326 # Lists count elements, maps count entries.
4327 LET $items: LIST<STRING> = ["a", "b", "c"]
4328 LET $nitems: INT = LEN($items)
4329 ASSERT_EQ $nitems 3
4330 LET $row: MAP<name: STRING> = {name: "ada"}
4331 LET $nkeys: INT = LEN($row)
4332 ASSERT_EQ $nkeys 1
4333 LET $empty: INT = LEN([])
4334 ASSERT_EQ $empty 0
4335 "###
4336)]
4337fn len(
4338 #[union(String, List, Map)]
4340 value: Value,
4341) -> Result<Value> {
4342 if let Some(text) = value.as_str() {
4343 return Ok(Value::int(text.chars().count() as i64));
4344 }
4345 if let Some(items) = value.as_list() {
4346 return Ok(Value::int(items.len() as i64));
4347 }
4348 if let Some(entries) = value.as_map() {
4349 return Ok(Value::int(entries.len() as i64));
4350 }
4351 Err(anyhow::anyhow!(
4352 "LEN needs a STRING, LIST, or MAP value, got {}",
4353 value.type_name()
4354 ))
4355}
4356
4357#[oxdock_func(pure, returns = TypeTag::Int)]
4365#[example(
4366 name = "count",
4367 code = r###"
4368 # Every non-overlapping occurrence counts once.
4369 IMPORT [STD]
4370 LET $n: INT = TEXT_COUNT("hello world", "o")
4371 ASSERT_EQ $n 2
4372
4373 # Overlapping candidates never double count.
4374 LET $once: INT = TEXT_COUNT("aaa", "aa")
4375 ASSERT_EQ $once 1
4376 "###
4377)]
4378fn text_count(
4379 text: String,
4381 needle: String,
4383) -> Result<Value> {
4384 let n = super::args::text_count_str(&text, &needle, "TEXT_COUNT")?;
4385 Ok(Value::int(n))
4386}
4387
4388#[oxdock_func(pure, returns = TypeTag::Int)]
4398#[example(
4399 name = "count matches",
4400 code = r###"
4401 # One line matches once no matter how many times it hits.
4402 IMPORT [STD]
4403 LET $n: INT = TEXT_COUNT_MATCHES("test a: test\ntest b: nope\ntest c: test", ": test")
4404 ASSERT_EQ $n 2
4405
4406 # A miss binds zero, never an error.
4407 LET $none: INT = TEXT_COUNT_MATCHES("test b: nope", ": test$")
4408 ASSERT_EQ $none 0
4409 "###
4410)]
4411fn text_count_matches(
4412 text: String,
4414 pattern: String,
4416) -> Result<Value> {
4417 let n = super::args::text_count_matches_str(&text, &pattern, "TEXT_COUNT_MATCHES")?;
4418 Ok(Value::int(n))
4419}
4420
4421#[oxdock_func(pure, returns = TypeTag::ListOf(std::sync::Arc::new(TypeTag::String)))]
4434#[example(
4435 name = "grep",
4436 code = r###"
4437 # Matching lines come back as a list, in order.
4438 IMPORT [STD]
4439 LET $hits: LIST<STRING> = TEXT_GREP("one\ntwo\none more", "^one")
4440 ASSERT_EQ $hits.0 "one"
4441 ASSERT_EQ $hits.1 "one more"
4442
4443 # A miss binds an empty list, never an error.
4444 LET $miss: LIST<STRING> = TEXT_GREP("one\ntwo", "^z")
4445 LET $joined: STRING = TEXT_JOIN($miss, ",")
4446 ASSERT_EQ $joined ""
4447
4448 # The (?i) flag ignores case, so uppercase lines match too.
4449 LET $folded: LIST<STRING> = TEXT_GREP("One\ntwo\nONE more", "(?i)^one")
4450 ASSERT_EQ $folded.0 "One"
4451 ASSERT_EQ $folded.1 "ONE more"
4452 "###
4453)]
4454#[example(
4455 name = "grep invert",
4456 code = r###"
4457 # The invert option keeps every non-matching line instead.
4458 IMPORT [STD]
4459 LET $kept: LIST<STRING> = TEXT_GREP("one\ntwo\none more", "^one", {invert: true})
4460 ASSERT_EQ $kept.0 "two"
4461
4462 # A pattern matching every line binds an empty list, never an error.
4463 LET $none: LIST<STRING> = TEXT_GREP("one\ntwo", "^", {invert: true})
4464 LET $joined: STRING = TEXT_JOIN($none, ",")
4465 ASSERT_EQ $joined ""
4466
4467 # Options ride into placeholders as MAP literals. Placeholder
4468 # strings unescape only backslash and quote, so multiline text
4469 # arrives through a variable.
4470 LET $two_lines: STRING = "one\ntwo"
4471 LET $msg: STRING = 'kept:{{ STD::TEXT_GREP($two_lines, "^one", {invert: true}) }}'
4472 ASSERT_EQ $msg "kept:two"
4473 "###
4474)]
4475fn text_grep(
4476 text: String,
4478 pattern: String,
4480 #[options("invert?: BOOL")]
4482 #[optional]
4483 options: BTreeMap<String, Value>,
4484) -> Result<Value> {
4485 let invert = super::args::text_invert_flag(&options);
4488 Ok(super::args::text_list_value(super::args::text_grep_str(
4489 &text,
4490 &pattern,
4491 invert,
4492 "TEXT_GREP",
4493 )?))
4494}
4495
4496#[oxdock_func(returns = TypeTag::Bool)]
4507#[example(
4508 name = "drain to end",
4509 code = r###"
4510 # Capture two lines, then drain to end of stream with no sentinel line.
4511 IMPORT [STD]
4512 LET $cap: PIPE
4513 WITH_IO [stdout=$cap] {
4514 ECHO "one"
4515 ECHO "two"
4516 }
4517
4518 # The loop exits on close, and the count proves both lines drained.
4519 LET $n: INT = 0
4520 WHILE !EOF($cap) {
4521 WITH_IO [stdin=$cap] READ_LINE $line
4522 $n = $n + 1
4523 }
4524 ASSERT_EQ $n 2
4525 "###
4526)]
4527fn eof<P: ProcessManager>(
4528 cx: &mut StepCtx<P>,
4529 pipe: PipeHandle,
4531) -> Result<Value> {
4532 let info = cx.state.io.inspect_pipe(&pipe);
4533 Ok(Value::bool(info.closed && info.buffered == 0))
4534}
4535
4536fn task_poll_result_fields() -> Arc<[Field]> {
4540 Arc::from(vec![
4541 Field {
4542 name: "state".to_string(),
4543 ty: TypeTag::String,
4544 docs: "Task phase: `running` or `finished`.",
4545 optional: false,
4546 default: None,
4547 },
4548 Field {
4549 name: "ok".to_string(),
4550 ty: TypeTag::Bool,
4551 docs: "True unless the task failed.",
4552 optional: false,
4553 default: None,
4554 },
4555 Field {
4556 name: "stdout_tail".to_string(),
4557 ty: TypeTag::String,
4558 docs: "Bounded stdout tail, live while running.",
4559 optional: false,
4560 default: None,
4561 },
4562 Field {
4563 name: "stderr_tail".to_string(),
4564 ty: TypeTag::String,
4565 docs: "Bounded stderr tail, live while running.",
4566 optional: false,
4567 default: None,
4568 },
4569 Field {
4570 name: "truncated_bytes".to_string(),
4571 ty: TypeTag::Int,
4572 docs: "Dropped head bytes past the per-stream cap.",
4573 optional: false,
4574 default: None,
4575 },
4576 Field {
4577 name: "exit_code".to_string(),
4578 ty: TypeTag::Int,
4579 docs: "Process exit code, present once finished.",
4580 optional: true,
4581 default: None,
4582 },
4583 Field {
4584 name: "result".to_string(),
4585 ty: TypeTag::Any,
4586 docs: "Task `RETURN` value, present on clean finish.",
4587 optional: true,
4588 default: None,
4589 },
4590 Field {
4591 name: "error".to_string(),
4592 ty: TypeTag::String,
4593 docs: "Failure text, present on failed finish.",
4594 optional: true,
4595 default: None,
4596 },
4597 ])
4598}
4599
4600#[oxdock_func(returns = TypeTag::Record(task_poll_result_fields()))]
4613#[example(
4614 name = "running poll",
4615 code = r###"
4616 # A sleeping task is still running on the first poll.
4617 IMPORT [STD]
4618 LET $t: HANDLE<STRING> = ASYNC { SLEEP 30s; RETURN "done" }
4619 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)
4620 ASSERT_EQ $m.state "running"
4621 ASSERT_EQ $m.ok true
4622 # Clean up the sleeper so the run ends promptly.
4623 CANCEL $t
4624 "###
4625)]
4626#[example(
4627 name = "finished poll",
4628 code = r###"
4629 # A finished task reports its value and final tails, then still awaits.
4630 IMPORT [STD]
4631 LET $t: HANDLE<STRING> = ASYNC { ECHO "hi"; SLEEP 1s; RETURN "done" }
4632 # Do other work while the task runs; poll once it should be done.
4633 SLEEP 2s
4634 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)
4635 ASSERT_EQ $m.state "finished"
4636 ASSERT_EQ $m.result "done"
4637 LET $o: STRING = AWAIT $t
4638 ASSERT_EQ $o "done"
4639 "###
4640)]
4641fn task_poll<P: ProcessManager>(
4642 cx: &mut StepCtx<P>,
4643 task: HandleValue,
4645) -> Result<Value> {
4646 let entry =
4647 super::handlers::resolve_task_entry_by_id(task.0, &format!("TASK_POLL({})", task.0), cx)?;
4648 let obs = entry.observe_completion();
4649 let (stdout_tail, stderr_tail, dropped) = entry.snapshot_tails();
4650 let mut out = BTreeMap::new();
4651 out.insert(
4652 "state".to_string(),
4653 Value::string(if obs.running { "running" } else { "finished" }.to_string()),
4654 );
4655 out.insert("ok".to_string(), Value::bool(obs.ok));
4656 if !obs.running {
4657 out.insert("exit_code".to_string(), Value::int(obs.exit_code));
4658 }
4659 if let Some(result) = obs.result {
4660 out.insert("result".to_string(), result);
4661 }
4662 if !obs.error.is_empty() {
4663 out.insert("error".to_string(), Value::string(obs.error));
4664 }
4665 out.insert("stdout_tail".to_string(), Value::string(stdout_tail));
4666 out.insert("stderr_tail".to_string(), Value::string(stderr_tail));
4667 out.insert(
4668 "truncated_bytes".to_string(),
4669 Value::int(dropped.min(i64::MAX as u64) as i64),
4670 );
4671 Ok(Value::map(out))
4672}
4673
4674fn meta_to_value(meta: &FuncMeta) -> Value {
4675 let mut map = BTreeMap::new();
4676 map.insert("name".to_string(), Value::string(meta.name.clone()));
4677 map.insert("module".to_string(), Value::string(meta.module.clone()));
4678 map.insert(
4679 "kind".to_string(),
4680 Value::string(meta.kind.label().to_string()),
4681 );
4682 let params = match &meta.params {
4683 Some(params) => Value::list(
4684 params
4685 .iter()
4686 .map(|p| {
4687 let mut entry = BTreeMap::new();
4688 entry.insert("name".to_string(), Value::string(p.name.clone()));
4689 entry.insert(
4690 "param_type".to_string(),
4691 Value::string(
4692 p.param_type
4693 .as_ref()
4694 .map(render_structural)
4695 .unwrap_or_default(),
4696 ),
4697 );
4698 entry.insert(
4699 "allowed".to_string(),
4700 Value::string(
4701 p.allowed
4702 .map(|values| values.join(", "))
4703 .unwrap_or_default(),
4704 ),
4705 );
4706 entry.insert("docs".to_string(), Value::string(String::new()));
4707 entry.insert("optional".to_string(), Value::bool(p.optional));
4708 entry.insert(
4709 "options".to_string(),
4710 match p.options {
4711 Some(keys) => Value::list(
4712 keys.iter()
4713 .map(|key| {
4714 let mut option = BTreeMap::new();
4715 option.insert(
4716 "name".to_string(),
4717 Value::string(key.name.to_string()),
4718 );
4719 option.insert(
4720 "value_type".to_string(),
4721 Value::string(render_structural(&key.value)),
4722 );
4723 option.insert(
4724 "required".to_string(),
4725 Value::bool(key.required),
4726 );
4727 option.insert(
4728 "default".to_string(),
4729 Value::string(
4730 key.default.unwrap_or_default().to_string(),
4731 ),
4732 );
4733 Value::map(option)
4734 })
4735 .collect(),
4736 ),
4737 None => Value::string(String::new()),
4738 },
4739 );
4740 Value::map(entry)
4741 })
4742 .collect(),
4743 ),
4744 None => Value::list(Vec::new()),
4748 };
4749 map.insert("params".to_string(), params);
4750 map.insert(
4751 "returns".to_string(),
4752 Value::string(
4753 meta.returns
4754 .as_ref()
4755 .map(render_structural)
4756 .unwrap_or_default(),
4757 ),
4758 );
4759 map.insert("rpn".to_string(), Value::bool(meta.rpn));
4760 map.insert(
4761 "summary".to_string(),
4762 Value::string(meta.summary.to_string()),
4763 );
4764 Value::map(map)
4765}
4766
4767#[derive(Debug, Clone)]
4771pub struct RecordSchema {
4772 pub name: &'static str,
4773 pub fields: std::sync::Arc<[Field]>,
4774}
4775
4776#[derive(Clone)]
4780pub struct HostModule<P: ProcessManager> {
4781 pub name: String,
4782 pub funcs: Vec<HostRegistration<P>>,
4783 pub types: Vec<&'static TypeDescriptor>,
4784 pub record_schemas: Vec<RecordSchema>,
4785 pub states: Vec<ModuleState>,
4792}
4793
4794#[derive(Clone)]
4798pub struct ModuleState {
4799 id: std::any::TypeId,
4800 state: std::sync::Arc<dyn std::any::Any + Send + Sync>,
4801}
4802
4803pub type PreRunInspector = dyn Fn(&[Step]) -> Result<()> + Send + Sync;
4807
4808#[derive(Clone)]
4814pub struct PreRunCheck {
4815 check: Arc<PreRunInspector>,
4816}
4817
4818impl PreRunCheck {
4819 pub fn new(check: impl Fn(&[Step]) -> Result<()> + Send + Sync + 'static) -> Self {
4821 Self {
4822 check: Arc::new(check),
4823 }
4824 }
4825
4826 pub fn run(&self, steps: &[Step]) -> Result<()> {
4828 (self.check)(steps)
4829 }
4830}
4831
4832impl<P: ProcessManager> HostModule<P> {
4833 pub fn with_state<T: Send + Sync + 'static>(mut self, state: std::sync::Arc<T>) -> Self {
4836 self.states.push(ModuleState {
4837 id: std::any::TypeId::of::<T>(),
4838 state,
4839 });
4840 self
4841 }
4842
4843 pub fn check_pre_run(&self, steps: &[Step]) -> Result<()> {
4847 for state in &self.states {
4848 if let Some(check) = state.state.downcast_ref::<PreRunCheck>() {
4849 check.run(steps)?;
4850 }
4851 }
4852 Ok(())
4853 }
4854}
4855
4856impl<P: ProcessManager> ExecState<P> {
4857 pub fn register_module(&mut self, module: HostModule<P>) {
4860 for registration in module.funcs {
4861 match registration {
4862 HostRegistration::Stateful { name, meta, func } => {
4863 self.functions.register_host(&module.name, name, meta, func);
4864 }
4865 HostRegistration::Pure { name, meta, func } => {
4866 self.functions
4867 .register_pure_host(&module.name, name, meta, func);
4868 }
4869 HostRegistration::Both {
4870 name,
4871 meta,
4872 func,
4873 template,
4874 } => {
4875 self.functions
4876 .register_both_host(&module.name, name, meta, func, template);
4877 }
4878 }
4879 }
4880 for descriptor in module.types {
4881 self.register_type(descriptor);
4882 }
4883 for schema in module.record_schemas {
4884 self.register_record_schema(schema.name, schema.fields);
4885 }
4886 for state in module.states {
4887 self.module_states
4888 .insert((module.name.clone(), state.id), state.state);
4889 }
4890 }
4891
4892 pub fn list_functions(&self) -> Vec<FuncMeta> {
4894 let mut out: Vec<FuncMeta> = self.functions.entries_metas().into_iter().collect();
4895 if !out.iter().any(|m| m.name == KEYWORD_INSPECT) {
4897 out.push(FuncMeta {
4898 name: KEYWORD_INSPECT.to_string(),
4899 module: STD_MODULE_NAME.to_string(),
4900 kind: FuncKind::HostCtx,
4901 params: None,
4902 returns: Some(TypeTag::Map),
4903 rpn: false,
4904 summary: "Inspect a variable binding.",
4905 docs: "INSPECT($var): dedicated AST node taking a variable, not a value.",
4906 examples: &[],
4907 });
4908 }
4909 out.sort_by(|a, b| a.name.cmp(&b.name));
4910 out
4911 }
4912
4913 pub fn describe_function(&self, name: &str) -> Option<Value> {
4915 if let Some(meta) = self.functions.meta(name) {
4916 return Some(meta_to_value(&meta));
4917 }
4918 if name == KEYWORD_INSPECT {
4920 return Some(meta_to_value(&FuncMeta {
4921 name: KEYWORD_INSPECT.to_string(),
4922 module: STD_MODULE_NAME.to_string(),
4923 kind: FuncKind::HostCtx,
4924 params: None,
4925 returns: Some(TypeTag::Map),
4926 rpn: false,
4927 summary: "Inspect a variable binding.",
4928 docs: "INSPECT($var): dedicated AST node taking a variable, not a value.",
4929 examples: &[],
4930 }));
4931 }
4932 None
4933 }
4934
4935 pub(super) fn clone_native_pure(&self, name: &str) -> Option<PureFn> {
4936 self.functions.clone_pure_fn(name)
4937 }
4938
4939 pub fn pure_function_table(&self) -> Arc<PureTable> {
4944 self.functions.pure_shared()
4945 }
4946
4947 pub(super) fn clone_native_ctx(&self, name: &str) -> Option<NativeFn<P>> {
4948 self.functions.clone_ctx_fn(name)
4949 }
4950
4951 pub(super) fn native_meta(&self, name: &str) -> Option<FuncMeta> {
4952 self.functions.meta(name)
4953 }
4954}
4955
4956#[cfg(test)]
4957mod tests {
4958 use super::*;
4959
4960 #[test]
4961 fn placeholder_resolver_dispatches_table_entries() {
4962 let echo: PureFn = Arc::new(|args| {
4966 args.into_iter()
4967 .next()
4968 .ok_or_else(|| anyhow::anyhow!("ECHO needs 1 arg"))
4969 });
4970 let mut entries = HashMap::new();
4971 entries.insert("ECHO".to_string(), echo);
4972 let mut table = PureTable::new();
4973 table.insert("T".to_string(), entries);
4974 let resolve = placeholder_resolver(Arc::new(table));
4975 let out = resolve("T", "ECHO", vec![Value::string("hi".to_string())]).expect("dispatch");
4976 assert_eq!(out.as_str().expect("string"), "hi");
4977 let err = format!(
4978 "{:#}",
4979 resolve("T", "NOPE", vec![]).expect_err("unknown must fail")
4980 );
4981 assert!(
4982 err.contains("unknown placeholder function 'T::NOPE'"),
4983 "names the call: {err}"
4984 );
4985 assert!(
4986 err.contains("known functions: T::ECHO"),
4987 "lists known names: {err}"
4988 );
4989 }
4990
4991 #[test]
4992 fn describe_entry_renders_union_spellings() {
4993 let union = oxdock_parser::union_tag!(String, Pipe);
4999 let meta = FuncMeta {
5000 name: "T::F".to_string(),
5001 module: "T".to_string(),
5002 kind: FuncKind::HostPure,
5003 params: Some(vec![FuncParam {
5004 name: "text".to_string(),
5005 param_type: Some(union.clone()),
5006 allowed: None,
5007 docs: "",
5008 options: None,
5009 optional: false,
5010 }]),
5011 returns: Some(union),
5012 rpn: false,
5013 summary: "test-only",
5014 docs: "test-only",
5015 examples: &[],
5016 };
5017 let value = meta_to_value(&meta);
5018 let map = value.as_map().expect("describe value is a map");
5019 let params = map
5020 .get("params")
5021 .expect("params key")
5022 .as_list()
5023 .expect("params is a list");
5024 let first = params[0].as_map().expect("entry is a map");
5025 assert_eq!(
5026 first.get("param_type").and_then(Value::as_str),
5027 Some("STRING|PIPE"),
5028 "param renders the set"
5029 );
5030 assert_eq!(
5031 map.get("returns").and_then(Value::as_str),
5032 Some("STRING|PIPE"),
5033 "returns render the set"
5034 );
5035 }
5036
5037 #[test]
5038 fn describe_entry_renders_handle_payload() {
5039 let meta = FuncMeta {
5043 name: "SCRIPT::FETCH".to_string(),
5044 module: "SCRIPT".to_string(),
5045 kind: FuncKind::Script,
5046 params: Some(vec![]),
5047 returns: Some(TypeTag::HandleOf(std::sync::Arc::new(TypeTag::String))),
5048 rpn: false,
5049 summary: "test-only",
5050 docs: "test-only",
5051 examples: &[],
5052 };
5053 let value = meta_to_value(&meta);
5054 let map = value.as_map().expect("describe value is a map");
5055 assert_eq!(
5056 map.get("returns").and_then(Value::as_str),
5057 Some("HANDLE<STRING>"),
5058 "returns render the payload"
5059 );
5060 }
5061
5062 #[test]
5063 fn describe_entry_carries_optional_flag() {
5064 let meta = FuncMeta {
5068 name: "T::F".to_string(),
5069 module: "T".to_string(),
5070 kind: FuncKind::HostPure,
5071 params: Some(vec![
5072 FuncParam {
5073 name: "url".to_string(),
5074 param_type: Some(TypeTag::String),
5075 allowed: None,
5076 docs: "",
5077 options: None,
5078 optional: false,
5079 },
5080 FuncParam {
5081 name: "options".to_string(),
5082 param_type: Some(TypeTag::Map),
5083 allowed: None,
5084 docs: "",
5085 options: None,
5086 optional: true,
5087 },
5088 ]),
5089 returns: Some(TypeTag::String),
5090 rpn: false,
5091 summary: "test-only",
5092 docs: "test-only",
5093 examples: &[],
5094 };
5095 let value = meta_to_value(&meta);
5096 let map = value.as_map().expect("describe value is a map");
5097 let params = map
5098 .get("params")
5099 .expect("params key")
5100 .as_list()
5101 .expect("params is a list");
5102 assert_eq!(params.len(), 2);
5103 let first = params[0].as_map().expect("entry is a map");
5104 let second = params[1].as_map().expect("entry is a map");
5105 assert_eq!(
5106 first.get("optional").and_then(Value::as_bool),
5107 Some(false),
5108 "required param must read false"
5109 );
5110 assert_eq!(
5111 second.get("optional").and_then(Value::as_bool),
5112 Some(true),
5113 "omittable param must read true"
5114 );
5115 }
5116
5117 #[test]
5118 fn template_twins_mirror_string_paths_and_refuse_pipes() {
5119 let pipe = Value::pipe_fresh();
5125 type TwinCase = (&'static str, Box<dyn Fn() -> Result<Value>>);
5126 let cases: Vec<TwinCase> = vec![
5127 (
5128 "TEXT_TRIM",
5129 Box::new(|| text_trim_string(Value::string(" hello ".to_string()))),
5130 ),
5131 (
5132 "TEXT_TRIM_PREFIX",
5133 Box::new(|| {
5134 text_trim_prefix_string(Value::string("v1".to_string()), "v".to_string())
5135 }),
5136 ),
5137 (
5138 "TEXT_TRIM_SUFFIX",
5139 Box::new(|| {
5140 text_trim_suffix_string(Value::string("a.gz".to_string()), "x".to_string())
5141 }),
5142 ),
5143 (
5144 "TEXT_TO_UPPER",
5145 Box::new(|| text_to_upper_string(Value::string("hi".to_string()))),
5146 ),
5147 (
5148 "TEXT_TO_LOWER",
5149 Box::new(|| text_to_lower_string(Value::string("HI".to_string()))),
5150 ),
5151 (
5152 "TEXT_REPLACE",
5153 Box::new(|| {
5154 text_replace_string(
5155 Value::string("ab".to_string()),
5156 "b".to_string(),
5157 "c".to_string(),
5158 )
5159 }),
5160 ),
5161 (
5162 "TEXT_REPLACE_REGEX",
5163 Box::new(|| {
5164 text_replace_regex_string(
5165 Value::string("ab".to_string()),
5166 "b".to_string(),
5167 "c".to_string(),
5168 )
5169 }),
5170 ),
5171 ];
5172 assert_eq!(cases.len(), 7, "every mirror op needs a twin row");
5173 for (name, run) in &cases {
5174 let value = run().unwrap_or_else(|e| panic!("{name} twin must answer strings: {e:#}"));
5175 assert!(
5176 value.as_str().is_some(),
5177 "{name} twin must answer STRING, got {}",
5178 value.type_name()
5179 );
5180 }
5181 assert_eq!(
5182 text_trim_string(Value::string(" hello ".to_string()))
5183 .expect("trim twin")
5184 .as_str(),
5185 Some("hello")
5186 );
5187 let pipe_cases: Vec<(&str, Result<Value>)> = vec![
5189 ("TEXT_TRIM", text_trim_string(pipe.clone())),
5190 (
5191 "TEXT_TRIM_PREFIX",
5192 text_trim_prefix_string(pipe.clone(), "v".to_string()),
5193 ),
5194 (
5195 "TEXT_TRIM_SUFFIX",
5196 text_trim_suffix_string(pipe.clone(), ".gz".to_string()),
5197 ),
5198 ("TEXT_TO_UPPER", text_to_upper_string(pipe.clone())),
5199 ("TEXT_TO_LOWER", text_to_lower_string(pipe.clone())),
5200 (
5201 "TEXT_REPLACE",
5202 text_replace_string(pipe.clone(), "a".to_string(), "b".to_string()),
5203 ),
5204 (
5205 "TEXT_REPLACE_REGEX",
5206 text_replace_regex_string(pipe.clone(), "a".to_string(), "b".to_string()),
5207 ),
5208 ];
5209 for (name, result) in pipe_cases {
5210 let err = result.expect_err(&format!("{name} twin must refuse PIPE"));
5211 assert!(
5212 format!("{err:#}").contains("step IO"),
5213 "{name} refusal names the missing context: {err:#}"
5214 );
5215 }
5216 }
5217
5218 #[test]
5219 fn shell_words_join_split_round_trip() {
5220 let words = vec![
5224 "gh".to_string(),
5225 "issue".to_string(),
5226 "comment".to_string(),
5227 "with spaces".to_string(),
5228 "it's".to_string(),
5229 "say \"hi\"".to_string(),
5230 "$HOME".to_string(),
5231 "$(whoami)".to_string(),
5232 "C:\\path\\to".to_string(),
5233 "naïve café".to_string(),
5234 "".to_string(),
5235 ];
5236 let joined = shell_words::join(&words);
5237 let back = shell_words::split(&joined).expect("join output must parse");
5238 assert_eq!(back, words);
5239 assert!(shell_words::split("unbalanced \"quote").is_err());
5240 }
5241}