1use std::collections::{BTreeMap, HashMap, HashSet};
2use std::sync::Arc;
3
4use anyhow::Result;
5use oxdock_func_macro::oxdock_func;
6use oxdock_parser::value::HandleValue;
7use oxdock_parser::{
8 Field, GuardExpr, KEYWORD_INSPECT, SCRIPT_MODULE_NAME, STD_MODULE_NAME, SemaphoreState, Step,
9 TypeTag, Value, base_name, guards_overlap, qualify, render_structural, split_qualified,
10};
11use oxdock_pipe::PipeHandle;
12use oxdock_process::{CommandStdin, DefaultProcessManager, ProcessManager};
13
14use super::io::StreamHandle;
15use super::state::ExecState;
16use super::steps::StepCtx;
17use super::typing::TypeDescriptor;
18
19#[derive(Debug, Clone, Copy, PartialEq, Eq)]
25pub enum FuncKind {
26 Script,
27 HostCtx,
28 HostPure,
29}
30
31pub(super) fn file_func_key(defining_file: &str, name: &str) -> String {
35 qualify(defining_file, name)
36}
37
38pub(super) fn ambiguous_alias_message(alias: &str, name: &str, files: &HashSet<String>) -> String {
41 let mut files: Vec<&str> = files.iter().map(|file| file.as_str()).collect();
42 files.sort();
43 format!(
44 "function `{alias}::{name}` is ambiguous: alias `{alias}` is imported from multiple files ({})",
45 files.join(", ")
46 )
47}
48
49pub(super) enum AliasResolution {
55 Global,
57 Canonical(String),
59 Unknown,
61 Ambiguous {
64 alias: String,
65 base: String,
66 files: HashSet<String>,
67 },
68 Any {
75 base: String,
76 files: HashSet<String>,
77 has_host: bool,
78 },
79}
80
81pub(super) type AliasTargets = HashMap<String, Vec<(Option<String>, Option<GuardExpr>)>>;
88
89pub(super) fn classify_alias_call(
95 unit_targets: &AliasTargets,
96 name: &str,
97 exists: &dyn Fn(&str) -> bool,
98) -> AliasResolution {
99 let Some((alias, base)) = name.split_once("::") else {
100 return AliasResolution::Global;
101 };
102 if alias == SCRIPT_MODULE_NAME {
103 return AliasResolution::Global;
104 }
105 let Some(entries) = unit_targets.get(alias) else {
106 return AliasResolution::Global;
107 };
108 if entries.is_empty() {
109 return AliasResolution::Unknown;
110 }
111 let mut files: Vec<(&str, Vec<Option<&GuardExpr>>)> = Vec::new();
114 let mut host_guards: Vec<Option<&GuardExpr>> = Vec::new();
115 for (file, guard) in entries {
116 match file {
117 Some(path) => match files.iter_mut().find(|(known, _)| *known == path) {
118 Some((_, guards)) => guards.push(guard.as_ref()),
119 None => files.push((path, vec![guard.as_ref()])),
120 },
121 None => host_guards.push(guard.as_ref()),
122 }
123 }
124 if files.is_empty() {
125 return AliasResolution::Unknown;
126 }
127 let overlaps = |left: &[Option<&GuardExpr>], right: &[Option<&GuardExpr>]| {
128 left.iter()
129 .any(|a| right.iter().any(|b| guards_overlap(*a, *b)))
130 };
131 if files.len() == 1 {
132 let disjoint_host = host_guards
136 .iter()
137 .any(|host| !overlaps(&files[0].1, &[*host]));
138 if !disjoint_host {
139 return AliasResolution::Canonical(file_func_key(files[0].0, base));
140 }
141 let mut all = HashSet::new();
142 all.insert(files[0].0.to_string());
143 return AliasResolution::Any {
144 base: base.to_string(),
145 files: all,
146 has_host: true,
147 };
148 }
149 let mut ambiguous = HashSet::new();
150 for (i, (file, guards)) in files.iter().enumerate() {
151 for (other, other_guards) in files.iter().skip(i + 1) {
152 if overlaps(guards, other_guards)
153 && (exists(&file_func_key(file, base)) || exists(&file_func_key(other, base)))
154 {
155 ambiguous.insert((*file).to_string());
156 ambiguous.insert((*other).to_string());
157 }
158 }
159 }
160 if !ambiguous.is_empty() {
161 return AliasResolution::Ambiguous {
162 alias: alias.to_string(),
163 base: base.to_string(),
164 files: ambiguous,
165 };
166 }
167 let all: HashSet<String> = files.iter().map(|(file, _)| (*file).to_string()).collect();
168 if all.iter().any(|file| exists(&file_func_key(file, base))) {
169 return AliasResolution::Any {
170 base: base.to_string(),
171 files: all,
172 has_host: !host_guards.is_empty(),
173 };
174 }
175 AliasResolution::Unknown
176}
177
178pub(super) fn disjoint_template_script_visible(
186 base: &str,
187 files: &HashSet<String>,
188 has_host: bool,
189 exists: &dyn Fn(&str) -> bool,
190) -> bool {
191 !has_host && !files.is_empty() && files.iter().all(|file| exists(&file_func_key(file, base)))
192}
193
194pub(super) fn disjoint_alias_placeholder_miss(
201 module: &str,
202 name: &str,
203 base: &str,
204 files: &HashSet<String>,
205 has_host: bool,
206 is_script: &dyn Fn(&str) -> bool,
207) -> String {
208 let script = disjoint_template_script_visible(base, files, has_host, is_script);
209 describe_placeholder_miss(module, name, script, false, !script)
210 .expect("disjoint miss always renders")
211}
212
213pub(super) fn spellings_for_defining_file(
220 unit_targets: &AliasTargets,
221 defining: &str,
222 base: &str,
223 is_script: &dyn Fn(&str) -> bool,
224) -> (Vec<String>, Vec<(String, HashSet<String>)>) {
225 let mut direct = Vec::new();
226 let mut ambiguous = Vec::new();
227 for (alias, files) in unit_targets {
228 if !files
229 .iter()
230 .any(|(file, _)| file.as_deref() == Some(defining))
231 {
232 continue;
233 }
234 let spelling = qualify(alias, base);
235 match classify_alias_call(unit_targets, &spelling, &|key| {
236 key == file_func_key(defining, base)
237 }) {
238 AliasResolution::Canonical(_) => direct.push(spelling),
239 AliasResolution::Ambiguous { files, .. } => {
240 ambiguous.push((spelling, files));
241 }
242 AliasResolution::Any {
243 base,
244 files,
245 has_host,
246 } => {
247 if disjoint_template_script_visible(&base, &files, has_host, is_script) {
248 direct.push(spelling);
249 }
250 }
251 AliasResolution::Global | AliasResolution::Unknown => {}
252 }
253 }
254 (direct, ambiguous)
255}
256
257impl FuncKind {
258 pub fn label(&self) -> &'static str {
259 match self {
260 FuncKind::Script => "script",
261 FuncKind::HostCtx | FuncKind::HostPure => "host",
262 }
263 }
264}
265
266#[derive(Debug, Clone)]
284pub struct FuncParam {
285 pub name: String,
286 pub param_type: Option<TypeTag>,
287 pub allowed: Option<&'static [&'static str]>,
288 pub docs: &'static str,
289 pub options: Option<&'static [ParamOption]>,
290 pub optional: bool,
291}
292
293pub fn required_arity(params: &[FuncParam]) -> usize {
298 params
299 .iter()
300 .rev()
301 .take_while(|param| param.optional)
302 .fold(params.len(), |count, _| count - 1)
303}
304
305pub fn fill_optional_args(params: &[FuncParam], mut values: Vec<Value>) -> Vec<Value> {
310 assert!(
311 values.len() <= params.len(),
312 "arity gate must run before fill_optional_args"
313 );
314 assert!(
315 values.len() >= required_arity(params),
316 "arity gate must run before fill_optional_args"
317 );
318 while values.len() < params.len() {
319 values.push(Value::map(BTreeMap::new()));
320 }
321 values
322}
323
324#[derive(Debug, Clone)]
331pub struct ParamOption {
332 pub name: &'static str,
333 pub value: TypeTag,
334 pub required: bool,
335 pub default: Option<&'static str>,
336}
337
338#[derive(Debug, Clone)]
344pub struct FuncMeta {
345 pub name: String,
346 pub module: String,
350 pub kind: FuncKind,
351 pub params: Option<Vec<FuncParam>>,
352 pub returns: Option<TypeTag>,
353 pub rpn: bool,
354 pub summary: &'static str,
355 pub docs: &'static str,
356 pub examples: &'static [crate::Example],
362}
363
364pub type PureFn = Arc<dyn Fn(Vec<Value>) -> Result<Value> + Send + Sync>;
367
368pub type NativeFn<P> = Arc<dyn Fn(&mut StepCtx<P>, Vec<Value>) -> Result<Value> + Send + Sync>;
370
371pub trait OxDockFn<P: ProcessManager> {
375 fn registration() -> HostRegistration<P>;
378}
379
380pub enum HostRegistration<P: ProcessManager> {
389 Stateful {
390 name: String,
391 meta: FuncMeta,
392 func: NativeFn<P>,
393 },
394 Pure {
395 name: String,
396 meta: FuncMeta,
397 func: PureFn,
398 },
399 Both {
400 name: String,
401 meta: FuncMeta,
402 func: NativeFn<P>,
403 template: PureFn,
404 },
405}
406
407impl<P: ProcessManager> Clone for HostRegistration<P> {
410 fn clone(&self) -> Self {
411 match self {
412 HostRegistration::Stateful { name, meta, func } => HostRegistration::Stateful {
413 name: name.clone(),
414 meta: meta.clone(),
415 func: Arc::clone(func),
416 },
417 HostRegistration::Pure { name, meta, func } => HostRegistration::Pure {
418 name: name.clone(),
419 meta: meta.clone(),
420 func: Arc::clone(func),
421 },
422 HostRegistration::Both {
423 name,
424 meta,
425 func,
426 template,
427 } => HostRegistration::Both {
428 name: name.clone(),
429 meta: meta.clone(),
430 func: Arc::clone(func),
431 template: Arc::clone(template),
432 },
433 }
434 }
435}
436
437impl<P: ProcessManager> HostRegistration<P> {
438 pub fn meta(&self) -> &FuncMeta {
441 match self {
442 HostRegistration::Stateful { meta, .. } => meta,
443 HostRegistration::Pure { meta, .. } => meta,
444 HostRegistration::Both { meta, .. } => meta,
445 }
446 }
447}
448
449#[derive(Debug, Clone)]
455pub(super) struct FuncDefData {
456 pub(super) params: Vec<(String, TypeTag, bool)>,
457 pub(super) return_type: TypeTag,
458 pub(super) return_spelling: String,
459 pub(super) is_async: bool,
460 pub(super) body: Vec<Step>,
461 pub(super) module: Option<String>,
466}
467
468pub fn optional_zero_value(tag: &TypeTag) -> Result<Value> {
476 match tag {
477 TypeTag::Bool => Ok(Value::bool(false)),
478 TypeTag::String | TypeTag::Any => Ok(Value::string(String::new())),
479 TypeTag::Int => Ok(Value::int(0)),
480 TypeTag::Float => Ok(Value::float(0.0)),
481 TypeTag::List | TypeTag::ListOf(_) => Ok(Value::list(Vec::new())),
482 TypeTag::Map | TypeTag::MapOf(_) => Ok(Value::map(BTreeMap::new())),
483 TypeTag::Record(fields)
484 if fields
485 .iter()
486 .all(|field| field.optional || field.default.is_some()) =>
487 {
488 Ok(Value::map(BTreeMap::new()))
489 }
490 other => anyhow::bail!(
491 "no zero value for {}; omit the `?` or pass the argument explicitly",
492 oxdock_parser::render_structural(other)
493 ),
494 }
495}
496
497pub fn resolve_script_params<P: ProcessManager>(
503 state: &ExecState<P>,
504 func_name: &str,
505 params: &[(String, String, bool)],
506) -> Result<Vec<(String, TypeTag, bool)>> {
507 let mut resolved = Vec::with_capacity(params.len());
508 for (pname, ptype, optional) in params {
509 let clean = pname.trim_start_matches('$').to_string();
510 let tag = state
511 .resolve_tag(ptype)
512 .map_err(|err| anyhow::anyhow!("function `{func_name}`: {err:#}"))?;
513 state.check_declaration_tag(&format!("function `{func_name}` param `${clean}`"), &tag)?;
514 if *optional {
515 optional_zero_value(&tag).map(|_| ()).map_err(|err| {
516 anyhow::anyhow!("function `{func_name}` optional param `${clean}`: {err:#}")
517 })?;
518 }
519 resolved.push((clean, tag, *optional));
520 }
521 Ok(resolved)
522}
523
524pub fn check_script_param_tags(func_name: &str, params: &[(String, TypeTag, bool)]) -> Result<()> {
527 for (pname, tag, optional) in params {
528 if *optional {
529 optional_zero_value(tag).map(|_| ()).map_err(|err| {
530 anyhow::anyhow!("function `{func_name}` optional param `${pname}`: {err:#}")
531 })?;
532 }
533 }
534 Ok(())
535}
536
537pub(super) enum FuncBody<P: ProcessManager> {
542 Script(FuncDefData),
543 Pure(PureFn),
544 Ctx(NativeFn<P>),
545 Both { pure: PureFn, ctx: NativeFn<P> },
546}
547
548impl<P: ProcessManager> Clone for FuncBody<P> {
550 fn clone(&self) -> Self {
551 match self {
552 FuncBody::Script(def) => FuncBody::Script(def.clone()),
553 FuncBody::Pure(func) => FuncBody::Pure(Arc::clone(func)),
554 FuncBody::Ctx(func) => FuncBody::Ctx(Arc::clone(func)),
555 FuncBody::Both { pure, ctx } => FuncBody::Both {
556 pure: Arc::clone(pure),
557 ctx: Arc::clone(ctx),
558 },
559 }
560 }
561}
562
563pub(super) struct FuncEntry<P: ProcessManager> {
567 pub(super) meta: FuncMeta,
568 pub(super) body: FuncBody<P>,
569}
570
571impl<P: ProcessManager> Clone for FuncEntry<P> {
573 fn clone(&self) -> Self {
574 Self {
575 meta: self.meta.clone(),
576 body: self.body.clone(),
577 }
578 }
579}
580
581struct ScopeFrame<P: ProcessManager> {
584 defined: HashSet<String>,
585 shadowed: Vec<(String, FuncEntry<P>)>,
586}
587
588impl<P: ProcessManager> Clone for ScopeFrame<P> {
590 fn clone(&self) -> Self {
591 Self {
592 defined: self.defined.clone(),
593 shadowed: self.shadowed.clone(),
594 }
595 }
596}
597
598pub type PureTable = HashMap<String, HashMap<String, PureFn>>;
608
609pub fn placeholder_resolver(table: Arc<PureTable>) -> oxdock_process::PlaceholderCall {
618 Arc::new(move |module, func, args| {
619 let callee = table
620 .get(module)
621 .and_then(|entries| entries.get(func))
622 .ok_or_else(|| {
623 let mut known: Vec<String> = table
624 .iter()
625 .flat_map(|(m, entries)| entries.keys().map(move |f| format!("{m}::{f}")))
626 .collect();
627 known.sort();
628 anyhow::anyhow!(
629 "unknown placeholder function '{module}::{func}'; known functions: {}",
630 known.join(", ")
631 )
632 })?;
633 callee(args)
634 })
635}
636
637pub(super) fn describe_placeholder_miss(
644 module: &str,
645 name: &str,
646 is_script: bool,
647 is_stateful: bool,
648 alias_known: bool,
649) -> Option<String> {
650 let qualified = qualify(module, name);
651 if is_script {
652 let call = if module == SCRIPT_MODULE_NAME {
653 format!("{name}(...)")
654 } else {
655 format!("{qualified}(...)")
656 };
657 return Some(format!(
658 "placeholder function '{qualified}' is a script function and cannot run in {{{{ }}}}; bind the result first with LET $v = {call} then interpolate {{{{ $v }}}}"
659 ));
660 }
661 if is_stateful {
662 return Some(format!(
663 "placeholder function '{qualified}' is stateful and cannot run in {{{{ }}}}; capture it first with LET then interpolate {{{{ $v }}}}"
664 ));
665 }
666 if alias_known {
667 return Some(format!(
668 "placeholder function '{qualified}': no function '{name}' under file alias '{module}'; check the file's EXPORT list and the IMPORT harvest, or bind a known function first with LET then interpolate {{{{ $v }}}}"
669 ));
670 }
671 None
672}
673
674pub(super) struct PlaceholderClasses {
677 pub script: HashSet<String>,
678 pub stateful: HashSet<String>,
679 pub aliases: HashSet<String>,
680 pub ambiguous: HashMap<String, HashSet<String>>,
682}
683
684impl PlaceholderClasses {
685 pub(super) fn describe(&self, module: &str, name: &str) -> Option<String> {
686 let qualified = qualify(module, name);
687 if let Some(files) = self.ambiguous.get(&qualified) {
688 return Some(ambiguous_alias_message(module, name, files));
689 }
690 describe_placeholder_miss(
691 module,
692 name,
693 self.script.contains(&qualified),
694 self.stateful.contains(&qualified),
695 self.aliases.contains(module),
696 )
697 }
698}
699
700pub struct FunctionRegistry<P: ProcessManager> {
701 entries: HashMap<String, FuncEntry<P>>,
702 scopes: Vec<ScopeFrame<P>>,
703 pure_shared: Arc<PureTable>,
704 script_docs: HashMap<String, (String, String)>,
708}
709
710impl<P: ProcessManager> FunctionRegistry<P> {
711 pub(super) fn with_builtins() -> Self {
712 let mut reg = Self {
713 entries: HashMap::new(),
714 pure_shared: Arc::new(HashMap::new()),
715 script_docs: HashMap::new(),
716 scopes: vec![ScopeFrame {
717 defined: HashSet::new(),
718 shadowed: Vec::new(),
719 }],
720 };
721 for host in Self::builtin_registrations() {
725 match host {
726 HostRegistration::Stateful { name, meta, func } => {
727 reg.insert_qualified(STD_MODULE_NAME, name, meta, FuncBody::Ctx(func));
728 }
729 HostRegistration::Pure { name, meta, func } => {
730 reg.insert_qualified(STD_MODULE_NAME, name, meta, FuncBody::Pure(func));
731 }
732 HostRegistration::Both {
733 name,
734 meta,
735 func,
736 template,
737 } => {
738 reg.insert_qualified(
739 STD_MODULE_NAME,
740 name,
741 meta,
742 FuncBody::Both {
743 pure: template,
744 ctx: func,
745 },
746 );
747 }
748 }
749 }
750 reg
751 }
752
753 pub(super) fn builtin_registrations() -> Vec<HostRegistration<P>> {
758 vec![
759 Int::registration(),
760 Float::registration(),
761 BoolConvert::registration(),
762 BoolOr::registration(),
763 FormatByteCount::registration(),
764 ParseByteCount::registration(),
765 FormatDuration::registration(),
766 ParseDuration::registration(),
767 Types::registration(),
768 TypeDescribe::registration(),
769 Glob::registration(),
770 LoadToml::registration(),
771 LoadJson::registration(),
772 HashSha256::registration(),
773 Cwd::registration(),
774 ParseToml::registration(),
775 ParseJson::registration(),
776 PathType::registration(),
777 PathWritable::registration(),
778 IsExec::registration(),
779 IsFile::registration(),
780 IsDir::registration(),
781 Exists::registration(),
782 HasKey::registration(),
783 Get::registration(),
784 MapSet::registration(),
785 MergeMaps::registration(),
786 Base64Encode::registration(),
787 Base64Decode::registration(),
788 Rand::registration(),
789 ToJson::registration(),
790 TypeOf::registration(),
791 Functions::registration(),
792 Describe::registration(),
793 IsMain::registration(),
794 IsTerminal::registration(),
795 Eof::registration(),
796 TaskPoll::registration(),
797 Version::registration(),
798 Interpreter::registration(),
799 Argv::registration(),
800 ParseArgs::registration(),
801 ParseFlags::registration(),
802 ParsePositionals::registration(),
803 TextTrim::registration(),
804 TextTrimPrefix::registration(),
805 TextTrimSuffix::registration(),
806 PathJoin::registration(),
807 PathBase::registration(),
808 PathRel::registration(),
809 TextToUpper::registration(),
810 TextToLower::registration(),
811 TextReplace::registration(),
812 TextReplaceRegex::registration(),
813 TextSplit::registration(),
814 TextJoin::registration(),
815 TextLines::registration(),
816 TextFields::registration(),
817 TextMatch::registration(),
818 TextExtract::registration(),
819 TextStartsWith::registration(),
820 TextEndsWith::registration(),
821 Contains::registration(),
822 Len::registration(),
823 TextCount::registration(),
824 TextCountMatches::registration(),
825 TextGrep::registration(),
826 TextLinesRange::registration(),
827 SemaphoreNew::registration(),
828 SemaphoreTryAcquire::registration(),
829 SemaphoreAvailable::registration(),
830 ShellSplitArgs::registration(),
831 ShellJoinArgs::registration(),
832 ]
833 }
834
835 pub(super) fn keys(&self) -> HashSet<String> {
838 self.entries.keys().cloned().collect()
839 }
840
841 pub(super) fn get(&self, name: &str) -> Option<FuncEntry<P>> {
843 self.entries.get(name).cloned()
844 }
845
846 pub(super) fn describe_unit_placeholder_miss(
852 &self,
853 unit_targets: &AliasTargets,
854 module: &str,
855 name: &str,
856 ) -> Option<String> {
857 let qualified = qualify(module, name);
858 match classify_alias_call(unit_targets, &qualified, &|key| {
863 self.entries.contains_key(key)
864 }) {
865 AliasResolution::Canonical(canonical) => {
866 if let Some(entry) = self.entries.get(&canonical) {
867 if let Some(miss) = Self::placeholder_miss_for_body(module, name, &entry.body) {
868 return Some(miss);
869 }
870 None
871 } else {
872 describe_placeholder_miss(module, name, false, false, true)
873 }
874 }
875 AliasResolution::Global => {
876 if let Some(entry) = self.entries.get(&qualified) {
877 if let Some(miss) = Self::placeholder_miss_for_body(module, name, &entry.body) {
881 return Some(miss);
882 }
883 }
884 None
885 }
886 AliasResolution::Ambiguous { files, .. } => {
887 Some(ambiguous_alias_message(module, name, &files))
888 }
889 AliasResolution::Unknown => describe_placeholder_miss(module, name, false, false, true),
890 AliasResolution::Any {
896 base,
897 files,
898 has_host,
899 } => Some(disjoint_alias_placeholder_miss(
900 module,
901 name,
902 &base,
903 &files,
904 has_host,
905 &|key| matches!(self.entries.get(key), Some(entry) if matches!(entry.body, FuncBody::Script(_))),
906 )),
907 }
908 }
909
910 fn placeholder_miss_for_body(module: &str, name: &str, body: &FuncBody<P>) -> Option<String> {
914 match body {
915 FuncBody::Script(_) => describe_placeholder_miss(module, name, true, false, false),
916 FuncBody::Ctx(_) => describe_placeholder_miss(module, name, false, true, false),
917 FuncBody::Pure(_) | FuncBody::Both { .. } => None,
918 }
919 }
920
921 pub(super) fn placeholder_snapshot(&self, unit_targets: &AliasTargets) -> PlaceholderClasses {
925 let mut script = HashSet::new();
926 let mut stateful = HashSet::new();
927 let mut ambiguous: HashMap<String, HashSet<String>> = HashMap::new();
928 for (key, entry) in self.entries.iter() {
929 let Some((module, base)) = split_qualified(key) else {
930 continue;
931 };
932 match &entry.body {
933 FuncBody::Script(def) => {
934 if module == SCRIPT_MODULE_NAME {
935 script.insert(key.clone());
937 continue;
938 }
939 let defining = def.module.as_deref().unwrap_or(module);
947 let (direct, ambiguous_here) = spellings_for_defining_file(
948 unit_targets,
949 defining,
950 base,
951 &|key| matches!(self.entries.get(key), Some(entry) if matches!(entry.body, FuncBody::Script(_))),
952 );
953 script.extend(direct);
954 for (spelling, files) in ambiguous_here {
955 ambiguous.entry(spelling).or_default().extend(files);
956 }
957 }
958 FuncBody::Ctx(_) => {
959 stateful.insert(key.clone());
960 }
961 FuncBody::Pure(_) | FuncBody::Both { .. } => {}
962 }
963 }
964 let aliases = unit_targets.keys().cloned().collect();
965 PlaceholderClasses {
966 script,
967 stateful,
968 aliases,
969 ambiguous,
970 }
971 }
972
973 fn insert_native(&mut self, name: String, meta: FuncMeta, body: FuncBody<P>) {
974 self.entries.insert(name, FuncEntry { meta, body });
975 self.rebuild_pure_shared();
976 }
977
978 fn rebuild_pure_shared(&mut self) {
984 let mut table: PureTable = HashMap::new();
985 for (name, entry) in &self.entries {
986 let func = match &entry.body {
987 FuncBody::Pure(func) => func,
988 FuncBody::Both { pure, .. } => pure,
989 FuncBody::Script(_) | FuncBody::Ctx(_) => continue,
990 };
991 if let Some((module, base)) = split_qualified(name) {
992 table
993 .entry(module.to_string())
994 .or_default()
995 .insert(base.to_string(), Arc::clone(func));
996 }
997 }
998 self.pure_shared = Arc::new(table);
999 }
1000
1001 fn insert_qualified(
1005 &mut self,
1006 module: &str,
1007 base: String,
1008 mut meta: FuncMeta,
1009 body: FuncBody<P>,
1010 ) {
1011 meta.name = qualify(module, &base);
1012 meta.module = module.to_string();
1013 if self.entries.contains_key(&meta.name) {
1018 panic!("duplicate function registration `{}`", meta.name);
1019 }
1020 self.insert_native(meta.name.clone(), meta, body);
1021 }
1022
1023 pub(super) fn register_host(
1024 &mut self,
1025 module: &str,
1026 name: String,
1027 mut meta: FuncMeta,
1028 func: NativeFn<P>,
1029 ) {
1030 meta.kind = FuncKind::HostCtx;
1031 self.insert_qualified(module, name, meta, FuncBody::Ctx(func));
1032 }
1033
1034 pub(super) fn register_pure_host(
1035 &mut self,
1036 module: &str,
1037 name: String,
1038 mut meta: FuncMeta,
1039 func: PureFn,
1040 ) {
1041 meta.kind = FuncKind::HostPure;
1042 self.insert_qualified(module, name, meta, FuncBody::Pure(func));
1043 }
1044
1045 pub(super) fn register_both_host(
1046 &mut self,
1047 module: &str,
1048 name: String,
1049 mut meta: FuncMeta,
1050 func: NativeFn<P>,
1051 template: PureFn,
1052 ) {
1053 meta.kind = FuncKind::HostCtx;
1054 self.insert_qualified(
1055 module,
1056 name,
1057 meta,
1058 FuncBody::Both {
1059 pure: template,
1060 ctx: func,
1061 },
1062 );
1063 }
1064
1065 #[allow(clippy::too_many_arguments)]
1070 pub(super) fn define_script(
1071 &mut self,
1072 name: &str,
1073 params: &[(String, TypeTag, bool)],
1074 return_type: TypeTag,
1075 return_spelling: &str,
1076 is_async: bool,
1077 body: &[Step],
1078 module: Option<&str>,
1079 ) -> Result<()> {
1080 let qualified = qualify(SCRIPT_MODULE_NAME, name);
1081 let shadowable = matches!(
1082 self.entries.get(&qualified).map(|entry| &entry.body),
1083 Some(FuncBody::Script(_))
1084 );
1085 let reserved = self.entries.iter().any(|(key, entry)| {
1090 split_qualified(key).is_some_and(|(_, base)| base == name)
1091 && !matches!(entry.body, FuncBody::Script(_))
1092 });
1093 if reserved && !shadowable {
1094 anyhow::bail!("cannot shadow reserved function `{name}`");
1095 }
1096 if self
1097 .scopes
1098 .last()
1099 .is_some_and(|frame| frame.defined.contains(&qualified))
1100 {
1101 anyhow::bail!("duplicate function `{name}` in same scope");
1102 }
1103 check_script_param_tags(name, params)?;
1104 let old = self.entries.insert(
1105 qualified.clone(),
1106 FuncEntry {
1107 meta: FuncMeta {
1108 name: qualified.clone(),
1109 module: SCRIPT_MODULE_NAME.to_string(),
1110 kind: FuncKind::Script,
1111 params: Some(
1112 params
1113 .iter()
1114 .map(|(pname, param_type, optional)| {
1115 Ok(FuncParam {
1116 name: pname.clone(),
1117 param_type: Some(param_type.clone()),
1118 allowed: None,
1119 docs: "",
1122 options: None,
1123 optional: *optional,
1124 })
1125 })
1126 .collect::<Result<_>>()?,
1127 ),
1128 returns: Some(return_type.clone()),
1129 rpn: false,
1130 summary: "DSL-defined function.",
1131 docs: "Defined via FUNC in script.",
1132 examples: &[],
1133 },
1134 body: FuncBody::Script(FuncDefData {
1135 params: params.to_vec(),
1136 return_type,
1137 return_spelling: return_spelling.to_string(),
1138 is_async,
1139 body: body.to_vec(),
1140 module: module.map(|m| m.to_string()),
1141 }),
1142 },
1143 );
1144 if let Some(frame) = self.scopes.last_mut() {
1145 frame.defined.insert(qualified.clone());
1146 if let Some(old) = old {
1147 frame.shadowed.push((qualified, old));
1148 }
1149 }
1150 Ok(())
1151 }
1152
1153 #[allow(clippy::too_many_arguments)]
1159 pub(super) fn define_file_func(
1160 &mut self,
1161 name: &str,
1162 params: &[(String, TypeTag, bool)],
1163 return_type: TypeTag,
1164 return_spelling: &str,
1165 is_async: bool,
1166 body: &[Step],
1167 defining: &str,
1168 ) -> Result<()> {
1169 let qualified = file_func_key(defining, name);
1173 let shadowable = matches!(
1174 self.entries.get(&qualified).map(|entry| &entry.body),
1175 Some(FuncBody::Script(_))
1176 );
1177 let reserved = self.entries.iter().any(|(key, entry)| {
1181 split_qualified(key).is_some_and(|(_, base)| base == name)
1182 && !matches!(entry.body, FuncBody::Script(_))
1183 });
1184 if reserved && !shadowable {
1185 anyhow::bail!("cannot shadow reserved function `{name}`");
1186 }
1187 let frame_idx = 0;
1191 if self
1192 .scopes
1193 .get(frame_idx)
1194 .is_some_and(|frame| frame.defined.contains(&qualified))
1195 {
1196 anyhow::bail!("duplicate function `{name}` in same scope");
1197 }
1198 check_script_param_tags(name, params)?;
1199 let old = self.entries.insert(
1200 qualified.clone(),
1201 FuncEntry {
1202 meta: FuncMeta {
1203 name: qualified.clone(),
1204 module: defining.to_string(),
1205 kind: FuncKind::Script,
1206 params: Some(
1207 params
1208 .iter()
1209 .map(|(pname, param_type, optional)| {
1210 Ok(FuncParam {
1211 name: pname.clone(),
1212 param_type: Some(param_type.clone()),
1213 allowed: None,
1214 docs: "",
1215 options: None,
1216 optional: *optional,
1217 })
1218 })
1219 .collect::<Result<_>>()?,
1220 ),
1221 returns: Some(return_type.clone()),
1222 rpn: false,
1223 summary: "DSL-defined function.",
1224 docs: "Defined via FUNC in an imported script.",
1225 examples: &[],
1226 },
1227 body: FuncBody::Script(FuncDefData {
1228 params: params.to_vec(),
1229 return_type,
1230 return_spelling: return_spelling.to_string(),
1231 is_async,
1232 body: body.to_vec(),
1233 module: Some(defining.to_string()),
1234 }),
1235 },
1236 );
1237 if let Some(frame) = self.scopes.get_mut(frame_idx) {
1238 frame.defined.insert(qualified.clone());
1239 if let Some(old) = old {
1240 frame.shadowed.push((qualified, old));
1241 }
1242 }
1243 Ok(())
1244 }
1245
1246 pub(super) fn push_scope(&mut self) {
1249 self.scopes.push(ScopeFrame {
1250 defined: HashSet::new(),
1251 shadowed: Vec::new(),
1252 });
1253 }
1254
1255 pub(super) fn pop_scope(&mut self) {
1258 let Some(frame) = self.scopes.pop() else {
1259 return;
1260 };
1261 for name in frame.defined {
1262 self.entries.remove(&name);
1263 }
1264 for (name, old) in frame.shadowed {
1265 self.entries.insert(name, old);
1266 }
1267 }
1268
1269 pub(super) fn contains_script(&self, name: &str) -> bool {
1274 matches!(
1275 self.entries.get(name).map(|entry| &entry.body),
1276 Some(FuncBody::Script(_))
1277 )
1278 }
1279
1280 pub(super) fn resolve_file_call_key(
1283 &self,
1284 unit_targets: &AliasTargets,
1285 name: &str,
1286 ) -> Result<Option<String>> {
1287 match classify_alias_call(unit_targets, name, &|key| self.entries.contains_key(key)) {
1288 AliasResolution::Global | AliasResolution::Unknown | AliasResolution::Any { .. } => {
1289 Ok(None)
1290 }
1291 AliasResolution::Canonical(key) => Ok(Some(key)),
1292 AliasResolution::Ambiguous { alias, base, files } => Err(anyhow::anyhow!(
1293 "{}",
1294 ambiguous_alias_message(&alias, &base, &files)
1295 )),
1296 }
1297 }
1298
1299 fn clone_pure_fn(&self, name: &str) -> Option<PureFn> {
1303 match self.entries.get(name)?.body {
1304 FuncBody::Pure(ref func) => Some(Arc::clone(func)),
1305 FuncBody::Both { ref pure, .. } => Some(Arc::clone(pure)),
1306 _ => None,
1307 }
1308 }
1309
1310 pub(super) fn pure_shared(&self) -> Arc<PureTable> {
1314 Arc::clone(&self.pure_shared)
1315 }
1316
1317 pub(super) fn all_metas(&self) -> Vec<FuncMeta> {
1320 self.entries_metas()
1321 }
1322
1323 fn clone_ctx_fn(&self, name: &str) -> Option<NativeFn<P>> {
1328 match self.entries.get(name)?.body {
1329 FuncBody::Ctx(ref func) => Some(Arc::clone(func)),
1330 FuncBody::Both { ref ctx, .. } => Some(Arc::clone(ctx)),
1331 _ => None,
1332 }
1333 }
1334
1335 fn meta(&self, name: &str) -> Option<FuncMeta> {
1336 self.entries.get(name).map(|entry| entry.meta.clone())
1337 }
1338
1339 fn native_metas(&self) -> Vec<FuncMeta> {
1340 let mut out: Vec<FuncMeta> = Vec::new();
1341 for entry in self.entries.values() {
1342 if !matches!(entry.body, FuncBody::Script(_)) {
1343 out.push(entry.meta.clone());
1344 }
1345 }
1346 out.sort_by(|a, b| a.name.cmp(&b.name));
1347 out
1348 }
1349
1350 pub(super) fn pure_metas(&self) -> Vec<FuncMeta> {
1355 let mut out: Vec<FuncMeta> = Vec::new();
1356 for entry in self.entries.values() {
1357 if matches!(entry.body, FuncBody::Pure(_) | FuncBody::Both { .. }) {
1358 out.push(entry.meta.clone());
1359 }
1360 }
1361 out.sort_by(|a, b| a.name.cmp(&b.name));
1362 out
1363 }
1364
1365 fn entries_metas(&self) -> Vec<FuncMeta> {
1368 let mut out: Vec<FuncMeta> = self
1369 .entries
1370 .values()
1371 .map(|entry| entry.meta.clone())
1372 .collect();
1373 out.sort_by(|a, b| a.name.cmp(&b.name));
1374 out
1375 }
1376
1377 pub fn set_script_docs(&mut self, docs: &HashMap<String, (String, String)>) {
1380 for (base, pair) in docs {
1381 self.script_docs
1382 .insert(qualify(SCRIPT_MODULE_NAME, base), pair.clone());
1383 }
1384 }
1385
1386 pub fn script_doc_for(&self, qualified: &str) -> Option<(String, String)> {
1388 self.script_docs.get(qualified).cloned()
1389 }
1390
1391 pub fn exported_metas(
1396 &self,
1397 func_exports: &[String],
1398 unit_targets: &AliasTargets,
1399 ) -> anyhow::Result<Vec<FuncMeta>> {
1400 let mut out = Vec::with_capacity(func_exports.len());
1401 for name in func_exports {
1402 let qualified = match split_qualified(name) {
1406 None => qualify(SCRIPT_MODULE_NAME, name),
1407 Some(_) => name.clone(),
1408 };
1409 let lookup = self
1410 .resolve_file_call_key(unit_targets, &qualified)?
1411 .unwrap_or_else(|| qualified.clone());
1412 if let Some(entry) = self.entries.get(&lookup) {
1413 let mut meta = entry.meta.clone();
1414 if lookup != qualified {
1415 meta.name = name.clone();
1416 }
1417 out.push(meta);
1418 continue;
1419 }
1420 anyhow::bail!(
1421 "EXPORT `{name}` matches no defined script function or known host function"
1422 );
1423 }
1424 Ok(out)
1425 }
1426}
1427
1428impl<P: ProcessManager> Clone for FunctionRegistry<P> {
1429 fn clone(&self) -> Self {
1430 Self {
1431 entries: self.entries.clone(),
1432 scopes: self.scopes.clone(),
1433 pure_shared: Arc::clone(&self.pure_shared),
1434 script_docs: self.script_docs.clone(),
1435 }
1436 }
1437}
1438
1439pub fn builtin_function_names() -> HashSet<String> {
1446 let mut names = FunctionRegistry::<DefaultProcessManager>::with_builtins().keys();
1447 names.insert(KEYWORD_INSPECT.to_string());
1448 names
1449}
1450
1451pub fn builtin_function_metas() -> Vec<FuncMeta> {
1455 FunctionRegistry::<DefaultProcessManager>::with_builtins().native_metas()
1456}
1457
1458pub fn std_module_table() -> oxdock_parser::ModuleTable {
1463 let func_names: HashSet<String> = builtin_function_metas()
1465 .into_iter()
1466 .map(|meta| base_name(&meta.name).to_string())
1467 .collect();
1468 oxdock_parser::ModuleTable {
1469 modules: HashMap::from([(
1470 STD_MODULE_NAME.to_string(),
1471 Some(oxdock_parser::ModuleFuncs { func_names }),
1472 )]),
1473 }
1474}
1475
1476#[oxdock_func(pure, returns = TypeTag::Int)]
1489#[example(
1490 name = "convert",
1491 code = r###"
1492 IMPORT [STD]
1493 LET $n: INT = INT("42")
1494 ASSERT_EQ $n 42
1495 LET $flag: INT = INT(true)
1496 ASSERT_EQ $flag 1
1497 "###
1498)]
1499fn int(
1500 #[union(Int, Float, String, Bool)]
1502 val: Value,
1503) -> Result<Value> {
1504 super::args::int_from_value(val)
1505}
1506
1507#[oxdock_func(pure, returns = TypeTag::Float)]
1512#[example(
1513 name = "convert",
1514 code = r###"
1515 IMPORT [STD]
1516 LET $f: FLOAT = FLOAT("1.5")
1517 ASSERT_EQ $f 1.5
1518 LET $whole: FLOAT = FLOAT(2)
1519 ASSERT_EQ $whole 2.0
1520 "###
1521)]
1522fn float(
1523 #[union(Float, Int, String)]
1525 val: Value,
1526) -> Result<Value> {
1527 super::args::float_from_value(val)
1528}
1529
1530#[oxdock_func(pure, returns = TypeTag::String)]
1535#[example(
1536 name = "format and round-trip",
1537 code = r###"
1538 # Byte counts render in the largest exact unit.
1539 IMPORT [STD]
1540 LET $pretty: STRING = FORMAT_BYTE_COUNT(1_048_576)
1541 ASSERT_EQ $pretty "1MiB"
1542
1543 # The pair round-trips through the parser.
1544 LET $back: INT = PARSE_BYTE_COUNT($pretty)
1545 ASSERT_EQ $back 1_048_576
1546 "###
1547)]
1548fn format_byte_count(
1549 bytes: i64,
1551) -> Result<Value> {
1552 if bytes < 0 {
1553 return Err(anyhow::anyhow!(
1554 "FORMAT_BYTE_COUNT needs a non-negative byte count, got {bytes}"
1555 ));
1556 }
1557 Ok(Value::string(oxdock_parser::command::format_byte_count(
1558 bytes as u64,
1559 )))
1560}
1561
1562#[oxdock_func(pure, returns = TypeTag::Int)]
1597#[example(
1598 name = "parse",
1599 code = r###"
1600 IMPORT [STD]
1601 LET $n: INT = PARSE_BYTE_COUNT("10KB")
1602 ASSERT_EQ $n 10_000
1603 LET $identity: INT = PARSE_BYTE_COUNT(512)
1604 ASSERT_EQ $identity 512
1605 "###
1606)]
1607fn parse_byte_count(
1608 #[union(Int, Float, String)]
1610 text: Value,
1611) -> Result<Value> {
1612 if let Some(n) = text.as_i64() {
1613 if n < 0 {
1614 return Err(anyhow::anyhow!(
1615 "PARSE_BYTE_COUNT needs a non-negative byte count, got {n}"
1616 ));
1617 }
1618 return Ok(Value::int(n));
1619 }
1620 if let Some(f) = text.as_f64() {
1621 if f.is_finite() && f.fract() == 0.0 && f >= 0.0 && f <= i64::MAX as f64 {
1622 return Ok(Value::int(f as i64));
1623 }
1624 return Err(anyhow::anyhow!(
1625 "PARSE_BYTE_COUNT needs an integral byte count, got {f:?}"
1626 ));
1627 }
1628 let Some(s) = text.as_str() else {
1629 return Err(anyhow::anyhow!(
1630 "PARSE_BYTE_COUNT needs a token or number, found {text:?}"
1631 ));
1632 };
1633 let n = oxdock_parser::command::parse_byte_count(s)?;
1634 let n = i64::try_from(n)
1635 .map_err(|_| anyhow::anyhow!("PARSE_BYTE_COUNT out of INT range: {s:?}"))?;
1636 Ok(Value::int(n))
1637}
1638
1639#[oxdock_func(pure, returns = TypeTag::String)]
1644#[example(
1645 name = "format and round-trip",
1646 code = r###"
1647 # Durations render in the largest exact unit.
1648 IMPORT [STD]
1649 LET $pretty: STRING = FORMAT_DURATION(90_000)
1650 ASSERT_EQ $pretty "90s"
1651
1652 # The pair round-trips through the parser.
1653 LET $back: INT = PARSE_DURATION($pretty)
1654 ASSERT_EQ $back 90_000
1655 "###
1656)]
1657fn format_duration(
1658 millis: i64,
1660) -> Result<Value> {
1661 if millis < 0 {
1662 return Err(anyhow::anyhow!(
1663 "FORMAT_DURATION needs non-negative milliseconds, got {millis}"
1664 ));
1665 }
1666 Ok(Value::string(oxdock_parser::command::format_duration(
1667 &std::time::Duration::from_millis(millis as u64),
1668 )))
1669}
1670
1671#[oxdock_func(pure, returns = TypeTag::Int)]
1677#[example(
1678 name = "parse",
1679 code = r###"
1680 # A bare number means seconds, like TIMEOUT.
1681 IMPORT [STD]
1682 LET $ms: INT = PARSE_DURATION("2m")
1683 ASSERT_EQ $ms 120_000
1684
1685 # Milliseconds stay exact.
1686 LET $exact: INT = PARSE_DURATION("1500ms")
1687 ASSERT_EQ $exact 1_500
1688
1689 # One optional space separates number from unit.
1690 LET $spaced: INT = PARSE_DURATION("1 h")
1691 ASSERT_EQ $spaced 3_600_000
1692 "###
1693)]
1694fn parse_duration(
1695 text: String,
1697) -> Result<Value> {
1698 let duration = oxdock_parser::command::parse_duration(&text)?;
1699 let millis = i64::try_from(duration.as_millis())
1700 .map_err(|_| anyhow::anyhow!("PARSE_DURATION out of INT range: {text:?}"))?;
1701 Ok(Value::int(millis))
1702}
1703
1704#[oxdock_func(rpn, returns = TypeTag::ListOf(std::sync::Arc::new(TypeTag::String)))]
1709#[example(
1710 name = "match",
1711 code = r###"
1712 IMPORT [STD]
1713 WRITE "notes-a.md" "a"
1714 WRITE "notes-b.md" "b"
1715 WRITE "other.txt" "c"
1716 LET $found: LIST<STRING> = GLOB("notes-*.md")
1717 ASSERT_EQ $found.0 "notes-a.md"
1718 ASSERT_EQ $found.1 "notes-b.md"
1719 "###
1720)]
1721fn glob<P: ProcessManager>(
1722 cx: &mut StepCtx<P>,
1723 #[union(String, Path)]
1725 pattern: Value,
1726) -> Result<Value> {
1727 let text = super::args::string_or_path_text(&pattern)?;
1728 super::args::glob_from_value(&[Value::string(text)], cx)
1729}
1730
1731#[oxdock_func(rpn, returns = TypeTag::MapOf(std::sync::Arc::new(TypeTag::Any)))]
1736#[example(
1737 name = "load",
1738 code = r###"
1739 IMPORT [STD]
1740 WRITE "cfg.toml" "title = \"demo\""
1741 LET $cfg: MAP<ANY> = LOAD_TOML("cfg.toml")
1742 ASSERT_EQ $cfg.title "demo"
1743 "###
1744)]
1745fn load_toml<P: ProcessManager>(
1746 cx: &mut StepCtx<P>,
1747 #[union(String, Path)]
1749 path: Value,
1750) -> Result<Value> {
1751 let text = super::args::string_or_path_text(&path)?;
1752 super::args::load_toml_from_value(&[Value::string(text)], cx)
1753}
1754
1755#[oxdock_func(rpn, returns = TypeTag::Any)]
1763#[example(
1764 name = "load",
1765 code = r###"
1766 IMPORT [STD]
1767 WRITE "data.json" "{\"a\": 1}"
1768 LET $doc: MAP<ANY> = LOAD_JSON("data.json")
1769 ASSERT_EQ $doc.a 1
1770 "###
1771)]
1772fn load_json<P: ProcessManager>(
1773 cx: &mut StepCtx<P>,
1774 #[union(String, Path)]
1776 path: Value,
1777) -> Result<Value> {
1778 let text = super::args::string_or_path_text(&path)?;
1779 super::args::load_json_from_value(&[Value::string(text)], cx)
1780}
1781
1782#[oxdock_func(rpn, returns = TypeTag::String)]
1792#[example(
1793 name = "hash",
1794 code = r###"
1795 IMPORT [STD]
1796 WRITE payload.txt hello
1797 LET $digest: STRING = HASH_SHA256("payload.txt")
1798 ASSERT_EQ $digest "2cf24dba5fb0a30e26e83b2ac5b9e29e1b161e5c1fa7425e73043362938b9824"
1799 "###
1800)]
1801fn hash_sha256<P: ProcessManager>(
1802 cx: &mut StepCtx<P>,
1803 #[union(String, Path)]
1805 path: Value,
1806) -> Result<Value> {
1807 use sha2::Digest;
1808
1809 let text = super::args::string_or_path_text(&path)?;
1810 let target = cx.state.fs.resolve_read(&cx.state.cwd, &text)?;
1811 let mut hasher = sha2::Sha256::new();
1812 super::fs_ops::hash_path(cx.state.fs.as_ref(), &target, "", &mut hasher)?;
1813 let digest = hasher.finalize();
1814 let bytes: &[u8] = digest.as_ref();
1815 Ok(Value::string(oxdock_utils::hex_encode(bytes)))
1816}
1817
1818#[oxdock_func(rpn, returns = TypeTag::String)]
1829#[example(
1830 name = "cwd",
1831 code = r###"
1832 IMPORT [STD]
1833 WORKDIR sub
1834 LET $c: STRING = CWD()
1835 ASSERT_CONTAINS $c "sub"
1836 "###
1837)]
1838fn cwd<P: ProcessManager>(cx: &mut StepCtx<P>) -> Result<Value> {
1839 if cx.state.fs.is_snapshot_pending() {
1840 return Ok(Value::string(super::SNAPSHOT_PENDING_DISPLAY.to_string()));
1841 }
1842 let concrete = cx.state.fs.concretize_cwd(&cx.state.cwd);
1843 let real = super::fs_ops::canonical_cwd(cx.state.fs.as_ref(), &concrete)?;
1844 Ok(Value::string(real))
1845}
1846
1847#[oxdock_func(pure, returns = TypeTag::MapOf(std::sync::Arc::new(TypeTag::Any)))]
1853#[example(
1854 name = "parse",
1855 code = r###"
1856 IMPORT [STD]
1857 LET $doc: MAP<ANY> = PARSE_TOML("title = \"demo\"")
1858 ASSERT_EQ $doc.title "demo"
1859 "###
1860)]
1861fn parse_toml(
1862 text: String,
1864) -> Result<Value> {
1865 super::args::parse_toml_from_value(Value::string(text))
1866}
1867
1868#[oxdock_func(pure, returns = TypeTag::Any)]
1877#[example(
1878 name = "parse",
1879 code = r###"
1880 # Parse in-memory JSON text with the same conversion as file loading.
1881 IMPORT [STD]
1882 LET $body: STRING = "{\"a\": 1}"
1883 LET $doc: ANY = PARSE_JSON($body)
1884 ASSERT_EQ $doc.a 1
1885
1886 # Top-level arrays parse to LIST, which is why the return is ANY.
1887 LET $items: LIST<ANY> = PARSE_JSON("[1, 2]")
1888 ASSERT_EQ $items.0 1
1889 ASSERT_EQ $items.1 2
1890 "###
1891)]
1892fn parse_json(
1893 text: String,
1895) -> Result<Value> {
1896 super::args::parse_json_from_value(Value::string(text))
1897}
1898
1899#[oxdock_func(returns = TypeTag::String)]
1905#[example(
1906 name = "describe",
1907 code = r###"
1908 IMPORT [STD]
1909 WRITE "entry.txt" "words"
1910 LET $kind: STRING = PATH_TYPE("entry.txt")
1911 ASSERT_EQ $kind "file"
1912 LET $missing: STRING = PATH_TYPE("no-such-entry.txt")
1913 ASSERT_EQ $missing "absent"
1914 "###
1915)]
1916fn path_type<P: ProcessManager>(
1917 cx: &mut StepCtx<P>,
1918 #[union(String, Path)]
1920 path: Value,
1921) -> Result<Value> {
1922 let text = super::args::string_or_path_text(&path)?;
1923 super::args::path_type_from_value(&[Value::string(text)], cx)
1924}
1925
1926#[oxdock_func(returns = TypeTag::Bool)]
1935#[example(
1936 name = "probe",
1937 code = r###"
1938 # An absent nested path is writable when its ancestor is.
1939 IMPORT [STD]
1940 LET $fresh: BOOL = PATH_WRITABLE("probe-check/nested/file.txt")
1941 ASSERT_EQ $fresh true
1942
1943 # The empty string never aliases the working directory.
1944 LET $empty: BOOL = PATH_WRITABLE("")
1945 ASSERT_EQ $empty false
1946 "###
1947)]
1948fn path_writable<P: ProcessManager>(
1949 cx: &mut StepCtx<P>,
1950 #[union(String, Path)]
1952 path: Value,
1953) -> Result<Value> {
1954 let text = super::args::string_or_path_text(&path)?;
1955 super::args::path_writable_from_value(&[Value::string(text)], cx)
1956}
1957
1958#[oxdock_func(returns = TypeTag::Bool)]
1971#[example(
1972 name = "probe",
1973 code = r###"
1974 # Missing tools read false instead of failing the run.
1975 IMPORT [STD]
1976 LET $missing: BOOL = IS_EXEC("no-such-tool-xyz")
1977 ASSERT_EQ $missing false
1978
1979 # Plain files are not executable on any platform.
1980 WRITE tool.txt payload
1981 LET $plain: BOOL = IS_EXEC("tool.txt")
1982 ASSERT_EQ $plain false
1983 "###
1984)]
1985fn is_exec<P: ProcessManager>(
1986 cx: &mut StepCtx<P>,
1987 #[union(String, Path)]
1989 name: Value,
1990) -> Result<Value> {
1991 let text = super::args::string_or_path_text(&name)?;
1992 super::args::is_exec_from_value(&[Value::string(text)], cx)
1993}
1994
1995#[oxdock_func(returns = TypeTag::Bool)]
2003#[example(
2004 name = "probe",
2005 code = r###"
2006 # Ordinary files read true; missing paths read false.
2007 IMPORT [STD]
2008 WRITE "entry.txt" "words"
2009 LET $hit: BOOL = IS_FILE("entry.txt")
2010 ASSERT_EQ $hit true
2011 LET $miss: BOOL = IS_FILE("no-such-entry.txt")
2012 ASSERT_EQ $miss false
2013 "###
2014)]
2015fn is_file<P: ProcessManager>(
2016 cx: &mut StepCtx<P>,
2017 #[union(String, Path)]
2019 path: Value,
2020) -> Result<Value> {
2021 let text = super::args::string_or_path_text(&path)?;
2022 Ok(Value::bool(super::args::path_is_file(cx, &text)))
2023}
2024
2025#[oxdock_func(returns = TypeTag::Bool)]
2033#[example(
2034 name = "probe",
2035 code = r###"
2036 # Directories read true; files read false.
2037 IMPORT [STD]
2038 LET $hit: BOOL = IS_DIR(".")
2039 ASSERT_EQ $hit true
2040 WRITE "entry.txt" "words"
2041 LET $miss: BOOL = IS_DIR("entry.txt")
2042 ASSERT_EQ $miss false
2043 "###
2044)]
2045fn is_dir<P: ProcessManager>(
2046 cx: &mut StepCtx<P>,
2047 #[union(String, Path)]
2049 path: Value,
2050) -> Result<Value> {
2051 let text = super::args::string_or_path_text(&path)?;
2052 Ok(Value::bool(super::args::path_is_dir(cx, &text)))
2053}
2054
2055#[oxdock_func(returns = TypeTag::Bool)]
2062#[example(
2063 name = "probe",
2064 code = r###"
2065 # Present entries read true; absent paths read false.
2066 IMPORT [STD]
2067 WRITE "entry.txt" "words"
2068 LET $hit: BOOL = EXISTS("entry.txt")
2069 ASSERT_EQ $hit true
2070 LET $miss: BOOL = EXISTS("no-such-entry.txt")
2071 ASSERT_EQ $miss false
2072 "###
2073)]
2074fn exists<P: ProcessManager>(
2075 cx: &mut StepCtx<P>,
2076 #[union(String, Path)]
2078 path: Value,
2079) -> Result<Value> {
2080 let text = super::args::string_or_path_text(&path)?;
2081 Ok(Value::bool(super::args::path_exists(cx, &text)))
2082}
2083
2084#[oxdock_func(pure, returns = TypeTag::Bool)]
2090#[example(
2091 name = "probe",
2092 code = r###"
2093 IMPORT [STD]
2094 LET $m: MAP<ANY> = PARSE_JSON("{\"a\": 1}")
2095 LET $hit: BOOL = HAS_KEY($m, "a")
2096 ASSERT_EQ $hit true
2097 LET $miss: BOOL = HAS_KEY($m, "b")
2098 ASSERT_EQ $miss false
2099 "###
2100)]
2101fn has_key(
2102 map: BTreeMap<String, Value>,
2104 key: String,
2106) -> Result<Value> {
2107 super::args::has_key_from_value(Value::map(map), &key)
2108}
2109
2110#[oxdock_func(pure, returns = TypeTag::Any)]
2116#[example(
2117 name = "present and absent",
2118 code = r###"
2119 IMPORT [STD]
2120 LET $m: MAP<ANY> = PARSE_JSON("{\"a\": 1}")
2121 LET $hit: INT = GET($m, "a", 0)
2122 ASSERT_EQ $hit 1
2123 LET $miss: INT = GET($m, "b", 0)
2124 ASSERT_EQ $miss 0
2125 "###
2126)]
2127fn get(
2128 map: BTreeMap<String, Value>,
2130 key: String,
2132 default: Value,
2134) -> Result<Value> {
2135 Ok(map.get(&key).cloned().unwrap_or(default))
2136}
2137
2138#[oxdock_func(pure, returns = TypeTag::MapOf(std::sync::Arc::new(TypeTag::Any)))]
2144#[example(
2145 name = "insert",
2146 code = r###"
2147 IMPORT [STD]
2148 LET $m: MAP<ANY> = MAP_SET({seed: 0}, "a", 1)
2149 ASSERT_EQ $m.a 1
2150 "###
2151)]
2152fn map_set(
2153 map: BTreeMap<String, Value>,
2155 key: String,
2157 value: Value,
2159) -> Result<Value> {
2160 super::args::map_set_from_value(Value::map(map), key, value)
2161}
2162
2163#[oxdock_func(returns = TypeTag::Float, summary = "Draw a random FLOAT uniformly from [0, 1), optionally seeded.")]
2171#[example(
2172 name = "seeded draw",
2173 code = r###"
2174 # A seed draws the same value on every run.
2175 IMPORT [STD]
2176 LET $one: FLOAT = RAND({seed: 7})
2177 LET $two: FLOAT = RAND({seed: 7})
2178 ASSERT_EQ $one $two
2179 "###
2180)]
2181#[example(
2182 name = "unseeded draw",
2183 code = r###"
2184 # Scale a unit draw into a backoff delay between 1 and 11 seconds.
2185 IMPORT [STD]
2186 LET $draw: FLOAT = RAND()
2187 LET $delay: FLOAT = 1.0 + $draw * 10.0
2188 IF $delay < 1.0 {
2189 EXIT 1
2190 }
2191 IF $delay >= 11.0 {
2192 EXIT 1
2193 }
2194 ECHO "retrying in {{ $delay }}s"
2195 "###
2196)]
2197fn rand<P: ProcessManager>(
2198 cx: &mut StepCtx<P>,
2199 #[options("seed?: INT")]
2201 #[optional]
2202 options: BTreeMap<String, Value>,
2203) -> Result<Value> {
2204 let _ = cx;
2205 let seed = options
2208 .get("seed")
2209 .map(|value| value.as_i64().expect("check_options verified INT"));
2210 super::args::rand_float_from_value(seed)
2211}
2212
2213#[oxdock_func(pure, returns = TypeTag::String)]
2219#[example(
2220 name = "encode",
2221 code = r###"
2222 # Encode text to standard base64.
2223 IMPORT [STD]
2224 LET $encoded: STRING = BASE64_ENCODE("hello")
2225 ASSERT_EQ $encoded "aGVsbG8="
2226 "###
2227)]
2228fn base64_encode(
2229 text: String,
2231) -> Result<Value> {
2232 super::args::base64_encode_from_value(Value::string(text))
2233}
2234
2235#[oxdock_func(pure, returns = TypeTag::String)]
2242#[example(
2243 name = "decode",
2244 code = r###"
2245 # Decode standard base64 back to text.
2246 IMPORT [STD]
2247 LET $decoded: STRING = BASE64_DECODE("aGVsbG8=")
2248 ASSERT_EQ $decoded "hello"
2249 "###
2250)]
2251fn base64_decode(
2252 text: String,
2254) -> Result<Value> {
2255 super::args::base64_decode_from_value(Value::string(text))
2256}
2257
2258#[oxdock_func(pure, returns = TypeTag::String)]
2265#[example(
2266 name = "encode",
2267 code = r###"
2268 IMPORT [STD]
2269 LET $json: STRING = TO_JSON({a: 1})
2270 ASSERT_EQ $json "{\"a\":1}\n"
2271 "###
2272)]
2273fn to_json(
2274 #[union(String, Int, Float, Bool, List, Map)]
2276 value: Value,
2277) -> Result<Value> {
2278 super::args::to_json_from_value(value)
2279}
2280
2281#[oxdock_func(pure, returns = TypeTag::String)]
2289#[example(
2290 name = "name the word",
2291 code = r###"
2292 IMPORT [STD]
2293 LET $word: STRING = TYPE_OF(42)
2294 ASSERT_EQ $word "INT"
2295 "###
2296)]
2297fn type_of(
2298 value: Value,
2300) -> Result<Value> {
2301 super::args::type_of_from_value(value)
2302}
2303
2304#[oxdock_func(pure, returns = TypeTag::MapOf(std::sync::Arc::new(TypeTag::Any)))]
2312#[example(
2313 name = "merge",
2314 code = r###"
2315 IMPORT [STD]
2316 LET $m: MAP<ANY> = MERGE_MAPS([{a: 1}, {b: 2}], "overwrite")
2317 ASSERT_EQ $m.a 1
2318 ASSERT_EQ $m.b 2
2319 "###
2320)]
2321fn merge_maps(
2322 maps: Vec<BTreeMap<String, Value>>,
2324 #[values("fail_on_duplicate", "overwrite")]
2326 policy: String,
2327) -> Result<Value> {
2328 super::args::merge_maps_from_value(
2329 Value::list(maps.into_iter().map(Value::map).collect()),
2330 policy,
2331 )
2332}
2333
2334#[oxdock_func(pure, returns = TypeTag::String)]
2339#[example(
2340 name = "report",
2341 code = r###"
2342 # The engine reports its own build version as a dotted string.
2343 IMPORT [STD]
2344 LET $v: STRING = VERSION()
2345 ASSERT_CONTAINS $v "."
2346 "###
2347)]
2348fn version() -> Result<Value> {
2349 Ok(Value::string(env!("CARGO_PKG_VERSION").to_string()))
2350}
2351
2352#[oxdock_func(returns = TypeTag::ListOf(std::sync::Arc::new(TypeTag::String)))]
2357#[example(
2358 name = "list",
2359 code = r###"
2360 IMPORT [STD]
2361 LET $names: LIST<STRING> = FUNCTIONS()
2362 ASSERT_CONTAINS $names "STD::INT"
2363 "###
2364)]
2365fn functions<P: ProcessManager>(cx: &mut StepCtx<P>) -> Result<Value> {
2366 let mut names: Vec<String> = cx
2367 .state
2368 .list_functions()
2369 .into_iter()
2370 .map(|meta| meta.name)
2371 .collect();
2372 names.sort();
2373 names.dedup();
2374 Ok(Value::list(names.into_iter().map(Value::string).collect()))
2375}
2376
2377#[oxdock_func(returns = TypeTag::ListOf(std::sync::Arc::new(TypeTag::String)))]
2384#[example(
2385 name = "empty",
2386 code = r###"
2387 # With no staged args the list is empty.
2388 IMPORT [STD]
2389 LET $args: LIST<STRING> = ARGV()
2390 LET $n: INT = LEN($args)
2391 ASSERT_EQ $n 0
2392 "###
2393)]
2394fn argv<P: ProcessManager>(cx: &mut StepCtx<P>) -> Result<Value> {
2395 Ok(Value::list(
2396 cx.state
2397 .io
2398 .script_args()
2399 .iter()
2400 .cloned()
2401 .map(Value::string)
2402 .collect(),
2403 ))
2404}
2405
2406pub struct ParseArgs;
2426
2427impl<P: ProcessManager> OxDockFn<P> for ParseArgs {
2428 fn registration() -> HostRegistration<P> {
2429 let func: NativeFn<P> = Arc::new(|cx: &mut StepCtx<P>, values: Vec<Value>| {
2430 if values.len() != 1 {
2431 anyhow::bail!("PARSE_ARGS() expects 1 argument, got {}", values.len());
2432 }
2433 let mut iter = values.into_iter();
2434 let args_val = iter.next().expect("arity checked above");
2435 let args = string_list_arg(&args_val, "PARSE_ARGS() argument `$args`")?;
2436 let specs = resolve_flags_specs(cx)?;
2437 let (raw, positionals) = tokenize_raw_args(args)?;
2438 let coerced = coerce_flags(&specs, &raw)?;
2439 let mut out = BTreeMap::new();
2440 out.insert("flags".to_string(), Value::map(coerced));
2441 if !positionals.is_empty() {
2442 out.insert("positionals".to_string(), Value::list(positionals));
2443 }
2444 Ok(Value::map(out))
2445 });
2446 HostRegistration::Stateful {
2447 name: "PARSE_ARGS".to_string(),
2448 meta: FuncMeta {
2449 name: "PARSE_ARGS".to_string(),
2450 module: String::new(),
2451 kind: FuncKind::HostPure,
2452 params: Some(vec![FuncParam {
2453 name: "args".to_string(),
2454 param_type: Some(TypeTag::ListOf(Arc::new(TypeTag::String))),
2455 allowed: None,
2456 docs: "Argv tail to parse, usually from `STD::ARGV()`.",
2457 options: None,
2458 optional: false,
2459 }]),
2460 returns: Some(TypeTag::Record(Arc::from([
2461 Field {
2462 name: "flags".to_string(),
2463 ty: TypeTag::Map,
2464 docs: "Flags coerced to `TYPE FLAGS`.",
2465 optional: false,
2466 default: None,
2467
2468 alias: None,
2469 },
2470 Field {
2471 name: "positionals".to_string(),
2472 ty: TypeTag::ListOf(Arc::new(TypeTag::String)),
2473 docs: "Trailing values and entries after the first double dash. Omitted when empty.",
2474 optional: true,
2475 default: None,
2476
2477 alias: None,
2478 },
2479 ]))),
2480 rpn: true,
2481 summary: "Parse an argv tail against TYPE FLAGS.",
2482 docs: "Consumes a `LIST<STRING>` with the `lexopt` tokenizer and coerces flags through `TYPE FLAGS`. See the function reference for the coercion and omission rules.",
2483 examples: &[
2484 crate::Example {
2485 name: "flags and positionals",
2486 fence_meta: None,
2487 code: indoc::indoc! {r#"
2488 IMPORT [STD]
2489 # One schema TYPE drives coercion; the pair binds both slots.
2490 TYPE FLAGS = MAP<model: STRING, verbose?: BOOL>
2491 TYPE POSITIONS = LIST<STRING>
2492 TYPE PARSED = MAP<flags: FLAGS, positionals?: POSITIONS>
2493 LET $parsed: PARSED = PARSE_ARGS(["--model=gpt-4", "--verbose", "serve"])
2494 LET $flags: FLAGS = $parsed.flags
2495 ASSERT_EQ $flags.model "gpt-4"
2496 ASSERT_EQ $flags.verbose true
2497 ASSERT_EQ $parsed.positionals.0 "serve"
2498 "#},
2499 },
2500 crate::Example {
2501 name: "optional stays absent",
2502 fence_meta: None,
2503 code: indoc::indoc! {r#"
2504 IMPORT [STD]
2505 # Absent optionals stay absent; read them with a typed GET default.
2506 TYPE FLAGS = MAP<model: STRING, propose?: BOOL>
2507 TYPE POSITIONS = LIST<STRING>
2508 TYPE PARSED = MAP<flags: FLAGS, positionals?: POSITIONS>
2509 LET $parsed: PARSED = PARSE_ARGS(["--model=x"])
2510 LET $flags: FLAGS = $parsed.flags
2511 LET $propose: BOOL = GET($flags, "propose", false)
2512 ASSERT_EQ $propose false
2513 "#},
2514 },
2515 crate::Example {
2516 name: "flags only omits positionals",
2517 fence_meta: None,
2518 code: indoc::indoc! {r#"
2519 IMPORT [STD]
2520 # Empty positionals are omitted, so a flags only shape binds clean.
2521 TYPE FLAGS = MAP<model: STRING>
2522 TYPE PARSED = MAP<flags: FLAGS>
2523 LET $parsed: PARSED = PARSE_ARGS(["--model=x"])
2524 LET $flags: FLAGS = $parsed.flags
2525 ASSERT_EQ $flags.model "x"
2526 "#},
2527 },
2528 crate::Example {
2529 name: "literal defaults",
2530 fence_meta: None,
2531 code: indoc::indoc! {r#"
2532 IMPORT [STD]
2533 # Defaults are literals only: INT, FLOAT, BOOL,
2534 # and double-quoted STRING fill absent flags.
2535 TYPE FLAGS = MAP<retries: INT = 2, ratio: FLOAT = 2.5, verbose: BOOL = true, model: STRING = "gpt-4">
2536 TYPE PARSED = MAP<flags: FLAGS>
2537 LET $parsed: PARSED = PARSE_ARGS([])
2538 LET $flags: FLAGS = $parsed.flags
2539 ASSERT_EQ $flags.retries 2
2540 ASSERT_EQ $flags.verbose true
2541 ASSERT_EQ $flags.model "gpt-4"
2542 LET $ratio_ok: BOOL = $flags.ratio == 2.5
2543 ASSERT_EQ $ratio_ok true
2544 "#},
2545 },
2546 crate::Example {
2547 name: "variable default fails",
2548 fence_meta: Some("expect_error:\"expected default literal\""),
2549 code: indoc::indoc! {r#"
2550 IMPORT [STD]
2551 # Defaults are literals: a variable in place
2552 # of a literal fails instead of evaluating.
2553 TYPE FLAGS = MAP<n: INT = $x>
2554 TYPE PARSED = MAP<flags: FLAGS>
2555 LET $p: PARSED = PARSE_ARGS([])
2556 "#},
2557 },
2558 crate::Example {
2559 name: "missing required",
2560 fence_meta: Some("expect_error:\"missing required flag\""),
2561 code: indoc::indoc! {r#"
2562 IMPORT [STD]
2563 # Absent required flags fail naming the flag.
2564 TYPE FLAGS = MAP<model: STRING>
2565 TYPE PARSED = MAP<flags: FLAGS>
2566 LET $parsed: PARSED = PARSE_ARGS([])
2567 "#},
2568 },
2569 crate::Example {
2570 name: "unknown flag",
2571 fence_meta: Some("expect_error:\"unknown flag\""),
2572 code: indoc::indoc! {r#"
2573 IMPORT [STD]
2574 # Undeclared flags fail instead of passing through.
2575 TYPE FLAGS = MAP<model: STRING>
2576 TYPE PARSED = MAP<flags: FLAGS>
2577 LET $parsed: PARSED = PARSE_ARGS(["--model=x", "--nope=1"])
2578 "#},
2579 },
2580 crate::Example {
2581 name: "alias accepted",
2582 fence_meta: None,
2583 code: indoc::indoc! {r#"
2584 IMPORT [STD]
2585 # One canonical key binds both spellings; the
2586 # alias never appears as a separate key.
2587 TYPE FLAGS = MAP<h: BOOL ALIAS help>
2588 TYPE PARSED = MAP<flags: FLAGS>
2589 LET $a: PARSED = PARSE_ARGS(["--help"])
2590 ASSERT_EQ $a.flags.h true
2591 LET $b: PARSED = PARSE_ARGS(["--h"])
2592 ASSERT_EQ $b.flags.h true
2593 "#},
2594 },
2595 crate::Example {
2596 name: "alias duplicate fails",
2597 fence_meta: Some("expect_error:\"duplicate flag\""),
2598 code: indoc::indoc! {r#"
2599 IMPORT [STD]
2600 # Canonical and alias together fail naming both.
2601 TYPE FLAGS = MAP<h: BOOL ALIAS help>
2602 TYPE PARSED = MAP<flags: FLAGS>
2603 LET $p: PARSED = PARSE_ARGS(["--h", "--help"])
2604 "#},
2605 },
2606 crate::Example {
2607 name: "alias missing names both",
2608 fence_meta: Some("expect_error:\"--h/--help\""),
2609 code: indoc::indoc! {r#"
2610 IMPORT [STD]
2611 # Missing required flags name both spellings.
2612 TYPE FLAGS = MAP<h: BOOL ALIAS help>
2613 TYPE PARSED = MAP<flags: FLAGS>
2614 LET $p: PARSED = PARSE_ARGS([])
2615 "#},
2616 },
2617 ],
2618 },
2619 func,
2620 }
2621 }
2622}
2623
2624#[derive(Debug, Clone, Copy, PartialEq, Eq)]
2628enum CliType {
2629 String,
2630 Bool,
2631 Int,
2632 Float,
2633}
2634
2635fn coerce_cli_flag(target: CliType, flag: &str, raw: Value) -> Result<Value> {
2640 match target {
2641 CliType::Bool => {
2642 if let Some(b) = raw.as_bool() {
2643 return Ok(Value::bool(b));
2644 }
2645 if let Some(s) = raw.as_str() {
2646 match super::args::parse_bool_str(s) {
2647 Some(b) => return Ok(Value::bool(b)),
2648 None => anyhow::bail!(
2649 "PARSE_ARGS flag --{flag} expects BOOL (true/false, 1/0, yes/no, on/off), got {s:?}"
2650 ),
2651 }
2652 }
2653 anyhow::bail!(
2654 "PARSE_ARGS flag --{flag} expects BOOL, got {}",
2655 raw.type_name()
2656 )
2657 }
2658 CliType::String => {
2659 if let Some(s) = raw.as_str() {
2660 return Ok(Value::string(s.to_string()));
2661 }
2662 anyhow::bail!("PARSE_ARGS flag --{flag} needs a value: use --{flag}=<value>");
2663 }
2664 CliType::Int => {
2665 if raw.as_bool().is_some() {
2666 anyhow::bail!("PARSE_ARGS flag --{flag} needs a value: use --{flag}=<value>");
2667 }
2668 super::args::int_from_value(raw)
2669 .map_err(|_| anyhow::anyhow!("PARSE_ARGS flag --{flag} expects INT"))
2670 }
2671 CliType::Float => {
2672 if raw.as_bool().is_some() {
2673 anyhow::bail!("PARSE_ARGS flag --{flag} needs a value: use --{flag}=<value>");
2674 }
2675 super::args::float_from_value(raw)
2676 .map_err(|_| anyhow::anyhow!("PARSE_ARGS flag --{flag} expects FLOAT"))
2677 }
2678 }
2679}
2680
2681#[derive(Debug, Clone)]
2685struct CliSpec {
2686 target: CliType,
2687 required: bool,
2688 default: Option<Value>,
2689 alias: Option<String>,
2690}
2691
2692type CliSpecs = BTreeMap<String, CliSpec>;
2694
2695fn string_list_arg(val: &Value, what: &str) -> Result<Vec<String>> {
2698 crate::check_value_at(&TypeTag::ListOf(Arc::new(TypeTag::String)), val, what)?;
2699 Ok(val
2700 .as_list()
2701 .expect("check_value_at enforces LIST")
2702 .iter()
2703 .map(|v| {
2704 v.as_str()
2705 .expect("check_value_at enforces STRING")
2706 .to_string()
2707 })
2708 .collect())
2709}
2710
2711fn tokenize_raw_args(args: Vec<String>) -> Result<(BTreeMap<String, Value>, Vec<Value>)> {
2715 use lexopt::Arg::{Long, Short, Value as ArgValue};
2716 let mut parser = lexopt::Parser::from_args(args);
2717 let mut flags: BTreeMap<String, Value> = BTreeMap::new();
2718 let mut positionals: Vec<Value> = Vec::new();
2719 let utf8 = |value: std::ffi::OsString| -> Result<String> {
2720 value
2721 .into_string()
2722 .map_err(|_| anyhow::anyhow!("PARSE_ARGS: argument must be UTF-8"))
2723 };
2724 loop {
2725 match parser.next() {
2726 Ok(None) => break,
2727 Ok(Some(Long(name))) => {
2728 let key = name.to_owned();
2729 if let Some(raw) = parser.optional_value() {
2730 flags.insert(key, Value::string(utf8(raw)?));
2731 } else {
2732 flags.insert(key, Value::bool(true));
2733 }
2734 }
2735 Ok(Some(Short(ch))) => {
2736 flags.insert(ch.to_string(), Value::bool(true));
2737 }
2738 Ok(Some(ArgValue(raw))) => {
2739 positionals.push(Value::string(utf8(raw)?));
2740 }
2741 Err(lexopt::Error::UnexpectedValue { option, value }) => {
2742 let key = option
2743 .strip_prefix("--")
2744 .or_else(|| option.strip_prefix('-'))
2745 .unwrap_or(option.as_str());
2746 flags.insert(key.to_string(), Value::string(utf8(value)?));
2747 }
2748 Err(err) => anyhow::bail!("PARSE_ARGS: {err}"),
2749 }
2750 }
2751 Ok((flags, positionals))
2752}
2753
2754fn coerce_flags(
2762 specs: &CliSpecs,
2763 raw: &BTreeMap<String, Value>,
2764) -> Result<BTreeMap<String, Value>> {
2765 let mut alias_to_canonical: BTreeMap<&str, &str> = BTreeMap::new();
2768 for (canonical, spec) in specs.iter() {
2769 if let Some(alias) = spec.alias.as_ref() {
2770 alias_to_canonical.insert(alias.as_str(), canonical.as_str());
2771 }
2772 }
2773 let mut coerced: BTreeMap<String, Value> = BTreeMap::new();
2774 for (flag, spec) in specs.iter() {
2775 if flag.is_empty() {
2776 anyhow::bail!("PARSE_ARGS schema flag names must be non-empty");
2777 }
2778 let canonical_raw = raw.get(flag);
2779 let alias_raw = spec.alias.as_ref().and_then(|alias| raw.get(alias));
2780 let display = match spec.alias.as_ref() {
2782 Some(alias) => format!("--{flag}/--{alias}"),
2783 None => format!("--{flag}"),
2784 };
2785 if canonical_raw.is_some() && alias_raw.is_some() {
2786 anyhow::bail!("PARSE_ARGS duplicate flag {display}");
2787 }
2788 if let Some(raw_val) = canonical_raw.or(alias_raw) {
2789 coerced.insert(
2790 flag.clone(),
2791 coerce_cli_flag(spec.target, flag, raw_val.clone())?,
2792 );
2793 } else if let Some(d) = spec.default.as_ref() {
2794 coerced.insert(flag.clone(), d.clone());
2795 } else if spec.required {
2796 anyhow::bail!("PARSE_ARGS missing required flag {display}");
2797 }
2798 }
2799 for flag in raw.keys() {
2800 if !specs.contains_key(flag) && !alias_to_canonical.contains_key(flag.as_str()) {
2801 anyhow::bail!("PARSE_ARGS unknown flag --{flag}");
2802 }
2803 }
2804 Ok(coerced)
2805}
2806
2807fn resolve_flags_specs<P: ProcessManager>(cx: &mut StepCtx<P>) -> Result<CliSpecs> {
2814 let name = "FLAGS";
2815 let tag = cx
2816 .state
2817 .resolve_tag(name)
2818 .map_err(|err| anyhow::anyhow!("PARSE_ARGS schema type {name:?}: {err:#}"))?;
2819 let TypeTag::Record(fields) = tag else {
2820 anyhow::bail!("PARSE_ARGS schema type {name:?} must be a MAP shape with scalar fields");
2821 };
2822 let mut specs = BTreeMap::new();
2823 for field in fields.iter() {
2824 let target = match field.ty {
2825 TypeTag::String => CliType::String,
2826 TypeTag::Bool => CliType::Bool,
2827 TypeTag::Int => CliType::Int,
2828 TypeTag::Float => CliType::Float,
2829 _ => anyhow::bail!(
2830 "PARSE_ARGS schema for --{}: type must be one of STRING, BOOL, INT, or FLOAT, got {}",
2831 field.name,
2832 field.ty.name(),
2833 ),
2834 };
2835 specs.insert(
2836 field.name.clone(),
2837 CliSpec {
2838 target,
2839 required: !field.optional && field.default.is_none(),
2840 default: field.default.clone(),
2841 alias: field.alias.clone(),
2842 },
2843 );
2844 }
2845 Ok(specs)
2846}
2847
2848pub struct ParseFlags;
2856
2857impl<P: ProcessManager> OxDockFn<P> for ParseFlags {
2858 fn registration() -> HostRegistration<P> {
2859 let func: NativeFn<P> = Arc::new(|cx: &mut StepCtx<P>, values: Vec<Value>| {
2860 if values.len() != 1 {
2861 anyhow::bail!("PARSE_FLAGS() expects 1 argument, got {}", values.len());
2862 }
2863 let mut iter = values.into_iter();
2864 let args_val = iter.next().expect("arity checked above");
2865 let args = string_list_arg(&args_val, "PARSE_FLAGS() argument `$args`")?;
2866 let specs = resolve_flags_specs(cx)?;
2867 let (raw, positionals) = tokenize_raw_args(args)?;
2868 if !positionals.is_empty() {
2869 let shown: Vec<String> = positionals.iter().map(|pos| pos.to_string()).collect();
2870 anyhow::bail!(
2871 "PARSE_FLAGS() does not accept positional arguments; found {}",
2872 shown.join(", ")
2873 );
2874 }
2875 Ok(Value::map(coerce_flags(&specs, &raw)?))
2876 });
2877 HostRegistration::Stateful {
2878 name: "PARSE_FLAGS".to_string(),
2879 meta: FuncMeta {
2880 name: "PARSE_FLAGS".to_string(),
2881 module: String::new(),
2882 kind: FuncKind::HostPure,
2883 params: Some(vec![FuncParam {
2884 name: "args".to_string(),
2885 param_type: Some(TypeTag::ListOf(Arc::new(TypeTag::String))),
2886 allowed: None,
2887 docs: "Argv tail to parse, usually from `STD::ARGV()`.",
2888 options: None,
2889 optional: false,
2890 }]),
2891 returns: Some(TypeTag::Map),
2892 rpn: true,
2893 summary: "Parse flags against TYPE FLAGS.",
2894 docs: "Consumes a `LIST<STRING>` and coerces flags through `TYPE FLAGS`. Returns the flags `MAP` directly; positional arguments fail.",
2895 examples: &[crate::Example {
2896 name: "flags only",
2897 fence_meta: None,
2898 code: indoc::indoc! {r#"
2899 IMPORT [STD]
2900 # Flags only returns the flags MAP directly.
2901 TYPE FLAGS = MAP<model: STRING, retries: INT = 2>
2902 LET $flags: FLAGS = PARSE_FLAGS(["--model=x"])
2903 ASSERT_EQ $flags.model "x"
2904 ASSERT_EQ $flags.retries 2
2905 "#},
2906 }],
2907 },
2908 func,
2909 }
2910 }
2911}
2912
2913pub struct ParsePositionals;
2918
2919impl<P: ProcessManager> OxDockFn<P> for ParsePositionals {
2920 fn registration() -> HostRegistration<P> {
2921 let func: NativeFn<P> = Arc::new(|_: &mut StepCtx<P>, values: Vec<Value>| {
2922 if values.len() != 1 {
2923 anyhow::bail!(
2924 "PARSE_POSITIONALS() expects 1 argument, got {}",
2925 values.len()
2926 );
2927 }
2928 let mut iter = values.into_iter();
2929 let args_val = iter.next().expect("arity checked above");
2930 let args = string_list_arg(&args_val, "PARSE_POSITIONALS() argument `$args`")?;
2931 let (_raw, positionals) = tokenize_raw_args(args)?;
2932 Ok(Value::list(positionals))
2933 });
2934 HostRegistration::Stateful {
2935 name: "PARSE_POSITIONALS".to_string(),
2936 meta: FuncMeta {
2937 name: "PARSE_POSITIONALS".to_string(),
2938 module: String::new(),
2939 kind: FuncKind::HostPure,
2940 params: Some(vec![FuncParam {
2941 name: "args".to_string(),
2942 param_type: Some(TypeTag::ListOf(Arc::new(TypeTag::String))),
2943 allowed: None,
2944 docs: "Argv tail to parse, usually from `STD::ARGV()`.",
2945 options: None,
2946 optional: false,
2947 }]),
2948 returns: Some(TypeTag::ListOf(Arc::new(TypeTag::String))),
2949 rpn: true,
2950 summary: "Parse positionals in argv order.",
2951 docs: "Consumes a `LIST<STRING>` and returns positionals in argv order with no schema.",
2952 examples: &[crate::Example {
2953 name: "positionals only",
2954 fence_meta: None,
2955 code: indoc::indoc! {r#"
2956 IMPORT [STD]
2957 # No schema needed: positionals are always strings in order.
2958 TYPE POSITIONS = LIST<STRING>
2959 LET $pos: POSITIONS = PARSE_POSITIONALS(["serve", "--", "--not-a-flag"])
2960 ASSERT_EQ $pos.0 "serve"
2961 ASSERT_EQ $pos.1 "--not-a-flag"
2962 "#},
2963 }],
2964 },
2965 func,
2966 }
2967 }
2968}
2969
2970#[oxdock_func(
2985 returns = TypeTag::Record(std::sync::Arc::from([Field {
2986 name: "name".to_string(),
2987 ty: TypeTag::String,
2988 docs: "Qualified function name.",
2989 optional: false,
2990 default: None,
2991
2992 alias: None,}, Field {
2993 name: "module".to_string(),
2994 ty: TypeTag::String,
2995 docs: "Owning module.",
2996 optional: false,
2997 default: None,
2998
2999 alias: None,}, Field {
3000 name: "kind".to_string(),
3001 ty: TypeTag::String,
3002 docs: "Origin label (`host` or `script`).",
3003 optional: false,
3004 default: None,
3005
3006 alias: None,}, Field {
3007 name: "params".to_string(),
3008 ty: TypeTag::ListOf(std::sync::Arc::new(TypeTag::MapOf(std::sync::Arc::new(
3009 TypeTag::Any,
3010 )))),
3011 docs: "Parameter entries (empty for parameterless functions).",
3012 optional: false,
3013 default: None,
3014
3015 alias: None,}, Field {
3016 name: "returns".to_string(),
3017 ty: TypeTag::String,
3018 docs: "Structural return shape (empty when untagged).",
3019 optional: false,
3020 default: None,
3021
3022 alias: None,}, Field {
3023 name: "rpn".to_string(),
3024 ty: TypeTag::Bool,
3025 docs: "True when callable in RPN position.",
3026 optional: false,
3027 default: None,
3028
3029 alias: None,}, Field {
3030 name: "summary".to_string(),
3031 ty: TypeTag::String,
3032 docs: "One-line description.",
3033 optional: false,
3034 default: None,
3035
3036 alias: None,}]))
3037 summary = "Describe one function by qualified name."
3038)]
3039#[example(
3040 name = "describe",
3041 code = r###"
3042 IMPORT [STD]
3043 LET $info: MAP<ANY> = DESCRIBE("STD::INT")
3044 ASSERT_EQ $info.name "STD::INT"
3045 ASSERT_EQ $info.returns "INT"
3046 "###
3047)]
3048fn describe<P: ProcessManager>(
3049 cx: &mut StepCtx<P>,
3050 name: String,
3052) -> Result<Value> {
3053 if split_qualified(&name).is_none() && name != KEYWORD_INSPECT {
3054 anyhow::bail!(
3055 "unknown function `{name}`: DESCRIBE requires a qualified name (e.g. `STD::{name}`)"
3056 );
3057 }
3058 cx.state
3059 .describe_function(&name)
3060 .ok_or_else(|| anyhow::anyhow!("unknown function {name}"))
3061}
3062
3063#[oxdock_func(returns = TypeTag::ListOf(std::sync::Arc::new(TypeTag::String)))]
3069#[example(
3070 name = "list",
3071 code = r###"
3072 IMPORT [STD]
3073 LET $names: LIST<STRING> = TYPES()
3074 ASSERT_CONTAINS $names "STRING"
3075 "###
3076)]
3077fn types<P: ProcessManager>(cx: &mut StepCtx<P>) -> Result<Value> {
3078 Ok(Value::list(
3079 cx.state
3080 .type_names()
3081 .into_iter()
3082 .map(Value::string)
3083 .collect(),
3084 ))
3085}
3086
3087#[oxdock_func(returns = TypeTag::Record(std::sync::Arc::from([Field {
3093 name: "name".to_string(),
3094 ty: TypeTag::String,
3095 docs: "Queried type name.",
3096 optional: false,
3097 default: None,
3098
3099 alias: None,}, Field {
3100 name: "summary".to_string(),
3101 ty: TypeTag::String,
3102 docs: "One-line description.",
3103 optional: false,
3104 default: None,
3105
3106 alias: None,}, Field {
3107 name: "docs".to_string(),
3108 ty: TypeTag::String,
3109 docs: "Full documentation text.",
3110 optional: false,
3111 default: None,
3112
3113 alias: None,}])))]
3114#[example(
3115 name = "describe",
3116 code = r###"
3117 IMPORT [STD]
3118 LET $info: MAP<ANY> = TYPE_DESCRIBE("STRING")
3119 ASSERT_EQ $info.name "STRING"
3120 "###
3121)]
3122fn type_describe<P: ProcessManager>(
3123 cx: &mut StepCtx<P>,
3124 name: String,
3126) -> Result<Value> {
3127 if let Some(descriptor) = cx.state.describe_type(&name) {
3128 let mut map = BTreeMap::new();
3129 map.insert(
3130 "name".to_string(),
3131 Value::string(descriptor.name.to_string()),
3132 );
3133 map.insert(
3134 "summary".to_string(),
3135 Value::string(descriptor.summary.to_string()),
3136 );
3137 map.insert(
3138 "docs".to_string(),
3139 Value::string(descriptor.docs.to_string()),
3140 );
3141 return Ok(Value::map(map));
3142 }
3143 if let Some(target) = cx.state.alias_target(&name) {
3146 let mut map = BTreeMap::new();
3147 map.insert("name".to_string(), Value::string(name.clone()));
3148 map.insert(
3149 "summary".to_string(),
3150 Value::string(format!("Script type alias for {target}.")),
3151 );
3152 map.insert(
3153 "docs".to_string(),
3154 Value::string(format!(
3155 "Declared with TYPE {name} = {target}. The alias expands structurally at every declaration."
3156 )),
3157 );
3158 return Ok(Value::map(map));
3159 }
3160 Err(anyhow::anyhow!("unknown type {name}"))
3161}
3162
3163#[oxdock_func(returns = TypeTag::String)]
3177#[example(
3178 name = "self",
3179 code = r###"
3180 # The running interpreter resolves to a non-empty path.
3181 IMPORT [STD]
3182 LET $exe: STRING = INTERPRETER()
3183 LET $nonempty: BOOL = $exe != ""
3184 ASSERT_EQ $nonempty true
3185 "###
3186)]
3187#[example(
3188 name = "dynamic assembly",
3189 code = r###"
3190 # Assemble the child script dynamically: the parent interpolates
3191 # its own bindings into the pipe, then runs the interpreter on it.
3192 # Unescaped {{ }} bakes in at render time; \{{ }} stays literal
3193 # so the child expands it with its own bindings.
3194 # The pipe delivers EOF when the producer step ends, so the child
3195 # reads exactly one script.
3196 IMPORT [STD]
3197 LET $exe: STRING = INTERPRETER()
3198 LET $who: STRING = "Ada"
3199 LET $child: PIPE
3200 WITH_IO [stdout=$child] ECHO """
3201 ECHO "hello {{ $who }}!"
3202 LET $who: STRING = "Grace"
3203 ECHO "child sees \{{ $who }}!"
3204 """
3205 LET $out: STRING = WITH_IO [stdin=$child] RUN [$exe]
3206 ASSERT_CONTAINS $out "hello Ada!"
3207 ASSERT_CONTAINS $out "child sees Grace!"
3208 "###
3209)]
3210fn interpreter<P: ProcessManager>(cx: &mut StepCtx<P>) -> Result<Value> {
3211 if let Some(staged) = cx.state.io.interpreter_override() {
3212 return Ok(Value::string(staged));
3213 }
3214 Ok(Value::string(oxdock_process::interpreter_exe()?))
3215}
3216
3217#[oxdock_func(returns = TypeTag::Bool)]
3225#[example(
3226 name = "main",
3227 code = r###"
3228 # Entry top level runs as main.
3229 IMPORT [STD]
3230 LET $m: BOOL = IS_MAIN()
3231 ASSERT_EQ $m true
3232 "###
3233)]
3234#[example(
3235 name = "library doubles as demo",
3236 fence_meta = "roots:unified",
3237 code = r###"
3238 # A library doubles as a runnable demo: guard the demo with
3239 # IF IS_MAIN() so importing it stays side effect free. The
3240 # parent writes both files, then runs each in a fresh
3241 # interpreter: direct execution prints the demo, importing
3242 # it does not. Unified roots: the child inherits one
3243 # workspace, so parent and child see the same files. The
3244 # exact stdout match proves the demo line stays out of the
3245 # importing run.
3246 IMPORT [STD]
3247
3248 # The library under test: demo guarded by IS_MAIN.
3249 WRITE lib.oxfile """
3250 IMPORT [STD]
3251 FUNC GREET($x: STRING): STRING { RETURN "hi \{{ $x }}" }
3252 EXPORT GREET
3253 IF IS_MAIN() {
3254 ECHO "demo: hi Ada"
3255 }
3256 """
3257
3258 # The importer: calls the library, prints only its own line.
3259 WRITE main.oxfile """
3260 IMPORT ["lib.oxfile" AS LIB]
3261 LET $g: STRING = LIB::GREET("Bo")
3262 ECHO "imported: \{{ $g }}"
3263 """
3264
3265 # Direct run executes the demo.
3266 LET $exe: STRING = INTERPRETER()
3267 LET $direct: STRING = RUN [$exe, "lib.oxfile"]
3268 ASSERT_CONTAINS $direct "demo: hi Ada"
3269
3270 # Importing run stays silent apart from its own line.
3271 LET $via: STRING = RUN [$exe, "main.oxfile"]
3272 ASSERT_EQ $via "imported: hi Bo\n"
3273 "###
3274)]
3275fn is_main<P: ProcessManager>(cx: &mut StepCtx<P>) -> Result<Value> {
3276 let main = match cx.state.module_stack.last() {
3277 None | Some(None) => true,
3278 Some(Some(_)) => false,
3279 };
3280 Ok(Value::bool(main))
3281}
3282
3283#[oxdock_func(returns = TypeTag::Bool)]
3297#[example(
3298 name = "null stdin",
3299 code = r###"
3300 # A null stdin is never a terminal, in every harness.
3301 IMPORT [STD]
3302 LET $term: BOOL = IS_TERMINAL("stdin")
3303 ASSERT_EQ $term false
3304 "###
3305)]
3306fn is_terminal<P: ProcessManager>(
3307 cx: &mut StepCtx<P>,
3308 #[values("stdin", "stdout", "stderr")]
3310 stream_name: String,
3311) -> Result<Value> {
3312 use std::io::IsTerminal;
3313 let terminal = match stream_name.as_str() {
3314 "stdin" => {
3315 if cx.stdin_pipe.is_some() {
3320 false
3321 } else {
3322 match &cx.stdin {
3323 CommandStdin::Null => false,
3324 #[cfg(not(miri))]
3325 CommandStdin::OsPipe(_) => false,
3326 CommandStdin::Stream(_) => false,
3327 CommandStdin::Inherit => std::io::stdin().is_terminal(),
3328 }
3329 }
3330 }
3331 "stdout" => {
3332 if cx.out_pipe.is_some() {
3333 false
3335 } else if cx.state.io.stdout().is_some() {
3336 false
3339 } else {
3340 match &cx.out {
3341 None => std::io::stdout().is_terminal(),
3343 #[cfg(not(miri))]
3345 Some(StreamHandle::Os(_)) => false,
3346 Some(StreamHandle::Stream(_)) => std::io::stdout().is_terminal(),
3356 }
3357 }
3358 }
3359 "stderr" => {
3360 if cx.state.io.stderr().is_some() {
3361 false
3363 } else {
3364 match &cx.err {
3365 None => std::io::stderr().is_terminal(),
3367 #[cfg(not(miri))]
3369 Some(StreamHandle::Os(_)) => false,
3370 Some(StreamHandle::Stream(_)) => false,
3373 }
3374 }
3375 }
3376 _ => anyhow::bail!(
3377 "IS_TERMINAL expects \"stdin\", \"stdout\", or \"stderr\", got {stream_name:?}"
3382 ),
3383 };
3384 Ok(Value::bool(terminal))
3385}
3386
3387#[oxdock_func(returns = TypeTag::Semaphore)]
3395#[example(
3396 name = "mint",
3397 code = r###"
3398 # Mint a semaphore admitting at most two holders.
3399 IMPORT [STD]
3400 LET $sem: SEMAPHORE = SEMAPHORE_NEW(2)
3401
3402 # A fresh semaphore reports its full cap as available.
3403 LET $free: INT = SEMAPHORE_AVAILABLE($sem)
3404 ASSERT_EQ $free 2
3405 "###
3406)]
3407fn semaphore_new<P: ProcessManager>(
3408 cx: &mut StepCtx<P>,
3409 max: i64,
3411) -> Result<Value> {
3412 let _ = cx;
3413 if max <= 0 {
3414 return Err(anyhow::anyhow!(
3415 "SEMAPHORE_NEW() requires a positive max, got {max}"
3416 ));
3417 }
3418 Ok(Value::semaphore(max as usize))
3419}
3420
3421#[oxdock_func(returns = TypeTag::Record(std::sync::Arc::from([Field {
3430 name: "held".to_string(),
3431 ty: TypeTag::Bool,
3432 docs: "`true` with the permit under `permit`, `false` with no `permit` key.",
3433 optional: false,
3434 default: None,
3435
3436 alias: None,}, Field {
3437 name: "permit".to_string(),
3438 ty: TypeTag::Permit,
3439 docs: "Permit handle; read only when `held`.",
3440 optional: true,
3441 default: None,
3442
3443 alias: None,}])))]
3444#[example(
3445 name = "acquire",
3446 code = r###"
3447 # First acquire holds with a permit to bind.
3448 IMPORT [STD]
3449 LET $sem: SEMAPHORE = SEMAPHORE_NEW(1)
3450 LET $first: MAP<held: BOOL, permit?: PERMIT> = SEMAPHORE_TRY_ACQUIRE($sem)
3451 ASSERT_EQ $first.held true
3452 LET $permit: PERMIT = $first.permit
3453
3454 # A capped semaphore answers held false with no permit key.
3455 LET $second: MAP<held: BOOL, permit?: PERMIT> = SEMAPHORE_TRY_ACQUIRE($sem)
3456 ASSERT_EQ $second.held false
3457 LET $has_permit: BOOL = HAS_KEY($second, "permit")
3458 ASSERT_EQ $has_permit false
3459 "###
3460)]
3461fn semaphore_try_acquire<P: ProcessManager>(
3462 cx: &mut StepCtx<P>,
3463 sem: Arc<SemaphoreState>,
3465) -> Result<Value> {
3466 let _ = cx;
3467 let mut map = BTreeMap::new();
3468 if sem.try_acquire() {
3469 map.insert("held".to_string(), Value::bool(true));
3470 map.insert("permit".to_string(), Value::permit(&sem));
3471 } else {
3472 map.insert("held".to_string(), Value::bool(false));
3473 }
3474 Ok(Value::map(map))
3475}
3476
3477#[oxdock_func(pure, returns = TypeTag::Int)]
3484#[example(
3485 name = "readout",
3486 code = r###"
3487 # Hold one permit on a cap of two.
3488 IMPORT [STD]
3489 LET $sem: SEMAPHORE = SEMAPHORE_NEW(2)
3490 LET $acq: MAP<held: BOOL, permit?: PERMIT> = SEMAPHORE_TRY_ACQUIRE($sem)
3491 ASSERT_EQ $acq.held true
3492
3493 # One held permit leaves exactly one free.
3494 LET $free: INT = SEMAPHORE_AVAILABLE($sem)
3495 ASSERT_EQ $free 1
3496 "###
3497)]
3498fn semaphore_available(
3499 sem: Arc<SemaphoreState>,
3501) -> Result<Value> {
3502 Ok(Value::int(sem.available() as i64))
3503}
3504
3505#[oxdock_func(
3514 rpn,
3515 returns = TypeTag::union(vec![TypeTag::String, TypeTag::Pipe]),
3516 template = text_trim_string
3517)]
3518#[example(
3519 name = "trim",
3520 code = r###"
3521 # Leading and trailing whitespace falls away.
3522 IMPORT [STD]
3523 LET $clean: STRING = TEXT_TRIM(" hello ")
3524 ASSERT_EQ $clean "hello"
3525 "###
3526)]
3527#[example(
3528 name = "trim pipe mirrors",
3529 code = r###"
3530 # Pipe input mints pipe output with the same transform.
3531 IMPORT [STD]
3532 LET $cap: PIPE
3533 WITH_IO [stdout=$cap] {
3534 ECHO " hello "
3535 }
3536 LET $out: PIPE = TEXT_TRIM($cap)
3537 WITH_IO [stdin=$out] READ_LINE $line
3538 ASSERT_EQ $line "hello"
3539 "###
3540)]
3541#[example(
3542 name = "trim template",
3543 code = r###"
3544 # String inputs run inside placeholders too.
3545 IMPORT [STD]
3546 LET $msg: STRING = 'clean:{{ STD::TEXT_TRIM(" hello ") }}'
3547 ASSERT_EQ $msg "clean:hello"
3548 "###
3549)]
3550#[example(
3551 name = "trim file template",
3552 code = r###"
3553 # EXPAND templates resolve the same registry.
3554 IMPORT [STD]
3555 WRITE "tpl.txt" "clean:\{{ STD::TEXT_TRIM(\" hello \") }}"
3556 LET $out: STRING = EXPAND "tpl.txt"
3557 ASSERT_EQ $out "clean:hello"
3558 "###
3559)]
3560fn text_trim<P: ProcessManager>(
3561 cx: &mut StepCtx<P>,
3562 #[union(String, Pipe)]
3564 text: Value,
3565) -> Result<Value> {
3566 super::args::mirror_stream(cx, "TEXT_TRIM", &text, super::args::TextPump::Trim)
3567}
3568
3569fn text_trim_string(text: Value) -> Result<Value> {
3572 super::args::mirror_string("TEXT_TRIM", &text, super::args::TextPump::Trim)
3573}
3574
3575#[oxdock_func(
3584 rpn,
3585 returns = TypeTag::union(vec![TypeTag::String, TypeTag::Pipe]),
3586 template = text_trim_prefix_string
3587)]
3588#[example(
3589 name = "strip prefix",
3590 code = r###"
3591 # A present prefix falls away; absence returns the input unchanged.
3592 IMPORT [STD]
3593 LET $bare: STRING = TEXT_TRIM_PREFIX("v1.2.3", "v")
3594 ASSERT_EQ $bare "1.2.3"
3595
3596 # Missing prefixes pass through untouched.
3597 LET $same: STRING = TEXT_TRIM_PREFIX("1.2.3", "v")
3598 ASSERT_EQ $same "1.2.3"
3599 "###
3600)]
3601#[example(
3602 name = "strip prefix pipe mirrors",
3603 code = r###"
3604 # Pipe input mints pipe output with the same strip.
3605 IMPORT [STD]
3606 LET $cap: PIPE
3607 WITH_IO [stdout=$cap] {
3608 ECHO "v1.2.3"
3609 }
3610 LET $trimmed: PIPE = TEXT_TRIM($cap)
3611 LET $out: PIPE = TEXT_TRIM_PREFIX($trimmed, "v")
3612 WITH_IO [stdin=$out] READ_LINE $line
3613 ASSERT_EQ $line "1.2.3"
3614 "###
3615)]
3616#[example(
3617 name = "strip prefix template",
3618 code = r###"
3619 # String inputs run inside placeholders too.
3620 IMPORT [STD]
3621 LET $msg: STRING = 'bare:{{ STD::TEXT_TRIM_PREFIX("v1.2.3", "v") }}'
3622 ASSERT_EQ $msg "bare:1.2.3"
3623 "###
3624)]
3625fn text_trim_prefix<P: ProcessManager>(
3626 cx: &mut StepCtx<P>,
3627 #[union(String, Pipe)]
3629 text: Value,
3630 prefix: String,
3632) -> Result<Value> {
3633 super::args::mirror_stream(
3634 cx,
3635 "TEXT_TRIM_PREFIX",
3636 &text,
3637 super::args::TextPump::TrimPrefix(prefix),
3638 )
3639}
3640
3641fn text_trim_prefix_string(text: Value, prefix: String) -> Result<Value> {
3644 super::args::mirror_string(
3645 "TEXT_TRIM_PREFIX",
3646 &text,
3647 super::args::TextPump::TrimPrefix(prefix),
3648 )
3649}
3650
3651#[oxdock_func(
3658 rpn,
3659 returns = TypeTag::union(vec![TypeTag::String, TypeTag::Pipe]),
3660 template = text_trim_suffix_string
3661)]
3662#[example(
3663 name = "strip suffix",
3664 code = r###"
3665 # A present suffix falls away; absence returns the input unchanged.
3666 IMPORT [STD]
3667 LET $bare: STRING = TEXT_TRIM_SUFFIX("archive.tar.gz", ".gz")
3668 ASSERT_EQ $bare "archive.tar"
3669
3670 # Missing suffixes pass through untouched.
3671 LET $same: STRING = TEXT_TRIM_SUFFIX("archive.tar", ".gz")
3672 ASSERT_EQ $same "archive.tar"
3673 "###
3674)]
3675#[example(
3676 name = "strip suffix pipe mirrors",
3677 code = r###"
3678 # Pipe input mints pipe output with the same strip.
3679 IMPORT [STD]
3680 LET $cap: PIPE
3681 WITH_IO [stdout=$cap] {
3682 ECHO "archive.tar.gz"
3683 }
3684 LET $trimmed: PIPE = TEXT_TRIM($cap)
3685 LET $out: PIPE = TEXT_TRIM_SUFFIX($trimmed, ".gz")
3686 WITH_IO [stdin=$out] READ_LINE $line
3687 ASSERT_EQ $line "archive.tar"
3688 "###
3689)]
3690#[example(
3691 name = "strip suffix template",
3692 code = r###"
3693 # String inputs run inside placeholders too.
3694 IMPORT [STD]
3695 LET $msg: STRING = 'bare:{{ STD::TEXT_TRIM_SUFFIX("archive.tar.gz", ".gz") }}'
3696 ASSERT_EQ $msg "bare:archive.tar"
3697 "###
3698)]
3699fn text_trim_suffix<P: ProcessManager>(
3700 cx: &mut StepCtx<P>,
3701 #[union(String, Pipe)]
3703 text: Value,
3704 suffix: String,
3706) -> Result<Value> {
3707 super::args::mirror_stream(
3708 cx,
3709 "TEXT_TRIM_SUFFIX",
3710 &text,
3711 super::args::TextPump::TrimSuffix(suffix),
3712 )
3713}
3714
3715fn text_trim_suffix_string(text: Value, suffix: String) -> Result<Value> {
3718 super::args::mirror_string(
3719 "TEXT_TRIM_SUFFIX",
3720 &text,
3721 super::args::TextPump::TrimSuffix(suffix),
3722 )
3723}
3724
3725#[oxdock_func(returns = TypeTag::String)]
3736#[example(
3737 name = "join path",
3738 code = r###"
3739 # Directory and file stem join with the native separator.
3740 # Source `\\` is one backslash at runtime; `/` works on Windows
3741 # too, native just reads better there.
3742 IMPORT [STD]
3743 LET $p: STRING = PATH_JOIN("some-dir", "some-file")
3744 [family:unix] ASSERT_EQ $p "some-dir/some-file"
3745 [family:windows] ASSERT_EQ $p "some-dir\\some-file"
3746 "###
3747)]
3748fn path_join<P: ProcessManager>(
3749 _cx: &mut StepCtx<P>,
3750 #[union(String, Path)]
3752 dir: Value,
3753 #[union(String, Path)]
3755 name: Value,
3756) -> Result<Value> {
3757 let d = super::args::string_or_path_text(&dir)?;
3758 let n = super::args::string_or_path_text(&name)?;
3759 Ok(Value::string(oxdock_fs::join_native(&d, &n)))
3760}
3761
3762#[oxdock_func(pure, returns = TypeTag::String)]
3770#[example(
3771 name = "base",
3772 code = r###"
3773 # Final segments bind without filesystem access.
3774 IMPORT [STD]
3775 LET $b: STRING = PATH_BASE("some-dir/some-file")
3776 ASSERT_EQ $b "some-file"
3777
3778 # Trailing slashes trim before the split.
3779 LET $d: STRING = PATH_BASE("some-dir/")
3780 ASSERT_EQ $d "some-dir"
3781 "###
3782)]
3783fn path_base(
3784 #[union(String, Path)]
3786 path: Value,
3787) -> Result<Value> {
3788 let text = super::args::string_or_path_text(&path)?;
3789 let base = oxdock_fs::path_base(&text).map_err(|e| anyhow::anyhow!("PATH_BASE: {e:#}"))?;
3790 Ok(Value::string(base))
3791}
3792
3793#[oxdock_func(pure, returns = TypeTag::String)]
3803#[example(
3804 name = "relativize",
3805 code = r###"
3806 # Prefix bases strip to their remainder.
3807 IMPORT [STD]
3808 LET $r: STRING = PATH_REL("some-dir", "some-dir/some-file")
3809 ASSERT_EQ $r "some-file"
3810
3811 # Equal paths bind dot.
3812 LET $dot: STRING = PATH_REL("some-dir", "some-dir")
3813 ASSERT_EQ $dot "."
3814 "###
3815)]
3816fn path_rel(
3817 #[union(String, Path)]
3819 base: Value,
3820 #[union(String, Path)]
3822 path: Value,
3823) -> Result<Value> {
3824 let b = super::args::string_or_path_text(&base)?;
3825 let p = super::args::string_or_path_text(&path)?;
3826 let rel = oxdock_fs::path_rel(&b, &p).map_err(|e| anyhow::anyhow!("PATH_REL: {e:#}"))?;
3827 Ok(Value::string(rel))
3828}
3829
3830#[oxdock_func(
3837 rpn,
3838 returns = TypeTag::union(vec![TypeTag::String, TypeTag::Pipe]),
3839 template = text_to_upper_string
3840)]
3841#[example(
3842 name = "uppercase",
3843 code = r###"
3844 # Text folds to uppercase.
3845 IMPORT [STD]
3846 LET $loud: STRING = TEXT_TO_UPPER("hello")
3847 ASSERT_EQ $loud "HELLO"
3848 "###
3849)]
3850#[example(
3851 name = "uppercase pipe mirrors",
3852 code = r###"
3853 # Pipe input mints pipe output with the same fold.
3854 IMPORT [STD]
3855 LET $cap: PIPE
3856 WITH_IO [stdout=$cap] {
3857 ECHO "hello"
3858 }
3859 LET $out: PIPE = TEXT_TO_UPPER($cap)
3860 WITH_IO [stdin=$out] READ_LINE $line
3861 ASSERT_EQ $line "HELLO"
3862 "###
3863)]
3864#[example(
3865 name = "uppercase template",
3866 code = r###"
3867 # String inputs run inside placeholders too.
3868 IMPORT [STD]
3869 LET $msg: STRING = 'loud:{{ STD::TEXT_TO_UPPER("hello") }}'
3870 ASSERT_EQ $msg "loud:HELLO"
3871 "###
3872)]
3873fn text_to_upper<P: ProcessManager>(
3874 cx: &mut StepCtx<P>,
3875 #[union(String, Pipe)]
3877 text: Value,
3878) -> Result<Value> {
3879 super::args::mirror_stream(cx, "TEXT_TO_UPPER", &text, super::args::TextPump::ToUpper)
3880}
3881
3882fn text_to_upper_string(text: Value) -> Result<Value> {
3885 super::args::mirror_string("TEXT_TO_UPPER", &text, super::args::TextPump::ToUpper)
3886}
3887
3888#[oxdock_func(
3895 rpn,
3896 returns = TypeTag::union(vec![TypeTag::String, TypeTag::Pipe]),
3897 template = text_to_lower_string
3898)]
3899#[example(
3900 name = "lowercase",
3901 code = r###"
3902 # Text folds to lowercase.
3903 IMPORT [STD]
3904 LET $quiet: STRING = TEXT_TO_LOWER("HELLO")
3905 ASSERT_EQ $quiet "hello"
3906 "###
3907)]
3908#[example(
3909 name = "lowercase pipe mirrors",
3910 code = r###"
3911 # Pipe input mints pipe output with the same fold.
3912 IMPORT [STD]
3913 LET $cap: PIPE
3914 WITH_IO [stdout=$cap] {
3915 ECHO "HELLO"
3916 }
3917 LET $out: PIPE = TEXT_TO_LOWER($cap)
3918 WITH_IO [stdin=$out] READ_LINE $line
3919 ASSERT_EQ $line "hello"
3920 "###
3921)]
3922#[example(
3923 name = "lowercase template",
3924 code = r###"
3925 # String inputs run inside placeholders too.
3926 IMPORT [STD]
3927 LET $msg: STRING = 'quiet:{{ STD::TEXT_TO_LOWER("HELLO") }}'
3928 ASSERT_EQ $msg "quiet:hello"
3929 "###
3930)]
3931fn text_to_lower<P: ProcessManager>(
3932 cx: &mut StepCtx<P>,
3933 #[union(String, Pipe)]
3935 text: Value,
3936) -> Result<Value> {
3937 super::args::mirror_stream(cx, "TEXT_TO_LOWER", &text, super::args::TextPump::ToLower)
3938}
3939
3940fn text_to_lower_string(text: Value) -> Result<Value> {
3943 super::args::mirror_string("TEXT_TO_LOWER", &text, super::args::TextPump::ToLower)
3944}
3945
3946#[oxdock_func(
3957 rpn,
3958 returns = TypeTag::union(vec![TypeTag::String, TypeTag::Pipe]),
3959 template = text_replace_string
3960)]
3961#[example(
3962 name = "replace",
3963 code = r###"
3964 # Every literal occurrence rewrites in place.
3965 IMPORT [STD]
3966 LET $fixed: STRING = TEXT_REPLACE("hello world", "world", "there")
3967 ASSERT_EQ $fixed "hello there"
3968 "###
3969)]
3970#[example(
3971 name = "replace pipe mirrors",
3972 code = r###"
3973 # Pipe input mints pipe output with the same rewrite.
3974 IMPORT [STD]
3975 LET $cap: PIPE
3976 WITH_IO [stdout=$cap] {
3977 ECHO "hello world"
3978 }
3979 LET $trimmed: PIPE = TEXT_TRIM($cap)
3980 LET $out: PIPE = TEXT_REPLACE($trimmed, "world", "there")
3981 WITH_IO [stdin=$out] READ_LINE $line
3982 ASSERT_EQ $line "hello there"
3983 "###
3984)]
3985#[example(
3986 name = "replace template",
3987 code = r###"
3988 # String inputs run inside placeholders too.
3989 IMPORT [STD]
3990 LET $msg: STRING = 'fixed:{{ STD::TEXT_REPLACE("hello world", "world", "there") }}'
3991 ASSERT_EQ $msg "fixed:hello there"
3992 "###
3993)]
3994fn text_replace<P: ProcessManager>(
3995 cx: &mut StepCtx<P>,
3996 #[union(String, Pipe)]
3998 text: Value,
3999 from: String,
4001 to: String,
4003) -> Result<Value> {
4004 super::args::mirror_stream(
4005 cx,
4006 "TEXT_REPLACE",
4007 &text,
4008 super::args::TextPump::ReplaceLiteral { from, to },
4009 )
4010}
4011
4012fn text_replace_string(text: Value, from: String, to: String) -> Result<Value> {
4015 super::args::mirror_string(
4016 "TEXT_REPLACE",
4017 &text,
4018 super::args::TextPump::ReplaceLiteral { from, to },
4019 )
4020}
4021
4022#[oxdock_func(
4034 rpn,
4035 returns = TypeTag::union(vec![TypeTag::String, TypeTag::Pipe]),
4036 template = text_replace_regex_string
4037)]
4038#[example(
4039 name = "replace with captures",
4040 code = r###"
4041 # Capture groups expand in the replacement.
4042 IMPORT [STD]
4043 LET $swapped: STRING = TEXT_REPLACE_REGEX("2026-10-13", "(\\d+)-(\\d+)-(\\d+)", "$3/$2/$1")
4044 ASSERT_EQ $swapped "13/10/2026"
4045 "###
4046)]
4047#[example(
4048 name = "replace regex pipe mirrors",
4049 code = r###"
4050 # Pipe input mints pipe output with the same rewrite.
4051 IMPORT [STD]
4052 LET $cap: PIPE
4053 WITH_IO [stdout=$cap] {
4054 ECHO "2026-10-13"
4055 }
4056 LET $trimmed: PIPE = TEXT_TRIM($cap)
4057 LET $out: PIPE = TEXT_REPLACE_REGEX($trimmed, "(\\d+)-(\\d+)-(\\d+)", "$3/$2/$1")
4058 WITH_IO [stdin=$out] READ_LINE $line
4059 ASSERT_EQ $line "13/10/2026"
4060 "###
4061)]
4062#[example(
4063 name = "replace regex template",
4064 code = r###"
4065 # String inputs run inside placeholders too.
4066 IMPORT [STD]
4067 LET $msg: STRING = 'swapped:{{ STD::TEXT_REPLACE_REGEX("2026-10-13", "(\\d+)-(\\d+)-(\\d+)", "$3/$2/$1") }}'
4068 ASSERT_EQ $msg "swapped:13/10/2026"
4069 "###
4070)]
4071fn text_replace_regex<P: ProcessManager>(
4072 cx: &mut StepCtx<P>,
4073 #[union(String, Pipe)]
4075 text: Value,
4076 pattern: String,
4078 replacement: String,
4080) -> Result<Value> {
4081 if let Some(s) = text.as_str() {
4082 let out =
4083 super::args::text_replace_regex_str(s, &pattern, &replacement, "TEXT_REPLACE_REGEX")?;
4084 return Ok(Value::string(out));
4085 }
4086 let content = super::args::read_pipe_eager(cx, "TEXT_REPLACE_REGEX", &text)?;
4087 let out = super::args::text_replace_regex_str(
4088 &content,
4089 &pattern,
4090 &replacement,
4091 "TEXT_REPLACE_REGEX",
4092 )?;
4093 super::args::write_completed_pipe(cx, "TEXT_REPLACE_REGEX", out)
4094}
4095
4096fn text_replace_regex_string(text: Value, pattern: String, replacement: String) -> Result<Value> {
4099 let Some(s) = text.as_str() else {
4100 return Err(super::args::pipe_needs_step_io("TEXT_REPLACE_REGEX"));
4101 };
4102 let out = super::args::text_replace_regex_str(s, &pattern, &replacement, "TEXT_REPLACE_REGEX")?;
4103 Ok(Value::string(out))
4104}
4105
4106#[oxdock_func(pure, returns = TypeTag::ListOf(std::sync::Arc::new(TypeTag::String)))]
4114#[example(
4115 name = "split",
4116 code = r###"
4117 # Delimiters split into list items.
4118 IMPORT [STD]
4119 LET $parts: LIST<STRING> = TEXT_SPLIT("a,b,c", ",")
4120 ASSERT_EQ $parts.0 "a"
4121 ASSERT_EQ $parts.1 "b"
4122 ASSERT_EQ $parts.2 "c"
4123 "###
4124)]
4125fn text_split(
4126 text: String,
4128 delimiter: String,
4130) -> Result<Value> {
4131 Ok(super::args::text_list_value(super::args::text_split_str(
4132 &text, &delimiter,
4133 )))
4134}
4135
4136#[oxdock_func(pure, returns = TypeTag::String)]
4139#[example(
4140 name = "join",
4141 code = r###"
4142 # List items join with the separator between them.
4143 IMPORT [STD]
4144 LET $joined: STRING = TEXT_JOIN(["a", "b", "c"], ",")
4145 ASSERT_EQ $joined "a,b,c"
4146 "###
4147)]
4148fn text_join(
4149 elements: Vec<String>,
4151 delimiter: String,
4153) -> Result<Value> {
4154 Ok(Value::string(elements.join(delimiter.as_str())))
4155}
4156
4157#[oxdock_func(pure, returns = TypeTag::ListOf(std::sync::Arc::new(TypeTag::String)))]
4169#[example(
4170 name = "split args",
4171 code = r###"
4172 # Quoted segments stay one word.
4173 IMPORT [STD]
4174 LET $argv: LIST<STRING> = SHELL_SPLIT_ARGS("gh issue comment 153 --body-file notes.md")
4175 ASSERT_EQ $argv.0 "gh"
4176 ASSERT_EQ $argv.3 "153"
4177 ASSERT_EQ $argv.5 "notes.md"
4178
4179 # Quotes and escapes parse the shell way.
4180 LET $quoted: LIST<STRING> = SHELL_SPLIT_ARGS("say \"hi there\" 'a b'")
4181 ASSERT_EQ $quoted.0 "say"
4182 ASSERT_EQ $quoted.1 "hi there"
4183 ASSERT_EQ $quoted.2 "a b"
4184 "###
4185)]
4186fn shell_split_args(
4187 command: String,
4189) -> Result<Value> {
4190 match shell_words::split(&command) {
4191 Ok(words) => Ok(super::args::text_list_value(words)),
4192 Err(err) => anyhow::bail!("SHELL_SPLIT_ARGS: {err}"),
4193 }
4194}
4195
4196#[oxdock_func(pure, returns = TypeTag::String)]
4204#[example(
4205 name = "join args",
4206 code = r###"
4207 # Plain words join with spaces and no quoting.
4208 IMPORT [STD]
4209 LET $plain: STRING = SHELL_JOIN_ARGS(["gh", "issue", "list"])
4210 ASSERT_EQ $plain "gh issue list"
4211
4212 # Words with spaces quote, and the round trip is exact.
4213 LET $words: LIST<STRING> = ["say", "hi there", "a'b"]
4214 LET $joined: STRING = SHELL_JOIN_ARGS($words)
4215 LET $back: LIST<STRING> = SHELL_SPLIT_ARGS($joined)
4216 ASSERT_EQ $back.0 "say"
4217 ASSERT_EQ $back.1 "hi there"
4218 ASSERT_EQ $back.2 "a'b"
4219 "###
4220)]
4221fn shell_join_args(
4222 words: Vec<String>,
4224) -> Result<Value> {
4225 Ok(Value::string(shell_words::join(&words)))
4226}
4227
4228#[oxdock_func(pure, returns = TypeTag::ListOf(std::sync::Arc::new(TypeTag::String)))]
4236#[example(
4237 name = "lines",
4238 code = r###"
4239 # Newlines split into line items.
4240 IMPORT [STD]
4241 LET $lines: LIST<STRING> = TEXT_LINES("one\ntwo\nthree")
4242 ASSERT_EQ $lines.0 "one"
4243 ASSERT_EQ $lines.1 "two"
4244 ASSERT_EQ $lines.2 "three"
4245
4246 # Windows endings split the same way after normalization.
4247 LET $crlf: LIST<STRING> = TEXT_LINES("one\r\ntwo\r\nthree")
4248 ASSERT_EQ $crlf.0 "one"
4249 ASSERT_EQ $crlf.1 "two"
4250 ASSERT_EQ $crlf.2 "three"
4251
4252 # Old Mac endings split too, and mixed endings split together because the input normalizes to LF before splitting.
4253 LET $mixed: LIST<STRING> = TEXT_LINES("a\r\nb\nc\rd")
4254 ASSERT_EQ $mixed.0 "a"
4255 ASSERT_EQ $mixed.1 "b"
4256 ASSERT_EQ $mixed.2 "c"
4257 ASSERT_EQ $mixed.3 "d"
4258 "###
4259)]
4260fn text_lines(
4261 text: String,
4263) -> Result<Value> {
4264 Ok(super::args::text_list_value(super::args::text_lines_str(
4265 &text,
4266 )))
4267}
4268
4269#[oxdock_func(pure, returns = TypeTag::ListOf(std::sync::Arc::new(TypeTag::String)))]
4275#[example(
4276 name = "fields",
4277 code = r###"
4278 # Runs of whitespace separate fields; empties never appear.
4279 IMPORT [STD]
4280 LET $fields: LIST<STRING> = TEXT_FIELDS(" abc def ")
4281 ASSERT_EQ $fields.0 "abc"
4282 ASSERT_EQ $fields.1 "def"
4283 "###
4284)]
4285fn text_fields(
4286 text: String,
4288) -> Result<Value> {
4289 Ok(super::args::text_list_value(super::args::text_fields_str(
4290 &text,
4291 )))
4292}
4293
4294#[oxdock_func(pure, returns = TypeTag::ListOf(std::sync::Arc::new(TypeTag::String)))]
4303#[example(
4304 name = "line range",
4305 code = r###"
4306 # Lines 2 through 3 come back as a list, 1-based inclusive.
4307 IMPORT [STD]
4308 LET $window: LIST<STRING> = TEXT_LINES_RANGE("one\ntwo\nthree\nfour", 2, 3)
4309 ASSERT_EQ $window.0 "two"
4310 ASSERT_EQ $window.1 "three"
4311
4312 # Ranges past the end clamp instead of failing.
4313 LET $tail: LIST<STRING> = TEXT_LINES_RANGE("one\ntwo", 2, 9)
4314 ASSERT_EQ $tail.0 "two"
4315 "###
4316)]
4317fn text_lines_range(
4318 text: String,
4320 from: i64,
4322 to: i64,
4324) -> Result<Value> {
4325 Ok(super::args::text_list_value(
4326 super::args::text_lines_range_str(&text, from, to, "TEXT_LINES_RANGE")?,
4327 ))
4328}
4329
4330#[oxdock_func(pure, returns = TypeTag::Bool)]
4338#[example(
4339 name = "match",
4340 code = r###"
4341 # Regex matches report true; misses report false.
4342 IMPORT [STD]
4343 LET $hit: BOOL = TEXT_MATCH("abc123", "\\d+")
4344 ASSERT_EQ $hit true
4345
4346 # A miss is false, not a failure.
4347 LET $miss: BOOL = TEXT_MATCH("abc", "^\\d+$")
4348 ASSERT_EQ $miss false
4349 "###
4350)]
4351fn text_match(
4352 text: String,
4354 pattern: String,
4356) -> Result<Value> {
4357 let re = super::args::text_compile_pattern("TEXT_MATCH", &pattern)?;
4358 Ok(Value::bool(re.is_match(&text)))
4359}
4360
4361#[oxdock_func(pure, name = "BOOL", returns = TypeTag::Bool)]
4370#[example(
4371 name = "convert",
4372 code = r###"
4373 IMPORT [STD]
4374 LET $n: BOOL = BOOL("yes")
4375 ASSERT_EQ $n true
4376 LET $f: BOOL = BOOL("0")
4377 ASSERT_EQ $f false
4378 "###
4379)]
4380fn bool_convert(
4381 #[union(Bool, String)]
4383 val: Value,
4384) -> Result<Value> {
4385 if let Some(b) = val.as_bool() {
4386 return Ok(Value::bool(b));
4387 }
4388 let Some(s) = val.as_str() else {
4389 return Err(anyhow::anyhow!(
4390 "BOOL needs a Bool or String, found {val:?}"
4391 ));
4392 };
4393 match super::args::parse_bool_str(s) {
4394 Some(b) => Ok(Value::bool(b)),
4395 None => anyhow::bail!("BOOL cannot coerce {s:?} to BOOL"),
4396 }
4397}
4398
4399#[oxdock_func(pure, returns = TypeTag::Bool)]
4409#[example(
4410 name = "absent-default",
4411 code = r###"
4412 # Absent names read empty; the default settles the polarity.
4413 IMPORT [STD]
4414 INHERIT_ENV [OXDOCK_TEST_ABSENT_FLAG]
4415 LET $dry: BOOL = BOOL_OR("{{ env:OXDOCK_TEST_ABSENT_FLAG }}", true)
4416 ASSERT_EQ $dry true
4417
4418 # Present values coerce strictly, ignoring the default.
4419 LET $off: BOOL = BOOL_OR("false", true)
4420 ASSERT_EQ $off false
4421 "###
4422)]
4423fn bool_or(
4424 text: String,
4426 default: bool,
4428) -> Result<Value> {
4429 if text.trim().is_empty() {
4430 return Ok(Value::bool(default));
4431 }
4432 match super::args::parse_bool_str(&text) {
4433 Some(b) => Ok(Value::bool(b)),
4434 None => anyhow::bail!("BOOL_OR cannot coerce {text:?} to BOOL"),
4435 }
4436}
4437
4438#[oxdock_func(pure, returns = TypeTag::ListOf(std::sync::Arc::new(TypeTag::String)))]
4447#[example(
4448 name = "extract",
4449 code = r###"
4450 # Index zero is the full match; groups follow in order.
4451 IMPORT [STD]
4452 LET $caps: LIST<STRING> = TEXT_EXTRACT("abc123", "([a-z]+)(\\d+)")
4453 ASSERT_EQ $caps.0 "abc123"
4454 ASSERT_EQ $caps.1 "abc"
4455 ASSERT_EQ $caps.2 "123"
4456 "###
4457)]
4458fn text_extract(
4459 text: String,
4461 pattern: String,
4463) -> Result<Value> {
4464 let groups = super::args::text_extract_str(&text, &pattern, "TEXT_EXTRACT")?;
4465 Ok(super::args::text_list_value(groups))
4466}
4467
4468#[oxdock_func(pure, returns = TypeTag::Bool)]
4475#[example(
4476 name = "starts with",
4477 code = r###"
4478 # Present prefixes report true; misses report false.
4479 IMPORT [STD]
4480 LET $hit: BOOL = TEXT_STARTS_WITH("linux-musl-x64", "linux")
4481 ASSERT_EQ $hit true
4482
4483 # A miss is false, not a failure.
4484 LET $miss: BOOL = TEXT_STARTS_WITH("macos-arm", "linux")
4485 ASSERT_EQ $miss false
4486 "###
4487)]
4488fn text_starts_with(
4489 text: String,
4491 prefix: String,
4493) -> Result<Value> {
4494 Ok(Value::bool(text.starts_with(prefix.as_str())))
4495}
4496
4497#[oxdock_func(pure, returns = TypeTag::Bool)]
4504#[example(
4505 name = "ends with",
4506 code = r###"
4507 # Present suffixes report true; misses report false.
4508 IMPORT [STD]
4509 LET $hit: BOOL = TEXT_ENDS_WITH("x86_64-linux-musl", "linux-musl")
4510 ASSERT_EQ $hit true
4511
4512 # A miss is false, not a failure.
4513 LET $miss: BOOL = TEXT_ENDS_WITH("x86_64-linux-gnu", "linux-musl")
4514 ASSERT_EQ $miss false
4515 "###
4516)]
4517fn text_ends_with(
4518 text: String,
4520 suffix: String,
4522) -> Result<Value> {
4523 Ok(Value::bool(text.ends_with(suffix.as_str())))
4524}
4525
4526#[oxdock_func(pure, returns = TypeTag::Bool)]
4536#[example(
4537 name = "contains",
4538 code = r###"
4539 # Present needles report true; misses report false.
4540 IMPORT [STD]
4541 LET $hit: BOOL = CONTAINS("x86_64-linux-musl", "musl")
4542 ASSERT_EQ $hit true
4543
4544 # A miss is false, not a failure.
4545 LET $miss: BOOL = CONTAINS("x86_64-linux-gnu", "musl")
4546 ASSERT_EQ $miss false
4547 "###
4548)]
4549#[example(
4550 name = "contains list",
4551 code = r###"
4552 # List membership uses strict equality across any element type.
4553 IMPORT [STD]
4554 LET $hit: BOOL = CONTAINS(["a", "b", "c"], "b")
4555 ASSERT_EQ $hit true
4556 LET $miss: BOOL = CONTAINS(["a", "b", "c"], "z")
4557 ASSERT_EQ $miss false
4558 LET $num: BOOL = CONTAINS([1, 2, 3], 2.0)
4559 ASSERT_EQ $num true
4560
4561 # Stringified numbers never coerce to integers.
4562 LET $strnum: BOOL = CONTAINS(["1", "2", "3"], 2)
4563 ASSERT_EQ $strnum false
4564
4565 # Boolean lists match true and miss false with no coercion.
4566 LET $bools: LIST<BOOL> = [true]
4567 LET $bhit: BOOL = CONTAINS($bools, true)
4568 ASSERT_EQ $bhit true
4569 LET $bmiss: BOOL = CONTAINS($bools, false)
4570 ASSERT_EQ $bmiss false
4571 LET $nocoerce: BOOL = CONTAINS($bools, 1)
4572 ASSERT_EQ $nocoerce false
4573 "###
4574)]
4575fn contains(
4576 #[union(String, List)]
4578 haystack: Value,
4579 needle: Value,
4581) -> Result<Value> {
4582 if let Some(text) = haystack.as_str() {
4583 let Some(n) = needle.as_str() else {
4584 return Err(anyhow::anyhow!(
4585 "CONTAINS needs a STRING needle for a STRING haystack, found {}",
4586 needle.type_name()
4587 ));
4588 };
4589 return Ok(Value::bool(text.contains(n)));
4590 }
4591 if let Some(items) = haystack.as_list() {
4592 for item in items {
4593 if super::args::values_equal(item, &needle) {
4594 return Ok(Value::bool(true));
4595 }
4596 }
4597 return Ok(Value::bool(false));
4598 }
4599 Err(anyhow::anyhow!(
4600 "CONTAINS needs a STRING or LIST haystack, found {}",
4601 haystack.type_name()
4602 ))
4603}
4604
4605#[oxdock_func(pure, returns = TypeTag::Int)]
4614#[example(
4615 name = "length",
4616 code = r###"
4617 # Plain text counts one per character.
4618 IMPORT [STD]
4619 LET $n: INT = LEN("hello")
4620 ASSERT_EQ $n 5
4621
4622 # Multibyte characters count once each, not per byte.
4623 LET $wide: INT = LEN("héllo")
4624 ASSERT_EQ $wide 5
4625
4626 # Lists count elements, maps count entries.
4627 LET $items: LIST<STRING> = ["a", "b", "c"]
4628 LET $nitems: INT = LEN($items)
4629 ASSERT_EQ $nitems 3
4630 LET $row: MAP<name: STRING> = {name: "ada"}
4631 LET $nkeys: INT = LEN($row)
4632 ASSERT_EQ $nkeys 1
4633 LET $empty: INT = LEN([])
4634 ASSERT_EQ $empty 0
4635 "###
4636)]
4637fn len(
4638 #[union(String, List, Map)]
4640 value: Value,
4641) -> Result<Value> {
4642 if let Some(text) = value.as_str() {
4643 return Ok(Value::int(text.chars().count() as i64));
4644 }
4645 if let Some(items) = value.as_list() {
4646 return Ok(Value::int(items.len() as i64));
4647 }
4648 if let Some(entries) = value.as_map() {
4649 return Ok(Value::int(entries.len() as i64));
4650 }
4651 Err(anyhow::anyhow!(
4652 "LEN needs a STRING, LIST, or MAP value, got {}",
4653 value.type_name()
4654 ))
4655}
4656
4657#[oxdock_func(pure, returns = TypeTag::Int)]
4665#[example(
4666 name = "count",
4667 code = r###"
4668 # Every non-overlapping occurrence counts once.
4669 IMPORT [STD]
4670 LET $n: INT = TEXT_COUNT("hello world", "o")
4671 ASSERT_EQ $n 2
4672
4673 # Overlapping candidates never double count.
4674 LET $once: INT = TEXT_COUNT("aaa", "aa")
4675 ASSERT_EQ $once 1
4676 "###
4677)]
4678fn text_count(
4679 text: String,
4681 needle: String,
4683) -> Result<Value> {
4684 let n = super::args::text_count_str(&text, &needle, "TEXT_COUNT")?;
4685 Ok(Value::int(n))
4686}
4687
4688#[oxdock_func(pure, returns = TypeTag::Int)]
4698#[example(
4699 name = "count matches",
4700 code = r###"
4701 # One line matches once no matter how many times it hits.
4702 IMPORT [STD]
4703 LET $n: INT = TEXT_COUNT_MATCHES("test a: test\ntest b: nope\ntest c: test", ": test")
4704 ASSERT_EQ $n 2
4705
4706 # A miss binds zero, never an error.
4707 LET $none: INT = TEXT_COUNT_MATCHES("test b: nope", ": test$")
4708 ASSERT_EQ $none 0
4709 "###
4710)]
4711fn text_count_matches(
4712 text: String,
4714 pattern: String,
4716) -> Result<Value> {
4717 let n = super::args::text_count_matches_str(&text, &pattern, "TEXT_COUNT_MATCHES")?;
4718 Ok(Value::int(n))
4719}
4720
4721#[oxdock_func(pure, returns = TypeTag::ListOf(std::sync::Arc::new(TypeTag::String)))]
4734#[example(
4735 name = "grep",
4736 code = r###"
4737 # Matching lines come back as a list, in order.
4738 IMPORT [STD]
4739 LET $hits: LIST<STRING> = TEXT_GREP("one\ntwo\none more", "^one")
4740 ASSERT_EQ $hits.0 "one"
4741 ASSERT_EQ $hits.1 "one more"
4742
4743 # A miss binds an empty list, never an error.
4744 LET $miss: LIST<STRING> = TEXT_GREP("one\ntwo", "^z")
4745 LET $joined: STRING = TEXT_JOIN($miss, ",")
4746 ASSERT_EQ $joined ""
4747
4748 # The (?i) flag ignores case, so uppercase lines match too.
4749 LET $folded: LIST<STRING> = TEXT_GREP("One\ntwo\nONE more", "(?i)^one")
4750 ASSERT_EQ $folded.0 "One"
4751 ASSERT_EQ $folded.1 "ONE more"
4752 "###
4753)]
4754#[example(
4755 name = "grep invert",
4756 code = r###"
4757 # The invert option keeps every non-matching line instead.
4758 IMPORT [STD]
4759 LET $kept: LIST<STRING> = TEXT_GREP("one\ntwo\none more", "^one", {invert: true})
4760 ASSERT_EQ $kept.0 "two"
4761
4762 # A pattern matching every line binds an empty list, never an error.
4763 LET $none: LIST<STRING> = TEXT_GREP("one\ntwo", "^", {invert: true})
4764 LET $joined: STRING = TEXT_JOIN($none, ",")
4765 ASSERT_EQ $joined ""
4766
4767 # Options ride into placeholders as MAP literals. Placeholder
4768 # strings unescape only backslash and quote, so multiline text
4769 # arrives through a variable.
4770 LET $two_lines: STRING = "one\ntwo"
4771 LET $msg: STRING = 'kept:{{ STD::TEXT_GREP($two_lines, "^one", {invert: true}) }}'
4772 ASSERT_EQ $msg "kept:two"
4773 "###
4774)]
4775fn text_grep(
4776 text: String,
4778 pattern: String,
4780 #[options("invert?: BOOL")]
4782 #[optional]
4783 options: BTreeMap<String, Value>,
4784) -> Result<Value> {
4785 let invert = super::args::text_invert_flag(&options);
4788 Ok(super::args::text_list_value(super::args::text_grep_str(
4789 &text,
4790 &pattern,
4791 invert,
4792 "TEXT_GREP",
4793 )?))
4794}
4795
4796#[oxdock_func(returns = TypeTag::Bool)]
4807#[example(
4808 name = "drain to end",
4809 code = r###"
4810 # Capture two lines, then drain to end of stream with no sentinel line.
4811 IMPORT [STD]
4812 LET $cap: PIPE
4813 WITH_IO [stdout=$cap] {
4814 ECHO "one"
4815 ECHO "two"
4816 }
4817
4818 # The loop exits on close, and the count proves both lines drained.
4819 LET $n: INT = 0
4820 WHILE !EOF($cap) {
4821 WITH_IO [stdin=$cap] READ_LINE $line
4822 $n = $n + 1
4823 }
4824 ASSERT_EQ $n 2
4825 "###
4826)]
4827fn eof<P: ProcessManager>(
4828 cx: &mut StepCtx<P>,
4829 pipe: PipeHandle,
4831) -> Result<Value> {
4832 let info = cx.state.io.inspect_pipe(&pipe);
4833 Ok(Value::bool(info.closed && info.buffered == 0))
4834}
4835
4836fn task_poll_result_fields() -> Arc<[Field]> {
4840 Arc::from(vec![
4841 Field {
4842 name: "state".to_string(),
4843 ty: TypeTag::String,
4844 docs: "Task phase: `running` or `finished`.",
4845 optional: false,
4846 default: None,
4847
4848 alias: None,
4849 },
4850 Field {
4851 name: "ok".to_string(),
4852 ty: TypeTag::Bool,
4853 docs: "True unless the task failed.",
4854 optional: false,
4855 default: None,
4856
4857 alias: None,
4858 },
4859 Field {
4860 name: "stdout_tail".to_string(),
4861 ty: TypeTag::String,
4862 docs: "Bounded stdout tail, live while running.",
4863 optional: false,
4864 default: None,
4865
4866 alias: None,
4867 },
4868 Field {
4869 name: "stderr_tail".to_string(),
4870 ty: TypeTag::String,
4871 docs: "Bounded stderr tail, live while running.",
4872 optional: false,
4873 default: None,
4874
4875 alias: None,
4876 },
4877 Field {
4878 name: "truncated_bytes".to_string(),
4879 ty: TypeTag::Int,
4880 docs: "Dropped head bytes past the per-stream cap.",
4881 optional: false,
4882 default: None,
4883
4884 alias: None,
4885 },
4886 Field {
4887 name: "exit_code".to_string(),
4888 ty: TypeTag::Int,
4889 docs: "Process exit code, present once finished.",
4890 optional: true,
4891 default: None,
4892
4893 alias: None,
4894 },
4895 Field {
4896 name: "result".to_string(),
4897 ty: TypeTag::Any,
4898 docs: "Task `RETURN` value, present on clean finish.",
4899 optional: true,
4900 default: None,
4901
4902 alias: None,
4903 },
4904 Field {
4905 name: "error".to_string(),
4906 ty: TypeTag::String,
4907 docs: "Failure text, present on failed finish.",
4908 optional: true,
4909 default: None,
4910
4911 alias: None,
4912 },
4913 ])
4914}
4915
4916#[oxdock_func(returns = TypeTag::Record(task_poll_result_fields()))]
4929#[example(
4930 name = "running poll",
4931 code = r###"
4932 # A sleeping task is still running on the first poll.
4933 IMPORT [STD]
4934 LET $t: HANDLE<STRING> = ASYNC { SLEEP 30s; RETURN "done" }
4935 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)
4936 ASSERT_EQ $m.state "running"
4937 ASSERT_EQ $m.ok true
4938 # Clean up the sleeper so the run ends promptly.
4939 CANCEL $t
4940 "###
4941)]
4942#[example(
4943 name = "finished poll",
4944 code = r###"
4945 # A finished task reports its value and final tails, then still awaits.
4946 IMPORT [STD]
4947 LET $t: HANDLE<STRING> = ASYNC { ECHO "hi"; SLEEP 1s; RETURN "done" }
4948 # Do other work while the task runs; poll once it should be done.
4949 SLEEP 2s
4950 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)
4951 ASSERT_EQ $m.state "finished"
4952 ASSERT_EQ $m.result "done"
4953 LET $o: STRING = AWAIT $t
4954 ASSERT_EQ $o "done"
4955 "###
4956)]
4957fn task_poll<P: ProcessManager>(
4958 cx: &mut StepCtx<P>,
4959 task: HandleValue,
4961) -> Result<Value> {
4962 let entry =
4963 super::handlers::resolve_task_entry_by_id(task.0, &format!("TASK_POLL({})", task.0), cx)?;
4964 let obs = entry.observe_completion();
4965 let (stdout_tail, stderr_tail, dropped) = entry.snapshot_tails();
4966 let mut out = BTreeMap::new();
4967 out.insert(
4968 "state".to_string(),
4969 Value::string(if obs.running { "running" } else { "finished" }.to_string()),
4970 );
4971 out.insert("ok".to_string(), Value::bool(obs.ok));
4972 if !obs.running {
4973 out.insert("exit_code".to_string(), Value::int(obs.exit_code));
4974 }
4975 if let Some(result) = obs.result {
4976 out.insert("result".to_string(), result);
4977 }
4978 if !obs.error.is_empty() {
4979 out.insert("error".to_string(), Value::string(obs.error));
4980 }
4981 out.insert("stdout_tail".to_string(), Value::string(stdout_tail));
4982 out.insert("stderr_tail".to_string(), Value::string(stderr_tail));
4983 out.insert(
4984 "truncated_bytes".to_string(),
4985 Value::int(dropped.min(i64::MAX as u64) as i64),
4986 );
4987 Ok(Value::map(out))
4988}
4989
4990fn meta_to_value(meta: &FuncMeta) -> Value {
4991 let mut map = BTreeMap::new();
4992 map.insert("name".to_string(), Value::string(meta.name.clone()));
4993 map.insert("module".to_string(), Value::string(meta.module.clone()));
4994 map.insert(
4995 "kind".to_string(),
4996 Value::string(meta.kind.label().to_string()),
4997 );
4998 let params = match &meta.params {
4999 Some(params) => Value::list(
5000 params
5001 .iter()
5002 .map(|p| {
5003 let mut entry = BTreeMap::new();
5004 entry.insert("name".to_string(), Value::string(p.name.clone()));
5005 entry.insert(
5006 "param_type".to_string(),
5007 Value::string(
5008 p.param_type
5009 .as_ref()
5010 .map(render_structural)
5011 .unwrap_or_default(),
5012 ),
5013 );
5014 entry.insert(
5015 "allowed".to_string(),
5016 Value::string(
5017 p.allowed
5018 .map(|values| values.join(", "))
5019 .unwrap_or_default(),
5020 ),
5021 );
5022 entry.insert("docs".to_string(), Value::string(String::new()));
5023 entry.insert("optional".to_string(), Value::bool(p.optional));
5024 entry.insert(
5025 "options".to_string(),
5026 match p.options {
5027 Some(keys) => Value::list(
5028 keys.iter()
5029 .map(|key| {
5030 let mut option = BTreeMap::new();
5031 option.insert(
5032 "name".to_string(),
5033 Value::string(key.name.to_string()),
5034 );
5035 option.insert(
5036 "value_type".to_string(),
5037 Value::string(render_structural(&key.value)),
5038 );
5039 option.insert(
5040 "required".to_string(),
5041 Value::bool(key.required),
5042 );
5043 option.insert(
5044 "default".to_string(),
5045 Value::string(
5046 key.default.unwrap_or_default().to_string(),
5047 ),
5048 );
5049 Value::map(option)
5050 })
5051 .collect(),
5052 ),
5053 None => Value::string(String::new()),
5054 },
5055 );
5056 Value::map(entry)
5057 })
5058 .collect(),
5059 ),
5060 None => Value::list(Vec::new()),
5064 };
5065 map.insert("params".to_string(), params);
5066 map.insert(
5067 "returns".to_string(),
5068 Value::string(
5069 meta.returns
5070 .as_ref()
5071 .map(render_structural)
5072 .unwrap_or_default(),
5073 ),
5074 );
5075 map.insert("rpn".to_string(), Value::bool(meta.rpn));
5076 map.insert(
5077 "summary".to_string(),
5078 Value::string(meta.summary.to_string()),
5079 );
5080 Value::map(map)
5081}
5082
5083#[derive(Debug, Clone)]
5087pub struct RecordSchema {
5088 pub name: &'static str,
5089 pub fields: std::sync::Arc<[Field]>,
5090}
5091
5092#[derive(Clone)]
5096pub struct HostModule<P: ProcessManager> {
5097 pub name: String,
5098 pub funcs: Vec<HostRegistration<P>>,
5099 pub types: Vec<&'static TypeDescriptor>,
5100 pub record_schemas: Vec<RecordSchema>,
5101 pub states: Vec<ModuleState>,
5108}
5109
5110#[derive(Clone)]
5114pub struct ModuleState {
5115 id: std::any::TypeId,
5116 state: std::sync::Arc<dyn std::any::Any + Send + Sync>,
5117}
5118
5119pub type PreRunInspector = dyn Fn(&[Step]) -> Result<()> + Send + Sync;
5123
5124#[derive(Clone)]
5130pub struct PreRunCheck {
5131 check: Arc<PreRunInspector>,
5132}
5133
5134impl PreRunCheck {
5135 pub fn new(check: impl Fn(&[Step]) -> Result<()> + Send + Sync + 'static) -> Self {
5137 Self {
5138 check: Arc::new(check),
5139 }
5140 }
5141
5142 pub fn run(&self, steps: &[Step]) -> Result<()> {
5144 (self.check)(steps)
5145 }
5146}
5147
5148impl<P: ProcessManager> HostModule<P> {
5149 pub fn with_state<T: Send + Sync + 'static>(mut self, state: std::sync::Arc<T>) -> Self {
5152 self.states.push(ModuleState {
5153 id: std::any::TypeId::of::<T>(),
5154 state,
5155 });
5156 self
5157 }
5158
5159 pub fn check_pre_run(&self, steps: &[Step]) -> Result<()> {
5163 for state in &self.states {
5164 if let Some(check) = state.state.downcast_ref::<PreRunCheck>() {
5165 check.run(steps)?;
5166 }
5167 }
5168 Ok(())
5169 }
5170}
5171
5172impl<P: ProcessManager> ExecState<P> {
5173 pub fn register_module(&mut self, module: HostModule<P>) {
5176 for registration in module.funcs {
5177 match registration {
5178 HostRegistration::Stateful { name, meta, func } => {
5179 self.functions.register_host(&module.name, name, meta, func);
5180 }
5181 HostRegistration::Pure { name, meta, func } => {
5182 self.functions
5183 .register_pure_host(&module.name, name, meta, func);
5184 }
5185 HostRegistration::Both {
5186 name,
5187 meta,
5188 func,
5189 template,
5190 } => {
5191 self.functions
5192 .register_both_host(&module.name, name, meta, func, template);
5193 }
5194 }
5195 }
5196 for descriptor in module.types {
5197 self.register_type(descriptor);
5198 }
5199 for schema in module.record_schemas {
5200 self.register_record_schema(schema.name, schema.fields);
5201 }
5202 for state in module.states {
5203 self.module_states
5204 .insert((module.name.clone(), state.id), state.state);
5205 }
5206 }
5207
5208 pub fn list_functions(&self) -> Vec<FuncMeta> {
5210 let mut out: Vec<FuncMeta> = self.functions.entries_metas().into_iter().collect();
5211 if !out.iter().any(|m| m.name == KEYWORD_INSPECT) {
5213 out.push(FuncMeta {
5214 name: KEYWORD_INSPECT.to_string(),
5215 module: STD_MODULE_NAME.to_string(),
5216 kind: FuncKind::HostCtx,
5217 params: None,
5218 returns: Some(TypeTag::Map),
5219 rpn: false,
5220 summary: "Inspect a variable binding.",
5221 docs: "INSPECT($var): dedicated AST node taking a variable, not a value.",
5222 examples: &[],
5223 });
5224 }
5225 out.sort_by(|a, b| a.name.cmp(&b.name));
5226 out
5227 }
5228
5229 pub fn describe_function(&self, name: &str) -> Option<Value> {
5231 if let Some(meta) = self.functions.meta(name) {
5232 return Some(meta_to_value(&meta));
5233 }
5234 if name == KEYWORD_INSPECT {
5236 return Some(meta_to_value(&FuncMeta {
5237 name: KEYWORD_INSPECT.to_string(),
5238 module: STD_MODULE_NAME.to_string(),
5239 kind: FuncKind::HostCtx,
5240 params: None,
5241 returns: Some(TypeTag::Map),
5242 rpn: false,
5243 summary: "Inspect a variable binding.",
5244 docs: "INSPECT($var): dedicated AST node taking a variable, not a value.",
5245 examples: &[],
5246 }));
5247 }
5248 None
5249 }
5250
5251 pub(super) fn clone_native_pure(&self, name: &str) -> Option<PureFn> {
5252 self.functions.clone_pure_fn(name)
5253 }
5254
5255 pub fn pure_function_table(&self) -> Arc<PureTable> {
5260 self.functions.pure_shared()
5261 }
5262
5263 pub(super) fn clone_native_ctx(&self, name: &str) -> Option<NativeFn<P>> {
5264 self.functions.clone_ctx_fn(name)
5265 }
5266
5267 pub(super) fn native_meta(&self, name: &str) -> Option<FuncMeta> {
5268 self.functions.meta(name)
5269 }
5270}
5271
5272#[cfg(test)]
5273mod tests {
5274 use super::*;
5275
5276 #[test]
5277 fn placeholder_resolver_dispatches_table_entries() {
5278 let echo: PureFn = Arc::new(|args| {
5282 args.into_iter()
5283 .next()
5284 .ok_or_else(|| anyhow::anyhow!("ECHO needs 1 arg"))
5285 });
5286 let mut entries = HashMap::new();
5287 entries.insert("ECHO".to_string(), echo);
5288 let mut table = PureTable::new();
5289 table.insert("T".to_string(), entries);
5290 let resolve = placeholder_resolver(Arc::new(table));
5291 let out = resolve("T", "ECHO", vec![Value::string("hi".to_string())]).expect("dispatch");
5292 assert_eq!(out.as_str().expect("string"), "hi");
5293 let err = format!(
5294 "{:#}",
5295 resolve("T", "NOPE", vec![]).expect_err("unknown must fail")
5296 );
5297 assert!(
5298 err.contains("unknown placeholder function 'T::NOPE'"),
5299 "names the call: {err}"
5300 );
5301 assert!(
5302 err.contains("known functions: T::ECHO"),
5303 "lists known names: {err}"
5304 );
5305 }
5306
5307 #[test]
5308 fn describe_entry_renders_union_spellings() {
5309 let union = oxdock_parser::union_tag!(String, Pipe);
5315 let meta = FuncMeta {
5316 name: "T::F".to_string(),
5317 module: "T".to_string(),
5318 kind: FuncKind::HostPure,
5319 params: Some(vec![FuncParam {
5320 name: "text".to_string(),
5321 param_type: Some(union.clone()),
5322 allowed: None,
5323 docs: "",
5324 options: None,
5325 optional: false,
5326 }]),
5327 returns: Some(union),
5328 rpn: false,
5329 summary: "test-only",
5330 docs: "test-only",
5331 examples: &[],
5332 };
5333 let value = meta_to_value(&meta);
5334 let map = value.as_map().expect("describe value is a map");
5335 let params = map
5336 .get("params")
5337 .expect("params key")
5338 .as_list()
5339 .expect("params is a list");
5340 let first = params[0].as_map().expect("entry is a map");
5341 assert_eq!(
5342 first.get("param_type").and_then(Value::as_str),
5343 Some("STRING|PIPE"),
5344 "param renders the set"
5345 );
5346 assert_eq!(
5347 map.get("returns").and_then(Value::as_str),
5348 Some("STRING|PIPE"),
5349 "returns render the set"
5350 );
5351 }
5352
5353 #[test]
5354 fn describe_entry_renders_handle_payload() {
5355 let meta = FuncMeta {
5359 name: "SCRIPT::FETCH".to_string(),
5360 module: "SCRIPT".to_string(),
5361 kind: FuncKind::Script,
5362 params: Some(vec![]),
5363 returns: Some(TypeTag::HandleOf(std::sync::Arc::new(TypeTag::String))),
5364 rpn: false,
5365 summary: "test-only",
5366 docs: "test-only",
5367 examples: &[],
5368 };
5369 let value = meta_to_value(&meta);
5370 let map = value.as_map().expect("describe value is a map");
5371 assert_eq!(
5372 map.get("returns").and_then(Value::as_str),
5373 Some("HANDLE<STRING>"),
5374 "returns render the payload"
5375 );
5376 }
5377
5378 #[test]
5379 fn describe_entry_carries_optional_flag() {
5380 let meta = FuncMeta {
5384 name: "T::F".to_string(),
5385 module: "T".to_string(),
5386 kind: FuncKind::HostPure,
5387 params: Some(vec![
5388 FuncParam {
5389 name: "url".to_string(),
5390 param_type: Some(TypeTag::String),
5391 allowed: None,
5392 docs: "",
5393 options: None,
5394 optional: false,
5395 },
5396 FuncParam {
5397 name: "options".to_string(),
5398 param_type: Some(TypeTag::Map),
5399 allowed: None,
5400 docs: "",
5401 options: None,
5402 optional: true,
5403 },
5404 ]),
5405 returns: Some(TypeTag::String),
5406 rpn: false,
5407 summary: "test-only",
5408 docs: "test-only",
5409 examples: &[],
5410 };
5411 let value = meta_to_value(&meta);
5412 let map = value.as_map().expect("describe value is a map");
5413 let params = map
5414 .get("params")
5415 .expect("params key")
5416 .as_list()
5417 .expect("params is a list");
5418 assert_eq!(params.len(), 2);
5419 let first = params[0].as_map().expect("entry is a map");
5420 let second = params[1].as_map().expect("entry is a map");
5421 assert_eq!(
5422 first.get("optional").and_then(Value::as_bool),
5423 Some(false),
5424 "required param must read false"
5425 );
5426 assert_eq!(
5427 second.get("optional").and_then(Value::as_bool),
5428 Some(true),
5429 "omittable param must read true"
5430 );
5431 }
5432
5433 #[test]
5434 fn template_twins_mirror_string_paths_and_refuse_pipes() {
5435 let pipe = Value::pipe_fresh();
5441 type TwinCase = (&'static str, Box<dyn Fn() -> Result<Value>>);
5442 let cases: Vec<TwinCase> = vec![
5443 (
5444 "TEXT_TRIM",
5445 Box::new(|| text_trim_string(Value::string(" hello ".to_string()))),
5446 ),
5447 (
5448 "TEXT_TRIM_PREFIX",
5449 Box::new(|| {
5450 text_trim_prefix_string(Value::string("v1".to_string()), "v".to_string())
5451 }),
5452 ),
5453 (
5454 "TEXT_TRIM_SUFFIX",
5455 Box::new(|| {
5456 text_trim_suffix_string(Value::string("a.gz".to_string()), "x".to_string())
5457 }),
5458 ),
5459 (
5460 "TEXT_TO_UPPER",
5461 Box::new(|| text_to_upper_string(Value::string("hi".to_string()))),
5462 ),
5463 (
5464 "TEXT_TO_LOWER",
5465 Box::new(|| text_to_lower_string(Value::string("HI".to_string()))),
5466 ),
5467 (
5468 "TEXT_REPLACE",
5469 Box::new(|| {
5470 text_replace_string(
5471 Value::string("ab".to_string()),
5472 "b".to_string(),
5473 "c".to_string(),
5474 )
5475 }),
5476 ),
5477 (
5478 "TEXT_REPLACE_REGEX",
5479 Box::new(|| {
5480 text_replace_regex_string(
5481 Value::string("ab".to_string()),
5482 "b".to_string(),
5483 "c".to_string(),
5484 )
5485 }),
5486 ),
5487 ];
5488 assert_eq!(cases.len(), 7, "every mirror op needs a twin row");
5489 for (name, run) in &cases {
5490 let value = run().unwrap_or_else(|e| panic!("{name} twin must answer strings: {e:#}"));
5491 assert!(
5492 value.as_str().is_some(),
5493 "{name} twin must answer STRING, got {}",
5494 value.type_name()
5495 );
5496 }
5497 assert_eq!(
5498 text_trim_string(Value::string(" hello ".to_string()))
5499 .expect("trim twin")
5500 .as_str(),
5501 Some("hello")
5502 );
5503 let pipe_cases: Vec<(&str, Result<Value>)> = vec![
5505 ("TEXT_TRIM", text_trim_string(pipe.clone())),
5506 (
5507 "TEXT_TRIM_PREFIX",
5508 text_trim_prefix_string(pipe.clone(), "v".to_string()),
5509 ),
5510 (
5511 "TEXT_TRIM_SUFFIX",
5512 text_trim_suffix_string(pipe.clone(), ".gz".to_string()),
5513 ),
5514 ("TEXT_TO_UPPER", text_to_upper_string(pipe.clone())),
5515 ("TEXT_TO_LOWER", text_to_lower_string(pipe.clone())),
5516 (
5517 "TEXT_REPLACE",
5518 text_replace_string(pipe.clone(), "a".to_string(), "b".to_string()),
5519 ),
5520 (
5521 "TEXT_REPLACE_REGEX",
5522 text_replace_regex_string(pipe.clone(), "a".to_string(), "b".to_string()),
5523 ),
5524 ];
5525 for (name, result) in pipe_cases {
5526 let err = result.expect_err(&format!("{name} twin must refuse PIPE"));
5527 assert!(
5528 format!("{err:#}").contains("step IO"),
5529 "{name} refusal names the missing context: {err:#}"
5530 );
5531 }
5532 }
5533
5534 #[test]
5535 fn shell_words_join_split_round_trip() {
5536 let words = vec![
5540 "gh".to_string(),
5541 "issue".to_string(),
5542 "comment".to_string(),
5543 "with spaces".to_string(),
5544 "it's".to_string(),
5545 "say \"hi\"".to_string(),
5546 "$HOME".to_string(),
5547 "$(whoami)".to_string(),
5548 "C:\\path\\to".to_string(),
5549 "naïve café".to_string(),
5550 "".to_string(),
5551 ];
5552 let joined = shell_words::join(&words);
5553 let back = shell_words::split(&joined).expect("join output must parse");
5554 assert_eq!(back, words);
5555 assert!(shell_words::split("unbalanced \"quote").is_err());
5556 }
5557}