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 Argv::registration(),
791 ParseArgs::registration(),
792 TextTrim::registration(),
793 TextTrimPrefix::registration(),
794 TextTrimSuffix::registration(),
795 PathJoin::registration(),
796 TextToUpper::registration(),
797 TextToLower::registration(),
798 TextReplace::registration(),
799 TextReplaceRegex::registration(),
800 TextSplit::registration(),
801 TextJoin::registration(),
802 TextLines::registration(),
803 TextFields::registration(),
804 TextMatch::registration(),
805 TextExtract::registration(),
806 TextStartsWith::registration(),
807 TextEndsWith::registration(),
808 TextContains::registration(),
809 Len::registration(),
810 TextCount::registration(),
811 TextCountMatches::registration(),
812 TextGrep::registration(),
813 TextLinesRange::registration(),
814 SemaphoreNew::registration(),
815 SemaphoreTryAcquire::registration(),
816 SemaphoreAvailable::registration(),
817 ShellSplitArgs::registration(),
818 ShellJoinArgs::registration(),
819 ]
820 }
821
822 pub(super) fn keys(&self) -> HashSet<String> {
825 self.entries.keys().cloned().collect()
826 }
827
828 pub(super) fn get(&self, name: &str) -> Option<FuncEntry<P>> {
830 self.entries.get(name).cloned()
831 }
832
833 pub(super) fn describe_unit_placeholder_miss(
839 &self,
840 unit_targets: &AliasTargets,
841 module: &str,
842 name: &str,
843 ) -> Option<String> {
844 let qualified = qualify(module, name);
845 match classify_alias_call(unit_targets, &qualified, &|key| {
850 self.entries.contains_key(key)
851 }) {
852 AliasResolution::Canonical(canonical) => {
853 if let Some(entry) = self.entries.get(&canonical) {
854 if let Some(miss) = Self::placeholder_miss_for_body(module, name, &entry.body) {
855 return Some(miss);
856 }
857 None
858 } else {
859 describe_placeholder_miss(module, name, false, false, true)
860 }
861 }
862 AliasResolution::Global => {
863 if let Some(entry) = self.entries.get(&qualified) {
864 if let Some(miss) = Self::placeholder_miss_for_body(module, name, &entry.body) {
868 return Some(miss);
869 }
870 }
871 None
872 }
873 AliasResolution::Ambiguous { files, .. } => {
874 Some(ambiguous_alias_message(module, name, &files))
875 }
876 AliasResolution::Unknown => describe_placeholder_miss(module, name, false, false, true),
877 AliasResolution::Any {
883 base,
884 files,
885 has_host,
886 } => Some(disjoint_alias_placeholder_miss(
887 module,
888 name,
889 &base,
890 &files,
891 has_host,
892 &|key| matches!(self.entries.get(key), Some(entry) if matches!(entry.body, FuncBody::Script(_))),
893 )),
894 }
895 }
896
897 fn placeholder_miss_for_body(module: &str, name: &str, body: &FuncBody<P>) -> Option<String> {
901 match body {
902 FuncBody::Script(_) => describe_placeholder_miss(module, name, true, false, false),
903 FuncBody::Ctx(_) => describe_placeholder_miss(module, name, false, true, false),
904 FuncBody::Pure(_) | FuncBody::Both { .. } => None,
905 }
906 }
907
908 pub(super) fn placeholder_snapshot(&self, unit_targets: &AliasTargets) -> PlaceholderClasses {
912 let mut script = HashSet::new();
913 let mut stateful = HashSet::new();
914 let mut ambiguous: HashMap<String, HashSet<String>> = HashMap::new();
915 for (key, entry) in self.entries.iter() {
916 let Some((module, base)) = split_qualified(key) else {
917 continue;
918 };
919 match &entry.body {
920 FuncBody::Script(def) => {
921 if module == SCRIPT_MODULE_NAME {
922 script.insert(key.clone());
924 continue;
925 }
926 let defining = def.module.as_deref().unwrap_or(module);
934 let (direct, ambiguous_here) = spellings_for_defining_file(
935 unit_targets,
936 defining,
937 base,
938 &|key| matches!(self.entries.get(key), Some(entry) if matches!(entry.body, FuncBody::Script(_))),
939 );
940 script.extend(direct);
941 for (spelling, files) in ambiguous_here {
942 ambiguous.entry(spelling).or_default().extend(files);
943 }
944 }
945 FuncBody::Ctx(_) => {
946 stateful.insert(key.clone());
947 }
948 FuncBody::Pure(_) | FuncBody::Both { .. } => {}
949 }
950 }
951 let aliases = unit_targets.keys().cloned().collect();
952 PlaceholderClasses {
953 script,
954 stateful,
955 aliases,
956 ambiguous,
957 }
958 }
959
960 fn insert_native(&mut self, name: String, meta: FuncMeta, body: FuncBody<P>) {
961 self.entries.insert(name, FuncEntry { meta, body });
962 self.rebuild_pure_shared();
963 }
964
965 fn rebuild_pure_shared(&mut self) {
971 let mut table: PureTable = HashMap::new();
972 for (name, entry) in &self.entries {
973 let func = match &entry.body {
974 FuncBody::Pure(func) => func,
975 FuncBody::Both { pure, .. } => pure,
976 FuncBody::Script(_) | FuncBody::Ctx(_) => continue,
977 };
978 if let Some((module, base)) = split_qualified(name) {
979 table
980 .entry(module.to_string())
981 .or_default()
982 .insert(base.to_string(), Arc::clone(func));
983 }
984 }
985 self.pure_shared = Arc::new(table);
986 }
987
988 fn insert_qualified(
992 &mut self,
993 module: &str,
994 base: String,
995 mut meta: FuncMeta,
996 body: FuncBody<P>,
997 ) {
998 meta.name = qualify(module, &base);
999 meta.module = module.to_string();
1000 if self.entries.contains_key(&meta.name) {
1005 panic!("duplicate function registration `{}`", meta.name);
1006 }
1007 self.insert_native(meta.name.clone(), meta, body);
1008 }
1009
1010 pub(super) fn register_host(
1011 &mut self,
1012 module: &str,
1013 name: String,
1014 mut meta: FuncMeta,
1015 func: NativeFn<P>,
1016 ) {
1017 meta.kind = FuncKind::HostCtx;
1018 self.insert_qualified(module, name, meta, FuncBody::Ctx(func));
1019 }
1020
1021 pub(super) fn register_pure_host(
1022 &mut self,
1023 module: &str,
1024 name: String,
1025 mut meta: FuncMeta,
1026 func: PureFn,
1027 ) {
1028 meta.kind = FuncKind::HostPure;
1029 self.insert_qualified(module, name, meta, FuncBody::Pure(func));
1030 }
1031
1032 pub(super) fn register_both_host(
1033 &mut self,
1034 module: &str,
1035 name: String,
1036 mut meta: FuncMeta,
1037 func: NativeFn<P>,
1038 template: PureFn,
1039 ) {
1040 meta.kind = FuncKind::HostCtx;
1041 self.insert_qualified(
1042 module,
1043 name,
1044 meta,
1045 FuncBody::Both {
1046 pure: template,
1047 ctx: func,
1048 },
1049 );
1050 }
1051
1052 #[allow(clippy::too_many_arguments)]
1057 pub(super) fn define_script(
1058 &mut self,
1059 name: &str,
1060 params: &[(String, TypeTag, bool)],
1061 return_type: TypeTag,
1062 return_spelling: &str,
1063 is_async: bool,
1064 body: &[Step],
1065 module: Option<&str>,
1066 ) -> Result<()> {
1067 let qualified = qualify(SCRIPT_MODULE_NAME, name);
1068 let shadowable = matches!(
1069 self.entries.get(&qualified).map(|entry| &entry.body),
1070 Some(FuncBody::Script(_))
1071 );
1072 let reserved = self.entries.iter().any(|(key, entry)| {
1077 split_qualified(key).is_some_and(|(_, base)| base == name)
1078 && !matches!(entry.body, FuncBody::Script(_))
1079 });
1080 if reserved && !shadowable {
1081 anyhow::bail!("cannot shadow reserved function `{name}`");
1082 }
1083 if self
1084 .scopes
1085 .last()
1086 .is_some_and(|frame| frame.defined.contains(&qualified))
1087 {
1088 anyhow::bail!("duplicate function `{name}` in same scope");
1089 }
1090 check_script_param_tags(name, params)?;
1091 let old = self.entries.insert(
1092 qualified.clone(),
1093 FuncEntry {
1094 meta: FuncMeta {
1095 name: qualified.clone(),
1096 module: SCRIPT_MODULE_NAME.to_string(),
1097 kind: FuncKind::Script,
1098 params: Some(
1099 params
1100 .iter()
1101 .map(|(pname, param_type, optional)| {
1102 Ok(FuncParam {
1103 name: pname.clone(),
1104 param_type: Some(param_type.clone()),
1105 allowed: None,
1106 docs: "",
1109 options: None,
1110 optional: *optional,
1111 })
1112 })
1113 .collect::<Result<_>>()?,
1114 ),
1115 returns: Some(return_type.clone()),
1116 rpn: false,
1117 summary: "DSL-defined function.",
1118 docs: "Defined via FUNC in script.",
1119 examples: &[],
1120 },
1121 body: FuncBody::Script(FuncDefData {
1122 params: params.to_vec(),
1123 return_type,
1124 return_spelling: return_spelling.to_string(),
1125 is_async,
1126 body: body.to_vec(),
1127 module: module.map(|m| m.to_string()),
1128 }),
1129 },
1130 );
1131 if let Some(frame) = self.scopes.last_mut() {
1132 frame.defined.insert(qualified.clone());
1133 if let Some(old) = old {
1134 frame.shadowed.push((qualified, old));
1135 }
1136 }
1137 Ok(())
1138 }
1139
1140 #[allow(clippy::too_many_arguments)]
1146 pub(super) fn define_file_func(
1147 &mut self,
1148 name: &str,
1149 params: &[(String, TypeTag, bool)],
1150 return_type: TypeTag,
1151 return_spelling: &str,
1152 is_async: bool,
1153 body: &[Step],
1154 defining: &str,
1155 ) -> Result<()> {
1156 let qualified = file_func_key(defining, name);
1160 let shadowable = matches!(
1161 self.entries.get(&qualified).map(|entry| &entry.body),
1162 Some(FuncBody::Script(_))
1163 );
1164 let reserved = self.entries.iter().any(|(key, entry)| {
1168 split_qualified(key).is_some_and(|(_, base)| base == name)
1169 && !matches!(entry.body, FuncBody::Script(_))
1170 });
1171 if reserved && !shadowable {
1172 anyhow::bail!("cannot shadow reserved function `{name}`");
1173 }
1174 let frame_idx = 0;
1178 if self
1179 .scopes
1180 .get(frame_idx)
1181 .is_some_and(|frame| frame.defined.contains(&qualified))
1182 {
1183 anyhow::bail!("duplicate function `{name}` in same scope");
1184 }
1185 check_script_param_tags(name, params)?;
1186 let old = self.entries.insert(
1187 qualified.clone(),
1188 FuncEntry {
1189 meta: FuncMeta {
1190 name: qualified.clone(),
1191 module: defining.to_string(),
1192 kind: FuncKind::Script,
1193 params: Some(
1194 params
1195 .iter()
1196 .map(|(pname, param_type, optional)| {
1197 Ok(FuncParam {
1198 name: pname.clone(),
1199 param_type: Some(param_type.clone()),
1200 allowed: None,
1201 docs: "",
1202 options: None,
1203 optional: *optional,
1204 })
1205 })
1206 .collect::<Result<_>>()?,
1207 ),
1208 returns: Some(return_type.clone()),
1209 rpn: false,
1210 summary: "DSL-defined function.",
1211 docs: "Defined via FUNC in an imported script.",
1212 examples: &[],
1213 },
1214 body: FuncBody::Script(FuncDefData {
1215 params: params.to_vec(),
1216 return_type,
1217 return_spelling: return_spelling.to_string(),
1218 is_async,
1219 body: body.to_vec(),
1220 module: Some(defining.to_string()),
1221 }),
1222 },
1223 );
1224 if let Some(frame) = self.scopes.get_mut(frame_idx) {
1225 frame.defined.insert(qualified.clone());
1226 if let Some(old) = old {
1227 frame.shadowed.push((qualified, old));
1228 }
1229 }
1230 Ok(())
1231 }
1232
1233 pub(super) fn push_scope(&mut self) {
1236 self.scopes.push(ScopeFrame {
1237 defined: HashSet::new(),
1238 shadowed: Vec::new(),
1239 });
1240 }
1241
1242 pub(super) fn pop_scope(&mut self) {
1245 let Some(frame) = self.scopes.pop() else {
1246 return;
1247 };
1248 for name in frame.defined {
1249 self.entries.remove(&name);
1250 }
1251 for (name, old) in frame.shadowed {
1252 self.entries.insert(name, old);
1253 }
1254 }
1255
1256 pub(super) fn contains_script(&self, name: &str) -> bool {
1261 matches!(
1262 self.entries.get(name).map(|entry| &entry.body),
1263 Some(FuncBody::Script(_))
1264 )
1265 }
1266
1267 pub(super) fn resolve_file_call_key(
1270 &self,
1271 unit_targets: &AliasTargets,
1272 name: &str,
1273 ) -> Result<Option<String>> {
1274 match classify_alias_call(unit_targets, name, &|key| self.entries.contains_key(key)) {
1275 AliasResolution::Global | AliasResolution::Unknown | AliasResolution::Any { .. } => {
1276 Ok(None)
1277 }
1278 AliasResolution::Canonical(key) => Ok(Some(key)),
1279 AliasResolution::Ambiguous { alias, base, files } => Err(anyhow::anyhow!(
1280 "{}",
1281 ambiguous_alias_message(&alias, &base, &files)
1282 )),
1283 }
1284 }
1285
1286 fn clone_pure_fn(&self, name: &str) -> Option<PureFn> {
1290 match self.entries.get(name)?.body {
1291 FuncBody::Pure(ref func) => Some(Arc::clone(func)),
1292 FuncBody::Both { ref pure, .. } => Some(Arc::clone(pure)),
1293 _ => None,
1294 }
1295 }
1296
1297 pub(super) fn pure_shared(&self) -> Arc<PureTable> {
1301 Arc::clone(&self.pure_shared)
1302 }
1303
1304 pub(super) fn all_metas(&self) -> Vec<FuncMeta> {
1307 self.entries_metas()
1308 }
1309
1310 fn clone_ctx_fn(&self, name: &str) -> Option<NativeFn<P>> {
1315 match self.entries.get(name)?.body {
1316 FuncBody::Ctx(ref func) => Some(Arc::clone(func)),
1317 FuncBody::Both { ref ctx, .. } => Some(Arc::clone(ctx)),
1318 _ => None,
1319 }
1320 }
1321
1322 fn meta(&self, name: &str) -> Option<FuncMeta> {
1323 self.entries.get(name).map(|entry| entry.meta.clone())
1324 }
1325
1326 fn native_metas(&self) -> Vec<FuncMeta> {
1327 let mut out: Vec<FuncMeta> = Vec::new();
1328 for entry in self.entries.values() {
1329 if !matches!(entry.body, FuncBody::Script(_)) {
1330 out.push(entry.meta.clone());
1331 }
1332 }
1333 out.sort_by(|a, b| a.name.cmp(&b.name));
1334 out
1335 }
1336
1337 pub(super) fn pure_metas(&self) -> Vec<FuncMeta> {
1342 let mut out: Vec<FuncMeta> = Vec::new();
1343 for entry in self.entries.values() {
1344 if matches!(entry.body, FuncBody::Pure(_) | FuncBody::Both { .. }) {
1345 out.push(entry.meta.clone());
1346 }
1347 }
1348 out.sort_by(|a, b| a.name.cmp(&b.name));
1349 out
1350 }
1351
1352 fn entries_metas(&self) -> Vec<FuncMeta> {
1355 let mut out: Vec<FuncMeta> = self
1356 .entries
1357 .values()
1358 .map(|entry| entry.meta.clone())
1359 .collect();
1360 out.sort_by(|a, b| a.name.cmp(&b.name));
1361 out
1362 }
1363
1364 pub fn set_script_docs(&mut self, docs: &HashMap<String, (String, String)>) {
1367 for (base, pair) in docs {
1368 self.script_docs
1369 .insert(qualify(SCRIPT_MODULE_NAME, base), pair.clone());
1370 }
1371 }
1372
1373 pub fn script_doc_for(&self, qualified: &str) -> Option<(String, String)> {
1375 self.script_docs.get(qualified).cloned()
1376 }
1377
1378 pub fn exported_metas(
1383 &self,
1384 func_exports: &[String],
1385 unit_targets: &AliasTargets,
1386 ) -> anyhow::Result<Vec<FuncMeta>> {
1387 let mut out = Vec::with_capacity(func_exports.len());
1388 for name in func_exports {
1389 let qualified = match split_qualified(name) {
1393 None => qualify(SCRIPT_MODULE_NAME, name),
1394 Some(_) => name.clone(),
1395 };
1396 let lookup = self
1397 .resolve_file_call_key(unit_targets, &qualified)?
1398 .unwrap_or_else(|| qualified.clone());
1399 if let Some(entry) = self.entries.get(&lookup) {
1400 let mut meta = entry.meta.clone();
1401 if lookup != qualified {
1402 meta.name = name.clone();
1403 }
1404 out.push(meta);
1405 continue;
1406 }
1407 anyhow::bail!(
1408 "EXPORT `{name}` matches no defined script function or known host function"
1409 );
1410 }
1411 Ok(out)
1412 }
1413}
1414
1415impl<P: ProcessManager> Clone for FunctionRegistry<P> {
1416 fn clone(&self) -> Self {
1417 Self {
1418 entries: self.entries.clone(),
1419 scopes: self.scopes.clone(),
1420 pure_shared: Arc::clone(&self.pure_shared),
1421 script_docs: self.script_docs.clone(),
1422 }
1423 }
1424}
1425
1426pub fn builtin_function_names() -> HashSet<String> {
1433 let mut names = FunctionRegistry::<DefaultProcessManager>::with_builtins().keys();
1434 names.insert(KEYWORD_INSPECT.to_string());
1435 names
1436}
1437
1438pub fn builtin_function_metas() -> Vec<FuncMeta> {
1442 FunctionRegistry::<DefaultProcessManager>::with_builtins().native_metas()
1443}
1444
1445pub fn std_module_table() -> oxdock_parser::ModuleTable {
1450 let func_names: HashSet<String> = builtin_function_metas()
1452 .into_iter()
1453 .map(|meta| base_name(&meta.name).to_string())
1454 .collect();
1455 oxdock_parser::ModuleTable {
1456 modules: HashMap::from([(
1457 STD_MODULE_NAME.to_string(),
1458 Some(oxdock_parser::ModuleFuncs { func_names }),
1459 )]),
1460 }
1461}
1462
1463#[oxdock_func(pure, returns = TypeTag::Int)]
1476#[example(
1477 name = "convert",
1478 code = r###"
1479 IMPORT [STD]
1480 LET $n: INT = INT("42")
1481 ASSERT_EQ $n 42
1482 LET $flag: INT = INT(true)
1483 ASSERT_EQ $flag 1
1484 "###
1485)]
1486fn int(
1487 #[union(Int, Float, String, Bool)]
1489 val: Value,
1490) -> Result<Value> {
1491 super::args::int_from_value(val)
1492}
1493
1494#[oxdock_func(pure, returns = TypeTag::Float)]
1499#[example(
1500 name = "convert",
1501 code = r###"
1502 IMPORT [STD]
1503 LET $f: FLOAT = FLOAT("1.5")
1504 ASSERT_EQ $f 1.5
1505 LET $whole: FLOAT = FLOAT(2)
1506 ASSERT_EQ $whole 2.0
1507 "###
1508)]
1509fn float(
1510 #[union(Float, Int, String)]
1512 val: Value,
1513) -> Result<Value> {
1514 super::args::float_from_value(val)
1515}
1516
1517#[oxdock_func(pure, returns = TypeTag::String)]
1522#[example(
1523 name = "format and round-trip",
1524 code = r###"
1525 # Byte counts render in the largest exact unit.
1526 IMPORT [STD]
1527 LET $pretty: STRING = FORMAT_BYTE_COUNT(1_048_576)
1528 ASSERT_EQ $pretty "1MiB"
1529
1530 # The pair round-trips through the parser.
1531 LET $back: INT = PARSE_BYTE_COUNT($pretty)
1532 ASSERT_EQ $back 1_048_576
1533 "###
1534)]
1535fn format_byte_count(
1536 bytes: i64,
1538) -> Result<Value> {
1539 if bytes < 0 {
1540 return Err(anyhow::anyhow!(
1541 "FORMAT_BYTE_COUNT needs a non-negative byte count, got {bytes}"
1542 ));
1543 }
1544 Ok(Value::string(oxdock_parser::command::format_byte_count(
1545 bytes as u64,
1546 )))
1547}
1548
1549#[oxdock_func(pure, returns = TypeTag::Int)]
1584#[example(
1585 name = "parse",
1586 code = r###"
1587 IMPORT [STD]
1588 LET $n: INT = PARSE_BYTE_COUNT("10KB")
1589 ASSERT_EQ $n 10_000
1590 LET $identity: INT = PARSE_BYTE_COUNT(512)
1591 ASSERT_EQ $identity 512
1592 "###
1593)]
1594fn parse_byte_count(
1595 #[union(Int, Float, String)]
1597 text: Value,
1598) -> Result<Value> {
1599 if let Some(n) = text.as_i64() {
1600 if n < 0 {
1601 return Err(anyhow::anyhow!(
1602 "PARSE_BYTE_COUNT needs a non-negative byte count, got {n}"
1603 ));
1604 }
1605 return Ok(Value::int(n));
1606 }
1607 if let Some(f) = text.as_f64() {
1608 if f.is_finite() && f.fract() == 0.0 && f >= 0.0 && f <= i64::MAX as f64 {
1609 return Ok(Value::int(f as i64));
1610 }
1611 return Err(anyhow::anyhow!(
1612 "PARSE_BYTE_COUNT needs an integral byte count, got {f:?}"
1613 ));
1614 }
1615 let Some(s) = text.as_str() else {
1616 return Err(anyhow::anyhow!(
1617 "PARSE_BYTE_COUNT needs a token or number, found {text:?}"
1618 ));
1619 };
1620 let n = oxdock_parser::command::parse_byte_count(s)?;
1621 let n = i64::try_from(n)
1622 .map_err(|_| anyhow::anyhow!("PARSE_BYTE_COUNT out of INT range: {s:?}"))?;
1623 Ok(Value::int(n))
1624}
1625
1626#[oxdock_func(pure, returns = TypeTag::String)]
1631#[example(
1632 name = "format and round-trip",
1633 code = r###"
1634 # Durations render in the largest exact unit.
1635 IMPORT [STD]
1636 LET $pretty: STRING = FORMAT_DURATION(90_000)
1637 ASSERT_EQ $pretty "90s"
1638
1639 # The pair round-trips through the parser.
1640 LET $back: INT = PARSE_DURATION($pretty)
1641 ASSERT_EQ $back 90_000
1642 "###
1643)]
1644fn format_duration(
1645 millis: i64,
1647) -> Result<Value> {
1648 if millis < 0 {
1649 return Err(anyhow::anyhow!(
1650 "FORMAT_DURATION needs non-negative milliseconds, got {millis}"
1651 ));
1652 }
1653 Ok(Value::string(oxdock_parser::command::format_duration(
1654 &std::time::Duration::from_millis(millis as u64),
1655 )))
1656}
1657
1658#[oxdock_func(pure, returns = TypeTag::Int)]
1664#[example(
1665 name = "parse",
1666 code = r###"
1667 # A bare number means seconds, like TIMEOUT.
1668 IMPORT [STD]
1669 LET $ms: INT = PARSE_DURATION("2m")
1670 ASSERT_EQ $ms 120_000
1671
1672 # Milliseconds stay exact.
1673 LET $exact: INT = PARSE_DURATION("1500ms")
1674 ASSERT_EQ $exact 1_500
1675
1676 # One optional space separates number from unit.
1677 LET $spaced: INT = PARSE_DURATION("1 h")
1678 ASSERT_EQ $spaced 3_600_000
1679 "###
1680)]
1681fn parse_duration(
1682 text: String,
1684) -> Result<Value> {
1685 let duration = oxdock_parser::command::parse_duration(&text)?;
1686 let millis = i64::try_from(duration.as_millis())
1687 .map_err(|_| anyhow::anyhow!("PARSE_DURATION out of INT range: {text:?}"))?;
1688 Ok(Value::int(millis))
1689}
1690
1691#[oxdock_func(rpn, returns = TypeTag::ListOf(std::sync::Arc::new(TypeTag::String)))]
1696#[example(
1697 name = "match",
1698 code = r###"
1699 IMPORT [STD]
1700 WRITE "notes-a.md" "a"
1701 WRITE "notes-b.md" "b"
1702 WRITE "other.txt" "c"
1703 LET $found: LIST<STRING> = GLOB("notes-*.md")
1704 ASSERT_EQ $found.0 "notes-a.md"
1705 ASSERT_EQ $found.1 "notes-b.md"
1706 "###
1707)]
1708fn glob<P: ProcessManager>(
1709 cx: &mut StepCtx<P>,
1710 #[union(String, Path)]
1712 pattern: Value,
1713) -> Result<Value> {
1714 let text = super::args::string_or_path_text(&pattern)?;
1715 super::args::glob_from_value(&[Value::string(text)], cx)
1716}
1717
1718#[oxdock_func(rpn, returns = TypeTag::MapOf(std::sync::Arc::new(TypeTag::Any)))]
1723#[example(
1724 name = "load",
1725 code = r###"
1726 IMPORT [STD]
1727 WRITE "cfg.toml" "title = \"demo\""
1728 LET $cfg: MAP<ANY> = LOAD_TOML("cfg.toml")
1729 ASSERT_EQ $cfg.title "demo"
1730 "###
1731)]
1732fn load_toml<P: ProcessManager>(
1733 cx: &mut StepCtx<P>,
1734 #[union(String, Path)]
1736 path: Value,
1737) -> Result<Value> {
1738 let text = super::args::string_or_path_text(&path)?;
1739 super::args::load_toml_from_value(&[Value::string(text)], cx)
1740}
1741
1742#[oxdock_func(rpn, returns = TypeTag::Any)]
1750#[example(
1751 name = "load",
1752 code = r###"
1753 IMPORT [STD]
1754 WRITE "data.json" "{\"a\": 1}"
1755 LET $doc: MAP<ANY> = LOAD_JSON("data.json")
1756 ASSERT_EQ $doc.a 1
1757 "###
1758)]
1759fn load_json<P: ProcessManager>(
1760 cx: &mut StepCtx<P>,
1761 #[union(String, Path)]
1763 path: Value,
1764) -> Result<Value> {
1765 let text = super::args::string_or_path_text(&path)?;
1766 super::args::load_json_from_value(&[Value::string(text)], cx)
1767}
1768
1769#[oxdock_func(rpn, returns = TypeTag::String)]
1779#[example(
1780 name = "hash",
1781 code = r###"
1782 IMPORT [STD]
1783 WRITE payload.txt hello
1784 LET $digest: STRING = HASH_SHA256("payload.txt")
1785 ASSERT_EQ $digest "2cf24dba5fb0a30e26e83b2ac5b9e29e1b161e5c1fa7425e73043362938b9824"
1786 "###
1787)]
1788fn hash_sha256<P: ProcessManager>(
1789 cx: &mut StepCtx<P>,
1790 #[union(String, Path)]
1792 path: Value,
1793) -> Result<Value> {
1794 use sha2::Digest;
1795
1796 let text = super::args::string_or_path_text(&path)?;
1797 let target = cx.state.fs.resolve_read(&cx.state.cwd, &text)?;
1798 let mut hasher = sha2::Sha256::new();
1799 super::fs_ops::hash_path(cx.state.fs.as_ref(), &target, "", &mut hasher)?;
1800 let digest = hasher.finalize();
1801 let bytes: &[u8] = digest.as_ref();
1802 Ok(Value::string(oxdock_utils::hex_encode(bytes)))
1803}
1804
1805#[oxdock_func(rpn, returns = TypeTag::String)]
1816#[example(
1817 name = "cwd",
1818 code = r###"
1819 IMPORT [STD]
1820 WORKDIR sub
1821 LET $c: STRING = CWD()
1822 ASSERT_CONTAINS $c "sub"
1823 "###
1824)]
1825fn cwd<P: ProcessManager>(cx: &mut StepCtx<P>) -> Result<Value> {
1826 if cx.state.fs.is_snapshot_pending() {
1827 return Ok(Value::string(super::SNAPSHOT_PENDING_DISPLAY.to_string()));
1828 }
1829 let concrete = cx.state.fs.concretize_cwd(&cx.state.cwd);
1830 let real = super::fs_ops::canonical_cwd(cx.state.fs.as_ref(), &concrete)?;
1831 Ok(Value::string(real))
1832}
1833
1834#[oxdock_func(pure, returns = TypeTag::MapOf(std::sync::Arc::new(TypeTag::Any)))]
1840#[example(
1841 name = "parse",
1842 code = r###"
1843 IMPORT [STD]
1844 LET $doc: MAP<ANY> = PARSE_TOML("title = \"demo\"")
1845 ASSERT_EQ $doc.title "demo"
1846 "###
1847)]
1848fn parse_toml(
1849 text: String,
1851) -> Result<Value> {
1852 super::args::parse_toml_from_value(Value::string(text))
1853}
1854
1855#[oxdock_func(pure, returns = TypeTag::Any)]
1864#[example(
1865 name = "parse",
1866 code = r###"
1867 # Parse in-memory JSON text with the same conversion as file loading.
1868 IMPORT [STD]
1869 LET $body: STRING = "{\"a\": 1}"
1870 LET $doc: ANY = PARSE_JSON($body)
1871 ASSERT_EQ $doc.a 1
1872
1873 # Top-level arrays parse to LIST, which is why the return is ANY.
1874 LET $items: LIST<ANY> = PARSE_JSON("[1, 2]")
1875 ASSERT_EQ $items.0 1
1876 ASSERT_EQ $items.1 2
1877 "###
1878)]
1879fn parse_json(
1880 text: String,
1882) -> Result<Value> {
1883 super::args::parse_json_from_value(Value::string(text))
1884}
1885
1886#[oxdock_func(returns = TypeTag::String)]
1892#[example(
1893 name = "describe",
1894 code = r###"
1895 IMPORT [STD]
1896 WRITE "entry.txt" "words"
1897 LET $kind: STRING = PATH_TYPE("entry.txt")
1898 ASSERT_EQ $kind "file"
1899 LET $missing: STRING = PATH_TYPE("no-such-entry.txt")
1900 ASSERT_EQ $missing "absent"
1901 "###
1902)]
1903fn path_type<P: ProcessManager>(
1904 cx: &mut StepCtx<P>,
1905 #[union(String, Path)]
1907 path: Value,
1908) -> Result<Value> {
1909 let text = super::args::string_or_path_text(&path)?;
1910 super::args::path_type_from_value(&[Value::string(text)], cx)
1911}
1912
1913#[oxdock_func(returns = TypeTag::Bool)]
1922#[example(
1923 name = "probe",
1924 code = r###"
1925 # An absent nested path is writable when its ancestor is.
1926 IMPORT [STD]
1927 LET $fresh: BOOL = PATH_WRITABLE("probe-check/nested/file.txt")
1928 ASSERT_EQ $fresh true
1929
1930 # The empty string never aliases the working directory.
1931 LET $empty: BOOL = PATH_WRITABLE("")
1932 ASSERT_EQ $empty false
1933 "###
1934)]
1935fn path_writable<P: ProcessManager>(
1936 cx: &mut StepCtx<P>,
1937 #[union(String, Path)]
1939 path: Value,
1940) -> Result<Value> {
1941 let text = super::args::string_or_path_text(&path)?;
1942 super::args::path_writable_from_value(&[Value::string(text)], cx)
1943}
1944
1945#[oxdock_func(returns = TypeTag::Bool)]
1958#[example(
1959 name = "probe",
1960 code = r###"
1961 # Missing tools read false instead of failing the run.
1962 IMPORT [STD]
1963 LET $missing: BOOL = IS_EXEC("no-such-tool-xyz")
1964 ASSERT_EQ $missing false
1965
1966 # Plain files are not executable on any platform.
1967 WRITE tool.txt payload
1968 LET $plain: BOOL = IS_EXEC("tool.txt")
1969 ASSERT_EQ $plain false
1970 "###
1971)]
1972fn is_exec<P: ProcessManager>(
1973 cx: &mut StepCtx<P>,
1974 #[union(String, Path)]
1976 name: Value,
1977) -> Result<Value> {
1978 let text = super::args::string_or_path_text(&name)?;
1979 super::args::is_exec_from_value(&[Value::string(text)], cx)
1980}
1981
1982#[oxdock_func(pure, returns = TypeTag::Bool)]
1988#[example(
1989 name = "probe",
1990 code = r###"
1991 IMPORT [STD]
1992 LET $m: MAP<ANY> = PARSE_JSON("{\"a\": 1}")
1993 LET $hit: BOOL = HAS_KEY($m, "a")
1994 ASSERT_EQ $hit true
1995 LET $miss: BOOL = HAS_KEY($m, "b")
1996 ASSERT_EQ $miss false
1997 "###
1998)]
1999fn has_key(
2000 map: BTreeMap<String, Value>,
2002 key: String,
2004) -> Result<Value> {
2005 super::args::has_key_from_value(Value::map(map), &key)
2006}
2007
2008#[oxdock_func(pure, returns = TypeTag::MapOf(std::sync::Arc::new(TypeTag::Any)))]
2014#[example(
2015 name = "insert",
2016 code = r###"
2017 IMPORT [STD]
2018 LET $m: MAP<ANY> = MAP_SET({seed: 0}, "a", 1)
2019 ASSERT_EQ $m.a 1
2020 "###
2021)]
2022fn map_set(
2023 map: BTreeMap<String, Value>,
2025 key: String,
2027 value: Value,
2029) -> Result<Value> {
2030 super::args::map_set_from_value(Value::map(map), key, value)
2031}
2032
2033#[oxdock_func(returns = TypeTag::Float, summary = "Draw a random FLOAT uniformly from [0, 1), optionally seeded.")]
2041#[example(
2042 name = "seeded draw",
2043 code = r###"
2044 # A seed draws the same value on every run.
2045 IMPORT [STD]
2046 LET $one: FLOAT = RAND({seed: 7})
2047 LET $two: FLOAT = RAND({seed: 7})
2048 ASSERT_EQ $one $two
2049 "###
2050)]
2051#[example(
2052 name = "unseeded draw",
2053 code = r###"
2054 # Scale a unit draw into a backoff delay between 1 and 11 seconds.
2055 IMPORT [STD]
2056 LET $draw: FLOAT = RAND()
2057 LET $delay: FLOAT = 1.0 + $draw * 10.0
2058 IF $delay < 1.0 {
2059 EXIT 1
2060 }
2061 IF $delay >= 11.0 {
2062 EXIT 1
2063 }
2064 ECHO "retrying in {{ $delay }}s"
2065 "###
2066)]
2067fn rand<P: ProcessManager>(
2068 cx: &mut StepCtx<P>,
2069 #[options("seed?: INT")]
2071 #[optional]
2072 options: BTreeMap<String, Value>,
2073) -> Result<Value> {
2074 let _ = cx;
2075 let seed = options
2078 .get("seed")
2079 .map(|value| value.as_i64().expect("check_options verified INT"));
2080 super::args::rand_float_from_value(seed)
2081}
2082
2083#[oxdock_func(pure, returns = TypeTag::String)]
2089#[example(
2090 name = "encode",
2091 code = r###"
2092 # Encode text to standard base64.
2093 IMPORT [STD]
2094 LET $encoded: STRING = BASE64_ENCODE("hello")
2095 ASSERT_EQ $encoded "aGVsbG8="
2096 "###
2097)]
2098fn base64_encode(
2099 text: String,
2101) -> Result<Value> {
2102 super::args::base64_encode_from_value(Value::string(text))
2103}
2104
2105#[oxdock_func(pure, returns = TypeTag::String)]
2112#[example(
2113 name = "decode",
2114 code = r###"
2115 # Decode standard base64 back to text.
2116 IMPORT [STD]
2117 LET $decoded: STRING = BASE64_DECODE("aGVsbG8=")
2118 ASSERT_EQ $decoded "hello"
2119 "###
2120)]
2121fn base64_decode(
2122 text: String,
2124) -> Result<Value> {
2125 super::args::base64_decode_from_value(Value::string(text))
2126}
2127
2128#[oxdock_func(pure, returns = TypeTag::String)]
2135#[example(
2136 name = "encode",
2137 code = r###"
2138 IMPORT [STD]
2139 LET $json: STRING = TO_JSON({a: 1})
2140 ASSERT_EQ $json "{\"a\":1}\n"
2141 "###
2142)]
2143fn to_json(
2144 #[union(String, Int, Float, Bool, List, Map)]
2146 value: Value,
2147) -> Result<Value> {
2148 super::args::to_json_from_value(value)
2149}
2150
2151#[oxdock_func(pure, returns = TypeTag::String)]
2159#[example(
2160 name = "name the word",
2161 code = r###"
2162 IMPORT [STD]
2163 LET $word: STRING = TYPE_OF(42)
2164 ASSERT_EQ $word "INT"
2165 "###
2166)]
2167fn type_of(
2168 value: Value,
2170) -> Result<Value> {
2171 super::args::type_of_from_value(value)
2172}
2173
2174#[oxdock_func(pure, returns = TypeTag::MapOf(std::sync::Arc::new(TypeTag::Any)))]
2182#[example(
2183 name = "merge",
2184 code = r###"
2185 IMPORT [STD]
2186 LET $m: MAP<ANY> = MERGE_MAPS([{a: 1}, {b: 2}], "overwrite")
2187 ASSERT_EQ $m.a 1
2188 ASSERT_EQ $m.b 2
2189 "###
2190)]
2191fn merge_maps(
2192 maps: Vec<BTreeMap<String, Value>>,
2194 #[values("fail_on_duplicate", "overwrite")]
2196 policy: String,
2197) -> Result<Value> {
2198 super::args::merge_maps_from_value(
2199 Value::list(maps.into_iter().map(Value::map).collect()),
2200 policy,
2201 )
2202}
2203
2204#[oxdock_func(pure, returns = TypeTag::String)]
2209#[example(
2210 name = "report",
2211 code = r###"
2212 # The engine reports its own build version as a dotted string.
2213 IMPORT [STD]
2214 LET $v: STRING = VERSION()
2215 ASSERT_CONTAINS $v "."
2216 "###
2217)]
2218fn version() -> Result<Value> {
2219 Ok(Value::string(env!("CARGO_PKG_VERSION").to_string()))
2220}
2221
2222#[oxdock_func(returns = TypeTag::ListOf(std::sync::Arc::new(TypeTag::String)))]
2227#[example(
2228 name = "list",
2229 code = r###"
2230 IMPORT [STD]
2231 LET $names: LIST<STRING> = FUNCTIONS()
2232 ASSERT_CONTAINS $names "STD::INT"
2233 "###
2234)]
2235fn functions<P: ProcessManager>(cx: &mut StepCtx<P>) -> Result<Value> {
2236 let mut names: Vec<String> = cx
2237 .state
2238 .list_functions()
2239 .into_iter()
2240 .map(|meta| meta.name)
2241 .collect();
2242 names.sort();
2243 names.dedup();
2244 Ok(Value::list(names.into_iter().map(Value::string).collect()))
2245}
2246
2247#[oxdock_func(returns = TypeTag::ListOf(std::sync::Arc::new(TypeTag::String)))]
2254#[example(
2255 name = "empty",
2256 code = r###"
2257 # With no staged args the list is empty.
2258 IMPORT [STD]
2259 LET $args: LIST<STRING> = ARGV()
2260 LET $n: INT = LEN($args)
2261 ASSERT_EQ $n 0
2262 "###
2263)]
2264fn argv<P: ProcessManager>(cx: &mut StepCtx<P>) -> Result<Value> {
2265 Ok(Value::list(
2266 cx.state
2267 .io
2268 .script_args()
2269 .iter()
2270 .cloned()
2271 .map(Value::string)
2272 .collect(),
2273 ))
2274}
2275
2276#[oxdock_func(
2287 pure,
2288 returns = TypeTag::Record(std::sync::Arc::from([Field {
2289 name: "flags".to_string(),
2290 ty: TypeTag::MapOf(std::sync::Arc::new(TypeTag::union(vec![
2291 TypeTag::Bool,
2292 TypeTag::String,
2293 ]))),
2294 docs: "Parsed flags: bare entries bind true, equals entries bind strings.",
2295 optional: false,
2296 }, Field {
2297 name: "positionals".to_string(),
2298 ty: TypeTag::ListOf(std::sync::Arc::new(TypeTag::String)),
2299 docs: "Trailing values and entries after the first double dash.",
2300 optional: false,
2301 }]))
2302)]
2303#[example(
2304 name = "longs",
2305 code = r###"
2306 # Long equals entries bind strings, bare longs bind true.
2307 IMPORT [STD]
2308 LET $parsed: MAP<ANY> = PARSE_ARGS(["--host=example.com", "--verbose", "serve"])
2309 ASSERT_EQ $parsed.flags.host "example.com"
2310 ASSERT_EQ $parsed.flags.verbose true
2311 ASSERT_EQ $parsed.positionals.0 "serve"
2312 "###
2313)]
2314#[example(
2315 name = "shorts and separator",
2316 code = r###"
2317 # Short clusters expand, short equals binds, and one double dash ends flags.
2318 IMPORT [STD]
2319 LET $parsed: MAP<ANY> = PARSE_ARGS(["-ab", "-k=value", "--flag", "--", "--not-a-flag"])
2320 ASSERT_EQ $parsed.flags.a true
2321 ASSERT_EQ $parsed.flags.b true
2322 ASSERT_EQ $parsed.flags.k "value"
2323 ASSERT_EQ $parsed.flags.flag true
2324 ASSERT_EQ $parsed.positionals.0 "--not-a-flag"
2325 "###
2326)]
2327#[example(
2328 name = "duplicates and separator",
2329 code = r###"
2330 # Duplicate keys overwrite in order, and a bare second double dash is positional.
2331 IMPORT [STD]
2332 LET $parsed: MAP<ANY> = PARSE_ARGS(["--x=1", "--x=2", "--", "--"])
2333 ASSERT_EQ $parsed.flags.x "2"
2334 ASSERT_EQ $parsed.positionals.0 "--"
2335 "###
2336)]
2337fn parse_args(
2338 args: Vec<String>,
2340) -> Result<Value> {
2341 use lexopt::Arg::{Long, Short, Value as ArgValue};
2342 let mut parser = lexopt::Parser::from_args(args);
2343 let mut flags: BTreeMap<String, Value> = BTreeMap::new();
2344 let mut positionals: Vec<Value> = Vec::new();
2345 let utf8 = |value: std::ffi::OsString| -> Result<String> {
2346 value
2347 .into_string()
2348 .map_err(|_| anyhow::anyhow!("PARSE_ARGS: argument must be UTF-8"))
2349 };
2350 loop {
2351 match parser.next() {
2352 Ok(None) => break,
2353 Ok(Some(Long(name))) => {
2354 let key = name.to_owned();
2355 if let Some(raw) = parser.optional_value() {
2356 flags.insert(key, Value::string(utf8(raw)?));
2357 } else {
2358 flags.insert(key, Value::bool(true));
2359 }
2360 }
2361 Ok(Some(Short(ch))) => {
2362 flags.insert(ch.to_string(), Value::bool(true));
2363 }
2364 Ok(Some(ArgValue(raw))) => {
2365 positionals.push(Value::string(utf8(raw)?));
2366 }
2367 Err(lexopt::Error::UnexpectedValue { option, value }) => {
2368 let key = option
2369 .strip_prefix("--")
2370 .or_else(|| option.strip_prefix('-'))
2371 .unwrap_or(option.as_str());
2372 flags.insert(key.to_string(), Value::string(utf8(value)?));
2373 }
2374 Err(err) => anyhow::bail!("PARSE_ARGS: {err}"),
2375 }
2376 }
2377 let mut out = BTreeMap::new();
2378 out.insert("flags".to_string(), Value::map(flags));
2379 out.insert("positionals".to_string(), Value::list(positionals));
2380 Ok(Value::map(out))
2381}
2382
2383#[oxdock_func(
2398 returns = TypeTag::Record(std::sync::Arc::from([Field {
2399 name: "name".to_string(),
2400 ty: TypeTag::String,
2401 docs: "Qualified function name.",
2402 optional: false,
2403 }, Field {
2404 name: "module".to_string(),
2405 ty: TypeTag::String,
2406 docs: "Owning module.",
2407 optional: false,
2408 }, Field {
2409 name: "kind".to_string(),
2410 ty: TypeTag::String,
2411 docs: "Origin label (`host` or `script`).",
2412 optional: false,
2413 }, Field {
2414 name: "params".to_string(),
2415 ty: TypeTag::ListOf(std::sync::Arc::new(TypeTag::MapOf(std::sync::Arc::new(
2416 TypeTag::Any,
2417 )))),
2418 docs: "Parameter entries (empty for parameterless functions).",
2419 optional: false,
2420 }, Field {
2421 name: "returns".to_string(),
2422 ty: TypeTag::String,
2423 docs: "Structural return shape (empty when untagged).",
2424 optional: false,
2425 }, Field {
2426 name: "rpn".to_string(),
2427 ty: TypeTag::Bool,
2428 docs: "True when callable in RPN position.",
2429 optional: false,
2430 }, Field {
2431 name: "summary".to_string(),
2432 ty: TypeTag::String,
2433 docs: "One-line description.",
2434 optional: false,
2435 }]))
2436 summary = "Describe one function by qualified name."
2437)]
2438#[example(
2439 name = "describe",
2440 code = r###"
2441 IMPORT [STD]
2442 LET $info: MAP<ANY> = DESCRIBE("STD::INT")
2443 ASSERT_EQ $info.name "STD::INT"
2444 ASSERT_EQ $info.returns "INT"
2445 "###
2446)]
2447fn describe<P: ProcessManager>(
2448 cx: &mut StepCtx<P>,
2449 name: String,
2451) -> Result<Value> {
2452 if split_qualified(&name).is_none() && name != KEYWORD_INSPECT {
2453 anyhow::bail!(
2454 "unknown function `{name}`: DESCRIBE requires a qualified name (e.g. `STD::{name}`)"
2455 );
2456 }
2457 cx.state
2458 .describe_function(&name)
2459 .ok_or_else(|| anyhow::anyhow!("unknown function {name}"))
2460}
2461
2462#[oxdock_func(returns = TypeTag::ListOf(std::sync::Arc::new(TypeTag::String)))]
2468#[example(
2469 name = "list",
2470 code = r###"
2471 IMPORT [STD]
2472 LET $names: LIST<STRING> = TYPES()
2473 ASSERT_CONTAINS $names "STRING"
2474 "###
2475)]
2476fn types<P: ProcessManager>(cx: &mut StepCtx<P>) -> Result<Value> {
2477 Ok(Value::list(
2478 cx.state
2479 .type_names()
2480 .into_iter()
2481 .map(Value::string)
2482 .collect(),
2483 ))
2484}
2485
2486#[oxdock_func(returns = TypeTag::Record(std::sync::Arc::from([Field {
2492 name: "name".to_string(),
2493 ty: TypeTag::String,
2494 docs: "Queried type name.",
2495 optional: false,
2496}, Field {
2497 name: "summary".to_string(),
2498 ty: TypeTag::String,
2499 docs: "One-line description.",
2500 optional: false,
2501}, Field {
2502 name: "docs".to_string(),
2503 ty: TypeTag::String,
2504 docs: "Full documentation text.",
2505 optional: false,
2506}])))]
2507#[example(
2508 name = "describe",
2509 code = r###"
2510 IMPORT [STD]
2511 LET $info: MAP<ANY> = TYPE_DESCRIBE("STRING")
2512 ASSERT_EQ $info.name "STRING"
2513 "###
2514)]
2515fn type_describe<P: ProcessManager>(
2516 cx: &mut StepCtx<P>,
2517 name: String,
2519) -> Result<Value> {
2520 if let Some(descriptor) = cx.state.describe_type(&name) {
2521 let mut map = BTreeMap::new();
2522 map.insert(
2523 "name".to_string(),
2524 Value::string(descriptor.name.to_string()),
2525 );
2526 map.insert(
2527 "summary".to_string(),
2528 Value::string(descriptor.summary.to_string()),
2529 );
2530 map.insert(
2531 "docs".to_string(),
2532 Value::string(descriptor.docs.to_string()),
2533 );
2534 return Ok(Value::map(map));
2535 }
2536 if let Some(target) = cx.state.alias_target(&name) {
2539 let mut map = BTreeMap::new();
2540 map.insert("name".to_string(), Value::string(name.clone()));
2541 map.insert(
2542 "summary".to_string(),
2543 Value::string(format!("Script type alias for {target}.")),
2544 );
2545 map.insert(
2546 "docs".to_string(),
2547 Value::string(format!(
2548 "Declared with TYPE {name} = {target}. The alias expands structurally at every declaration."
2549 )),
2550 );
2551 return Ok(Value::map(map));
2552 }
2553 Err(anyhow::anyhow!("unknown type {name}"))
2554}
2555
2556#[oxdock_func(returns = TypeTag::String)]
2570#[example(
2571 name = "self",
2572 code = r###"
2573 # The running interpreter resolves to a non-empty path.
2574 IMPORT [STD]
2575 LET $exe: STRING = INTERPRETER()
2576 LET $nonempty: BOOL = $exe != ""
2577 ASSERT_EQ $nonempty true
2578 "###
2579)]
2580#[example(
2581 name = "dynamic assembly",
2582 code = r###"
2583 # Assemble the child script dynamically: the parent interpolates
2584 # its own bindings into the pipe, then runs the interpreter on it.
2585 # Unescaped {{ }} bakes in at render time; \{{ }} stays literal
2586 # so the child expands it with its own bindings.
2587 # The pipe delivers EOF when the producer step ends, so the child
2588 # reads exactly one script.
2589 IMPORT [STD]
2590 LET $exe: STRING = INTERPRETER()
2591 LET $who: STRING = "Ada"
2592 LET $child: PIPE
2593 WITH_IO [stdout=$child] ECHO """
2594 ECHO "hello {{ $who }}!"
2595 LET $who: STRING = "Grace"
2596 ECHO "child sees \{{ $who }}!"
2597 """
2598 LET $out: STRING = WITH_IO [stdin=$child] RUN [$exe]
2599 ASSERT_CONTAINS $out "hello Ada!"
2600 ASSERT_CONTAINS $out "child sees Grace!"
2601 "###
2602)]
2603fn interpreter<P: ProcessManager>(cx: &mut StepCtx<P>) -> Result<Value> {
2604 if let Some(staged) = cx.state.io.interpreter_override() {
2605 return Ok(Value::string(staged));
2606 }
2607 Ok(Value::string(oxdock_process::interpreter_exe()?))
2608}
2609
2610#[oxdock_func(returns = TypeTag::Bool)]
2618#[example(
2619 name = "main",
2620 code = r###"
2621 # Entry top level runs as main.
2622 IMPORT [STD]
2623 LET $m: BOOL = IS_MAIN()
2624 ASSERT_EQ $m true
2625 "###
2626)]
2627#[example(
2628 name = "library doubles as demo",
2629 fence_meta = "roots:unified",
2630 code = r###"
2631 # A library doubles as a runnable demo: guard the demo with
2632 # IF IS_MAIN() so importing it stays side effect free. The
2633 # parent writes both files, then runs each in a fresh
2634 # interpreter: direct execution prints the demo, importing
2635 # it does not. Unified roots: the child inherits one
2636 # workspace, so parent and child see the same files. The
2637 # exact stdout match proves the demo line stays out of the
2638 # importing run.
2639 IMPORT [STD]
2640
2641 # The library under test: demo guarded by IS_MAIN.
2642 WRITE lib.oxfile """
2643 IMPORT [STD]
2644 FUNC GREET($x: STRING): STRING { RETURN "hi \{{ $x }}" }
2645 EXPORT GREET
2646 IF IS_MAIN() {
2647 ECHO "demo: hi Ada"
2648 }
2649 """
2650
2651 # The importer: calls the library, prints only its own line.
2652 WRITE main.oxfile """
2653 IMPORT ["lib.oxfile" AS LIB]
2654 LET $g: STRING = LIB::GREET("Bo")
2655 ECHO "imported: \{{ $g }}"
2656 """
2657
2658 # Direct run executes the demo.
2659 LET $exe: STRING = INTERPRETER()
2660 LET $direct: STRING = RUN [$exe, "lib.oxfile"]
2661 ASSERT_CONTAINS $direct "demo: hi Ada"
2662
2663 # Importing run stays silent apart from its own line.
2664 LET $via: STRING = RUN [$exe, "main.oxfile"]
2665 ASSERT_EQ $via "imported: hi Bo\n"
2666 "###
2667)]
2668fn is_main<P: ProcessManager>(cx: &mut StepCtx<P>) -> Result<Value> {
2669 let main = match cx.state.module_stack.last() {
2670 None | Some(None) => true,
2671 Some(Some(_)) => false,
2672 };
2673 Ok(Value::bool(main))
2674}
2675
2676#[oxdock_func(returns = TypeTag::Bool)]
2690#[example(
2691 name = "null stdin",
2692 code = r###"
2693 # A null stdin is never a terminal, in every harness.
2694 IMPORT [STD]
2695 LET $term: BOOL = IS_TERMINAL("stdin")
2696 ASSERT_EQ $term false
2697 "###
2698)]
2699fn is_terminal<P: ProcessManager>(
2700 cx: &mut StepCtx<P>,
2701 #[values("stdin", "stdout", "stderr")]
2703 stream_name: String,
2704) -> Result<Value> {
2705 use std::io::IsTerminal;
2706 let terminal = match stream_name.as_str() {
2707 "stdin" => {
2708 if cx.stdin_pipe.is_some() {
2713 false
2714 } else {
2715 match &cx.stdin {
2716 CommandStdin::Null => false,
2717 #[cfg(not(miri))]
2718 CommandStdin::OsPipe(_) => false,
2719 CommandStdin::Stream(_) => false,
2720 CommandStdin::Inherit => std::io::stdin().is_terminal(),
2721 }
2722 }
2723 }
2724 "stdout" => {
2725 if cx.out_pipe.is_some() {
2726 false
2728 } else if cx.state.io.stdout().is_some() {
2729 false
2732 } else {
2733 match &cx.out {
2734 None => std::io::stdout().is_terminal(),
2736 #[cfg(not(miri))]
2738 Some(StreamHandle::Os(_)) => false,
2739 Some(StreamHandle::Stream(_)) => std::io::stdout().is_terminal(),
2749 }
2750 }
2751 }
2752 "stderr" => {
2753 if cx.state.io.stderr().is_some() {
2754 false
2756 } else {
2757 match &cx.err {
2758 None => std::io::stderr().is_terminal(),
2760 #[cfg(not(miri))]
2762 Some(StreamHandle::Os(_)) => false,
2763 Some(StreamHandle::Stream(_)) => false,
2766 }
2767 }
2768 }
2769 _ => anyhow::bail!(
2770 "IS_TERMINAL expects \"stdin\", \"stdout\", or \"stderr\", got {stream_name:?}"
2775 ),
2776 };
2777 Ok(Value::bool(terminal))
2778}
2779
2780#[oxdock_func(returns = TypeTag::Semaphore)]
2788#[example(
2789 name = "mint",
2790 code = r###"
2791 # Mint a semaphore admitting at most two holders.
2792 IMPORT [STD]
2793 LET $sem: SEMAPHORE = SEMAPHORE_NEW(2)
2794
2795 # A fresh semaphore reports its full cap as available.
2796 LET $free: INT = SEMAPHORE_AVAILABLE($sem)
2797 ASSERT_EQ $free 2
2798 "###
2799)]
2800fn semaphore_new<P: ProcessManager>(
2801 cx: &mut StepCtx<P>,
2802 max: i64,
2804) -> Result<Value> {
2805 let _ = cx;
2806 if max <= 0 {
2807 return Err(anyhow::anyhow!(
2808 "SEMAPHORE_NEW() requires a positive max, got {max}"
2809 ));
2810 }
2811 Ok(Value::semaphore(max as usize))
2812}
2813
2814#[oxdock_func(returns = TypeTag::Record(std::sync::Arc::from([Field {
2823 name: "held".to_string(),
2824 ty: TypeTag::Bool,
2825 docs: "`true` with the permit under `permit`, `false` with no `permit` key.",
2826 optional: false,
2827}, Field {
2828 name: "permit".to_string(),
2829 ty: TypeTag::Permit,
2830 docs: "Permit handle; read only when `held`.",
2831 optional: true,
2832}])))]
2833#[example(
2834 name = "acquire",
2835 code = r###"
2836 # First acquire holds with a permit to bind.
2837 IMPORT [STD]
2838 LET $sem: SEMAPHORE = SEMAPHORE_NEW(1)
2839 LET $first: MAP<held: BOOL, permit?: PERMIT> = SEMAPHORE_TRY_ACQUIRE($sem)
2840 ASSERT_EQ $first.held true
2841 LET $permit: PERMIT = $first.permit
2842
2843 # A capped semaphore answers held false with no permit key.
2844 LET $second: MAP<held: BOOL, permit?: PERMIT> = SEMAPHORE_TRY_ACQUIRE($sem)
2845 ASSERT_EQ $second.held false
2846 LET $has_permit: BOOL = HAS_KEY($second, "permit")
2847 ASSERT_EQ $has_permit false
2848 "###
2849)]
2850fn semaphore_try_acquire<P: ProcessManager>(
2851 cx: &mut StepCtx<P>,
2852 sem: Arc<SemaphoreState>,
2854) -> Result<Value> {
2855 let _ = cx;
2856 let mut map = BTreeMap::new();
2857 if sem.try_acquire() {
2858 map.insert("held".to_string(), Value::bool(true));
2859 map.insert("permit".to_string(), Value::permit(&sem));
2860 } else {
2861 map.insert("held".to_string(), Value::bool(false));
2862 }
2863 Ok(Value::map(map))
2864}
2865
2866#[oxdock_func(pure, returns = TypeTag::Int)]
2873#[example(
2874 name = "readout",
2875 code = r###"
2876 # Hold one permit on a cap of two.
2877 IMPORT [STD]
2878 LET $sem: SEMAPHORE = SEMAPHORE_NEW(2)
2879 LET $acq: MAP<held: BOOL, permit?: PERMIT> = SEMAPHORE_TRY_ACQUIRE($sem)
2880 ASSERT_EQ $acq.held true
2881
2882 # One held permit leaves exactly one free.
2883 LET $free: INT = SEMAPHORE_AVAILABLE($sem)
2884 ASSERT_EQ $free 1
2885 "###
2886)]
2887fn semaphore_available(
2888 sem: Arc<SemaphoreState>,
2890) -> Result<Value> {
2891 Ok(Value::int(sem.available() as i64))
2892}
2893
2894#[oxdock_func(
2903 rpn,
2904 returns = TypeTag::union(vec![TypeTag::String, TypeTag::Pipe]),
2905 template = text_trim_string
2906)]
2907#[example(
2908 name = "trim",
2909 code = r###"
2910 # Leading and trailing whitespace falls away.
2911 IMPORT [STD]
2912 LET $clean: STRING = TEXT_TRIM(" hello ")
2913 ASSERT_EQ $clean "hello"
2914 "###
2915)]
2916#[example(
2917 name = "trim pipe mirrors",
2918 code = r###"
2919 # Pipe input mints pipe output with the same transform.
2920 IMPORT [STD]
2921 LET $cap: PIPE
2922 WITH_IO [stdout=$cap] {
2923 ECHO " hello "
2924 }
2925 LET $out: PIPE = TEXT_TRIM($cap)
2926 WITH_IO [stdin=$out] READ_LINE $line
2927 ASSERT_EQ $line "hello"
2928 "###
2929)]
2930#[example(
2931 name = "trim template",
2932 code = r###"
2933 # String inputs run inside placeholders too.
2934 IMPORT [STD]
2935 LET $msg: STRING = 'clean:{{ STD::TEXT_TRIM(" hello ") }}'
2936 ASSERT_EQ $msg "clean:hello"
2937 "###
2938)]
2939#[example(
2940 name = "trim file template",
2941 code = r###"
2942 # EXPAND templates resolve the same registry.
2943 IMPORT [STD]
2944 WRITE "tpl.txt" "clean:\{{ STD::TEXT_TRIM(\" hello \") }}"
2945 LET $out: STRING = EXPAND "tpl.txt"
2946 ASSERT_EQ $out "clean:hello"
2947 "###
2948)]
2949fn text_trim<P: ProcessManager>(
2950 cx: &mut StepCtx<P>,
2951 #[union(String, Pipe)]
2953 text: Value,
2954) -> Result<Value> {
2955 super::args::mirror_stream(cx, "TEXT_TRIM", &text, super::args::TextPump::Trim)
2956}
2957
2958fn text_trim_string(text: Value) -> Result<Value> {
2961 super::args::mirror_string("TEXT_TRIM", &text, super::args::TextPump::Trim)
2962}
2963
2964#[oxdock_func(
2973 rpn,
2974 returns = TypeTag::union(vec![TypeTag::String, TypeTag::Pipe]),
2975 template = text_trim_prefix_string
2976)]
2977#[example(
2978 name = "strip prefix",
2979 code = r###"
2980 # A present prefix falls away; absence returns the input unchanged.
2981 IMPORT [STD]
2982 LET $bare: STRING = TEXT_TRIM_PREFIX("v1.2.3", "v")
2983 ASSERT_EQ $bare "1.2.3"
2984
2985 # Missing prefixes pass through untouched.
2986 LET $same: STRING = TEXT_TRIM_PREFIX("1.2.3", "v")
2987 ASSERT_EQ $same "1.2.3"
2988 "###
2989)]
2990#[example(
2991 name = "strip prefix pipe mirrors",
2992 code = r###"
2993 # Pipe input mints pipe output with the same strip.
2994 IMPORT [STD]
2995 LET $cap: PIPE
2996 WITH_IO [stdout=$cap] {
2997 ECHO "v1.2.3"
2998 }
2999 LET $trimmed: PIPE = TEXT_TRIM($cap)
3000 LET $out: PIPE = TEXT_TRIM_PREFIX($trimmed, "v")
3001 WITH_IO [stdin=$out] READ_LINE $line
3002 ASSERT_EQ $line "1.2.3"
3003 "###
3004)]
3005#[example(
3006 name = "strip prefix template",
3007 code = r###"
3008 # String inputs run inside placeholders too.
3009 IMPORT [STD]
3010 LET $msg: STRING = 'bare:{{ STD::TEXT_TRIM_PREFIX("v1.2.3", "v") }}'
3011 ASSERT_EQ $msg "bare:1.2.3"
3012 "###
3013)]
3014fn text_trim_prefix<P: ProcessManager>(
3015 cx: &mut StepCtx<P>,
3016 #[union(String, Pipe)]
3018 text: Value,
3019 prefix: String,
3021) -> Result<Value> {
3022 super::args::mirror_stream(
3023 cx,
3024 "TEXT_TRIM_PREFIX",
3025 &text,
3026 super::args::TextPump::TrimPrefix(prefix),
3027 )
3028}
3029
3030fn text_trim_prefix_string(text: Value, prefix: String) -> Result<Value> {
3033 super::args::mirror_string(
3034 "TEXT_TRIM_PREFIX",
3035 &text,
3036 super::args::TextPump::TrimPrefix(prefix),
3037 )
3038}
3039
3040#[oxdock_func(
3047 rpn,
3048 returns = TypeTag::union(vec![TypeTag::String, TypeTag::Pipe]),
3049 template = text_trim_suffix_string
3050)]
3051#[example(
3052 name = "strip suffix",
3053 code = r###"
3054 # A present suffix falls away; absence returns the input unchanged.
3055 IMPORT [STD]
3056 LET $bare: STRING = TEXT_TRIM_SUFFIX("archive.tar.gz", ".gz")
3057 ASSERT_EQ $bare "archive.tar"
3058
3059 # Missing suffixes pass through untouched.
3060 LET $same: STRING = TEXT_TRIM_SUFFIX("archive.tar", ".gz")
3061 ASSERT_EQ $same "archive.tar"
3062 "###
3063)]
3064#[example(
3065 name = "strip suffix pipe mirrors",
3066 code = r###"
3067 # Pipe input mints pipe output with the same strip.
3068 IMPORT [STD]
3069 LET $cap: PIPE
3070 WITH_IO [stdout=$cap] {
3071 ECHO "archive.tar.gz"
3072 }
3073 LET $trimmed: PIPE = TEXT_TRIM($cap)
3074 LET $out: PIPE = TEXT_TRIM_SUFFIX($trimmed, ".gz")
3075 WITH_IO [stdin=$out] READ_LINE $line
3076 ASSERT_EQ $line "archive.tar"
3077 "###
3078)]
3079#[example(
3080 name = "strip suffix template",
3081 code = r###"
3082 # String inputs run inside placeholders too.
3083 IMPORT [STD]
3084 LET $msg: STRING = 'bare:{{ STD::TEXT_TRIM_SUFFIX("archive.tar.gz", ".gz") }}'
3085 ASSERT_EQ $msg "bare:archive.tar"
3086 "###
3087)]
3088fn text_trim_suffix<P: ProcessManager>(
3089 cx: &mut StepCtx<P>,
3090 #[union(String, Pipe)]
3092 text: Value,
3093 suffix: String,
3095) -> Result<Value> {
3096 super::args::mirror_stream(
3097 cx,
3098 "TEXT_TRIM_SUFFIX",
3099 &text,
3100 super::args::TextPump::TrimSuffix(suffix),
3101 )
3102}
3103
3104fn text_trim_suffix_string(text: Value, suffix: String) -> Result<Value> {
3107 super::args::mirror_string(
3108 "TEXT_TRIM_SUFFIX",
3109 &text,
3110 super::args::TextPump::TrimSuffix(suffix),
3111 )
3112}
3113
3114#[oxdock_func(returns = TypeTag::String)]
3125#[example(
3126 name = "join path",
3127 code = r###"
3128 # Directory and file stem join with the native separator.
3129 # Source `\\` is one backslash at runtime; `/` works on Windows
3130 # too, native just reads better there.
3131 IMPORT [STD]
3132 LET $p: STRING = PATH_JOIN("some-dir", "some-file")
3133 [family:unix] ASSERT_EQ $p "some-dir/some-file"
3134 [family:windows] ASSERT_EQ $p "some-dir\\some-file"
3135 "###
3136)]
3137fn path_join<P: ProcessManager>(
3138 _cx: &mut StepCtx<P>,
3139 #[union(String, Path)]
3141 dir: Value,
3142 #[union(String, Path)]
3144 name: Value,
3145) -> Result<Value> {
3146 let d = super::args::string_or_path_text(&dir)?;
3147 let n = super::args::string_or_path_text(&name)?;
3148 Ok(Value::string(oxdock_fs::join_native(&d, &n)))
3149}
3150
3151#[oxdock_func(
3158 rpn,
3159 returns = TypeTag::union(vec![TypeTag::String, TypeTag::Pipe]),
3160 template = text_to_upper_string
3161)]
3162#[example(
3163 name = "uppercase",
3164 code = r###"
3165 # Text folds to uppercase.
3166 IMPORT [STD]
3167 LET $loud: STRING = TEXT_TO_UPPER("hello")
3168 ASSERT_EQ $loud "HELLO"
3169 "###
3170)]
3171#[example(
3172 name = "uppercase pipe mirrors",
3173 code = r###"
3174 # Pipe input mints pipe output with the same fold.
3175 IMPORT [STD]
3176 LET $cap: PIPE
3177 WITH_IO [stdout=$cap] {
3178 ECHO "hello"
3179 }
3180 LET $out: PIPE = TEXT_TO_UPPER($cap)
3181 WITH_IO [stdin=$out] READ_LINE $line
3182 ASSERT_EQ $line "HELLO"
3183 "###
3184)]
3185#[example(
3186 name = "uppercase template",
3187 code = r###"
3188 # String inputs run inside placeholders too.
3189 IMPORT [STD]
3190 LET $msg: STRING = 'loud:{{ STD::TEXT_TO_UPPER("hello") }}'
3191 ASSERT_EQ $msg "loud:HELLO"
3192 "###
3193)]
3194fn text_to_upper<P: ProcessManager>(
3195 cx: &mut StepCtx<P>,
3196 #[union(String, Pipe)]
3198 text: Value,
3199) -> Result<Value> {
3200 super::args::mirror_stream(cx, "TEXT_TO_UPPER", &text, super::args::TextPump::ToUpper)
3201}
3202
3203fn text_to_upper_string(text: Value) -> Result<Value> {
3206 super::args::mirror_string("TEXT_TO_UPPER", &text, super::args::TextPump::ToUpper)
3207}
3208
3209#[oxdock_func(
3216 rpn,
3217 returns = TypeTag::union(vec![TypeTag::String, TypeTag::Pipe]),
3218 template = text_to_lower_string
3219)]
3220#[example(
3221 name = "lowercase",
3222 code = r###"
3223 # Text folds to lowercase.
3224 IMPORT [STD]
3225 LET $quiet: STRING = TEXT_TO_LOWER("HELLO")
3226 ASSERT_EQ $quiet "hello"
3227 "###
3228)]
3229#[example(
3230 name = "lowercase pipe mirrors",
3231 code = r###"
3232 # Pipe input mints pipe output with the same fold.
3233 IMPORT [STD]
3234 LET $cap: PIPE
3235 WITH_IO [stdout=$cap] {
3236 ECHO "HELLO"
3237 }
3238 LET $out: PIPE = TEXT_TO_LOWER($cap)
3239 WITH_IO [stdin=$out] READ_LINE $line
3240 ASSERT_EQ $line "hello"
3241 "###
3242)]
3243#[example(
3244 name = "lowercase template",
3245 code = r###"
3246 # String inputs run inside placeholders too.
3247 IMPORT [STD]
3248 LET $msg: STRING = 'quiet:{{ STD::TEXT_TO_LOWER("HELLO") }}'
3249 ASSERT_EQ $msg "quiet:hello"
3250 "###
3251)]
3252fn text_to_lower<P: ProcessManager>(
3253 cx: &mut StepCtx<P>,
3254 #[union(String, Pipe)]
3256 text: Value,
3257) -> Result<Value> {
3258 super::args::mirror_stream(cx, "TEXT_TO_LOWER", &text, super::args::TextPump::ToLower)
3259}
3260
3261fn text_to_lower_string(text: Value) -> Result<Value> {
3264 super::args::mirror_string("TEXT_TO_LOWER", &text, super::args::TextPump::ToLower)
3265}
3266
3267#[oxdock_func(
3278 rpn,
3279 returns = TypeTag::union(vec![TypeTag::String, TypeTag::Pipe]),
3280 template = text_replace_string
3281)]
3282#[example(
3283 name = "replace",
3284 code = r###"
3285 # Every literal occurrence rewrites in place.
3286 IMPORT [STD]
3287 LET $fixed: STRING = TEXT_REPLACE("hello world", "world", "there")
3288 ASSERT_EQ $fixed "hello there"
3289 "###
3290)]
3291#[example(
3292 name = "replace pipe mirrors",
3293 code = r###"
3294 # Pipe input mints pipe output with the same rewrite.
3295 IMPORT [STD]
3296 LET $cap: PIPE
3297 WITH_IO [stdout=$cap] {
3298 ECHO "hello world"
3299 }
3300 LET $trimmed: PIPE = TEXT_TRIM($cap)
3301 LET $out: PIPE = TEXT_REPLACE($trimmed, "world", "there")
3302 WITH_IO [stdin=$out] READ_LINE $line
3303 ASSERT_EQ $line "hello there"
3304 "###
3305)]
3306#[example(
3307 name = "replace template",
3308 code = r###"
3309 # String inputs run inside placeholders too.
3310 IMPORT [STD]
3311 LET $msg: STRING = 'fixed:{{ STD::TEXT_REPLACE("hello world", "world", "there") }}'
3312 ASSERT_EQ $msg "fixed:hello there"
3313 "###
3314)]
3315fn text_replace<P: ProcessManager>(
3316 cx: &mut StepCtx<P>,
3317 #[union(String, Pipe)]
3319 text: Value,
3320 from: String,
3322 to: String,
3324) -> Result<Value> {
3325 super::args::mirror_stream(
3326 cx,
3327 "TEXT_REPLACE",
3328 &text,
3329 super::args::TextPump::ReplaceLiteral { from, to },
3330 )
3331}
3332
3333fn text_replace_string(text: Value, from: String, to: String) -> Result<Value> {
3336 super::args::mirror_string(
3337 "TEXT_REPLACE",
3338 &text,
3339 super::args::TextPump::ReplaceLiteral { from, to },
3340 )
3341}
3342
3343#[oxdock_func(
3355 rpn,
3356 returns = TypeTag::union(vec![TypeTag::String, TypeTag::Pipe]),
3357 template = text_replace_regex_string
3358)]
3359#[example(
3360 name = "replace with captures",
3361 code = r###"
3362 # Capture groups expand in the replacement.
3363 IMPORT [STD]
3364 LET $swapped: STRING = TEXT_REPLACE_REGEX("2026-10-13", "(\\d+)-(\\d+)-(\\d+)", "$3/$2/$1")
3365 ASSERT_EQ $swapped "13/10/2026"
3366 "###
3367)]
3368#[example(
3369 name = "replace regex pipe mirrors",
3370 code = r###"
3371 # Pipe input mints pipe output with the same rewrite.
3372 IMPORT [STD]
3373 LET $cap: PIPE
3374 WITH_IO [stdout=$cap] {
3375 ECHO "2026-10-13"
3376 }
3377 LET $trimmed: PIPE = TEXT_TRIM($cap)
3378 LET $out: PIPE = TEXT_REPLACE_REGEX($trimmed, "(\\d+)-(\\d+)-(\\d+)", "$3/$2/$1")
3379 WITH_IO [stdin=$out] READ_LINE $line
3380 ASSERT_EQ $line "13/10/2026"
3381 "###
3382)]
3383#[example(
3384 name = "replace regex template",
3385 code = r###"
3386 # String inputs run inside placeholders too.
3387 IMPORT [STD]
3388 LET $msg: STRING = 'swapped:{{ STD::TEXT_REPLACE_REGEX("2026-10-13", "(\\d+)-(\\d+)-(\\d+)", "$3/$2/$1") }}'
3389 ASSERT_EQ $msg "swapped:13/10/2026"
3390 "###
3391)]
3392fn text_replace_regex<P: ProcessManager>(
3393 cx: &mut StepCtx<P>,
3394 #[union(String, Pipe)]
3396 text: Value,
3397 pattern: String,
3399 replacement: String,
3401) -> Result<Value> {
3402 if let Some(s) = text.as_str() {
3403 let out =
3404 super::args::text_replace_regex_str(s, &pattern, &replacement, "TEXT_REPLACE_REGEX")?;
3405 return Ok(Value::string(out));
3406 }
3407 let content = super::args::read_pipe_eager(cx, "TEXT_REPLACE_REGEX", &text)?;
3408 let out = super::args::text_replace_regex_str(
3409 &content,
3410 &pattern,
3411 &replacement,
3412 "TEXT_REPLACE_REGEX",
3413 )?;
3414 super::args::write_completed_pipe(cx, "TEXT_REPLACE_REGEX", out)
3415}
3416
3417fn text_replace_regex_string(text: Value, pattern: String, replacement: String) -> Result<Value> {
3420 let Some(s) = text.as_str() else {
3421 return Err(super::args::pipe_needs_step_io("TEXT_REPLACE_REGEX"));
3422 };
3423 let out = super::args::text_replace_regex_str(s, &pattern, &replacement, "TEXT_REPLACE_REGEX")?;
3424 Ok(Value::string(out))
3425}
3426
3427#[oxdock_func(pure, returns = TypeTag::ListOf(std::sync::Arc::new(TypeTag::String)))]
3435#[example(
3436 name = "split",
3437 code = r###"
3438 # Delimiters split into list items.
3439 IMPORT [STD]
3440 LET $parts: LIST<STRING> = TEXT_SPLIT("a,b,c", ",")
3441 ASSERT_EQ $parts.0 "a"
3442 ASSERT_EQ $parts.1 "b"
3443 ASSERT_EQ $parts.2 "c"
3444 "###
3445)]
3446fn text_split(
3447 text: String,
3449 delimiter: String,
3451) -> Result<Value> {
3452 Ok(super::args::text_list_value(super::args::text_split_str(
3453 &text, &delimiter,
3454 )))
3455}
3456
3457#[oxdock_func(pure, returns = TypeTag::String)]
3460#[example(
3461 name = "join",
3462 code = r###"
3463 # List items join with the separator between them.
3464 IMPORT [STD]
3465 LET $joined: STRING = TEXT_JOIN(["a", "b", "c"], ",")
3466 ASSERT_EQ $joined "a,b,c"
3467 "###
3468)]
3469fn text_join(
3470 elements: Vec<String>,
3472 delimiter: String,
3474) -> Result<Value> {
3475 Ok(Value::string(elements.join(delimiter.as_str())))
3476}
3477
3478#[oxdock_func(pure, returns = TypeTag::ListOf(std::sync::Arc::new(TypeTag::String)))]
3490#[example(
3491 name = "split args",
3492 code = r###"
3493 # Quoted segments stay one word.
3494 IMPORT [STD]
3495 LET $argv: LIST<STRING> = SHELL_SPLIT_ARGS("gh issue comment 153 --body-file notes.md")
3496 ASSERT_EQ $argv.0 "gh"
3497 ASSERT_EQ $argv.3 "153"
3498 ASSERT_EQ $argv.5 "notes.md"
3499
3500 # Quotes and escapes parse the shell way.
3501 LET $quoted: LIST<STRING> = SHELL_SPLIT_ARGS("say \"hi there\" 'a b'")
3502 ASSERT_EQ $quoted.0 "say"
3503 ASSERT_EQ $quoted.1 "hi there"
3504 ASSERT_EQ $quoted.2 "a b"
3505 "###
3506)]
3507fn shell_split_args(
3508 command: String,
3510) -> Result<Value> {
3511 match shell_words::split(&command) {
3512 Ok(words) => Ok(super::args::text_list_value(words)),
3513 Err(err) => anyhow::bail!("SHELL_SPLIT_ARGS: {err}"),
3514 }
3515}
3516
3517#[oxdock_func(pure, returns = TypeTag::String)]
3525#[example(
3526 name = "join args",
3527 code = r###"
3528 # Plain words join with spaces and no quoting.
3529 IMPORT [STD]
3530 LET $plain: STRING = SHELL_JOIN_ARGS(["gh", "issue", "list"])
3531 ASSERT_EQ $plain "gh issue list"
3532
3533 # Words with spaces quote, and the round trip is exact.
3534 LET $words: LIST<STRING> = ["say", "hi there", "a'b"]
3535 LET $joined: STRING = SHELL_JOIN_ARGS($words)
3536 LET $back: LIST<STRING> = SHELL_SPLIT_ARGS($joined)
3537 ASSERT_EQ $back.0 "say"
3538 ASSERT_EQ $back.1 "hi there"
3539 ASSERT_EQ $back.2 "a'b"
3540 "###
3541)]
3542fn shell_join_args(
3543 words: Vec<String>,
3545) -> Result<Value> {
3546 Ok(Value::string(shell_words::join(&words)))
3547}
3548
3549#[oxdock_func(pure, returns = TypeTag::ListOf(std::sync::Arc::new(TypeTag::String)))]
3557#[example(
3558 name = "lines",
3559 code = r###"
3560 # Newlines split into line items.
3561 IMPORT [STD]
3562 LET $lines: LIST<STRING> = TEXT_LINES("one\ntwo\nthree")
3563 ASSERT_EQ $lines.0 "one"
3564 ASSERT_EQ $lines.1 "two"
3565 ASSERT_EQ $lines.2 "three"
3566
3567 # Windows endings split the same way after normalization.
3568 LET $crlf: LIST<STRING> = TEXT_LINES("one\r\ntwo\r\nthree")
3569 ASSERT_EQ $crlf.0 "one"
3570 ASSERT_EQ $crlf.1 "two"
3571 ASSERT_EQ $crlf.2 "three"
3572
3573 # Old Mac endings split too, and mixed endings split together because the input normalizes to LF before splitting.
3574 LET $mixed: LIST<STRING> = TEXT_LINES("a\r\nb\nc\rd")
3575 ASSERT_EQ $mixed.0 "a"
3576 ASSERT_EQ $mixed.1 "b"
3577 ASSERT_EQ $mixed.2 "c"
3578 ASSERT_EQ $mixed.3 "d"
3579 "###
3580)]
3581fn text_lines(
3582 text: String,
3584) -> Result<Value> {
3585 Ok(super::args::text_list_value(super::args::text_lines_str(
3586 &text,
3587 )))
3588}
3589
3590#[oxdock_func(pure, returns = TypeTag::ListOf(std::sync::Arc::new(TypeTag::String)))]
3596#[example(
3597 name = "fields",
3598 code = r###"
3599 # Runs of whitespace separate fields; empties never appear.
3600 IMPORT [STD]
3601 LET $fields: LIST<STRING> = TEXT_FIELDS(" abc def ")
3602 ASSERT_EQ $fields.0 "abc"
3603 ASSERT_EQ $fields.1 "def"
3604 "###
3605)]
3606fn text_fields(
3607 text: String,
3609) -> Result<Value> {
3610 Ok(super::args::text_list_value(super::args::text_fields_str(
3611 &text,
3612 )))
3613}
3614
3615#[oxdock_func(pure, returns = TypeTag::ListOf(std::sync::Arc::new(TypeTag::String)))]
3624#[example(
3625 name = "line range",
3626 code = r###"
3627 # Lines 2 through 3 come back as a list, 1-based inclusive.
3628 IMPORT [STD]
3629 LET $window: LIST<STRING> = TEXT_LINES_RANGE("one\ntwo\nthree\nfour", 2, 3)
3630 ASSERT_EQ $window.0 "two"
3631 ASSERT_EQ $window.1 "three"
3632
3633 # Ranges past the end clamp instead of failing.
3634 LET $tail: LIST<STRING> = TEXT_LINES_RANGE("one\ntwo", 2, 9)
3635 ASSERT_EQ $tail.0 "two"
3636 "###
3637)]
3638fn text_lines_range(
3639 text: String,
3641 from: i64,
3643 to: i64,
3645) -> Result<Value> {
3646 Ok(super::args::text_list_value(
3647 super::args::text_lines_range_str(&text, from, to, "TEXT_LINES_RANGE")?,
3648 ))
3649}
3650
3651#[oxdock_func(pure, returns = TypeTag::Bool)]
3659#[example(
3660 name = "match",
3661 code = r###"
3662 # Regex matches report true; misses report false.
3663 IMPORT [STD]
3664 LET $hit: BOOL = TEXT_MATCH("abc123", "\\d+")
3665 ASSERT_EQ $hit true
3666
3667 # A miss is false, not a failure.
3668 LET $miss: BOOL = TEXT_MATCH("abc", "^\\d+$")
3669 ASSERT_EQ $miss false
3670 "###
3671)]
3672fn text_match(
3673 text: String,
3675 pattern: String,
3677) -> Result<Value> {
3678 let re = super::args::text_compile_pattern("TEXT_MATCH", &pattern)?;
3679 Ok(Value::bool(re.is_match(&text)))
3680}
3681
3682#[oxdock_func(pure, name = "BOOL", returns = TypeTag::Bool)]
3691#[example(
3692 name = "convert",
3693 code = r###"
3694 IMPORT [STD]
3695 LET $n: BOOL = BOOL("yes")
3696 ASSERT_EQ $n true
3697 LET $f: BOOL = BOOL("0")
3698 ASSERT_EQ $f false
3699 "###
3700)]
3701fn bool_convert(
3702 #[union(Bool, String)]
3704 val: Value,
3705) -> Result<Value> {
3706 if let Some(b) = val.as_bool() {
3707 return Ok(Value::bool(b));
3708 }
3709 let Some(s) = val.as_str() else {
3710 return Err(anyhow::anyhow!(
3711 "BOOL needs a Bool or String, found {val:?}"
3712 ));
3713 };
3714 match super::args::parse_bool_str(s) {
3715 Some(b) => Ok(Value::bool(b)),
3716 None => anyhow::bail!("BOOL cannot coerce {s:?} to BOOL"),
3717 }
3718}
3719
3720#[oxdock_func(pure, returns = TypeTag::Bool)]
3730#[example(
3731 name = "absent-default",
3732 code = r###"
3733 # Absent names read empty; the default settles the polarity.
3734 IMPORT [STD]
3735 INHERIT_ENV [OXDOCK_TEST_ABSENT_FLAG]
3736 LET $dry: BOOL = BOOL_OR("{{ env:OXDOCK_TEST_ABSENT_FLAG }}", true)
3737 ASSERT_EQ $dry true
3738
3739 # Present values coerce strictly, ignoring the default.
3740 LET $off: BOOL = BOOL_OR("false", true)
3741 ASSERT_EQ $off false
3742 "###
3743)]
3744fn bool_or(
3745 text: String,
3747 default: bool,
3749) -> Result<Value> {
3750 if text.trim().is_empty() {
3751 return Ok(Value::bool(default));
3752 }
3753 match super::args::parse_bool_str(&text) {
3754 Some(b) => Ok(Value::bool(b)),
3755 None => anyhow::bail!("BOOL_OR cannot coerce {text:?} to BOOL"),
3756 }
3757}
3758
3759#[oxdock_func(pure, returns = TypeTag::ListOf(std::sync::Arc::new(TypeTag::String)))]
3768#[example(
3769 name = "extract",
3770 code = r###"
3771 # Index zero is the full match; groups follow in order.
3772 IMPORT [STD]
3773 LET $caps: LIST<STRING> = TEXT_EXTRACT("abc123", "([a-z]+)(\\d+)")
3774 ASSERT_EQ $caps.0 "abc123"
3775 ASSERT_EQ $caps.1 "abc"
3776 ASSERT_EQ $caps.2 "123"
3777 "###
3778)]
3779fn text_extract(
3780 text: String,
3782 pattern: String,
3784) -> Result<Value> {
3785 let groups = super::args::text_extract_str(&text, &pattern, "TEXT_EXTRACT")?;
3786 Ok(super::args::text_list_value(groups))
3787}
3788
3789#[oxdock_func(pure, returns = TypeTag::Bool)]
3796#[example(
3797 name = "starts with",
3798 code = r###"
3799 # Present prefixes report true; misses report false.
3800 IMPORT [STD]
3801 LET $hit: BOOL = TEXT_STARTS_WITH("linux-musl-x64", "linux")
3802 ASSERT_EQ $hit true
3803
3804 # A miss is false, not a failure.
3805 LET $miss: BOOL = TEXT_STARTS_WITH("macos-arm", "linux")
3806 ASSERT_EQ $miss false
3807 "###
3808)]
3809fn text_starts_with(
3810 text: String,
3812 prefix: String,
3814) -> Result<Value> {
3815 Ok(Value::bool(text.starts_with(prefix.as_str())))
3816}
3817
3818#[oxdock_func(pure, returns = TypeTag::Bool)]
3825#[example(
3826 name = "ends with",
3827 code = r###"
3828 # Present suffixes report true; misses report false.
3829 IMPORT [STD]
3830 LET $hit: BOOL = TEXT_ENDS_WITH("x86_64-linux-musl", "linux-musl")
3831 ASSERT_EQ $hit true
3832
3833 # A miss is false, not a failure.
3834 LET $miss: BOOL = TEXT_ENDS_WITH("x86_64-linux-gnu", "linux-musl")
3835 ASSERT_EQ $miss false
3836 "###
3837)]
3838fn text_ends_with(
3839 text: String,
3841 suffix: String,
3843) -> Result<Value> {
3844 Ok(Value::bool(text.ends_with(suffix.as_str())))
3845}
3846
3847#[oxdock_func(pure, returns = TypeTag::Bool)]
3854#[example(
3855 name = "contains",
3856 code = r###"
3857 # Present needles report true; misses report false.
3858 IMPORT [STD]
3859 LET $hit: BOOL = TEXT_CONTAINS("x86_64-linux-musl", "musl")
3860 ASSERT_EQ $hit true
3861
3862 # A miss is false, not a failure.
3863 LET $miss: BOOL = TEXT_CONTAINS("x86_64-linux-gnu", "musl")
3864 ASSERT_EQ $miss false
3865 "###
3866)]
3867fn text_contains(
3868 text: String,
3870 needle: String,
3872) -> Result<Value> {
3873 Ok(Value::bool(text.contains(needle.as_str())))
3874}
3875
3876#[oxdock_func(pure, returns = TypeTag::Int)]
3885#[example(
3886 name = "length",
3887 code = r###"
3888 # Plain text counts one per character.
3889 IMPORT [STD]
3890 LET $n: INT = LEN("hello")
3891 ASSERT_EQ $n 5
3892
3893 # Multibyte characters count once each, not per byte.
3894 LET $wide: INT = LEN("héllo")
3895 ASSERT_EQ $wide 5
3896
3897 # Lists count elements, maps count entries.
3898 LET $items: LIST<STRING> = ["a", "b", "c"]
3899 LET $nitems: INT = LEN($items)
3900 ASSERT_EQ $nitems 3
3901 LET $row: MAP<name: STRING> = {name: "ada"}
3902 LET $nkeys: INT = LEN($row)
3903 ASSERT_EQ $nkeys 1
3904 LET $empty: INT = LEN([])
3905 ASSERT_EQ $empty 0
3906 "###
3907)]
3908fn len(
3909 #[union(String, List, Map)]
3911 value: Value,
3912) -> Result<Value> {
3913 if let Some(text) = value.as_str() {
3914 return Ok(Value::int(text.chars().count() as i64));
3915 }
3916 if let Some(items) = value.as_list() {
3917 return Ok(Value::int(items.len() as i64));
3918 }
3919 if let Some(entries) = value.as_map() {
3920 return Ok(Value::int(entries.len() as i64));
3921 }
3922 Err(anyhow::anyhow!(
3923 "LEN needs a STRING, LIST, or MAP value, got {}",
3924 value.type_name()
3925 ))
3926}
3927
3928#[oxdock_func(pure, returns = TypeTag::Int)]
3936#[example(
3937 name = "count",
3938 code = r###"
3939 # Every non-overlapping occurrence counts once.
3940 IMPORT [STD]
3941 LET $n: INT = TEXT_COUNT("hello world", "o")
3942 ASSERT_EQ $n 2
3943
3944 # Overlapping candidates never double count.
3945 LET $once: INT = TEXT_COUNT("aaa", "aa")
3946 ASSERT_EQ $once 1
3947 "###
3948)]
3949fn text_count(
3950 text: String,
3952 needle: String,
3954) -> Result<Value> {
3955 let n = super::args::text_count_str(&text, &needle, "TEXT_COUNT")?;
3956 Ok(Value::int(n))
3957}
3958
3959#[oxdock_func(pure, returns = TypeTag::Int)]
3969#[example(
3970 name = "count matches",
3971 code = r###"
3972 # One line matches once no matter how many times it hits.
3973 IMPORT [STD]
3974 LET $n: INT = TEXT_COUNT_MATCHES("test a: test\ntest b: nope\ntest c: test", ": test")
3975 ASSERT_EQ $n 2
3976
3977 # A miss binds zero, never an error.
3978 LET $none: INT = TEXT_COUNT_MATCHES("test b: nope", ": test$")
3979 ASSERT_EQ $none 0
3980 "###
3981)]
3982fn text_count_matches(
3983 text: String,
3985 pattern: String,
3987) -> Result<Value> {
3988 let n = super::args::text_count_matches_str(&text, &pattern, "TEXT_COUNT_MATCHES")?;
3989 Ok(Value::int(n))
3990}
3991
3992#[oxdock_func(pure, returns = TypeTag::ListOf(std::sync::Arc::new(TypeTag::String)))]
4005#[example(
4006 name = "grep",
4007 code = r###"
4008 # Matching lines come back as a list, in order.
4009 IMPORT [STD]
4010 LET $hits: LIST<STRING> = TEXT_GREP("one\ntwo\none more", "^one")
4011 ASSERT_EQ $hits.0 "one"
4012 ASSERT_EQ $hits.1 "one more"
4013
4014 # A miss binds an empty list, never an error.
4015 LET $miss: LIST<STRING> = TEXT_GREP("one\ntwo", "^z")
4016 LET $joined: STRING = TEXT_JOIN($miss, ",")
4017 ASSERT_EQ $joined ""
4018
4019 # The (?i) flag ignores case, so uppercase lines match too.
4020 LET $folded: LIST<STRING> = TEXT_GREP("One\ntwo\nONE more", "(?i)^one")
4021 ASSERT_EQ $folded.0 "One"
4022 ASSERT_EQ $folded.1 "ONE more"
4023 "###
4024)]
4025#[example(
4026 name = "grep invert",
4027 code = r###"
4028 # The invert option keeps every non-matching line instead.
4029 IMPORT [STD]
4030 LET $kept: LIST<STRING> = TEXT_GREP("one\ntwo\none more", "^one", {invert: true})
4031 ASSERT_EQ $kept.0 "two"
4032
4033 # A pattern matching every line binds an empty list, never an error.
4034 LET $none: LIST<STRING> = TEXT_GREP("one\ntwo", "^", {invert: true})
4035 LET $joined: STRING = TEXT_JOIN($none, ",")
4036 ASSERT_EQ $joined ""
4037
4038 # Options ride into placeholders as MAP literals. Placeholder
4039 # strings unescape only backslash and quote, so multiline text
4040 # arrives through a variable.
4041 LET $two_lines: STRING = "one\ntwo"
4042 LET $msg: STRING = 'kept:{{ STD::TEXT_GREP($two_lines, "^one", {invert: true}) }}'
4043 ASSERT_EQ $msg "kept:two"
4044 "###
4045)]
4046fn text_grep(
4047 text: String,
4049 pattern: String,
4051 #[options("invert?: BOOL")]
4053 #[optional]
4054 options: BTreeMap<String, Value>,
4055) -> Result<Value> {
4056 let invert = super::args::text_invert_flag(&options);
4059 Ok(super::args::text_list_value(super::args::text_grep_str(
4060 &text,
4061 &pattern,
4062 invert,
4063 "TEXT_GREP",
4064 )?))
4065}
4066
4067#[oxdock_func(returns = TypeTag::Bool)]
4078#[example(
4079 name = "drain to end",
4080 code = r###"
4081 # Capture two lines, then drain to end of stream with no sentinel line.
4082 IMPORT [STD]
4083 LET $cap: PIPE
4084 WITH_IO [stdout=$cap] {
4085 ECHO "one"
4086 ECHO "two"
4087 }
4088
4089 # The loop exits on close, and the count proves both lines drained.
4090 LET $n: INT = 0
4091 WHILE !EOF($cap) {
4092 WITH_IO [stdin=$cap] READ_LINE $line
4093 $n = $n + 1
4094 }
4095 ASSERT_EQ $n 2
4096 "###
4097)]
4098fn eof<P: ProcessManager>(
4099 cx: &mut StepCtx<P>,
4100 pipe: PipeHandle,
4102) -> Result<Value> {
4103 let info = cx.state.io.inspect_pipe(&pipe);
4104 Ok(Value::bool(info.closed && info.buffered == 0))
4105}
4106
4107fn task_poll_result_fields() -> Arc<[Field]> {
4111 Arc::from(vec![
4112 Field {
4113 name: "state".to_string(),
4114 ty: TypeTag::String,
4115 docs: "Task phase: `running` or `finished`.",
4116 optional: false,
4117 },
4118 Field {
4119 name: "ok".to_string(),
4120 ty: TypeTag::Bool,
4121 docs: "True unless the task failed.",
4122 optional: false,
4123 },
4124 Field {
4125 name: "stdout_tail".to_string(),
4126 ty: TypeTag::String,
4127 docs: "Bounded stdout tail, live while running.",
4128 optional: false,
4129 },
4130 Field {
4131 name: "stderr_tail".to_string(),
4132 ty: TypeTag::String,
4133 docs: "Bounded stderr tail, live while running.",
4134 optional: false,
4135 },
4136 Field {
4137 name: "truncated_bytes".to_string(),
4138 ty: TypeTag::Int,
4139 docs: "Dropped head bytes past the per-stream cap.",
4140 optional: false,
4141 },
4142 Field {
4143 name: "exit_code".to_string(),
4144 ty: TypeTag::Int,
4145 docs: "Process exit code, present once finished.",
4146 optional: true,
4147 },
4148 Field {
4149 name: "result".to_string(),
4150 ty: TypeTag::Any,
4151 docs: "Task `RETURN` value, present on clean finish.",
4152 optional: true,
4153 },
4154 Field {
4155 name: "error".to_string(),
4156 ty: TypeTag::String,
4157 docs: "Failure text, present on failed finish.",
4158 optional: true,
4159 },
4160 ])
4161}
4162
4163#[oxdock_func(returns = TypeTag::Record(task_poll_result_fields()))]
4176#[example(
4177 name = "running poll",
4178 code = r###"
4179 # A sleeping task is still running on the first poll.
4180 IMPORT [STD]
4181 LET $t: HANDLE<STRING> = ASYNC { SLEEP 30s; RETURN "done" }
4182 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)
4183 ASSERT_EQ $m.state "running"
4184 ASSERT_EQ $m.ok true
4185 # Clean up the sleeper so the run ends promptly.
4186 CANCEL $t
4187 "###
4188)]
4189#[example(
4190 name = "finished poll",
4191 code = r###"
4192 # A finished task reports its value and final tails, then still awaits.
4193 IMPORT [STD]
4194 LET $t: HANDLE<STRING> = ASYNC { ECHO "hi"; SLEEP 1s; RETURN "done" }
4195 # Do other work while the task runs; poll once it should be done.
4196 SLEEP 2s
4197 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)
4198 ASSERT_EQ $m.state "finished"
4199 ASSERT_EQ $m.result "done"
4200 LET $o: STRING = AWAIT $t
4201 ASSERT_EQ $o "done"
4202 "###
4203)]
4204fn task_poll<P: ProcessManager>(
4205 cx: &mut StepCtx<P>,
4206 task: HandleValue,
4208) -> Result<Value> {
4209 let entry =
4210 super::handlers::resolve_task_entry_by_id(task.0, &format!("TASK_POLL({})", task.0), cx)?;
4211 let obs = entry.observe_completion();
4212 let (stdout_tail, stderr_tail, dropped) = entry.snapshot_tails();
4213 let mut out = BTreeMap::new();
4214 out.insert(
4215 "state".to_string(),
4216 Value::string(if obs.running { "running" } else { "finished" }.to_string()),
4217 );
4218 out.insert("ok".to_string(), Value::bool(obs.ok));
4219 if !obs.running {
4220 out.insert("exit_code".to_string(), Value::int(obs.exit_code));
4221 }
4222 if let Some(result) = obs.result {
4223 out.insert("result".to_string(), result);
4224 }
4225 if !obs.error.is_empty() {
4226 out.insert("error".to_string(), Value::string(obs.error));
4227 }
4228 out.insert("stdout_tail".to_string(), Value::string(stdout_tail));
4229 out.insert("stderr_tail".to_string(), Value::string(stderr_tail));
4230 out.insert(
4231 "truncated_bytes".to_string(),
4232 Value::int(dropped.min(i64::MAX as u64) as i64),
4233 );
4234 Ok(Value::map(out))
4235}
4236
4237fn meta_to_value(meta: &FuncMeta) -> Value {
4238 let mut map = BTreeMap::new();
4239 map.insert("name".to_string(), Value::string(meta.name.clone()));
4240 map.insert("module".to_string(), Value::string(meta.module.clone()));
4241 map.insert(
4242 "kind".to_string(),
4243 Value::string(meta.kind.label().to_string()),
4244 );
4245 let params = match &meta.params {
4246 Some(params) => Value::list(
4247 params
4248 .iter()
4249 .map(|p| {
4250 let mut entry = BTreeMap::new();
4251 entry.insert("name".to_string(), Value::string(p.name.clone()));
4252 entry.insert(
4253 "param_type".to_string(),
4254 Value::string(
4255 p.param_type
4256 .as_ref()
4257 .map(render_structural)
4258 .unwrap_or_default(),
4259 ),
4260 );
4261 entry.insert(
4262 "allowed".to_string(),
4263 Value::string(
4264 p.allowed
4265 .map(|values| values.join(", "))
4266 .unwrap_or_default(),
4267 ),
4268 );
4269 entry.insert("docs".to_string(), Value::string(String::new()));
4270 entry.insert("optional".to_string(), Value::bool(p.optional));
4271 entry.insert(
4272 "options".to_string(),
4273 match p.options {
4274 Some(keys) => Value::list(
4275 keys.iter()
4276 .map(|key| {
4277 let mut option = BTreeMap::new();
4278 option.insert(
4279 "name".to_string(),
4280 Value::string(key.name.to_string()),
4281 );
4282 option.insert(
4283 "value_type".to_string(),
4284 Value::string(render_structural(&key.value)),
4285 );
4286 option.insert(
4287 "required".to_string(),
4288 Value::bool(key.required),
4289 );
4290 option.insert(
4291 "default".to_string(),
4292 Value::string(
4293 key.default.unwrap_or_default().to_string(),
4294 ),
4295 );
4296 Value::map(option)
4297 })
4298 .collect(),
4299 ),
4300 None => Value::string(String::new()),
4301 },
4302 );
4303 Value::map(entry)
4304 })
4305 .collect(),
4306 ),
4307 None => Value::list(Vec::new()),
4311 };
4312 map.insert("params".to_string(), params);
4313 map.insert(
4314 "returns".to_string(),
4315 Value::string(
4316 meta.returns
4317 .as_ref()
4318 .map(render_structural)
4319 .unwrap_or_default(),
4320 ),
4321 );
4322 map.insert("rpn".to_string(), Value::bool(meta.rpn));
4323 map.insert(
4324 "summary".to_string(),
4325 Value::string(meta.summary.to_string()),
4326 );
4327 Value::map(map)
4328}
4329
4330#[derive(Debug, Clone)]
4334pub struct RecordSchema {
4335 pub name: &'static str,
4336 pub fields: std::sync::Arc<[Field]>,
4337}
4338
4339#[derive(Clone)]
4343pub struct HostModule<P: ProcessManager> {
4344 pub name: String,
4345 pub funcs: Vec<HostRegistration<P>>,
4346 pub types: Vec<&'static TypeDescriptor>,
4347 pub record_schemas: Vec<RecordSchema>,
4348 pub states: Vec<ModuleState>,
4355}
4356
4357#[derive(Clone)]
4361pub struct ModuleState {
4362 id: std::any::TypeId,
4363 state: std::sync::Arc<dyn std::any::Any + Send + Sync>,
4364}
4365
4366pub type PreRunInspector = dyn Fn(&[Step]) -> Result<()> + Send + Sync;
4370
4371#[derive(Clone)]
4377pub struct PreRunCheck {
4378 check: Arc<PreRunInspector>,
4379}
4380
4381impl PreRunCheck {
4382 pub fn new(check: impl Fn(&[Step]) -> Result<()> + Send + Sync + 'static) -> Self {
4384 Self {
4385 check: Arc::new(check),
4386 }
4387 }
4388
4389 pub fn run(&self, steps: &[Step]) -> Result<()> {
4391 (self.check)(steps)
4392 }
4393}
4394
4395impl<P: ProcessManager> HostModule<P> {
4396 pub fn with_state<T: Send + Sync + 'static>(mut self, state: std::sync::Arc<T>) -> Self {
4399 self.states.push(ModuleState {
4400 id: std::any::TypeId::of::<T>(),
4401 state,
4402 });
4403 self
4404 }
4405
4406 pub fn check_pre_run(&self, steps: &[Step]) -> Result<()> {
4410 for state in &self.states {
4411 if let Some(check) = state.state.downcast_ref::<PreRunCheck>() {
4412 check.run(steps)?;
4413 }
4414 }
4415 Ok(())
4416 }
4417}
4418
4419impl<P: ProcessManager> ExecState<P> {
4420 pub fn register_module(&mut self, module: HostModule<P>) {
4423 for registration in module.funcs {
4424 match registration {
4425 HostRegistration::Stateful { name, meta, func } => {
4426 self.functions.register_host(&module.name, name, meta, func);
4427 }
4428 HostRegistration::Pure { name, meta, func } => {
4429 self.functions
4430 .register_pure_host(&module.name, name, meta, func);
4431 }
4432 HostRegistration::Both {
4433 name,
4434 meta,
4435 func,
4436 template,
4437 } => {
4438 self.functions
4439 .register_both_host(&module.name, name, meta, func, template);
4440 }
4441 }
4442 }
4443 for descriptor in module.types {
4444 self.register_type(descriptor);
4445 }
4446 for schema in module.record_schemas {
4447 self.register_record_schema(schema.name, schema.fields);
4448 }
4449 for state in module.states {
4450 self.module_states
4451 .insert((module.name.clone(), state.id), state.state);
4452 }
4453 }
4454
4455 pub fn list_functions(&self) -> Vec<FuncMeta> {
4457 let mut out: Vec<FuncMeta> = self.functions.entries_metas().into_iter().collect();
4458 if !out.iter().any(|m| m.name == KEYWORD_INSPECT) {
4460 out.push(FuncMeta {
4461 name: KEYWORD_INSPECT.to_string(),
4462 module: STD_MODULE_NAME.to_string(),
4463 kind: FuncKind::HostCtx,
4464 params: None,
4465 returns: Some(TypeTag::Map),
4466 rpn: false,
4467 summary: "Inspect a variable binding.",
4468 docs: "INSPECT($var): dedicated AST node taking a variable, not a value.",
4469 examples: &[],
4470 });
4471 }
4472 out.sort_by(|a, b| a.name.cmp(&b.name));
4473 out
4474 }
4475
4476 pub fn describe_function(&self, name: &str) -> Option<Value> {
4478 if let Some(meta) = self.functions.meta(name) {
4479 return Some(meta_to_value(&meta));
4480 }
4481 if name == KEYWORD_INSPECT {
4483 return Some(meta_to_value(&FuncMeta {
4484 name: KEYWORD_INSPECT.to_string(),
4485 module: STD_MODULE_NAME.to_string(),
4486 kind: FuncKind::HostCtx,
4487 params: None,
4488 returns: Some(TypeTag::Map),
4489 rpn: false,
4490 summary: "Inspect a variable binding.",
4491 docs: "INSPECT($var): dedicated AST node taking a variable, not a value.",
4492 examples: &[],
4493 }));
4494 }
4495 None
4496 }
4497
4498 pub(super) fn clone_native_pure(&self, name: &str) -> Option<PureFn> {
4499 self.functions.clone_pure_fn(name)
4500 }
4501
4502 pub fn pure_function_table(&self) -> Arc<PureTable> {
4507 self.functions.pure_shared()
4508 }
4509
4510 pub(super) fn clone_native_ctx(&self, name: &str) -> Option<NativeFn<P>> {
4511 self.functions.clone_ctx_fn(name)
4512 }
4513
4514 pub(super) fn native_meta(&self, name: &str) -> Option<FuncMeta> {
4515 self.functions.meta(name)
4516 }
4517}
4518
4519#[cfg(test)]
4520mod tests {
4521 use super::*;
4522
4523 #[test]
4524 fn placeholder_resolver_dispatches_table_entries() {
4525 let echo: PureFn = Arc::new(|args| {
4529 args.into_iter()
4530 .next()
4531 .ok_or_else(|| anyhow::anyhow!("ECHO needs 1 arg"))
4532 });
4533 let mut entries = HashMap::new();
4534 entries.insert("ECHO".to_string(), echo);
4535 let mut table = PureTable::new();
4536 table.insert("T".to_string(), entries);
4537 let resolve = placeholder_resolver(Arc::new(table));
4538 let out = resolve("T", "ECHO", vec![Value::string("hi".to_string())]).expect("dispatch");
4539 assert_eq!(out.as_str().expect("string"), "hi");
4540 let err = format!(
4541 "{:#}",
4542 resolve("T", "NOPE", vec![]).expect_err("unknown must fail")
4543 );
4544 assert!(
4545 err.contains("unknown placeholder function 'T::NOPE'"),
4546 "names the call: {err}"
4547 );
4548 assert!(
4549 err.contains("known functions: T::ECHO"),
4550 "lists known names: {err}"
4551 );
4552 }
4553
4554 #[test]
4555 fn describe_entry_renders_union_spellings() {
4556 let union = oxdock_parser::union_tag!(String, Pipe);
4562 let meta = FuncMeta {
4563 name: "T::F".to_string(),
4564 module: "T".to_string(),
4565 kind: FuncKind::HostPure,
4566 params: Some(vec![FuncParam {
4567 name: "text".to_string(),
4568 param_type: Some(union.clone()),
4569 allowed: None,
4570 docs: "",
4571 options: None,
4572 optional: false,
4573 }]),
4574 returns: Some(union),
4575 rpn: false,
4576 summary: "test-only",
4577 docs: "test-only",
4578 examples: &[],
4579 };
4580 let value = meta_to_value(&meta);
4581 let map = value.as_map().expect("describe value is a map");
4582 let params = map
4583 .get("params")
4584 .expect("params key")
4585 .as_list()
4586 .expect("params is a list");
4587 let first = params[0].as_map().expect("entry is a map");
4588 assert_eq!(
4589 first.get("param_type").and_then(Value::as_str),
4590 Some("STRING|PIPE"),
4591 "param renders the set"
4592 );
4593 assert_eq!(
4594 map.get("returns").and_then(Value::as_str),
4595 Some("STRING|PIPE"),
4596 "returns render the set"
4597 );
4598 }
4599
4600 #[test]
4601 fn describe_entry_renders_handle_payload() {
4602 let meta = FuncMeta {
4606 name: "SCRIPT::FETCH".to_string(),
4607 module: "SCRIPT".to_string(),
4608 kind: FuncKind::Script,
4609 params: Some(vec![]),
4610 returns: Some(TypeTag::HandleOf(std::sync::Arc::new(TypeTag::String))),
4611 rpn: false,
4612 summary: "test-only",
4613 docs: "test-only",
4614 examples: &[],
4615 };
4616 let value = meta_to_value(&meta);
4617 let map = value.as_map().expect("describe value is a map");
4618 assert_eq!(
4619 map.get("returns").and_then(Value::as_str),
4620 Some("HANDLE<STRING>"),
4621 "returns render the payload"
4622 );
4623 }
4624
4625 #[test]
4626 fn describe_entry_carries_optional_flag() {
4627 let meta = FuncMeta {
4631 name: "T::F".to_string(),
4632 module: "T".to_string(),
4633 kind: FuncKind::HostPure,
4634 params: Some(vec![
4635 FuncParam {
4636 name: "url".to_string(),
4637 param_type: Some(TypeTag::String),
4638 allowed: None,
4639 docs: "",
4640 options: None,
4641 optional: false,
4642 },
4643 FuncParam {
4644 name: "options".to_string(),
4645 param_type: Some(TypeTag::Map),
4646 allowed: None,
4647 docs: "",
4648 options: None,
4649 optional: true,
4650 },
4651 ]),
4652 returns: Some(TypeTag::String),
4653 rpn: false,
4654 summary: "test-only",
4655 docs: "test-only",
4656 examples: &[],
4657 };
4658 let value = meta_to_value(&meta);
4659 let map = value.as_map().expect("describe value is a map");
4660 let params = map
4661 .get("params")
4662 .expect("params key")
4663 .as_list()
4664 .expect("params is a list");
4665 assert_eq!(params.len(), 2);
4666 let first = params[0].as_map().expect("entry is a map");
4667 let second = params[1].as_map().expect("entry is a map");
4668 assert_eq!(
4669 first.get("optional").and_then(Value::as_bool),
4670 Some(false),
4671 "required param must read false"
4672 );
4673 assert_eq!(
4674 second.get("optional").and_then(Value::as_bool),
4675 Some(true),
4676 "omittable param must read true"
4677 );
4678 }
4679
4680 #[test]
4681 fn template_twins_mirror_string_paths_and_refuse_pipes() {
4682 let pipe = Value::pipe_fresh();
4688 type TwinCase = (&'static str, Box<dyn Fn() -> Result<Value>>);
4689 let cases: Vec<TwinCase> = vec![
4690 (
4691 "TEXT_TRIM",
4692 Box::new(|| text_trim_string(Value::string(" hello ".to_string()))),
4693 ),
4694 (
4695 "TEXT_TRIM_PREFIX",
4696 Box::new(|| {
4697 text_trim_prefix_string(Value::string("v1".to_string()), "v".to_string())
4698 }),
4699 ),
4700 (
4701 "TEXT_TRIM_SUFFIX",
4702 Box::new(|| {
4703 text_trim_suffix_string(Value::string("a.gz".to_string()), "x".to_string())
4704 }),
4705 ),
4706 (
4707 "TEXT_TO_UPPER",
4708 Box::new(|| text_to_upper_string(Value::string("hi".to_string()))),
4709 ),
4710 (
4711 "TEXT_TO_LOWER",
4712 Box::new(|| text_to_lower_string(Value::string("HI".to_string()))),
4713 ),
4714 (
4715 "TEXT_REPLACE",
4716 Box::new(|| {
4717 text_replace_string(
4718 Value::string("ab".to_string()),
4719 "b".to_string(),
4720 "c".to_string(),
4721 )
4722 }),
4723 ),
4724 (
4725 "TEXT_REPLACE_REGEX",
4726 Box::new(|| {
4727 text_replace_regex_string(
4728 Value::string("ab".to_string()),
4729 "b".to_string(),
4730 "c".to_string(),
4731 )
4732 }),
4733 ),
4734 ];
4735 assert_eq!(cases.len(), 7, "every mirror op needs a twin row");
4736 for (name, run) in &cases {
4737 let value = run().unwrap_or_else(|e| panic!("{name} twin must answer strings: {e:#}"));
4738 assert!(
4739 value.as_str().is_some(),
4740 "{name} twin must answer STRING, got {}",
4741 value.type_name()
4742 );
4743 }
4744 assert_eq!(
4745 text_trim_string(Value::string(" hello ".to_string()))
4746 .expect("trim twin")
4747 .as_str(),
4748 Some("hello")
4749 );
4750 let pipe_cases: Vec<(&str, Result<Value>)> = vec![
4752 ("TEXT_TRIM", text_trim_string(pipe.clone())),
4753 (
4754 "TEXT_TRIM_PREFIX",
4755 text_trim_prefix_string(pipe.clone(), "v".to_string()),
4756 ),
4757 (
4758 "TEXT_TRIM_SUFFIX",
4759 text_trim_suffix_string(pipe.clone(), ".gz".to_string()),
4760 ),
4761 ("TEXT_TO_UPPER", text_to_upper_string(pipe.clone())),
4762 ("TEXT_TO_LOWER", text_to_lower_string(pipe.clone())),
4763 (
4764 "TEXT_REPLACE",
4765 text_replace_string(pipe.clone(), "a".to_string(), "b".to_string()),
4766 ),
4767 (
4768 "TEXT_REPLACE_REGEX",
4769 text_replace_regex_string(pipe.clone(), "a".to_string(), "b".to_string()),
4770 ),
4771 ];
4772 for (name, result) in pipe_cases {
4773 let err = result.expect_err(&format!("{name} twin must refuse PIPE"));
4774 assert!(
4775 format!("{err:#}").contains("step IO"),
4776 "{name} refusal names the missing context: {err:#}"
4777 );
4778 }
4779 }
4780
4781 #[test]
4782 fn shell_words_join_split_round_trip() {
4783 let words = vec![
4787 "gh".to_string(),
4788 "issue".to_string(),
4789 "comment".to_string(),
4790 "with spaces".to_string(),
4791 "it's".to_string(),
4792 "say \"hi\"".to_string(),
4793 "$HOME".to_string(),
4794 "$(whoami)".to_string(),
4795 "C:\\path\\to".to_string(),
4796 "naïve café".to_string(),
4797 "".to_string(),
4798 ];
4799 let joined = shell_words::join(&words);
4800 let back = shell_words::split(&joined).expect("join output must parse");
4801 assert_eq!(back, words);
4802 assert!(shell_words::split("unbalanced \"quote").is_err());
4803 }
4804}