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> {
475 match tag {
476 TypeTag::Bool => Ok(Value::bool(false)),
477 TypeTag::String | TypeTag::Any => Ok(Value::string(String::new())),
478 TypeTag::Int => Ok(Value::int(0)),
479 TypeTag::Float => Ok(Value::float(0.0)),
480 TypeTag::List | TypeTag::ListOf(_) => Ok(Value::list(Vec::new())),
481 TypeTag::Map | TypeTag::MapOf(_) => Ok(Value::map(BTreeMap::new())),
482 TypeTag::Record(fields) if fields.iter().all(|field| field.optional) => {
483 Ok(Value::map(BTreeMap::new()))
484 }
485 other => anyhow::bail!(
486 "no zero value for {}; omit the `?` or pass the argument explicitly",
487 oxdock_parser::render_structural(other)
488 ),
489 }
490}
491
492pub fn resolve_script_params<P: ProcessManager>(
498 state: &ExecState<P>,
499 func_name: &str,
500 params: &[(String, String, bool)],
501) -> Result<Vec<(String, TypeTag, bool)>> {
502 let mut resolved = Vec::with_capacity(params.len());
503 for (pname, ptype, optional) in params {
504 let clean = pname.trim_start_matches('$').to_string();
505 let tag = state
506 .resolve_tag(ptype)
507 .map_err(|err| anyhow::anyhow!("function `{func_name}`: {err:#}"))?;
508 state.check_declaration_tag(&format!("function `{func_name}` param `${clean}`"), &tag)?;
509 if *optional {
510 optional_zero_value(&tag).map(|_| ()).map_err(|err| {
511 anyhow::anyhow!("function `{func_name}` optional param `${clean}`: {err:#}")
512 })?;
513 }
514 resolved.push((clean, tag, *optional));
515 }
516 Ok(resolved)
517}
518
519pub fn check_script_param_tags(func_name: &str, params: &[(String, TypeTag, bool)]) -> Result<()> {
522 for (pname, tag, optional) in params {
523 if *optional {
524 optional_zero_value(tag).map(|_| ()).map_err(|err| {
525 anyhow::anyhow!("function `{func_name}` optional param `${pname}`: {err:#}")
526 })?;
527 }
528 }
529 Ok(())
530}
531
532pub(super) enum FuncBody<P: ProcessManager> {
537 Script(FuncDefData),
538 Pure(PureFn),
539 Ctx(NativeFn<P>),
540 Both { pure: PureFn, ctx: NativeFn<P> },
541}
542
543impl<P: ProcessManager> Clone for FuncBody<P> {
545 fn clone(&self) -> Self {
546 match self {
547 FuncBody::Script(def) => FuncBody::Script(def.clone()),
548 FuncBody::Pure(func) => FuncBody::Pure(Arc::clone(func)),
549 FuncBody::Ctx(func) => FuncBody::Ctx(Arc::clone(func)),
550 FuncBody::Both { pure, ctx } => FuncBody::Both {
551 pure: Arc::clone(pure),
552 ctx: Arc::clone(ctx),
553 },
554 }
555 }
556}
557
558pub(super) struct FuncEntry<P: ProcessManager> {
562 pub(super) meta: FuncMeta,
563 pub(super) body: FuncBody<P>,
564}
565
566impl<P: ProcessManager> Clone for FuncEntry<P> {
568 fn clone(&self) -> Self {
569 Self {
570 meta: self.meta.clone(),
571 body: self.body.clone(),
572 }
573 }
574}
575
576struct ScopeFrame<P: ProcessManager> {
579 defined: HashSet<String>,
580 shadowed: Vec<(String, FuncEntry<P>)>,
581}
582
583impl<P: ProcessManager> Clone for ScopeFrame<P> {
585 fn clone(&self) -> Self {
586 Self {
587 defined: self.defined.clone(),
588 shadowed: self.shadowed.clone(),
589 }
590 }
591}
592
593pub type PureTable = HashMap<String, HashMap<String, PureFn>>;
603
604pub fn placeholder_resolver(table: Arc<PureTable>) -> oxdock_process::PlaceholderCall {
613 Arc::new(move |module, func, args| {
614 let callee = table
615 .get(module)
616 .and_then(|entries| entries.get(func))
617 .ok_or_else(|| {
618 let mut known: Vec<String> = table
619 .iter()
620 .flat_map(|(m, entries)| entries.keys().map(move |f| format!("{m}::{f}")))
621 .collect();
622 known.sort();
623 anyhow::anyhow!(
624 "unknown placeholder function '{module}::{func}'; known functions: {}",
625 known.join(", ")
626 )
627 })?;
628 callee(args)
629 })
630}
631
632pub(super) fn describe_placeholder_miss(
639 module: &str,
640 name: &str,
641 is_script: bool,
642 is_stateful: bool,
643 alias_known: bool,
644) -> Option<String> {
645 let qualified = qualify(module, name);
646 if is_script {
647 let call = if module == SCRIPT_MODULE_NAME {
648 format!("{name}(...)")
649 } else {
650 format!("{qualified}(...)")
651 };
652 return Some(format!(
653 "placeholder function '{qualified}' is a script function and cannot run in {{{{ }}}}; bind the result first with LET $v = {call} then interpolate {{{{ $v }}}}"
654 ));
655 }
656 if is_stateful {
657 return Some(format!(
658 "placeholder function '{qualified}' is stateful and cannot run in {{{{ }}}}; capture it first with LET then interpolate {{{{ $v }}}}"
659 ));
660 }
661 if alias_known {
662 return Some(format!(
663 "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 }}}}"
664 ));
665 }
666 None
667}
668
669pub(super) struct PlaceholderClasses {
672 pub script: HashSet<String>,
673 pub stateful: HashSet<String>,
674 pub aliases: HashSet<String>,
675 pub ambiguous: HashMap<String, HashSet<String>>,
677}
678
679impl PlaceholderClasses {
680 pub(super) fn describe(&self, module: &str, name: &str) -> Option<String> {
681 let qualified = qualify(module, name);
682 if let Some(files) = self.ambiguous.get(&qualified) {
683 return Some(ambiguous_alias_message(module, name, files));
684 }
685 describe_placeholder_miss(
686 module,
687 name,
688 self.script.contains(&qualified),
689 self.stateful.contains(&qualified),
690 self.aliases.contains(module),
691 )
692 }
693}
694
695pub struct FunctionRegistry<P: ProcessManager> {
696 entries: HashMap<String, FuncEntry<P>>,
697 scopes: Vec<ScopeFrame<P>>,
698 pure_shared: Arc<PureTable>,
699 script_docs: HashMap<String, (String, String)>,
703}
704
705impl<P: ProcessManager> FunctionRegistry<P> {
706 pub(super) fn with_builtins() -> Self {
707 let mut reg = Self {
708 entries: HashMap::new(),
709 pure_shared: Arc::new(HashMap::new()),
710 script_docs: HashMap::new(),
711 scopes: vec![ScopeFrame {
712 defined: HashSet::new(),
713 shadowed: Vec::new(),
714 }],
715 };
716 for host in Self::builtin_registrations() {
720 match host {
721 HostRegistration::Stateful { name, meta, func } => {
722 reg.insert_qualified(STD_MODULE_NAME, name, meta, FuncBody::Ctx(func));
723 }
724 HostRegistration::Pure { name, meta, func } => {
725 reg.insert_qualified(STD_MODULE_NAME, name, meta, FuncBody::Pure(func));
726 }
727 HostRegistration::Both {
728 name,
729 meta,
730 func,
731 template,
732 } => {
733 reg.insert_qualified(
734 STD_MODULE_NAME,
735 name,
736 meta,
737 FuncBody::Both {
738 pure: template,
739 ctx: func,
740 },
741 );
742 }
743 }
744 }
745 reg
746 }
747
748 pub(super) fn builtin_registrations() -> Vec<HostRegistration<P>> {
753 vec![
754 Int::registration(),
755 Float::registration(),
756 BoolConvert::registration(),
757 BoolOr::registration(),
758 FormatByteCount::registration(),
759 ParseByteCount::registration(),
760 FormatDuration::registration(),
761 ParseDuration::registration(),
762 Types::registration(),
763 TypeDescribe::registration(),
764 Glob::registration(),
765 LoadToml::registration(),
766 LoadJson::registration(),
767 HashSha256::registration(),
768 Cwd::registration(),
769 ParseToml::registration(),
770 ParseJson::registration(),
771 PathType::registration(),
772 PathWritable::registration(),
773 IsExec::registration(),
774 HasKey::registration(),
775 MapSet::registration(),
776 MergeMaps::registration(),
777 Base64Encode::registration(),
778 Base64Decode::registration(),
779 Rand::registration(),
780 ToJson::registration(),
781 TypeOf::registration(),
782 Functions::registration(),
783 Describe::registration(),
784 IsMain::registration(),
785 IsTerminal::registration(),
786 Eof::registration(),
787 TaskPoll::registration(),
788 Version::registration(),
789 Interpreter::registration(),
790 TextTrim::registration(),
791 TextTrimPrefix::registration(),
792 TextTrimSuffix::registration(),
793 PathJoin::registration(),
794 TextToUpper::registration(),
795 TextToLower::registration(),
796 TextReplace::registration(),
797 TextReplaceRegex::registration(),
798 TextSplit::registration(),
799 TextJoin::registration(),
800 TextLines::registration(),
801 TextFields::registration(),
802 TextMatch::registration(),
803 TextExtract::registration(),
804 TextStartsWith::registration(),
805 TextEndsWith::registration(),
806 TextContains::registration(),
807 Len::registration(),
808 TextCount::registration(),
809 TextCountMatches::registration(),
810 TextGrep::registration(),
811 TextLinesRange::registration(),
812 SemaphoreNew::registration(),
813 SemaphoreTryAcquire::registration(),
814 SemaphoreAvailable::registration(),
815 ShellSplitArgs::registration(),
816 ShellJoinArgs::registration(),
817 ]
818 }
819
820 pub(super) fn keys(&self) -> HashSet<String> {
823 self.entries.keys().cloned().collect()
824 }
825
826 pub(super) fn get(&self, name: &str) -> Option<FuncEntry<P>> {
828 self.entries.get(name).cloned()
829 }
830
831 pub(super) fn describe_unit_placeholder_miss(
837 &self,
838 unit_targets: &AliasTargets,
839 module: &str,
840 name: &str,
841 ) -> Option<String> {
842 let qualified = qualify(module, name);
843 match classify_alias_call(unit_targets, &qualified, &|key| {
848 self.entries.contains_key(key)
849 }) {
850 AliasResolution::Canonical(canonical) => {
851 if let Some(entry) = self.entries.get(&canonical) {
852 if let Some(miss) = Self::placeholder_miss_for_body(module, name, &entry.body) {
853 return Some(miss);
854 }
855 None
856 } else {
857 describe_placeholder_miss(module, name, false, false, true)
858 }
859 }
860 AliasResolution::Global => {
861 if let Some(entry) = self.entries.get(&qualified) {
862 if let Some(miss) = Self::placeholder_miss_for_body(module, name, &entry.body) {
866 return Some(miss);
867 }
868 }
869 None
870 }
871 AliasResolution::Ambiguous { files, .. } => {
872 Some(ambiguous_alias_message(module, name, &files))
873 }
874 AliasResolution::Unknown => describe_placeholder_miss(module, name, false, false, true),
875 AliasResolution::Any {
881 base,
882 files,
883 has_host,
884 } => Some(disjoint_alias_placeholder_miss(
885 module,
886 name,
887 &base,
888 &files,
889 has_host,
890 &|key| matches!(self.entries.get(key), Some(entry) if matches!(entry.body, FuncBody::Script(_))),
891 )),
892 }
893 }
894
895 fn placeholder_miss_for_body(module: &str, name: &str, body: &FuncBody<P>) -> Option<String> {
899 match body {
900 FuncBody::Script(_) => describe_placeholder_miss(module, name, true, false, false),
901 FuncBody::Ctx(_) => describe_placeholder_miss(module, name, false, true, false),
902 FuncBody::Pure(_) | FuncBody::Both { .. } => None,
903 }
904 }
905
906 pub(super) fn placeholder_snapshot(&self, unit_targets: &AliasTargets) -> PlaceholderClasses {
910 let mut script = HashSet::new();
911 let mut stateful = HashSet::new();
912 let mut ambiguous: HashMap<String, HashSet<String>> = HashMap::new();
913 for (key, entry) in self.entries.iter() {
914 let Some((module, base)) = split_qualified(key) else {
915 continue;
916 };
917 match &entry.body {
918 FuncBody::Script(def) => {
919 if module == SCRIPT_MODULE_NAME {
920 script.insert(key.clone());
922 continue;
923 }
924 let defining = def.module.as_deref().unwrap_or(module);
932 let (direct, ambiguous_here) = spellings_for_defining_file(
933 unit_targets,
934 defining,
935 base,
936 &|key| matches!(self.entries.get(key), Some(entry) if matches!(entry.body, FuncBody::Script(_))),
937 );
938 script.extend(direct);
939 for (spelling, files) in ambiguous_here {
940 ambiguous.entry(spelling).or_default().extend(files);
941 }
942 }
943 FuncBody::Ctx(_) => {
944 stateful.insert(key.clone());
945 }
946 FuncBody::Pure(_) | FuncBody::Both { .. } => {}
947 }
948 }
949 let aliases = unit_targets.keys().cloned().collect();
950 PlaceholderClasses {
951 script,
952 stateful,
953 aliases,
954 ambiguous,
955 }
956 }
957
958 fn insert_native(&mut self, name: String, meta: FuncMeta, body: FuncBody<P>) {
959 self.entries.insert(name, FuncEntry { meta, body });
960 self.rebuild_pure_shared();
961 }
962
963 fn rebuild_pure_shared(&mut self) {
969 let mut table: PureTable = HashMap::new();
970 for (name, entry) in &self.entries {
971 let func = match &entry.body {
972 FuncBody::Pure(func) => func,
973 FuncBody::Both { pure, .. } => pure,
974 FuncBody::Script(_) | FuncBody::Ctx(_) => continue,
975 };
976 if let Some((module, base)) = split_qualified(name) {
977 table
978 .entry(module.to_string())
979 .or_default()
980 .insert(base.to_string(), Arc::clone(func));
981 }
982 }
983 self.pure_shared = Arc::new(table);
984 }
985
986 fn insert_qualified(
990 &mut self,
991 module: &str,
992 base: String,
993 mut meta: FuncMeta,
994 body: FuncBody<P>,
995 ) {
996 meta.name = qualify(module, &base);
997 meta.module = module.to_string();
998 if self.entries.contains_key(&meta.name) {
1003 panic!("duplicate function registration `{}`", meta.name);
1004 }
1005 self.insert_native(meta.name.clone(), meta, body);
1006 }
1007
1008 pub(super) fn register_host(
1009 &mut self,
1010 module: &str,
1011 name: String,
1012 mut meta: FuncMeta,
1013 func: NativeFn<P>,
1014 ) {
1015 meta.kind = FuncKind::HostCtx;
1016 self.insert_qualified(module, name, meta, FuncBody::Ctx(func));
1017 }
1018
1019 pub(super) fn register_pure_host(
1020 &mut self,
1021 module: &str,
1022 name: String,
1023 mut meta: FuncMeta,
1024 func: PureFn,
1025 ) {
1026 meta.kind = FuncKind::HostPure;
1027 self.insert_qualified(module, name, meta, FuncBody::Pure(func));
1028 }
1029
1030 pub(super) fn register_both_host(
1031 &mut self,
1032 module: &str,
1033 name: String,
1034 mut meta: FuncMeta,
1035 func: NativeFn<P>,
1036 template: PureFn,
1037 ) {
1038 meta.kind = FuncKind::HostCtx;
1039 self.insert_qualified(
1040 module,
1041 name,
1042 meta,
1043 FuncBody::Both {
1044 pure: template,
1045 ctx: func,
1046 },
1047 );
1048 }
1049
1050 #[allow(clippy::too_many_arguments)]
1055 pub(super) fn define_script(
1056 &mut self,
1057 name: &str,
1058 params: &[(String, TypeTag, bool)],
1059 return_type: TypeTag,
1060 return_spelling: &str,
1061 is_async: bool,
1062 body: &[Step],
1063 module: Option<&str>,
1064 ) -> Result<()> {
1065 let qualified = qualify(SCRIPT_MODULE_NAME, name);
1066 let shadowable = matches!(
1067 self.entries.get(&qualified).map(|entry| &entry.body),
1068 Some(FuncBody::Script(_))
1069 );
1070 let reserved = self.entries.iter().any(|(key, entry)| {
1075 split_qualified(key).is_some_and(|(_, base)| base == name)
1076 && !matches!(entry.body, FuncBody::Script(_))
1077 });
1078 if reserved && !shadowable {
1079 anyhow::bail!("cannot shadow reserved function `{name}`");
1080 }
1081 if self
1082 .scopes
1083 .last()
1084 .is_some_and(|frame| frame.defined.contains(&qualified))
1085 {
1086 anyhow::bail!("duplicate function `{name}` in same scope");
1087 }
1088 check_script_param_tags(name, params)?;
1089 let old = self.entries.insert(
1090 qualified.clone(),
1091 FuncEntry {
1092 meta: FuncMeta {
1093 name: qualified.clone(),
1094 module: SCRIPT_MODULE_NAME.to_string(),
1095 kind: FuncKind::Script,
1096 params: Some(
1097 params
1098 .iter()
1099 .map(|(pname, param_type, optional)| {
1100 Ok(FuncParam {
1101 name: pname.clone(),
1102 param_type: Some(param_type.clone()),
1103 allowed: None,
1104 docs: "",
1107 options: None,
1108 optional: *optional,
1109 })
1110 })
1111 .collect::<Result<_>>()?,
1112 ),
1113 returns: Some(return_type.clone()),
1114 rpn: false,
1115 summary: "DSL-defined function.",
1116 docs: "Defined via FUNC in script.",
1117 examples: &[],
1118 },
1119 body: FuncBody::Script(FuncDefData {
1120 params: params.to_vec(),
1121 return_type,
1122 return_spelling: return_spelling.to_string(),
1123 is_async,
1124 body: body.to_vec(),
1125 module: module.map(|m| m.to_string()),
1126 }),
1127 },
1128 );
1129 if let Some(frame) = self.scopes.last_mut() {
1130 frame.defined.insert(qualified.clone());
1131 if let Some(old) = old {
1132 frame.shadowed.push((qualified, old));
1133 }
1134 }
1135 Ok(())
1136 }
1137
1138 #[allow(clippy::too_many_arguments)]
1144 pub(super) fn define_file_func(
1145 &mut self,
1146 name: &str,
1147 params: &[(String, TypeTag, bool)],
1148 return_type: TypeTag,
1149 return_spelling: &str,
1150 is_async: bool,
1151 body: &[Step],
1152 defining: &str,
1153 ) -> Result<()> {
1154 let qualified = file_func_key(defining, name);
1158 let shadowable = matches!(
1159 self.entries.get(&qualified).map(|entry| &entry.body),
1160 Some(FuncBody::Script(_))
1161 );
1162 let reserved = self.entries.iter().any(|(key, entry)| {
1166 split_qualified(key).is_some_and(|(_, base)| base == name)
1167 && !matches!(entry.body, FuncBody::Script(_))
1168 });
1169 if reserved && !shadowable {
1170 anyhow::bail!("cannot shadow reserved function `{name}`");
1171 }
1172 let frame_idx = 0;
1176 if self
1177 .scopes
1178 .get(frame_idx)
1179 .is_some_and(|frame| frame.defined.contains(&qualified))
1180 {
1181 anyhow::bail!("duplicate function `{name}` in same scope");
1182 }
1183 check_script_param_tags(name, params)?;
1184 let old = self.entries.insert(
1185 qualified.clone(),
1186 FuncEntry {
1187 meta: FuncMeta {
1188 name: qualified.clone(),
1189 module: defining.to_string(),
1190 kind: FuncKind::Script,
1191 params: Some(
1192 params
1193 .iter()
1194 .map(|(pname, param_type, optional)| {
1195 Ok(FuncParam {
1196 name: pname.clone(),
1197 param_type: Some(param_type.clone()),
1198 allowed: None,
1199 docs: "",
1200 options: None,
1201 optional: *optional,
1202 })
1203 })
1204 .collect::<Result<_>>()?,
1205 ),
1206 returns: Some(return_type.clone()),
1207 rpn: false,
1208 summary: "DSL-defined function.",
1209 docs: "Defined via FUNC in an imported script.",
1210 examples: &[],
1211 },
1212 body: FuncBody::Script(FuncDefData {
1213 params: params.to_vec(),
1214 return_type,
1215 return_spelling: return_spelling.to_string(),
1216 is_async,
1217 body: body.to_vec(),
1218 module: Some(defining.to_string()),
1219 }),
1220 },
1221 );
1222 if let Some(frame) = self.scopes.get_mut(frame_idx) {
1223 frame.defined.insert(qualified.clone());
1224 if let Some(old) = old {
1225 frame.shadowed.push((qualified, old));
1226 }
1227 }
1228 Ok(())
1229 }
1230
1231 pub(super) fn push_scope(&mut self) {
1234 self.scopes.push(ScopeFrame {
1235 defined: HashSet::new(),
1236 shadowed: Vec::new(),
1237 });
1238 }
1239
1240 pub(super) fn pop_scope(&mut self) {
1243 let Some(frame) = self.scopes.pop() else {
1244 return;
1245 };
1246 for name in frame.defined {
1247 self.entries.remove(&name);
1248 }
1249 for (name, old) in frame.shadowed {
1250 self.entries.insert(name, old);
1251 }
1252 }
1253
1254 pub(super) fn contains_script(&self, name: &str) -> bool {
1259 matches!(
1260 self.entries.get(name).map(|entry| &entry.body),
1261 Some(FuncBody::Script(_))
1262 )
1263 }
1264
1265 pub(super) fn resolve_file_call_key(
1268 &self,
1269 unit_targets: &AliasTargets,
1270 name: &str,
1271 ) -> Result<Option<String>> {
1272 match classify_alias_call(unit_targets, name, &|key| self.entries.contains_key(key)) {
1273 AliasResolution::Global | AliasResolution::Unknown | AliasResolution::Any { .. } => {
1274 Ok(None)
1275 }
1276 AliasResolution::Canonical(key) => Ok(Some(key)),
1277 AliasResolution::Ambiguous { alias, base, files } => Err(anyhow::anyhow!(
1278 "{}",
1279 ambiguous_alias_message(&alias, &base, &files)
1280 )),
1281 }
1282 }
1283
1284 fn clone_pure_fn(&self, name: &str) -> Option<PureFn> {
1288 match self.entries.get(name)?.body {
1289 FuncBody::Pure(ref func) => Some(Arc::clone(func)),
1290 FuncBody::Both { ref pure, .. } => Some(Arc::clone(pure)),
1291 _ => None,
1292 }
1293 }
1294
1295 pub(super) fn pure_shared(&self) -> Arc<PureTable> {
1299 Arc::clone(&self.pure_shared)
1300 }
1301
1302 pub(super) fn all_metas(&self) -> Vec<FuncMeta> {
1305 self.entries_metas()
1306 }
1307
1308 fn clone_ctx_fn(&self, name: &str) -> Option<NativeFn<P>> {
1313 match self.entries.get(name)?.body {
1314 FuncBody::Ctx(ref func) => Some(Arc::clone(func)),
1315 FuncBody::Both { ref ctx, .. } => Some(Arc::clone(ctx)),
1316 _ => None,
1317 }
1318 }
1319
1320 fn meta(&self, name: &str) -> Option<FuncMeta> {
1321 self.entries.get(name).map(|entry| entry.meta.clone())
1322 }
1323
1324 fn native_metas(&self) -> Vec<FuncMeta> {
1325 let mut out: Vec<FuncMeta> = Vec::new();
1326 for entry in self.entries.values() {
1327 if !matches!(entry.body, FuncBody::Script(_)) {
1328 out.push(entry.meta.clone());
1329 }
1330 }
1331 out.sort_by(|a, b| a.name.cmp(&b.name));
1332 out
1333 }
1334
1335 pub(super) fn pure_metas(&self) -> Vec<FuncMeta> {
1340 let mut out: Vec<FuncMeta> = Vec::new();
1341 for entry in self.entries.values() {
1342 if matches!(entry.body, FuncBody::Pure(_) | FuncBody::Both { .. }) {
1343 out.push(entry.meta.clone());
1344 }
1345 }
1346 out.sort_by(|a, b| a.name.cmp(&b.name));
1347 out
1348 }
1349
1350 fn entries_metas(&self) -> Vec<FuncMeta> {
1353 let mut out: Vec<FuncMeta> = self
1354 .entries
1355 .values()
1356 .map(|entry| entry.meta.clone())
1357 .collect();
1358 out.sort_by(|a, b| a.name.cmp(&b.name));
1359 out
1360 }
1361
1362 pub fn set_script_docs(&mut self, docs: &HashMap<String, (String, String)>) {
1365 for (base, pair) in docs {
1366 self.script_docs
1367 .insert(qualify(SCRIPT_MODULE_NAME, base), pair.clone());
1368 }
1369 }
1370
1371 pub fn script_doc_for(&self, qualified: &str) -> Option<(String, String)> {
1373 self.script_docs.get(qualified).cloned()
1374 }
1375
1376 pub fn exported_metas(
1381 &self,
1382 func_exports: &[String],
1383 unit_targets: &AliasTargets,
1384 ) -> anyhow::Result<Vec<FuncMeta>> {
1385 let mut out = Vec::with_capacity(func_exports.len());
1386 for name in func_exports {
1387 let qualified = match split_qualified(name) {
1391 None => qualify(SCRIPT_MODULE_NAME, name),
1392 Some(_) => name.clone(),
1393 };
1394 let lookup = self
1395 .resolve_file_call_key(unit_targets, &qualified)?
1396 .unwrap_or_else(|| qualified.clone());
1397 if let Some(entry) = self.entries.get(&lookup) {
1398 let mut meta = entry.meta.clone();
1399 if lookup != qualified {
1400 meta.name = name.clone();
1401 }
1402 out.push(meta);
1403 continue;
1404 }
1405 anyhow::bail!(
1406 "EXPORT `{name}` matches no defined script function or known host function"
1407 );
1408 }
1409 Ok(out)
1410 }
1411}
1412
1413impl<P: ProcessManager> Clone for FunctionRegistry<P> {
1414 fn clone(&self) -> Self {
1415 Self {
1416 entries: self.entries.clone(),
1417 scopes: self.scopes.clone(),
1418 pure_shared: Arc::clone(&self.pure_shared),
1419 script_docs: self.script_docs.clone(),
1420 }
1421 }
1422}
1423
1424pub fn builtin_function_names() -> HashSet<String> {
1431 let mut names = FunctionRegistry::<DefaultProcessManager>::with_builtins().keys();
1432 names.insert(KEYWORD_INSPECT.to_string());
1433 names
1434}
1435
1436pub fn builtin_function_metas() -> Vec<FuncMeta> {
1440 FunctionRegistry::<DefaultProcessManager>::with_builtins().native_metas()
1441}
1442
1443pub fn std_module_table() -> oxdock_parser::ModuleTable {
1448 let func_names: HashSet<String> = builtin_function_metas()
1450 .into_iter()
1451 .map(|meta| base_name(&meta.name).to_string())
1452 .collect();
1453 oxdock_parser::ModuleTable {
1454 modules: HashMap::from([(
1455 STD_MODULE_NAME.to_string(),
1456 Some(oxdock_parser::ModuleFuncs { func_names }),
1457 )]),
1458 }
1459}
1460
1461#[oxdock_func(pure, returns = TypeTag::Int)]
1474#[example(
1475 name = "convert",
1476 code = r###"
1477 IMPORT [STD]
1478 LET $n: INT = INT("42")
1479 ASSERT_EQ $n 42
1480 LET $flag: INT = INT(true)
1481 ASSERT_EQ $flag 1
1482 "###
1483)]
1484fn int(
1485 #[union(Int, Float, String, Bool)]
1487 val: Value,
1488) -> Result<Value> {
1489 super::args::int_from_value(val)
1490}
1491
1492#[oxdock_func(pure, returns = TypeTag::Float)]
1497#[example(
1498 name = "convert",
1499 code = r###"
1500 IMPORT [STD]
1501 LET $f: FLOAT = FLOAT("1.5")
1502 ASSERT_EQ $f 1.5
1503 LET $whole: FLOAT = FLOAT(2)
1504 ASSERT_EQ $whole 2.0
1505 "###
1506)]
1507fn float(
1508 #[union(Float, Int, String)]
1510 val: Value,
1511) -> Result<Value> {
1512 super::args::float_from_value(val)
1513}
1514
1515#[oxdock_func(pure, returns = TypeTag::String)]
1520#[example(
1521 name = "format and round-trip",
1522 code = r###"
1523 # Byte counts render in the largest exact unit.
1524 IMPORT [STD]
1525 LET $pretty: STRING = FORMAT_BYTE_COUNT(1_048_576)
1526 ASSERT_EQ $pretty "1MiB"
1527
1528 # The pair round-trips through the parser.
1529 LET $back: INT = PARSE_BYTE_COUNT($pretty)
1530 ASSERT_EQ $back 1_048_576
1531 "###
1532)]
1533fn format_byte_count(
1534 bytes: i64,
1536) -> Result<Value> {
1537 if bytes < 0 {
1538 return Err(anyhow::anyhow!(
1539 "FORMAT_BYTE_COUNT needs a non-negative byte count, got {bytes}"
1540 ));
1541 }
1542 Ok(Value::string(oxdock_parser::command::format_byte_count(
1543 bytes as u64,
1544 )))
1545}
1546
1547#[oxdock_func(pure, returns = TypeTag::Int)]
1582#[example(
1583 name = "parse",
1584 code = r###"
1585 IMPORT [STD]
1586 LET $n: INT = PARSE_BYTE_COUNT("10KB")
1587 ASSERT_EQ $n 10_000
1588 LET $identity: INT = PARSE_BYTE_COUNT(512)
1589 ASSERT_EQ $identity 512
1590 "###
1591)]
1592fn parse_byte_count(
1593 #[union(Int, Float, String)]
1595 text: Value,
1596) -> Result<Value> {
1597 if let Some(n) = text.as_i64() {
1598 if n < 0 {
1599 return Err(anyhow::anyhow!(
1600 "PARSE_BYTE_COUNT needs a non-negative byte count, got {n}"
1601 ));
1602 }
1603 return Ok(Value::int(n));
1604 }
1605 if let Some(f) = text.as_f64() {
1606 if f.is_finite() && f.fract() == 0.0 && f >= 0.0 && f <= i64::MAX as f64 {
1607 return Ok(Value::int(f as i64));
1608 }
1609 return Err(anyhow::anyhow!(
1610 "PARSE_BYTE_COUNT needs an integral byte count, got {f:?}"
1611 ));
1612 }
1613 let Some(s) = text.as_str() else {
1614 return Err(anyhow::anyhow!(
1615 "PARSE_BYTE_COUNT needs a token or number, found {text:?}"
1616 ));
1617 };
1618 let n = oxdock_parser::command::parse_byte_count(s)?;
1619 let n = i64::try_from(n)
1620 .map_err(|_| anyhow::anyhow!("PARSE_BYTE_COUNT out of INT range: {s:?}"))?;
1621 Ok(Value::int(n))
1622}
1623
1624#[oxdock_func(pure, returns = TypeTag::String)]
1629#[example(
1630 name = "format and round-trip",
1631 code = r###"
1632 # Durations render in the largest exact unit.
1633 IMPORT [STD]
1634 LET $pretty: STRING = FORMAT_DURATION(90_000)
1635 ASSERT_EQ $pretty "90s"
1636
1637 # The pair round-trips through the parser.
1638 LET $back: INT = PARSE_DURATION($pretty)
1639 ASSERT_EQ $back 90_000
1640 "###
1641)]
1642fn format_duration(
1643 millis: i64,
1645) -> Result<Value> {
1646 if millis < 0 {
1647 return Err(anyhow::anyhow!(
1648 "FORMAT_DURATION needs non-negative milliseconds, got {millis}"
1649 ));
1650 }
1651 Ok(Value::string(oxdock_parser::command::format_duration(
1652 &std::time::Duration::from_millis(millis as u64),
1653 )))
1654}
1655
1656#[oxdock_func(pure, returns = TypeTag::Int)]
1662#[example(
1663 name = "parse",
1664 code = r###"
1665 # A bare number means seconds, like TIMEOUT.
1666 IMPORT [STD]
1667 LET $ms: INT = PARSE_DURATION("2m")
1668 ASSERT_EQ $ms 120_000
1669
1670 # Milliseconds stay exact.
1671 LET $exact: INT = PARSE_DURATION("1500ms")
1672 ASSERT_EQ $exact 1_500
1673
1674 # One optional space separates number from unit.
1675 LET $spaced: INT = PARSE_DURATION("1 h")
1676 ASSERT_EQ $spaced 3_600_000
1677 "###
1678)]
1679fn parse_duration(
1680 text: String,
1682) -> Result<Value> {
1683 let duration = oxdock_parser::command::parse_duration(&text)?;
1684 let millis = i64::try_from(duration.as_millis())
1685 .map_err(|_| anyhow::anyhow!("PARSE_DURATION out of INT range: {text:?}"))?;
1686 Ok(Value::int(millis))
1687}
1688
1689#[oxdock_func(rpn, returns = TypeTag::ListOf(std::sync::Arc::new(TypeTag::String)))]
1694#[example(
1695 name = "match",
1696 code = r###"
1697 IMPORT [STD]
1698 WRITE "notes-a.md" "a"
1699 WRITE "notes-b.md" "b"
1700 WRITE "other.txt" "c"
1701 LET $found: LIST<STRING> = GLOB("notes-*.md")
1702 ASSERT_EQ $found.0 "notes-a.md"
1703 ASSERT_EQ $found.1 "notes-b.md"
1704 "###
1705)]
1706fn glob<P: ProcessManager>(
1707 cx: &mut StepCtx<P>,
1708 #[union(String, Path)]
1710 pattern: Value,
1711) -> Result<Value> {
1712 let text = super::args::string_or_path_text(&pattern)?;
1713 super::args::glob_from_value(&[Value::string(text)], cx)
1714}
1715
1716#[oxdock_func(rpn, returns = TypeTag::MapOf(std::sync::Arc::new(TypeTag::Any)))]
1721#[example(
1722 name = "load",
1723 code = r###"
1724 IMPORT [STD]
1725 WRITE "cfg.toml" "title = \"demo\""
1726 LET $cfg: MAP<ANY> = LOAD_TOML("cfg.toml")
1727 ASSERT_EQ $cfg.title "demo"
1728 "###
1729)]
1730fn load_toml<P: ProcessManager>(
1731 cx: &mut StepCtx<P>,
1732 #[union(String, Path)]
1734 path: Value,
1735) -> Result<Value> {
1736 let text = super::args::string_or_path_text(&path)?;
1737 super::args::load_toml_from_value(&[Value::string(text)], cx)
1738}
1739
1740#[oxdock_func(rpn, returns = TypeTag::Any)]
1748#[example(
1749 name = "load",
1750 code = r###"
1751 IMPORT [STD]
1752 WRITE "data.json" "{\"a\": 1}"
1753 LET $doc: MAP<ANY> = LOAD_JSON("data.json")
1754 ASSERT_EQ $doc.a 1
1755 "###
1756)]
1757fn load_json<P: ProcessManager>(
1758 cx: &mut StepCtx<P>,
1759 #[union(String, Path)]
1761 path: Value,
1762) -> Result<Value> {
1763 let text = super::args::string_or_path_text(&path)?;
1764 super::args::load_json_from_value(&[Value::string(text)], cx)
1765}
1766
1767#[oxdock_func(rpn, returns = TypeTag::String)]
1777#[example(
1778 name = "hash",
1779 code = r###"
1780 IMPORT [STD]
1781 WRITE payload.txt hello
1782 LET $digest: STRING = HASH_SHA256("payload.txt")
1783 ASSERT_EQ $digest "2cf24dba5fb0a30e26e83b2ac5b9e29e1b161e5c1fa7425e73043362938b9824"
1784 "###
1785)]
1786fn hash_sha256<P: ProcessManager>(
1787 cx: &mut StepCtx<P>,
1788 #[union(String, Path)]
1790 path: Value,
1791) -> Result<Value> {
1792 use sha2::Digest;
1793
1794 let text = super::args::string_or_path_text(&path)?;
1795 let target = cx.state.fs.resolve_read(&cx.state.cwd, &text)?;
1796 let mut hasher = sha2::Sha256::new();
1797 super::fs_ops::hash_path(cx.state.fs.as_ref(), &target, "", &mut hasher)?;
1798 let digest = hasher.finalize();
1799 let bytes: &[u8] = digest.as_ref();
1800 Ok(Value::string(oxdock_utils::hex_encode(bytes)))
1801}
1802
1803#[oxdock_func(rpn, returns = TypeTag::String)]
1814#[example(
1815 name = "cwd",
1816 code = r###"
1817 IMPORT [STD]
1818 WORKDIR sub
1819 LET $c: STRING = CWD()
1820 ASSERT_CONTAINS $c "sub"
1821 "###
1822)]
1823fn cwd<P: ProcessManager>(cx: &mut StepCtx<P>) -> Result<Value> {
1824 if cx.state.fs.is_snapshot_pending() {
1825 return Ok(Value::string(super::SNAPSHOT_PENDING_DISPLAY.to_string()));
1826 }
1827 let concrete = cx.state.fs.concretize_cwd(&cx.state.cwd);
1828 let real = super::fs_ops::canonical_cwd(cx.state.fs.as_ref(), &concrete)?;
1829 Ok(Value::string(real))
1830}
1831
1832#[oxdock_func(pure, returns = TypeTag::MapOf(std::sync::Arc::new(TypeTag::Any)))]
1838#[example(
1839 name = "parse",
1840 code = r###"
1841 IMPORT [STD]
1842 LET $doc: MAP<ANY> = PARSE_TOML("title = \"demo\"")
1843 ASSERT_EQ $doc.title "demo"
1844 "###
1845)]
1846fn parse_toml(
1847 text: String,
1849) -> Result<Value> {
1850 super::args::parse_toml_from_value(Value::string(text))
1851}
1852
1853#[oxdock_func(pure, returns = TypeTag::Any)]
1862#[example(
1863 name = "parse",
1864 code = r###"
1865 # Parse in-memory JSON text with the same conversion as file loading.
1866 IMPORT [STD]
1867 LET $body: STRING = "{\"a\": 1}"
1868 LET $doc: ANY = PARSE_JSON($body)
1869 ASSERT_EQ $doc.a 1
1870
1871 # Top-level arrays parse to LIST, which is why the return is ANY.
1872 LET $items: LIST<ANY> = PARSE_JSON("[1, 2]")
1873 ASSERT_EQ $items.0 1
1874 ASSERT_EQ $items.1 2
1875 "###
1876)]
1877fn parse_json(
1878 text: String,
1880) -> Result<Value> {
1881 super::args::parse_json_from_value(Value::string(text))
1882}
1883
1884#[oxdock_func(returns = TypeTag::String)]
1890#[example(
1891 name = "describe",
1892 code = r###"
1893 IMPORT [STD]
1894 WRITE "entry.txt" "words"
1895 LET $kind: STRING = PATH_TYPE("entry.txt")
1896 ASSERT_EQ $kind "file"
1897 LET $missing: STRING = PATH_TYPE("no-such-entry.txt")
1898 ASSERT_EQ $missing "absent"
1899 "###
1900)]
1901fn path_type<P: ProcessManager>(
1902 cx: &mut StepCtx<P>,
1903 #[union(String, Path)]
1905 path: Value,
1906) -> Result<Value> {
1907 let text = super::args::string_or_path_text(&path)?;
1908 super::args::path_type_from_value(&[Value::string(text)], cx)
1909}
1910
1911#[oxdock_func(returns = TypeTag::Bool)]
1920#[example(
1921 name = "probe",
1922 code = r###"
1923 # An absent nested path is writable when its ancestor is.
1924 IMPORT [STD]
1925 LET $fresh: BOOL = PATH_WRITABLE("probe-check/nested/file.txt")
1926 ASSERT_EQ $fresh true
1927
1928 # The empty string never aliases the working directory.
1929 LET $empty: BOOL = PATH_WRITABLE("")
1930 ASSERT_EQ $empty false
1931 "###
1932)]
1933fn path_writable<P: ProcessManager>(
1934 cx: &mut StepCtx<P>,
1935 #[union(String, Path)]
1937 path: Value,
1938) -> Result<Value> {
1939 let text = super::args::string_or_path_text(&path)?;
1940 super::args::path_writable_from_value(&[Value::string(text)], cx)
1941}
1942
1943#[oxdock_func(returns = TypeTag::Bool)]
1956#[example(
1957 name = "probe",
1958 code = r###"
1959 # Missing tools read false instead of failing the run.
1960 IMPORT [STD]
1961 LET $missing: BOOL = IS_EXEC("no-such-tool-xyz")
1962 ASSERT_EQ $missing false
1963
1964 # Plain files are not executable on any platform.
1965 WRITE tool.txt payload
1966 LET $plain: BOOL = IS_EXEC("tool.txt")
1967 ASSERT_EQ $plain false
1968 "###
1969)]
1970fn is_exec<P: ProcessManager>(
1971 cx: &mut StepCtx<P>,
1972 #[union(String, Path)]
1974 name: Value,
1975) -> Result<Value> {
1976 let text = super::args::string_or_path_text(&name)?;
1977 super::args::is_exec_from_value(&[Value::string(text)], cx)
1978}
1979
1980#[oxdock_func(pure, returns = TypeTag::Bool)]
1986#[example(
1987 name = "probe",
1988 code = r###"
1989 IMPORT [STD]
1990 LET $m: MAP<ANY> = PARSE_JSON("{\"a\": 1}")
1991 LET $hit: BOOL = HAS_KEY($m, "a")
1992 ASSERT_EQ $hit true
1993 LET $miss: BOOL = HAS_KEY($m, "b")
1994 ASSERT_EQ $miss false
1995 "###
1996)]
1997fn has_key(
1998 map: BTreeMap<String, Value>,
2000 key: String,
2002) -> Result<Value> {
2003 super::args::has_key_from_value(Value::map(map), &key)
2004}
2005
2006#[oxdock_func(pure, returns = TypeTag::MapOf(std::sync::Arc::new(TypeTag::Any)))]
2012#[example(
2013 name = "insert",
2014 code = r###"
2015 IMPORT [STD]
2016 LET $m: MAP<ANY> = MAP_SET({seed: 0}, "a", 1)
2017 ASSERT_EQ $m.a 1
2018 "###
2019)]
2020fn map_set(
2021 map: BTreeMap<String, Value>,
2023 key: String,
2025 value: Value,
2027) -> Result<Value> {
2028 super::args::map_set_from_value(Value::map(map), key, value)
2029}
2030
2031#[oxdock_func(returns = TypeTag::Float, summary = "Draw a random FLOAT uniformly from [0, 1), optionally seeded.")]
2039#[example(
2040 name = "seeded draw",
2041 code = r###"
2042 # A seed draws the same value on every run.
2043 IMPORT [STD]
2044 LET $one: FLOAT = RAND({seed: 7})
2045 LET $two: FLOAT = RAND({seed: 7})
2046 ASSERT_EQ $one $two
2047 "###
2048)]
2049#[example(
2050 name = "unseeded draw",
2051 code = r###"
2052 # Scale a unit draw into a backoff delay between 1 and 11 seconds.
2053 IMPORT [STD]
2054 LET $draw: FLOAT = RAND()
2055 LET $delay: FLOAT = 1.0 + $draw * 10.0
2056 IF $delay < 1.0 {
2057 EXIT 1
2058 }
2059 IF $delay >= 11.0 {
2060 EXIT 1
2061 }
2062 ECHO "retrying in {{ $delay }}s"
2063 "###
2064)]
2065fn rand<P: ProcessManager>(
2066 cx: &mut StepCtx<P>,
2067 #[options("seed?: INT")]
2069 #[optional]
2070 options: BTreeMap<String, Value>,
2071) -> Result<Value> {
2072 let _ = cx;
2073 let seed = options
2076 .get("seed")
2077 .map(|value| value.as_i64().expect("check_options verified INT"));
2078 super::args::rand_float_from_value(seed)
2079}
2080
2081#[oxdock_func(pure, returns = TypeTag::String)]
2087#[example(
2088 name = "encode",
2089 code = r###"
2090 # Encode text to standard base64.
2091 IMPORT [STD]
2092 LET $encoded: STRING = BASE64_ENCODE("hello")
2093 ASSERT_EQ $encoded "aGVsbG8="
2094 "###
2095)]
2096fn base64_encode(
2097 text: String,
2099) -> Result<Value> {
2100 super::args::base64_encode_from_value(Value::string(text))
2101}
2102
2103#[oxdock_func(pure, returns = TypeTag::String)]
2110#[example(
2111 name = "decode",
2112 code = r###"
2113 # Decode standard base64 back to text.
2114 IMPORT [STD]
2115 LET $decoded: STRING = BASE64_DECODE("aGVsbG8=")
2116 ASSERT_EQ $decoded "hello"
2117 "###
2118)]
2119fn base64_decode(
2120 text: String,
2122) -> Result<Value> {
2123 super::args::base64_decode_from_value(Value::string(text))
2124}
2125
2126#[oxdock_func(pure, returns = TypeTag::String)]
2133#[example(
2134 name = "encode",
2135 code = r###"
2136 IMPORT [STD]
2137 LET $json: STRING = TO_JSON({a: 1})
2138 ASSERT_EQ $json "{\"a\":1}\n"
2139 "###
2140)]
2141fn to_json(
2142 #[union(String, Int, Float, Bool, List, Map)]
2144 value: Value,
2145) -> Result<Value> {
2146 super::args::to_json_from_value(value)
2147}
2148
2149#[oxdock_func(pure, returns = TypeTag::String)]
2157#[example(
2158 name = "name the word",
2159 code = r###"
2160 IMPORT [STD]
2161 LET $word: STRING = TYPE_OF(42)
2162 ASSERT_EQ $word "INT"
2163 "###
2164)]
2165fn type_of(
2166 value: Value,
2168) -> Result<Value> {
2169 super::args::type_of_from_value(value)
2170}
2171
2172#[oxdock_func(pure, returns = TypeTag::MapOf(std::sync::Arc::new(TypeTag::Any)))]
2180#[example(
2181 name = "merge",
2182 code = r###"
2183 IMPORT [STD]
2184 LET $m: MAP<ANY> = MERGE_MAPS([{a: 1}, {b: 2}], "overwrite")
2185 ASSERT_EQ $m.a 1
2186 ASSERT_EQ $m.b 2
2187 "###
2188)]
2189fn merge_maps(
2190 maps: Vec<BTreeMap<String, Value>>,
2192 #[values("fail_on_duplicate", "overwrite")]
2194 policy: String,
2195) -> Result<Value> {
2196 super::args::merge_maps_from_value(
2197 Value::list(maps.into_iter().map(Value::map).collect()),
2198 policy,
2199 )
2200}
2201
2202#[oxdock_func(pure, returns = TypeTag::String)]
2207#[example(
2208 name = "report",
2209 code = r###"
2210 # The engine reports its own build version as a dotted string.
2211 IMPORT [STD]
2212 LET $v: STRING = VERSION()
2213 ASSERT_CONTAINS $v "."
2214 "###
2215)]
2216fn version() -> Result<Value> {
2217 Ok(Value::string(env!("CARGO_PKG_VERSION").to_string()))
2218}
2219
2220#[oxdock_func(returns = TypeTag::ListOf(std::sync::Arc::new(TypeTag::String)))]
2225#[example(
2226 name = "list",
2227 code = r###"
2228 IMPORT [STD]
2229 LET $names: LIST<STRING> = FUNCTIONS()
2230 ASSERT_CONTAINS $names "STD::INT"
2231 "###
2232)]
2233fn functions<P: ProcessManager>(cx: &mut StepCtx<P>) -> Result<Value> {
2234 let mut names: Vec<String> = cx
2235 .state
2236 .list_functions()
2237 .into_iter()
2238 .map(|meta| meta.name)
2239 .collect();
2240 names.sort();
2241 names.dedup();
2242 Ok(Value::list(names.into_iter().map(Value::string).collect()))
2243}
2244
2245#[oxdock_func(
2260 returns = TypeTag::Record(std::sync::Arc::from([Field {
2261 name: "name".to_string(),
2262 ty: TypeTag::String,
2263 docs: "Qualified function name.",
2264 optional: false,
2265 }, Field {
2266 name: "module".to_string(),
2267 ty: TypeTag::String,
2268 docs: "Owning module.",
2269 optional: false,
2270 }, Field {
2271 name: "kind".to_string(),
2272 ty: TypeTag::String,
2273 docs: "Origin label (`host` or `script`).",
2274 optional: false,
2275 }, Field {
2276 name: "params".to_string(),
2277 ty: TypeTag::ListOf(std::sync::Arc::new(TypeTag::MapOf(std::sync::Arc::new(
2278 TypeTag::Any,
2279 )))),
2280 docs: "Parameter entries (empty for parameterless functions).",
2281 optional: false,
2282 }, Field {
2283 name: "returns".to_string(),
2284 ty: TypeTag::String,
2285 docs: "Structural return shape (empty when untagged).",
2286 optional: false,
2287 }, Field {
2288 name: "rpn".to_string(),
2289 ty: TypeTag::Bool,
2290 docs: "True when callable in RPN position.",
2291 optional: false,
2292 }, Field {
2293 name: "summary".to_string(),
2294 ty: TypeTag::String,
2295 docs: "One-line description.",
2296 optional: false,
2297 }]))
2298 summary = "Describe one function by qualified name."
2299)]
2300#[example(
2301 name = "describe",
2302 code = r###"
2303 IMPORT [STD]
2304 LET $info: MAP<ANY> = DESCRIBE("STD::INT")
2305 ASSERT_EQ $info.name "STD::INT"
2306 ASSERT_EQ $info.returns "INT"
2307 "###
2308)]
2309fn describe<P: ProcessManager>(
2310 cx: &mut StepCtx<P>,
2311 name: String,
2313) -> Result<Value> {
2314 if split_qualified(&name).is_none() && name != KEYWORD_INSPECT {
2315 anyhow::bail!(
2316 "unknown function `{name}`: DESCRIBE requires a qualified name (e.g. `STD::{name}`)"
2317 );
2318 }
2319 cx.state
2320 .describe_function(&name)
2321 .ok_or_else(|| anyhow::anyhow!("unknown function {name}"))
2322}
2323
2324#[oxdock_func(returns = TypeTag::ListOf(std::sync::Arc::new(TypeTag::String)))]
2330#[example(
2331 name = "list",
2332 code = r###"
2333 IMPORT [STD]
2334 LET $names: LIST<STRING> = TYPES()
2335 ASSERT_CONTAINS $names "STRING"
2336 "###
2337)]
2338fn types<P: ProcessManager>(cx: &mut StepCtx<P>) -> Result<Value> {
2339 Ok(Value::list(
2340 cx.state
2341 .type_names()
2342 .into_iter()
2343 .map(Value::string)
2344 .collect(),
2345 ))
2346}
2347
2348#[oxdock_func(returns = TypeTag::Record(std::sync::Arc::from([Field {
2354 name: "name".to_string(),
2355 ty: TypeTag::String,
2356 docs: "Queried type name.",
2357 optional: false,
2358}, Field {
2359 name: "summary".to_string(),
2360 ty: TypeTag::String,
2361 docs: "One-line description.",
2362 optional: false,
2363}, Field {
2364 name: "docs".to_string(),
2365 ty: TypeTag::String,
2366 docs: "Full documentation text.",
2367 optional: false,
2368}])))]
2369#[example(
2370 name = "describe",
2371 code = r###"
2372 IMPORT [STD]
2373 LET $info: MAP<ANY> = TYPE_DESCRIBE("STRING")
2374 ASSERT_EQ $info.name "STRING"
2375 "###
2376)]
2377fn type_describe<P: ProcessManager>(
2378 cx: &mut StepCtx<P>,
2379 name: String,
2381) -> Result<Value> {
2382 if let Some(descriptor) = cx.state.describe_type(&name) {
2383 let mut map = BTreeMap::new();
2384 map.insert(
2385 "name".to_string(),
2386 Value::string(descriptor.name.to_string()),
2387 );
2388 map.insert(
2389 "summary".to_string(),
2390 Value::string(descriptor.summary.to_string()),
2391 );
2392 map.insert(
2393 "docs".to_string(),
2394 Value::string(descriptor.docs.to_string()),
2395 );
2396 return Ok(Value::map(map));
2397 }
2398 if let Some(target) = cx.state.alias_target(&name) {
2401 let mut map = BTreeMap::new();
2402 map.insert("name".to_string(), Value::string(name.clone()));
2403 map.insert(
2404 "summary".to_string(),
2405 Value::string(format!("Script type alias for {target}.")),
2406 );
2407 map.insert(
2408 "docs".to_string(),
2409 Value::string(format!(
2410 "Declared with TYPE {name} = {target}. The alias expands structurally at every declaration."
2411 )),
2412 );
2413 return Ok(Value::map(map));
2414 }
2415 Err(anyhow::anyhow!("unknown type {name}"))
2416}
2417
2418#[oxdock_func(returns = TypeTag::String)]
2432#[example(
2433 name = "self",
2434 code = r###"
2435 # The running interpreter resolves to a non-empty path.
2436 IMPORT [STD]
2437 LET $exe: STRING = INTERPRETER()
2438 LET $nonempty: BOOL = $exe != ""
2439 ASSERT_EQ $nonempty true
2440 "###
2441)]
2442#[example(
2443 name = "dynamic assembly",
2444 code = r###"
2445 # Assemble the child script dynamically: the parent interpolates
2446 # its own bindings into the pipe, then runs the interpreter on it.
2447 # Unescaped {{ }} bakes in at render time; \{{ }} stays literal
2448 # so the child expands it with its own bindings.
2449 # The pipe delivers EOF when the producer step ends, so the child
2450 # reads exactly one script.
2451 IMPORT [STD]
2452 LET $exe: STRING = INTERPRETER()
2453 LET $who: STRING = "Ada"
2454 LET $child: PIPE
2455 WITH_IO [stdout=$child] ECHO """
2456 ECHO "hello {{ $who }}!"
2457 LET $who: STRING = "Grace"
2458 ECHO "child sees \{{ $who }}!"
2459 """
2460 LET $out: STRING = WITH_IO [stdin=$child] RUN [$exe]
2461 ASSERT_CONTAINS $out "hello Ada!"
2462 ASSERT_CONTAINS $out "child sees Grace!"
2463 "###
2464)]
2465fn interpreter<P: ProcessManager>(cx: &mut StepCtx<P>) -> Result<Value> {
2466 if let Some(staged) = cx.state.io.interpreter_override() {
2467 return Ok(Value::string(staged));
2468 }
2469 Ok(Value::string(oxdock_process::interpreter_exe()?))
2470}
2471
2472#[oxdock_func(returns = TypeTag::Bool)]
2480#[example(
2481 name = "main",
2482 code = r###"
2483 # Entry top level runs as main.
2484 IMPORT [STD]
2485 LET $m: BOOL = IS_MAIN()
2486 ASSERT_EQ $m true
2487 "###
2488)]
2489#[example(
2490 name = "library doubles as demo",
2491 fence_meta = "roots:unified",
2492 code = r###"
2493 # A library doubles as a runnable demo: guard the demo with
2494 # IF IS_MAIN() so importing it stays side effect free. The
2495 # parent writes both files, then runs each in a fresh
2496 # interpreter: direct execution prints the demo, importing
2497 # it does not. Unified roots: the child inherits one
2498 # workspace, so parent and child see the same files. The
2499 # exact stdout match proves the demo line stays out of the
2500 # importing run.
2501 IMPORT [STD]
2502
2503 # The library under test: demo guarded by IS_MAIN.
2504 WRITE lib.oxfile """
2505 IMPORT [STD]
2506 FUNC GREET($x: STRING): STRING { RETURN "hi \{{ $x }}" }
2507 EXPORT GREET
2508 IF IS_MAIN() {
2509 ECHO "demo: hi Ada"
2510 }
2511 """
2512
2513 # The importer: calls the library, prints only its own line.
2514 WRITE main.oxfile """
2515 IMPORT ["lib.oxfile" AS LIB]
2516 LET $g: STRING = LIB::GREET("Bo")
2517 ECHO "imported: \{{ $g }}"
2518 """
2519
2520 # Direct run executes the demo.
2521 LET $exe: STRING = INTERPRETER()
2522 LET $direct: STRING = RUN [$exe, "lib.oxfile"]
2523 ASSERT_CONTAINS $direct "demo: hi Ada"
2524
2525 # Importing run stays silent apart from its own line.
2526 LET $via: STRING = RUN [$exe, "main.oxfile"]
2527 ASSERT_EQ $via "imported: hi Bo\n"
2528 "###
2529)]
2530fn is_main<P: ProcessManager>(cx: &mut StepCtx<P>) -> Result<Value> {
2531 let main = match cx.state.module_stack.last() {
2532 None | Some(None) => true,
2533 Some(Some(_)) => false,
2534 };
2535 Ok(Value::bool(main))
2536}
2537
2538#[oxdock_func(returns = TypeTag::Bool)]
2552#[example(
2553 name = "null stdin",
2554 code = r###"
2555 # A null stdin is never a terminal, in every harness.
2556 IMPORT [STD]
2557 LET $term: BOOL = IS_TERMINAL("stdin")
2558 ASSERT_EQ $term false
2559 "###
2560)]
2561fn is_terminal<P: ProcessManager>(
2562 cx: &mut StepCtx<P>,
2563 #[values("stdin", "stdout", "stderr")]
2565 stream_name: String,
2566) -> Result<Value> {
2567 use std::io::IsTerminal;
2568 let terminal = match stream_name.as_str() {
2569 "stdin" => {
2570 if cx.stdin_pipe.is_some() {
2575 false
2576 } else {
2577 match &cx.stdin {
2578 CommandStdin::Null => false,
2579 #[cfg(not(miri))]
2580 CommandStdin::OsPipe(_) => false,
2581 CommandStdin::Stream(_) => false,
2582 CommandStdin::Inherit => std::io::stdin().is_terminal(),
2583 }
2584 }
2585 }
2586 "stdout" => {
2587 if cx.out_pipe.is_some() {
2588 false
2590 } else if cx.state.io.stdout().is_some() {
2591 false
2594 } else {
2595 match &cx.out {
2596 None => std::io::stdout().is_terminal(),
2598 #[cfg(not(miri))]
2600 Some(StreamHandle::Os(_)) => false,
2601 Some(StreamHandle::Stream(_)) => std::io::stdout().is_terminal(),
2611 }
2612 }
2613 }
2614 "stderr" => {
2615 if cx.state.io.stderr().is_some() {
2616 false
2618 } else {
2619 match &cx.err {
2620 None => std::io::stderr().is_terminal(),
2622 #[cfg(not(miri))]
2624 Some(StreamHandle::Os(_)) => false,
2625 Some(StreamHandle::Stream(_)) => false,
2628 }
2629 }
2630 }
2631 _ => anyhow::bail!(
2632 "IS_TERMINAL expects \"stdin\", \"stdout\", or \"stderr\", got {stream_name:?}"
2637 ),
2638 };
2639 Ok(Value::bool(terminal))
2640}
2641
2642#[oxdock_func(returns = TypeTag::Semaphore)]
2650#[example(
2651 name = "mint",
2652 code = r###"
2653 # Mint a semaphore admitting at most two holders.
2654 IMPORT [STD]
2655 LET $sem: SEMAPHORE = SEMAPHORE_NEW(2)
2656
2657 # A fresh semaphore reports its full cap as available.
2658 LET $free: INT = SEMAPHORE_AVAILABLE($sem)
2659 ASSERT_EQ $free 2
2660 "###
2661)]
2662fn semaphore_new<P: ProcessManager>(
2663 cx: &mut StepCtx<P>,
2664 max: i64,
2666) -> Result<Value> {
2667 let _ = cx;
2668 if max <= 0 {
2669 return Err(anyhow::anyhow!(
2670 "SEMAPHORE_NEW() requires a positive max, got {max}"
2671 ));
2672 }
2673 Ok(Value::semaphore(max as usize))
2674}
2675
2676#[oxdock_func(returns = TypeTag::Record(std::sync::Arc::from([Field {
2685 name: "held".to_string(),
2686 ty: TypeTag::Bool,
2687 docs: "`true` with the permit under `permit`, `false` with no `permit` key.",
2688 optional: false,
2689}, Field {
2690 name: "permit".to_string(),
2691 ty: TypeTag::Permit,
2692 docs: "Permit handle; read only when `held`.",
2693 optional: true,
2694}])))]
2695#[example(
2696 name = "acquire",
2697 code = r###"
2698 # First acquire holds with a permit to bind.
2699 IMPORT [STD]
2700 LET $sem: SEMAPHORE = SEMAPHORE_NEW(1)
2701 LET $first: MAP<held: BOOL, permit?: PERMIT> = SEMAPHORE_TRY_ACQUIRE($sem)
2702 ASSERT_EQ $first.held true
2703 LET $permit: PERMIT = $first.permit
2704
2705 # A capped semaphore answers held false with no permit key.
2706 LET $second: MAP<held: BOOL, permit?: PERMIT> = SEMAPHORE_TRY_ACQUIRE($sem)
2707 ASSERT_EQ $second.held false
2708 LET $has_permit: BOOL = HAS_KEY($second, "permit")
2709 ASSERT_EQ $has_permit false
2710 "###
2711)]
2712fn semaphore_try_acquire<P: ProcessManager>(
2713 cx: &mut StepCtx<P>,
2714 sem: Arc<SemaphoreState>,
2716) -> Result<Value> {
2717 let _ = cx;
2718 let mut map = BTreeMap::new();
2719 if sem.try_acquire() {
2720 map.insert("held".to_string(), Value::bool(true));
2721 map.insert("permit".to_string(), Value::permit(&sem));
2722 } else {
2723 map.insert("held".to_string(), Value::bool(false));
2724 }
2725 Ok(Value::map(map))
2726}
2727
2728#[oxdock_func(pure, returns = TypeTag::Int)]
2735#[example(
2736 name = "readout",
2737 code = r###"
2738 # Hold one permit on a cap of two.
2739 IMPORT [STD]
2740 LET $sem: SEMAPHORE = SEMAPHORE_NEW(2)
2741 LET $acq: MAP<held: BOOL, permit?: PERMIT> = SEMAPHORE_TRY_ACQUIRE($sem)
2742 ASSERT_EQ $acq.held true
2743
2744 # One held permit leaves exactly one free.
2745 LET $free: INT = SEMAPHORE_AVAILABLE($sem)
2746 ASSERT_EQ $free 1
2747 "###
2748)]
2749fn semaphore_available(
2750 sem: Arc<SemaphoreState>,
2752) -> Result<Value> {
2753 Ok(Value::int(sem.available() as i64))
2754}
2755
2756#[oxdock_func(
2765 rpn,
2766 returns = TypeTag::union(vec![TypeTag::String, TypeTag::Pipe]),
2767 template = text_trim_string
2768)]
2769#[example(
2770 name = "trim",
2771 code = r###"
2772 # Leading and trailing whitespace falls away.
2773 IMPORT [STD]
2774 LET $clean: STRING = TEXT_TRIM(" hello ")
2775 ASSERT_EQ $clean "hello"
2776 "###
2777)]
2778#[example(
2779 name = "trim pipe mirrors",
2780 code = r###"
2781 # Pipe input mints pipe output with the same transform.
2782 IMPORT [STD]
2783 LET $cap: PIPE
2784 WITH_IO [stdout=$cap] {
2785 ECHO " hello "
2786 }
2787 LET $out: PIPE = TEXT_TRIM($cap)
2788 WITH_IO [stdin=$out] READ_LINE $line
2789 ASSERT_EQ $line "hello"
2790 "###
2791)]
2792#[example(
2793 name = "trim template",
2794 code = r###"
2795 # String inputs run inside placeholders too.
2796 IMPORT [STD]
2797 LET $msg: STRING = 'clean:{{ STD::TEXT_TRIM(" hello ") }}'
2798 ASSERT_EQ $msg "clean:hello"
2799 "###
2800)]
2801#[example(
2802 name = "trim file template",
2803 code = r###"
2804 # EXPAND templates resolve the same registry.
2805 IMPORT [STD]
2806 WRITE "tpl.txt" "clean:\{{ STD::TEXT_TRIM(\" hello \") }}"
2807 LET $out: STRING = EXPAND "tpl.txt"
2808 ASSERT_EQ $out "clean:hello"
2809 "###
2810)]
2811fn text_trim<P: ProcessManager>(
2812 cx: &mut StepCtx<P>,
2813 #[union(String, Pipe)]
2815 text: Value,
2816) -> Result<Value> {
2817 super::args::mirror_stream(cx, "TEXT_TRIM", &text, super::args::TextPump::Trim)
2818}
2819
2820fn text_trim_string(text: Value) -> Result<Value> {
2823 super::args::mirror_string("TEXT_TRIM", &text, super::args::TextPump::Trim)
2824}
2825
2826#[oxdock_func(
2835 rpn,
2836 returns = TypeTag::union(vec![TypeTag::String, TypeTag::Pipe]),
2837 template = text_trim_prefix_string
2838)]
2839#[example(
2840 name = "strip prefix",
2841 code = r###"
2842 # A present prefix falls away; absence returns the input unchanged.
2843 IMPORT [STD]
2844 LET $bare: STRING = TEXT_TRIM_PREFIX("v1.2.3", "v")
2845 ASSERT_EQ $bare "1.2.3"
2846
2847 # Missing prefixes pass through untouched.
2848 LET $same: STRING = TEXT_TRIM_PREFIX("1.2.3", "v")
2849 ASSERT_EQ $same "1.2.3"
2850 "###
2851)]
2852#[example(
2853 name = "strip prefix pipe mirrors",
2854 code = r###"
2855 # Pipe input mints pipe output with the same strip.
2856 IMPORT [STD]
2857 LET $cap: PIPE
2858 WITH_IO [stdout=$cap] {
2859 ECHO "v1.2.3"
2860 }
2861 LET $trimmed: PIPE = TEXT_TRIM($cap)
2862 LET $out: PIPE = TEXT_TRIM_PREFIX($trimmed, "v")
2863 WITH_IO [stdin=$out] READ_LINE $line
2864 ASSERT_EQ $line "1.2.3"
2865 "###
2866)]
2867#[example(
2868 name = "strip prefix template",
2869 code = r###"
2870 # String inputs run inside placeholders too.
2871 IMPORT [STD]
2872 LET $msg: STRING = 'bare:{{ STD::TEXT_TRIM_PREFIX("v1.2.3", "v") }}'
2873 ASSERT_EQ $msg "bare:1.2.3"
2874 "###
2875)]
2876fn text_trim_prefix<P: ProcessManager>(
2877 cx: &mut StepCtx<P>,
2878 #[union(String, Pipe)]
2880 text: Value,
2881 prefix: String,
2883) -> Result<Value> {
2884 super::args::mirror_stream(
2885 cx,
2886 "TEXT_TRIM_PREFIX",
2887 &text,
2888 super::args::TextPump::TrimPrefix(prefix),
2889 )
2890}
2891
2892fn text_trim_prefix_string(text: Value, prefix: String) -> Result<Value> {
2895 super::args::mirror_string(
2896 "TEXT_TRIM_PREFIX",
2897 &text,
2898 super::args::TextPump::TrimPrefix(prefix),
2899 )
2900}
2901
2902#[oxdock_func(
2909 rpn,
2910 returns = TypeTag::union(vec![TypeTag::String, TypeTag::Pipe]),
2911 template = text_trim_suffix_string
2912)]
2913#[example(
2914 name = "strip suffix",
2915 code = r###"
2916 # A present suffix falls away; absence returns the input unchanged.
2917 IMPORT [STD]
2918 LET $bare: STRING = TEXT_TRIM_SUFFIX("archive.tar.gz", ".gz")
2919 ASSERT_EQ $bare "archive.tar"
2920
2921 # Missing suffixes pass through untouched.
2922 LET $same: STRING = TEXT_TRIM_SUFFIX("archive.tar", ".gz")
2923 ASSERT_EQ $same "archive.tar"
2924 "###
2925)]
2926#[example(
2927 name = "strip suffix pipe mirrors",
2928 code = r###"
2929 # Pipe input mints pipe output with the same strip.
2930 IMPORT [STD]
2931 LET $cap: PIPE
2932 WITH_IO [stdout=$cap] {
2933 ECHO "archive.tar.gz"
2934 }
2935 LET $trimmed: PIPE = TEXT_TRIM($cap)
2936 LET $out: PIPE = TEXT_TRIM_SUFFIX($trimmed, ".gz")
2937 WITH_IO [stdin=$out] READ_LINE $line
2938 ASSERT_EQ $line "archive.tar"
2939 "###
2940)]
2941#[example(
2942 name = "strip suffix template",
2943 code = r###"
2944 # String inputs run inside placeholders too.
2945 IMPORT [STD]
2946 LET $msg: STRING = 'bare:{{ STD::TEXT_TRIM_SUFFIX("archive.tar.gz", ".gz") }}'
2947 ASSERT_EQ $msg "bare:archive.tar"
2948 "###
2949)]
2950fn text_trim_suffix<P: ProcessManager>(
2951 cx: &mut StepCtx<P>,
2952 #[union(String, Pipe)]
2954 text: Value,
2955 suffix: String,
2957) -> Result<Value> {
2958 super::args::mirror_stream(
2959 cx,
2960 "TEXT_TRIM_SUFFIX",
2961 &text,
2962 super::args::TextPump::TrimSuffix(suffix),
2963 )
2964}
2965
2966fn text_trim_suffix_string(text: Value, suffix: String) -> Result<Value> {
2969 super::args::mirror_string(
2970 "TEXT_TRIM_SUFFIX",
2971 &text,
2972 super::args::TextPump::TrimSuffix(suffix),
2973 )
2974}
2975
2976#[oxdock_func(returns = TypeTag::String)]
2987#[example(
2988 name = "join path",
2989 code = r###"
2990 # Directory and file stem join with the native separator.
2991 # Source `\\` is one backslash at runtime; `/` works on Windows
2992 # too, native just reads better there.
2993 IMPORT [STD]
2994 LET $p: STRING = PATH_JOIN("some-dir", "some-file")
2995 [family:unix] ASSERT_EQ $p "some-dir/some-file"
2996 [family:windows] ASSERT_EQ $p "some-dir\\some-file"
2997 "###
2998)]
2999fn path_join<P: ProcessManager>(
3000 _cx: &mut StepCtx<P>,
3001 #[union(String, Path)]
3003 dir: Value,
3004 #[union(String, Path)]
3006 name: Value,
3007) -> Result<Value> {
3008 let d = super::args::string_or_path_text(&dir)?;
3009 let n = super::args::string_or_path_text(&name)?;
3010 Ok(Value::string(oxdock_fs::join_native(&d, &n)))
3011}
3012
3013#[oxdock_func(
3020 rpn,
3021 returns = TypeTag::union(vec![TypeTag::String, TypeTag::Pipe]),
3022 template = text_to_upper_string
3023)]
3024#[example(
3025 name = "uppercase",
3026 code = r###"
3027 # Text folds to uppercase.
3028 IMPORT [STD]
3029 LET $loud: STRING = TEXT_TO_UPPER("hello")
3030 ASSERT_EQ $loud "HELLO"
3031 "###
3032)]
3033#[example(
3034 name = "uppercase pipe mirrors",
3035 code = r###"
3036 # Pipe input mints pipe output with the same fold.
3037 IMPORT [STD]
3038 LET $cap: PIPE
3039 WITH_IO [stdout=$cap] {
3040 ECHO "hello"
3041 }
3042 LET $out: PIPE = TEXT_TO_UPPER($cap)
3043 WITH_IO [stdin=$out] READ_LINE $line
3044 ASSERT_EQ $line "HELLO"
3045 "###
3046)]
3047#[example(
3048 name = "uppercase template",
3049 code = r###"
3050 # String inputs run inside placeholders too.
3051 IMPORT [STD]
3052 LET $msg: STRING = 'loud:{{ STD::TEXT_TO_UPPER("hello") }}'
3053 ASSERT_EQ $msg "loud:HELLO"
3054 "###
3055)]
3056fn text_to_upper<P: ProcessManager>(
3057 cx: &mut StepCtx<P>,
3058 #[union(String, Pipe)]
3060 text: Value,
3061) -> Result<Value> {
3062 super::args::mirror_stream(cx, "TEXT_TO_UPPER", &text, super::args::TextPump::ToUpper)
3063}
3064
3065fn text_to_upper_string(text: Value) -> Result<Value> {
3068 super::args::mirror_string("TEXT_TO_UPPER", &text, super::args::TextPump::ToUpper)
3069}
3070
3071#[oxdock_func(
3078 rpn,
3079 returns = TypeTag::union(vec![TypeTag::String, TypeTag::Pipe]),
3080 template = text_to_lower_string
3081)]
3082#[example(
3083 name = "lowercase",
3084 code = r###"
3085 # Text folds to lowercase.
3086 IMPORT [STD]
3087 LET $quiet: STRING = TEXT_TO_LOWER("HELLO")
3088 ASSERT_EQ $quiet "hello"
3089 "###
3090)]
3091#[example(
3092 name = "lowercase pipe mirrors",
3093 code = r###"
3094 # Pipe input mints pipe output with the same fold.
3095 IMPORT [STD]
3096 LET $cap: PIPE
3097 WITH_IO [stdout=$cap] {
3098 ECHO "HELLO"
3099 }
3100 LET $out: PIPE = TEXT_TO_LOWER($cap)
3101 WITH_IO [stdin=$out] READ_LINE $line
3102 ASSERT_EQ $line "hello"
3103 "###
3104)]
3105#[example(
3106 name = "lowercase template",
3107 code = r###"
3108 # String inputs run inside placeholders too.
3109 IMPORT [STD]
3110 LET $msg: STRING = 'quiet:{{ STD::TEXT_TO_LOWER("HELLO") }}'
3111 ASSERT_EQ $msg "quiet:hello"
3112 "###
3113)]
3114fn text_to_lower<P: ProcessManager>(
3115 cx: &mut StepCtx<P>,
3116 #[union(String, Pipe)]
3118 text: Value,
3119) -> Result<Value> {
3120 super::args::mirror_stream(cx, "TEXT_TO_LOWER", &text, super::args::TextPump::ToLower)
3121}
3122
3123fn text_to_lower_string(text: Value) -> Result<Value> {
3126 super::args::mirror_string("TEXT_TO_LOWER", &text, super::args::TextPump::ToLower)
3127}
3128
3129#[oxdock_func(
3140 rpn,
3141 returns = TypeTag::union(vec![TypeTag::String, TypeTag::Pipe]),
3142 template = text_replace_string
3143)]
3144#[example(
3145 name = "replace",
3146 code = r###"
3147 # Every literal occurrence rewrites in place.
3148 IMPORT [STD]
3149 LET $fixed: STRING = TEXT_REPLACE("hello world", "world", "there")
3150 ASSERT_EQ $fixed "hello there"
3151 "###
3152)]
3153#[example(
3154 name = "replace pipe mirrors",
3155 code = r###"
3156 # Pipe input mints pipe output with the same rewrite.
3157 IMPORT [STD]
3158 LET $cap: PIPE
3159 WITH_IO [stdout=$cap] {
3160 ECHO "hello world"
3161 }
3162 LET $trimmed: PIPE = TEXT_TRIM($cap)
3163 LET $out: PIPE = TEXT_REPLACE($trimmed, "world", "there")
3164 WITH_IO [stdin=$out] READ_LINE $line
3165 ASSERT_EQ $line "hello there"
3166 "###
3167)]
3168#[example(
3169 name = "replace template",
3170 code = r###"
3171 # String inputs run inside placeholders too.
3172 IMPORT [STD]
3173 LET $msg: STRING = 'fixed:{{ STD::TEXT_REPLACE("hello world", "world", "there") }}'
3174 ASSERT_EQ $msg "fixed:hello there"
3175 "###
3176)]
3177fn text_replace<P: ProcessManager>(
3178 cx: &mut StepCtx<P>,
3179 #[union(String, Pipe)]
3181 text: Value,
3182 from: String,
3184 to: String,
3186) -> Result<Value> {
3187 super::args::mirror_stream(
3188 cx,
3189 "TEXT_REPLACE",
3190 &text,
3191 super::args::TextPump::ReplaceLiteral { from, to },
3192 )
3193}
3194
3195fn text_replace_string(text: Value, from: String, to: String) -> Result<Value> {
3198 super::args::mirror_string(
3199 "TEXT_REPLACE",
3200 &text,
3201 super::args::TextPump::ReplaceLiteral { from, to },
3202 )
3203}
3204
3205#[oxdock_func(
3217 rpn,
3218 returns = TypeTag::union(vec![TypeTag::String, TypeTag::Pipe]),
3219 template = text_replace_regex_string
3220)]
3221#[example(
3222 name = "replace with captures",
3223 code = r###"
3224 # Capture groups expand in the replacement.
3225 IMPORT [STD]
3226 LET $swapped: STRING = TEXT_REPLACE_REGEX("2026-10-13", "(\\d+)-(\\d+)-(\\d+)", "$3/$2/$1")
3227 ASSERT_EQ $swapped "13/10/2026"
3228 "###
3229)]
3230#[example(
3231 name = "replace regex pipe mirrors",
3232 code = r###"
3233 # Pipe input mints pipe output with the same rewrite.
3234 IMPORT [STD]
3235 LET $cap: PIPE
3236 WITH_IO [stdout=$cap] {
3237 ECHO "2026-10-13"
3238 }
3239 LET $trimmed: PIPE = TEXT_TRIM($cap)
3240 LET $out: PIPE = TEXT_REPLACE_REGEX($trimmed, "(\\d+)-(\\d+)-(\\d+)", "$3/$2/$1")
3241 WITH_IO [stdin=$out] READ_LINE $line
3242 ASSERT_EQ $line "13/10/2026"
3243 "###
3244)]
3245#[example(
3246 name = "replace regex template",
3247 code = r###"
3248 # String inputs run inside placeholders too.
3249 IMPORT [STD]
3250 LET $msg: STRING = 'swapped:{{ STD::TEXT_REPLACE_REGEX("2026-10-13", "(\\d+)-(\\d+)-(\\d+)", "$3/$2/$1") }}'
3251 ASSERT_EQ $msg "swapped:13/10/2026"
3252 "###
3253)]
3254fn text_replace_regex<P: ProcessManager>(
3255 cx: &mut StepCtx<P>,
3256 #[union(String, Pipe)]
3258 text: Value,
3259 pattern: String,
3261 replacement: String,
3263) -> Result<Value> {
3264 if let Some(s) = text.as_str() {
3265 let out =
3266 super::args::text_replace_regex_str(s, &pattern, &replacement, "TEXT_REPLACE_REGEX")?;
3267 return Ok(Value::string(out));
3268 }
3269 let content = super::args::read_pipe_eager(cx, "TEXT_REPLACE_REGEX", &text)?;
3270 let out = super::args::text_replace_regex_str(
3271 &content,
3272 &pattern,
3273 &replacement,
3274 "TEXT_REPLACE_REGEX",
3275 )?;
3276 super::args::write_completed_pipe(cx, "TEXT_REPLACE_REGEX", out)
3277}
3278
3279fn text_replace_regex_string(text: Value, pattern: String, replacement: String) -> Result<Value> {
3282 let Some(s) = text.as_str() else {
3283 return Err(super::args::pipe_needs_step_io("TEXT_REPLACE_REGEX"));
3284 };
3285 let out = super::args::text_replace_regex_str(s, &pattern, &replacement, "TEXT_REPLACE_REGEX")?;
3286 Ok(Value::string(out))
3287}
3288
3289#[oxdock_func(pure, returns = TypeTag::ListOf(std::sync::Arc::new(TypeTag::String)))]
3297#[example(
3298 name = "split",
3299 code = r###"
3300 # Delimiters split into list items.
3301 IMPORT [STD]
3302 LET $parts: LIST<STRING> = TEXT_SPLIT("a,b,c", ",")
3303 ASSERT_EQ $parts.0 "a"
3304 ASSERT_EQ $parts.1 "b"
3305 ASSERT_EQ $parts.2 "c"
3306 "###
3307)]
3308fn text_split(
3309 text: String,
3311 delimiter: String,
3313) -> Result<Value> {
3314 Ok(super::args::text_list_value(super::args::text_split_str(
3315 &text, &delimiter,
3316 )))
3317}
3318
3319#[oxdock_func(pure, returns = TypeTag::String)]
3322#[example(
3323 name = "join",
3324 code = r###"
3325 # List items join with the separator between them.
3326 IMPORT [STD]
3327 LET $joined: STRING = TEXT_JOIN(["a", "b", "c"], ",")
3328 ASSERT_EQ $joined "a,b,c"
3329 "###
3330)]
3331fn text_join(
3332 elements: Vec<String>,
3334 delimiter: String,
3336) -> Result<Value> {
3337 Ok(Value::string(elements.join(delimiter.as_str())))
3338}
3339
3340#[oxdock_func(pure, returns = TypeTag::ListOf(std::sync::Arc::new(TypeTag::String)))]
3352#[example(
3353 name = "split args",
3354 code = r###"
3355 # Quoted segments stay one word.
3356 IMPORT [STD]
3357 LET $argv: LIST<STRING> = SHELL_SPLIT_ARGS("gh issue comment 153 --body-file notes.md")
3358 ASSERT_EQ $argv.0 "gh"
3359 ASSERT_EQ $argv.3 "153"
3360 ASSERT_EQ $argv.5 "notes.md"
3361
3362 # Quotes and escapes parse the shell way.
3363 LET $quoted: LIST<STRING> = SHELL_SPLIT_ARGS("say \"hi there\" 'a b'")
3364 ASSERT_EQ $quoted.0 "say"
3365 ASSERT_EQ $quoted.1 "hi there"
3366 ASSERT_EQ $quoted.2 "a b"
3367 "###
3368)]
3369fn shell_split_args(
3370 command: String,
3372) -> Result<Value> {
3373 match shell_words::split(&command) {
3374 Ok(words) => Ok(super::args::text_list_value(words)),
3375 Err(err) => anyhow::bail!("SHELL_SPLIT_ARGS: {err}"),
3376 }
3377}
3378
3379#[oxdock_func(pure, returns = TypeTag::String)]
3387#[example(
3388 name = "join args",
3389 code = r###"
3390 # Plain words join with spaces and no quoting.
3391 IMPORT [STD]
3392 LET $plain: STRING = SHELL_JOIN_ARGS(["gh", "issue", "list"])
3393 ASSERT_EQ $plain "gh issue list"
3394
3395 # Words with spaces quote, and the round trip is exact.
3396 LET $words: LIST<STRING> = ["say", "hi there", "a'b"]
3397 LET $joined: STRING = SHELL_JOIN_ARGS($words)
3398 LET $back: LIST<STRING> = SHELL_SPLIT_ARGS($joined)
3399 ASSERT_EQ $back.0 "say"
3400 ASSERT_EQ $back.1 "hi there"
3401 ASSERT_EQ $back.2 "a'b"
3402 "###
3403)]
3404fn shell_join_args(
3405 words: Vec<String>,
3407) -> Result<Value> {
3408 Ok(Value::string(shell_words::join(&words)))
3409}
3410
3411#[oxdock_func(pure, returns = TypeTag::ListOf(std::sync::Arc::new(TypeTag::String)))]
3419#[example(
3420 name = "lines",
3421 code = r###"
3422 # Newlines split into line items.
3423 IMPORT [STD]
3424 LET $lines: LIST<STRING> = TEXT_LINES("one\ntwo\nthree")
3425 ASSERT_EQ $lines.0 "one"
3426 ASSERT_EQ $lines.1 "two"
3427 ASSERT_EQ $lines.2 "three"
3428
3429 # Windows endings split the same way after normalization.
3430 LET $crlf: LIST<STRING> = TEXT_LINES("one\r\ntwo\r\nthree")
3431 ASSERT_EQ $crlf.0 "one"
3432 ASSERT_EQ $crlf.1 "two"
3433 ASSERT_EQ $crlf.2 "three"
3434
3435 # Old Mac endings split too, and mixed endings split together because the input normalizes to LF before splitting.
3436 LET $mixed: LIST<STRING> = TEXT_LINES("a\r\nb\nc\rd")
3437 ASSERT_EQ $mixed.0 "a"
3438 ASSERT_EQ $mixed.1 "b"
3439 ASSERT_EQ $mixed.2 "c"
3440 ASSERT_EQ $mixed.3 "d"
3441 "###
3442)]
3443fn text_lines(
3444 text: String,
3446) -> Result<Value> {
3447 Ok(super::args::text_list_value(super::args::text_lines_str(
3448 &text,
3449 )))
3450}
3451
3452#[oxdock_func(pure, returns = TypeTag::ListOf(std::sync::Arc::new(TypeTag::String)))]
3458#[example(
3459 name = "fields",
3460 code = r###"
3461 # Runs of whitespace separate fields; empties never appear.
3462 IMPORT [STD]
3463 LET $fields: LIST<STRING> = TEXT_FIELDS(" abc def ")
3464 ASSERT_EQ $fields.0 "abc"
3465 ASSERT_EQ $fields.1 "def"
3466 "###
3467)]
3468fn text_fields(
3469 text: String,
3471) -> Result<Value> {
3472 Ok(super::args::text_list_value(super::args::text_fields_str(
3473 &text,
3474 )))
3475}
3476
3477#[oxdock_func(pure, returns = TypeTag::ListOf(std::sync::Arc::new(TypeTag::String)))]
3486#[example(
3487 name = "line range",
3488 code = r###"
3489 # Lines 2 through 3 come back as a list, 1-based inclusive.
3490 IMPORT [STD]
3491 LET $window: LIST<STRING> = TEXT_LINES_RANGE("one\ntwo\nthree\nfour", 2, 3)
3492 ASSERT_EQ $window.0 "two"
3493 ASSERT_EQ $window.1 "three"
3494
3495 # Ranges past the end clamp instead of failing.
3496 LET $tail: LIST<STRING> = TEXT_LINES_RANGE("one\ntwo", 2, 9)
3497 ASSERT_EQ $tail.0 "two"
3498 "###
3499)]
3500fn text_lines_range(
3501 text: String,
3503 from: i64,
3505 to: i64,
3507) -> Result<Value> {
3508 Ok(super::args::text_list_value(
3509 super::args::text_lines_range_str(&text, from, to, "TEXT_LINES_RANGE")?,
3510 ))
3511}
3512
3513#[oxdock_func(pure, returns = TypeTag::Bool)]
3521#[example(
3522 name = "match",
3523 code = r###"
3524 # Regex matches report true; misses report false.
3525 IMPORT [STD]
3526 LET $hit: BOOL = TEXT_MATCH("abc123", "\\d+")
3527 ASSERT_EQ $hit true
3528
3529 # A miss is false, not a failure.
3530 LET $miss: BOOL = TEXT_MATCH("abc", "^\\d+$")
3531 ASSERT_EQ $miss false
3532 "###
3533)]
3534fn text_match(
3535 text: String,
3537 pattern: String,
3539) -> Result<Value> {
3540 let re = super::args::text_compile_pattern("TEXT_MATCH", &pattern)?;
3541 Ok(Value::bool(re.is_match(&text)))
3542}
3543
3544#[oxdock_func(pure, name = "BOOL", returns = TypeTag::Bool)]
3553#[example(
3554 name = "convert",
3555 code = r###"
3556 IMPORT [STD]
3557 LET $n: BOOL = BOOL("yes")
3558 ASSERT_EQ $n true
3559 LET $f: BOOL = BOOL("0")
3560 ASSERT_EQ $f false
3561 "###
3562)]
3563fn bool_convert(
3564 #[union(Bool, String)]
3566 val: Value,
3567) -> Result<Value> {
3568 if let Some(b) = val.as_bool() {
3569 return Ok(Value::bool(b));
3570 }
3571 let Some(s) = val.as_str() else {
3572 return Err(anyhow::anyhow!(
3573 "BOOL needs a Bool or String, found {val:?}"
3574 ));
3575 };
3576 match super::args::parse_bool_str(s) {
3577 Some(b) => Ok(Value::bool(b)),
3578 None => anyhow::bail!("BOOL cannot coerce {s:?} to BOOL"),
3579 }
3580}
3581
3582#[oxdock_func(pure, returns = TypeTag::Bool)]
3592#[example(
3593 name = "absent-default",
3594 code = r###"
3595 # Absent names read empty; the default settles the polarity.
3596 IMPORT [STD]
3597 INHERIT_ENV [OXDOCK_TEST_ABSENT_FLAG]
3598 LET $dry: BOOL = BOOL_OR("{{ env:OXDOCK_TEST_ABSENT_FLAG }}", true)
3599 ASSERT_EQ $dry true
3600
3601 # Present values coerce strictly, ignoring the default.
3602 LET $off: BOOL = BOOL_OR("false", true)
3603 ASSERT_EQ $off false
3604 "###
3605)]
3606fn bool_or(
3607 text: String,
3609 default: bool,
3611) -> Result<Value> {
3612 if text.trim().is_empty() {
3613 return Ok(Value::bool(default));
3614 }
3615 match super::args::parse_bool_str(&text) {
3616 Some(b) => Ok(Value::bool(b)),
3617 None => anyhow::bail!("BOOL_OR cannot coerce {text:?} to BOOL"),
3618 }
3619}
3620
3621#[oxdock_func(pure, returns = TypeTag::ListOf(std::sync::Arc::new(TypeTag::String)))]
3630#[example(
3631 name = "extract",
3632 code = r###"
3633 # Index zero is the full match; groups follow in order.
3634 IMPORT [STD]
3635 LET $caps: LIST<STRING> = TEXT_EXTRACT("abc123", "([a-z]+)(\\d+)")
3636 ASSERT_EQ $caps.0 "abc123"
3637 ASSERT_EQ $caps.1 "abc"
3638 ASSERT_EQ $caps.2 "123"
3639 "###
3640)]
3641fn text_extract(
3642 text: String,
3644 pattern: String,
3646) -> Result<Value> {
3647 let groups = super::args::text_extract_str(&text, &pattern, "TEXT_EXTRACT")?;
3648 Ok(super::args::text_list_value(groups))
3649}
3650
3651#[oxdock_func(pure, returns = TypeTag::Bool)]
3658#[example(
3659 name = "starts with",
3660 code = r###"
3661 # Present prefixes report true; misses report false.
3662 IMPORT [STD]
3663 LET $hit: BOOL = TEXT_STARTS_WITH("linux-musl-x64", "linux")
3664 ASSERT_EQ $hit true
3665
3666 # A miss is false, not a failure.
3667 LET $miss: BOOL = TEXT_STARTS_WITH("macos-arm", "linux")
3668 ASSERT_EQ $miss false
3669 "###
3670)]
3671fn text_starts_with(
3672 text: String,
3674 prefix: String,
3676) -> Result<Value> {
3677 Ok(Value::bool(text.starts_with(prefix.as_str())))
3678}
3679
3680#[oxdock_func(pure, returns = TypeTag::Bool)]
3687#[example(
3688 name = "ends with",
3689 code = r###"
3690 # Present suffixes report true; misses report false.
3691 IMPORT [STD]
3692 LET $hit: BOOL = TEXT_ENDS_WITH("x86_64-linux-musl", "linux-musl")
3693 ASSERT_EQ $hit true
3694
3695 # A miss is false, not a failure.
3696 LET $miss: BOOL = TEXT_ENDS_WITH("x86_64-linux-gnu", "linux-musl")
3697 ASSERT_EQ $miss false
3698 "###
3699)]
3700fn text_ends_with(
3701 text: String,
3703 suffix: String,
3705) -> Result<Value> {
3706 Ok(Value::bool(text.ends_with(suffix.as_str())))
3707}
3708
3709#[oxdock_func(pure, returns = TypeTag::Bool)]
3716#[example(
3717 name = "contains",
3718 code = r###"
3719 # Present needles report true; misses report false.
3720 IMPORT [STD]
3721 LET $hit: BOOL = TEXT_CONTAINS("x86_64-linux-musl", "musl")
3722 ASSERT_EQ $hit true
3723
3724 # A miss is false, not a failure.
3725 LET $miss: BOOL = TEXT_CONTAINS("x86_64-linux-gnu", "musl")
3726 ASSERT_EQ $miss false
3727 "###
3728)]
3729fn text_contains(
3730 text: String,
3732 needle: String,
3734) -> Result<Value> {
3735 Ok(Value::bool(text.contains(needle.as_str())))
3736}
3737
3738#[oxdock_func(pure, returns = TypeTag::Int)]
3747#[example(
3748 name = "length",
3749 code = r###"
3750 # Plain text counts one per character.
3751 IMPORT [STD]
3752 LET $n: INT = LEN("hello")
3753 ASSERT_EQ $n 5
3754
3755 # Multibyte characters count once each, not per byte.
3756 LET $wide: INT = LEN("héllo")
3757 ASSERT_EQ $wide 5
3758
3759 # Lists count elements, maps count entries.
3760 LET $items: LIST<STRING> = ["a", "b", "c"]
3761 LET $nitems: INT = LEN($items)
3762 ASSERT_EQ $nitems 3
3763 LET $row: MAP<name: STRING> = {name: "ada"}
3764 LET $nkeys: INT = LEN($row)
3765 ASSERT_EQ $nkeys 1
3766 LET $empty: INT = LEN([])
3767 ASSERT_EQ $empty 0
3768 "###
3769)]
3770fn len(
3771 #[union(String, List, Map)]
3773 value: Value,
3774) -> Result<Value> {
3775 if let Some(text) = value.as_str() {
3776 return Ok(Value::int(text.chars().count() as i64));
3777 }
3778 if let Some(items) = value.as_list() {
3779 return Ok(Value::int(items.len() as i64));
3780 }
3781 if let Some(entries) = value.as_map() {
3782 return Ok(Value::int(entries.len() as i64));
3783 }
3784 Err(anyhow::anyhow!(
3785 "LEN needs a STRING, LIST, or MAP value, got {}",
3786 value.type_name()
3787 ))
3788}
3789
3790#[oxdock_func(pure, returns = TypeTag::Int)]
3798#[example(
3799 name = "count",
3800 code = r###"
3801 # Every non-overlapping occurrence counts once.
3802 IMPORT [STD]
3803 LET $n: INT = TEXT_COUNT("hello world", "o")
3804 ASSERT_EQ $n 2
3805
3806 # Overlapping candidates never double count.
3807 LET $once: INT = TEXT_COUNT("aaa", "aa")
3808 ASSERT_EQ $once 1
3809 "###
3810)]
3811fn text_count(
3812 text: String,
3814 needle: String,
3816) -> Result<Value> {
3817 let n = super::args::text_count_str(&text, &needle, "TEXT_COUNT")?;
3818 Ok(Value::int(n))
3819}
3820
3821#[oxdock_func(pure, returns = TypeTag::Int)]
3831#[example(
3832 name = "count matches",
3833 code = r###"
3834 # One line matches once no matter how many times it hits.
3835 IMPORT [STD]
3836 LET $n: INT = TEXT_COUNT_MATCHES("test a: test\ntest b: nope\ntest c: test", ": test")
3837 ASSERT_EQ $n 2
3838
3839 # A miss binds zero, never an error.
3840 LET $none: INT = TEXT_COUNT_MATCHES("test b: nope", ": test$")
3841 ASSERT_EQ $none 0
3842 "###
3843)]
3844fn text_count_matches(
3845 text: String,
3847 pattern: String,
3849) -> Result<Value> {
3850 let n = super::args::text_count_matches_str(&text, &pattern, "TEXT_COUNT_MATCHES")?;
3851 Ok(Value::int(n))
3852}
3853
3854#[oxdock_func(pure, returns = TypeTag::ListOf(std::sync::Arc::new(TypeTag::String)))]
3867#[example(
3868 name = "grep",
3869 code = r###"
3870 # Matching lines come back as a list, in order.
3871 IMPORT [STD]
3872 LET $hits: LIST<STRING> = TEXT_GREP("one\ntwo\none more", "^one")
3873 ASSERT_EQ $hits.0 "one"
3874 ASSERT_EQ $hits.1 "one more"
3875
3876 # A miss binds an empty list, never an error.
3877 LET $miss: LIST<STRING> = TEXT_GREP("one\ntwo", "^z")
3878 LET $joined: STRING = TEXT_JOIN($miss, ",")
3879 ASSERT_EQ $joined ""
3880
3881 # The (?i) flag ignores case, so uppercase lines match too.
3882 LET $folded: LIST<STRING> = TEXT_GREP("One\ntwo\nONE more", "(?i)^one")
3883 ASSERT_EQ $folded.0 "One"
3884 ASSERT_EQ $folded.1 "ONE more"
3885 "###
3886)]
3887#[example(
3888 name = "grep invert",
3889 code = r###"
3890 # The invert option keeps every non-matching line instead.
3891 IMPORT [STD]
3892 LET $kept: LIST<STRING> = TEXT_GREP("one\ntwo\none more", "^one", {invert: true})
3893 ASSERT_EQ $kept.0 "two"
3894
3895 # A pattern matching every line binds an empty list, never an error.
3896 LET $none: LIST<STRING> = TEXT_GREP("one\ntwo", "^", {invert: true})
3897 LET $joined: STRING = TEXT_JOIN($none, ",")
3898 ASSERT_EQ $joined ""
3899
3900 # Options ride into placeholders as MAP literals. Placeholder
3901 # strings unescape only backslash and quote, so multiline text
3902 # arrives through a variable.
3903 LET $two_lines: STRING = "one\ntwo"
3904 LET $msg: STRING = 'kept:{{ STD::TEXT_GREP($two_lines, "^one", {invert: true}) }}'
3905 ASSERT_EQ $msg "kept:two"
3906 "###
3907)]
3908fn text_grep(
3909 text: String,
3911 pattern: String,
3913 #[options("invert?: BOOL")]
3915 #[optional]
3916 options: BTreeMap<String, Value>,
3917) -> Result<Value> {
3918 let invert = super::args::text_invert_flag(&options);
3921 Ok(super::args::text_list_value(super::args::text_grep_str(
3922 &text,
3923 &pattern,
3924 invert,
3925 "TEXT_GREP",
3926 )?))
3927}
3928
3929#[oxdock_func(returns = TypeTag::Bool)]
3940#[example(
3941 name = "drain to end",
3942 code = r###"
3943 # Capture two lines, then drain to end of stream with no sentinel line.
3944 IMPORT [STD]
3945 LET $cap: PIPE
3946 WITH_IO [stdout=$cap] {
3947 ECHO "one"
3948 ECHO "two"
3949 }
3950
3951 # The loop exits on close, and the count proves both lines drained.
3952 LET $n: INT = 0
3953 WHILE !EOF($cap) {
3954 WITH_IO [stdin=$cap] READ_LINE $line
3955 $n = $n + 1
3956 }
3957 ASSERT_EQ $n 2
3958 "###
3959)]
3960fn eof<P: ProcessManager>(
3961 cx: &mut StepCtx<P>,
3962 pipe: PipeHandle,
3964) -> Result<Value> {
3965 let info = cx.state.io.inspect_pipe(&pipe);
3966 Ok(Value::bool(info.closed && info.buffered == 0))
3967}
3968
3969fn task_poll_result_fields() -> Arc<[Field]> {
3973 Arc::from(vec![
3974 Field {
3975 name: "state".to_string(),
3976 ty: TypeTag::String,
3977 docs: "Task phase: `running` or `finished`.",
3978 optional: false,
3979 },
3980 Field {
3981 name: "ok".to_string(),
3982 ty: TypeTag::Bool,
3983 docs: "True unless the task failed.",
3984 optional: false,
3985 },
3986 Field {
3987 name: "stdout_tail".to_string(),
3988 ty: TypeTag::String,
3989 docs: "Bounded stdout tail, live while running.",
3990 optional: false,
3991 },
3992 Field {
3993 name: "stderr_tail".to_string(),
3994 ty: TypeTag::String,
3995 docs: "Bounded stderr tail, live while running.",
3996 optional: false,
3997 },
3998 Field {
3999 name: "truncated_bytes".to_string(),
4000 ty: TypeTag::Int,
4001 docs: "Dropped head bytes past the per-stream cap.",
4002 optional: false,
4003 },
4004 Field {
4005 name: "exit_code".to_string(),
4006 ty: TypeTag::Int,
4007 docs: "Process exit code, present once finished.",
4008 optional: true,
4009 },
4010 Field {
4011 name: "result".to_string(),
4012 ty: TypeTag::Any,
4013 docs: "Task `RETURN` value, present on clean finish.",
4014 optional: true,
4015 },
4016 Field {
4017 name: "error".to_string(),
4018 ty: TypeTag::String,
4019 docs: "Failure text, present on failed finish.",
4020 optional: true,
4021 },
4022 ])
4023}
4024
4025#[oxdock_func(returns = TypeTag::Record(task_poll_result_fields()))]
4038#[example(
4039 name = "running poll",
4040 code = r###"
4041 # A sleeping task is still running on the first poll.
4042 IMPORT [STD]
4043 LET $t: HANDLE<STRING> = ASYNC { SLEEP 30s; RETURN "done" }
4044 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)
4045 ASSERT_EQ $m.state "running"
4046 ASSERT_EQ $m.ok true
4047 # Clean up the sleeper so the run ends promptly.
4048 CANCEL $t
4049 "###
4050)]
4051#[example(
4052 name = "finished poll",
4053 code = r###"
4054 # A finished task reports its value and final tails, then still awaits.
4055 IMPORT [STD]
4056 LET $t: HANDLE<STRING> = ASYNC { ECHO "hi"; SLEEP 1s; RETURN "done" }
4057 # Do other work while the task runs; poll once it should be done.
4058 SLEEP 2s
4059 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)
4060 ASSERT_EQ $m.state "finished"
4061 ASSERT_EQ $m.result "done"
4062 LET $o: STRING = AWAIT $t
4063 ASSERT_EQ $o "done"
4064 "###
4065)]
4066fn task_poll<P: ProcessManager>(
4067 cx: &mut StepCtx<P>,
4068 task: HandleValue,
4070) -> Result<Value> {
4071 let entry =
4072 super::handlers::resolve_task_entry_by_id(task.0, &format!("TASK_POLL({})", task.0), cx)?;
4073 let obs = entry.observe_completion();
4074 let (stdout_tail, stderr_tail, dropped) = entry.snapshot_tails();
4075 let mut out = BTreeMap::new();
4076 out.insert(
4077 "state".to_string(),
4078 Value::string(if obs.running { "running" } else { "finished" }.to_string()),
4079 );
4080 out.insert("ok".to_string(), Value::bool(obs.ok));
4081 if !obs.running {
4082 out.insert("exit_code".to_string(), Value::int(obs.exit_code));
4083 }
4084 if let Some(result) = obs.result {
4085 out.insert("result".to_string(), result);
4086 }
4087 if !obs.error.is_empty() {
4088 out.insert("error".to_string(), Value::string(obs.error));
4089 }
4090 out.insert("stdout_tail".to_string(), Value::string(stdout_tail));
4091 out.insert("stderr_tail".to_string(), Value::string(stderr_tail));
4092 out.insert(
4093 "truncated_bytes".to_string(),
4094 Value::int(dropped.min(i64::MAX as u64) as i64),
4095 );
4096 Ok(Value::map(out))
4097}
4098
4099fn meta_to_value(meta: &FuncMeta) -> Value {
4100 let mut map = BTreeMap::new();
4101 map.insert("name".to_string(), Value::string(meta.name.clone()));
4102 map.insert("module".to_string(), Value::string(meta.module.clone()));
4103 map.insert(
4104 "kind".to_string(),
4105 Value::string(meta.kind.label().to_string()),
4106 );
4107 let params = match &meta.params {
4108 Some(params) => Value::list(
4109 params
4110 .iter()
4111 .map(|p| {
4112 let mut entry = BTreeMap::new();
4113 entry.insert("name".to_string(), Value::string(p.name.clone()));
4114 entry.insert(
4115 "param_type".to_string(),
4116 Value::string(
4117 p.param_type
4118 .as_ref()
4119 .map(render_structural)
4120 .unwrap_or_default(),
4121 ),
4122 );
4123 entry.insert(
4124 "allowed".to_string(),
4125 Value::string(
4126 p.allowed
4127 .map(|values| values.join(", "))
4128 .unwrap_or_default(),
4129 ),
4130 );
4131 entry.insert("docs".to_string(), Value::string(String::new()));
4132 entry.insert("optional".to_string(), Value::bool(p.optional));
4133 entry.insert(
4134 "options".to_string(),
4135 match p.options {
4136 Some(keys) => Value::list(
4137 keys.iter()
4138 .map(|key| {
4139 let mut option = BTreeMap::new();
4140 option.insert(
4141 "name".to_string(),
4142 Value::string(key.name.to_string()),
4143 );
4144 option.insert(
4145 "value_type".to_string(),
4146 Value::string(render_structural(&key.value)),
4147 );
4148 option.insert(
4149 "required".to_string(),
4150 Value::bool(key.required),
4151 );
4152 option.insert(
4153 "default".to_string(),
4154 Value::string(
4155 key.default.unwrap_or_default().to_string(),
4156 ),
4157 );
4158 Value::map(option)
4159 })
4160 .collect(),
4161 ),
4162 None => Value::string(String::new()),
4163 },
4164 );
4165 Value::map(entry)
4166 })
4167 .collect(),
4168 ),
4169 None => Value::list(Vec::new()),
4173 };
4174 map.insert("params".to_string(), params);
4175 map.insert(
4176 "returns".to_string(),
4177 Value::string(
4178 meta.returns
4179 .as_ref()
4180 .map(render_structural)
4181 .unwrap_or_default(),
4182 ),
4183 );
4184 map.insert("rpn".to_string(), Value::bool(meta.rpn));
4185 map.insert(
4186 "summary".to_string(),
4187 Value::string(meta.summary.to_string()),
4188 );
4189 Value::map(map)
4190}
4191
4192#[derive(Debug, Clone)]
4196pub struct RecordSchema {
4197 pub name: &'static str,
4198 pub fields: std::sync::Arc<[Field]>,
4199}
4200
4201#[derive(Clone)]
4205pub struct HostModule<P: ProcessManager> {
4206 pub name: String,
4207 pub funcs: Vec<HostRegistration<P>>,
4208 pub types: Vec<&'static TypeDescriptor>,
4209 pub record_schemas: Vec<RecordSchema>,
4210 pub states: Vec<ModuleState>,
4217}
4218
4219#[derive(Clone)]
4223pub struct ModuleState {
4224 id: std::any::TypeId,
4225 state: std::sync::Arc<dyn std::any::Any + Send + Sync>,
4226}
4227
4228pub type PreRunInspector = dyn Fn(&[Step]) -> Result<()> + Send + Sync;
4232
4233#[derive(Clone)]
4239pub struct PreRunCheck {
4240 check: Arc<PreRunInspector>,
4241}
4242
4243impl PreRunCheck {
4244 pub fn new(check: impl Fn(&[Step]) -> Result<()> + Send + Sync + 'static) -> Self {
4246 Self {
4247 check: Arc::new(check),
4248 }
4249 }
4250
4251 pub fn run(&self, steps: &[Step]) -> Result<()> {
4253 (self.check)(steps)
4254 }
4255}
4256
4257impl<P: ProcessManager> HostModule<P> {
4258 pub fn with_state<T: Send + Sync + 'static>(mut self, state: std::sync::Arc<T>) -> Self {
4261 self.states.push(ModuleState {
4262 id: std::any::TypeId::of::<T>(),
4263 state,
4264 });
4265 self
4266 }
4267
4268 pub fn check_pre_run(&self, steps: &[Step]) -> Result<()> {
4272 for state in &self.states {
4273 if let Some(check) = state.state.downcast_ref::<PreRunCheck>() {
4274 check.run(steps)?;
4275 }
4276 }
4277 Ok(())
4278 }
4279}
4280
4281impl<P: ProcessManager> ExecState<P> {
4282 pub fn register_module(&mut self, module: HostModule<P>) {
4285 for registration in module.funcs {
4286 match registration {
4287 HostRegistration::Stateful { name, meta, func } => {
4288 self.functions.register_host(&module.name, name, meta, func);
4289 }
4290 HostRegistration::Pure { name, meta, func } => {
4291 self.functions
4292 .register_pure_host(&module.name, name, meta, func);
4293 }
4294 HostRegistration::Both {
4295 name,
4296 meta,
4297 func,
4298 template,
4299 } => {
4300 self.functions
4301 .register_both_host(&module.name, name, meta, func, template);
4302 }
4303 }
4304 }
4305 for descriptor in module.types {
4306 self.register_type(descriptor);
4307 }
4308 for schema in module.record_schemas {
4309 self.register_record_schema(schema.name, schema.fields);
4310 }
4311 for state in module.states {
4312 self.module_states
4313 .insert((module.name.clone(), state.id), state.state);
4314 }
4315 }
4316
4317 pub fn list_functions(&self) -> Vec<FuncMeta> {
4319 let mut out: Vec<FuncMeta> = self.functions.entries_metas().into_iter().collect();
4320 if !out.iter().any(|m| m.name == KEYWORD_INSPECT) {
4322 out.push(FuncMeta {
4323 name: KEYWORD_INSPECT.to_string(),
4324 module: STD_MODULE_NAME.to_string(),
4325 kind: FuncKind::HostCtx,
4326 params: None,
4327 returns: Some(TypeTag::Map),
4328 rpn: false,
4329 summary: "Inspect a variable binding.",
4330 docs: "INSPECT($var): dedicated AST node taking a variable, not a value.",
4331 examples: &[],
4332 });
4333 }
4334 out.sort_by(|a, b| a.name.cmp(&b.name));
4335 out
4336 }
4337
4338 pub fn describe_function(&self, name: &str) -> Option<Value> {
4340 if let Some(meta) = self.functions.meta(name) {
4341 return Some(meta_to_value(&meta));
4342 }
4343 if name == KEYWORD_INSPECT {
4345 return Some(meta_to_value(&FuncMeta {
4346 name: KEYWORD_INSPECT.to_string(),
4347 module: STD_MODULE_NAME.to_string(),
4348 kind: FuncKind::HostCtx,
4349 params: None,
4350 returns: Some(TypeTag::Map),
4351 rpn: false,
4352 summary: "Inspect a variable binding.",
4353 docs: "INSPECT($var): dedicated AST node taking a variable, not a value.",
4354 examples: &[],
4355 }));
4356 }
4357 None
4358 }
4359
4360 pub(super) fn clone_native_pure(&self, name: &str) -> Option<PureFn> {
4361 self.functions.clone_pure_fn(name)
4362 }
4363
4364 pub fn pure_function_table(&self) -> Arc<PureTable> {
4369 self.functions.pure_shared()
4370 }
4371
4372 pub(super) fn clone_native_ctx(&self, name: &str) -> Option<NativeFn<P>> {
4373 self.functions.clone_ctx_fn(name)
4374 }
4375
4376 pub(super) fn native_meta(&self, name: &str) -> Option<FuncMeta> {
4377 self.functions.meta(name)
4378 }
4379}
4380
4381#[cfg(test)]
4382mod tests {
4383 use super::*;
4384
4385 #[test]
4386 fn placeholder_resolver_dispatches_table_entries() {
4387 let echo: PureFn = Arc::new(|args| {
4391 args.into_iter()
4392 .next()
4393 .ok_or_else(|| anyhow::anyhow!("ECHO needs 1 arg"))
4394 });
4395 let mut entries = HashMap::new();
4396 entries.insert("ECHO".to_string(), echo);
4397 let mut table = PureTable::new();
4398 table.insert("T".to_string(), entries);
4399 let resolve = placeholder_resolver(Arc::new(table));
4400 let out = resolve("T", "ECHO", vec![Value::string("hi".to_string())]).expect("dispatch");
4401 assert_eq!(out.as_str().expect("string"), "hi");
4402 let err = format!(
4403 "{:#}",
4404 resolve("T", "NOPE", vec![]).expect_err("unknown must fail")
4405 );
4406 assert!(
4407 err.contains("unknown placeholder function 'T::NOPE'"),
4408 "names the call: {err}"
4409 );
4410 assert!(
4411 err.contains("known functions: T::ECHO"),
4412 "lists known names: {err}"
4413 );
4414 }
4415
4416 #[test]
4417 fn describe_entry_renders_union_spellings() {
4418 let union = oxdock_parser::union_tag!(String, Pipe);
4424 let meta = FuncMeta {
4425 name: "T::F".to_string(),
4426 module: "T".to_string(),
4427 kind: FuncKind::HostPure,
4428 params: Some(vec![FuncParam {
4429 name: "text".to_string(),
4430 param_type: Some(union.clone()),
4431 allowed: None,
4432 docs: "",
4433 options: None,
4434 optional: false,
4435 }]),
4436 returns: Some(union),
4437 rpn: false,
4438 summary: "test-only",
4439 docs: "test-only",
4440 examples: &[],
4441 };
4442 let value = meta_to_value(&meta);
4443 let map = value.as_map().expect("describe value is a map");
4444 let params = map
4445 .get("params")
4446 .expect("params key")
4447 .as_list()
4448 .expect("params is a list");
4449 let first = params[0].as_map().expect("entry is a map");
4450 assert_eq!(
4451 first.get("param_type").and_then(Value::as_str),
4452 Some("STRING|PIPE"),
4453 "param renders the set"
4454 );
4455 assert_eq!(
4456 map.get("returns").and_then(Value::as_str),
4457 Some("STRING|PIPE"),
4458 "returns render the set"
4459 );
4460 }
4461
4462 #[test]
4463 fn describe_entry_renders_handle_payload() {
4464 let meta = FuncMeta {
4468 name: "SCRIPT::FETCH".to_string(),
4469 module: "SCRIPT".to_string(),
4470 kind: FuncKind::Script,
4471 params: Some(vec![]),
4472 returns: Some(TypeTag::HandleOf(std::sync::Arc::new(TypeTag::String))),
4473 rpn: false,
4474 summary: "test-only",
4475 docs: "test-only",
4476 examples: &[],
4477 };
4478 let value = meta_to_value(&meta);
4479 let map = value.as_map().expect("describe value is a map");
4480 assert_eq!(
4481 map.get("returns").and_then(Value::as_str),
4482 Some("HANDLE<STRING>"),
4483 "returns render the payload"
4484 );
4485 }
4486
4487 #[test]
4488 fn describe_entry_carries_optional_flag() {
4489 let meta = FuncMeta {
4493 name: "T::F".to_string(),
4494 module: "T".to_string(),
4495 kind: FuncKind::HostPure,
4496 params: Some(vec![
4497 FuncParam {
4498 name: "url".to_string(),
4499 param_type: Some(TypeTag::String),
4500 allowed: None,
4501 docs: "",
4502 options: None,
4503 optional: false,
4504 },
4505 FuncParam {
4506 name: "options".to_string(),
4507 param_type: Some(TypeTag::Map),
4508 allowed: None,
4509 docs: "",
4510 options: None,
4511 optional: true,
4512 },
4513 ]),
4514 returns: Some(TypeTag::String),
4515 rpn: false,
4516 summary: "test-only",
4517 docs: "test-only",
4518 examples: &[],
4519 };
4520 let value = meta_to_value(&meta);
4521 let map = value.as_map().expect("describe value is a map");
4522 let params = map
4523 .get("params")
4524 .expect("params key")
4525 .as_list()
4526 .expect("params is a list");
4527 assert_eq!(params.len(), 2);
4528 let first = params[0].as_map().expect("entry is a map");
4529 let second = params[1].as_map().expect("entry is a map");
4530 assert_eq!(
4531 first.get("optional").and_then(Value::as_bool),
4532 Some(false),
4533 "required param must read false"
4534 );
4535 assert_eq!(
4536 second.get("optional").and_then(Value::as_bool),
4537 Some(true),
4538 "omittable param must read true"
4539 );
4540 }
4541
4542 #[test]
4543 fn template_twins_mirror_string_paths_and_refuse_pipes() {
4544 let pipe = Value::pipe_fresh();
4550 type TwinCase = (&'static str, Box<dyn Fn() -> Result<Value>>);
4551 let cases: Vec<TwinCase> = vec![
4552 (
4553 "TEXT_TRIM",
4554 Box::new(|| text_trim_string(Value::string(" hello ".to_string()))),
4555 ),
4556 (
4557 "TEXT_TRIM_PREFIX",
4558 Box::new(|| {
4559 text_trim_prefix_string(Value::string("v1".to_string()), "v".to_string())
4560 }),
4561 ),
4562 (
4563 "TEXT_TRIM_SUFFIX",
4564 Box::new(|| {
4565 text_trim_suffix_string(Value::string("a.gz".to_string()), "x".to_string())
4566 }),
4567 ),
4568 (
4569 "TEXT_TO_UPPER",
4570 Box::new(|| text_to_upper_string(Value::string("hi".to_string()))),
4571 ),
4572 (
4573 "TEXT_TO_LOWER",
4574 Box::new(|| text_to_lower_string(Value::string("HI".to_string()))),
4575 ),
4576 (
4577 "TEXT_REPLACE",
4578 Box::new(|| {
4579 text_replace_string(
4580 Value::string("ab".to_string()),
4581 "b".to_string(),
4582 "c".to_string(),
4583 )
4584 }),
4585 ),
4586 (
4587 "TEXT_REPLACE_REGEX",
4588 Box::new(|| {
4589 text_replace_regex_string(
4590 Value::string("ab".to_string()),
4591 "b".to_string(),
4592 "c".to_string(),
4593 )
4594 }),
4595 ),
4596 ];
4597 assert_eq!(cases.len(), 7, "every mirror op needs a twin row");
4598 for (name, run) in &cases {
4599 let value = run().unwrap_or_else(|e| panic!("{name} twin must answer strings: {e:#}"));
4600 assert!(
4601 value.as_str().is_some(),
4602 "{name} twin must answer STRING, got {}",
4603 value.type_name()
4604 );
4605 }
4606 assert_eq!(
4607 text_trim_string(Value::string(" hello ".to_string()))
4608 .expect("trim twin")
4609 .as_str(),
4610 Some("hello")
4611 );
4612 let pipe_cases: Vec<(&str, Result<Value>)> = vec![
4614 ("TEXT_TRIM", text_trim_string(pipe.clone())),
4615 (
4616 "TEXT_TRIM_PREFIX",
4617 text_trim_prefix_string(pipe.clone(), "v".to_string()),
4618 ),
4619 (
4620 "TEXT_TRIM_SUFFIX",
4621 text_trim_suffix_string(pipe.clone(), ".gz".to_string()),
4622 ),
4623 ("TEXT_TO_UPPER", text_to_upper_string(pipe.clone())),
4624 ("TEXT_TO_LOWER", text_to_lower_string(pipe.clone())),
4625 (
4626 "TEXT_REPLACE",
4627 text_replace_string(pipe.clone(), "a".to_string(), "b".to_string()),
4628 ),
4629 (
4630 "TEXT_REPLACE_REGEX",
4631 text_replace_regex_string(pipe.clone(), "a".to_string(), "b".to_string()),
4632 ),
4633 ];
4634 for (name, result) in pipe_cases {
4635 let err = result.expect_err(&format!("{name} twin must refuse PIPE"));
4636 assert!(
4637 format!("{err:#}").contains("step IO"),
4638 "{name} refusal names the missing context: {err:#}"
4639 );
4640 }
4641 }
4642
4643 #[test]
4644 fn shell_words_join_split_round_trip() {
4645 let words = vec![
4649 "gh".to_string(),
4650 "issue".to_string(),
4651 "comment".to_string(),
4652 "with spaces".to_string(),
4653 "it's".to_string(),
4654 "say \"hi\"".to_string(),
4655 "$HOME".to_string(),
4656 "$(whoami)".to_string(),
4657 "C:\\path\\to".to_string(),
4658 "naïve café".to_string(),
4659 "".to_string(),
4660 ];
4661 let joined = shell_words::join(&words);
4662 let back = shell_words::split(&joined).expect("join output must parse");
4663 assert_eq!(back, words);
4664 assert!(shell_words::split("unbalanced \"quote").is_err());
4665 }
4666}