1use std::collections::{BTreeMap, HashMap, HashSet};
2use std::sync::Arc;
3
4use anyhow::Result;
5use oxdock_fs::to_forward_slashes;
6use oxdock_fs::{GuardedPath, WorkspaceSelection};
7use oxdock_func_macro::oxdock_func;
8use oxdock_parser::value::HandleValue;
9use oxdock_parser::{
10 Field, GuardExpr, KEYWORD_INSPECT, MODULE_SEPARATOR, SCRIPT_MODULE_NAME, STD_MODULE_NAME,
11 SemaphoreState, Step, TypeTag, Value, base_name, guards_overlap, qualify, render_structural,
12 split_qualified,
13};
14use oxdock_pipe::PipeHandle;
15use oxdock_process::{CommandStdin, DefaultProcessManager, ProcessManager};
16
17use super::io::StreamHandle;
18use super::state::ExecState;
19use super::steps::StepCtx;
20use super::typing::TypeDescriptor;
21
22#[derive(Debug, Clone, Copy, PartialEq, Eq)]
28pub enum FuncKind {
29 Script,
30 HostCtx,
31 HostPure,
32}
33
34pub(super) fn file_func_key(defining_file: &str, name: &str) -> String {
38 qualify(defining_file, name)
39}
40
41pub(super) fn ambiguous_alias_message(alias: &str, name: &str, files: &HashSet<String>) -> String {
44 let mut files: Vec<&str> = files.iter().map(|file| file.as_str()).collect();
45 files.sort();
46 format!(
47 "function `{alias}::{name}` is ambiguous: alias `{alias}` is imported from multiple files ({})",
48 files.join(", ")
49 )
50}
51
52pub(super) enum AliasResolution {
58 Global,
60 Canonical(String),
62 Unknown,
64 Ambiguous {
67 alias: String,
68 base: String,
69 files: HashSet<String>,
70 },
71 Any {
78 base: String,
79 files: HashSet<String>,
80 has_host: bool,
81 },
82}
83
84pub(super) type AliasTargets = HashMap<String, Vec<(Option<String>, Option<GuardExpr>)>>;
91
92pub(super) trait FuncFrameView {
98 type Hit;
100 fn find_nested(&self, base: &str) -> Option<Self::Hit>;
102 fn find_home(&self, unit: &str, base: &str) -> Option<Self::Hit>;
104 fn find_harvest(&self, unit: &str, base: &str) -> Option<Self::Hit>;
106 fn walk(&self, unit: &str, base: &str) -> Option<Self::Hit> {
108 self.find_nested(base)
109 .or_else(|| self.find_home(unit, base))
110 .or_else(|| self.find_harvest(unit, base))
111 }
112}
113
114pub(super) fn classify_alias_call(
120 unit_targets: &AliasTargets,
121 name: &str,
122 exists: &dyn Fn(&str) -> bool,
123) -> AliasResolution {
124 let Some((alias, base)) = split_qualified(name) else {
125 return AliasResolution::Global;
126 };
127 if alias == SCRIPT_MODULE_NAME {
128 return AliasResolution::Global;
129 }
130 let Some(entries) = unit_targets.get(alias) else {
131 return AliasResolution::Global;
132 };
133 if entries.is_empty() {
134 return AliasResolution::Unknown;
135 }
136 let mut files: Vec<(&str, Vec<Option<&GuardExpr>>)> = Vec::new();
139 let mut host_guards: Vec<Option<&GuardExpr>> = Vec::new();
140 for (file, guard) in entries {
141 match file {
142 Some(path) => match files.iter_mut().find(|(known, _)| *known == path) {
143 Some((_, guards)) => guards.push(guard.as_ref()),
144 None => files.push((path, vec![guard.as_ref()])),
145 },
146 None => host_guards.push(guard.as_ref()),
147 }
148 }
149 if files.is_empty() {
150 return AliasResolution::Unknown;
151 }
152 let overlaps = |left: &[Option<&GuardExpr>], right: &[Option<&GuardExpr>]| {
153 left.iter()
154 .any(|a| right.iter().any(|b| guards_overlap(*a, *b)))
155 };
156 if files.len() == 1 {
157 let disjoint_host = host_guards
161 .iter()
162 .any(|host| !overlaps(&files[0].1, &[*host]));
163 if !disjoint_host {
164 return AliasResolution::Canonical(file_func_key(files[0].0, base));
165 }
166 let mut all = HashSet::new();
167 all.insert(files[0].0.to_string());
168 return AliasResolution::Any {
169 base: base.to_string(),
170 files: all,
171 has_host: true,
172 };
173 }
174 let mut ambiguous = HashSet::new();
175 for (i, (file, guards)) in files.iter().enumerate() {
176 for (other, other_guards) in files.iter().skip(i + 1) {
177 if overlaps(guards, other_guards)
178 && (exists(&file_func_key(file, base)) || exists(&file_func_key(other, base)))
179 {
180 ambiguous.insert((*file).to_string());
181 ambiguous.insert((*other).to_string());
182 }
183 }
184 }
185 if !ambiguous.is_empty() {
186 return AliasResolution::Ambiguous {
187 alias: alias.to_string(),
188 base: base.to_string(),
189 files: ambiguous,
190 };
191 }
192 let all: HashSet<String> = files.iter().map(|(file, _)| (*file).to_string()).collect();
193 if all.iter().any(|file| exists(&file_func_key(file, base))) {
194 return AliasResolution::Any {
195 base: base.to_string(),
196 files: all,
197 has_host: !host_guards.is_empty(),
198 };
199 }
200 AliasResolution::Unknown
201}
202
203pub(super) fn missing_import_hint<'a>(
213 files: impl IntoIterator<Item = (&'a str, &'a [String])>,
214 unit_targets: &AliasTargets,
215 name: &str,
216) -> Option<String> {
217 let base = match split_qualified(name) {
218 Some((_, base)) => base,
219 None => name,
220 };
221 if base.is_empty() {
222 return None;
223 }
224 let mut exporters: Vec<&str> = files
225 .into_iter()
226 .filter(|(_, exports)| exports.iter().any(|exported| exported == base))
227 .map(|(file, _)| file)
228 .collect();
229 exporters.sort();
230 exporters.dedup();
231 if exporters.is_empty() {
232 return None;
233 }
234 let imported_as = |file: &str| {
236 let mut aliases: Vec<&str> = unit_targets
237 .iter()
238 .filter(|(_, targets)| {
239 targets
240 .iter()
241 .any(|(target, _)| target.as_deref() == Some(file))
242 })
243 .map(|(alias, _)| alias.as_str())
244 .collect();
245 aliases.sort();
246 aliases
247 };
248 if exporters.len() == 1 {
249 let file = exporters[0];
250 let aliases = imported_as(file);
251 let import_alias = aliases
256 .iter()
257 .find(|alias| qualify(alias, base) != name)
258 .or(aliases.first())
259 .copied();
260 let suggestion = match import_alias {
261 Some(import_alias) => {
262 let spelling = qualify(import_alias, base);
263 if spelling == name {
264 format!(
267 "file \"{file}\" exports `{base}` but the `{import_alias}` view does not resolve it here"
268 )
269 } else {
270 format!("did you mean `{spelling}`? (file \"{file}\" exports `{base}`)")
271 }
272 }
273 None => {
274 let path = to_forward_slashes(file);
277 format!(
278 "file \"{file}\" exports `{base}`: add `[FUNC {base} FROM \"{path}\"]` to an IMPORT"
279 )
280 }
281 };
282 return Some(format!("; {suggestion}"));
283 }
284 let mut files = exporters.join("\", \"");
285 files.insert(0, '"');
286 files.push('"');
287 Some(format!(
288 "; files {files} export `{base}`: qualify the call with the importing alias"
289 ))
290}
291
292pub(super) fn const_export_covers(entry: &str, name: &str) -> bool {
297 base_name(entry) == name
298}
299
300pub(super) enum BindingPresence {
303 Const,
304 Let,
305 Absent,
306}
307
308pub(super) fn missing_const_hint<S: ModuleGraphView>(
315 view: &S,
316 targets: &AliasTargets,
317 alias: &str,
318 name: &str,
319) -> Option<String> {
320 targets
321 .get(alias)
322 .map(|entries| {
323 entries
324 .iter()
325 .filter_map(|(file, _)| file.as_ref())
326 .collect::<Vec<_>>()
327 })
328 .unwrap_or_default()
329 .iter()
330 .find_map(|file| match view.binding(file, name) {
331 BindingPresence::Const => Some(format!(
332 "module holds `{name}` as CONST but does not export it: add `EXPORT CONST ${name}`"
333 )),
334 BindingPresence::Let => Some(format!(
335 "`{name}` is a LET binding and cannot be exported: only CONST bindings cross the module boundary"
336 )),
337 BindingPresence::Absent => None,
338 })
339}
340
341pub(super) trait ModuleGraphView {
348 fn const_exports(&self, file: &str) -> Option<&[String]>;
350 fn alias_targets(&self, file: &str) -> AliasTargets;
353 fn binding(&self, file: &str, name: &str) -> BindingPresence;
355}
356
357#[derive(Debug)]
363pub(super) enum ConstHolders {
364 Found(Vec<String>),
367 NoAlias,
369 Ambiguous {
371 alias: String,
372 base: String,
373 files: HashSet<String>,
374 },
375}
376
377fn const_canonical_suffix(name: &str) -> String {
382 format!("{MODULE_SEPARATOR}{name}")
383}
384
385pub(super) fn const_holder_files<S: ModuleGraphView>(
387 view: &S,
388 unit_targets: &AliasTargets,
389 alias: &str,
390 name: &str,
391) -> ConstHolders {
392 let qualified = qualify(alias, name);
393 let suffix = const_canonical_suffix(name);
394 let exports = |canonical: &str| {
398 canonical
399 .strip_suffix(suffix.as_str())
400 .and_then(|file| view.const_exports(file))
401 .is_some_and(|names| names.iter().any(|entry| const_export_covers(entry, name)))
402 };
403 let mut holders = match classify_alias_call(unit_targets, &qualified, &exports) {
404 AliasResolution::Global | AliasResolution::Unknown => return ConstHolders::NoAlias,
405 AliasResolution::Ambiguous { alias, base, files } => {
406 return ConstHolders::Ambiguous { alias, base, files };
407 }
408 AliasResolution::Canonical(canonical) => {
409 let Some(file) = canonical.strip_suffix(suffix.as_str()) else {
410 return ConstHolders::NoAlias;
411 };
412 vec![file.to_string()]
413 }
414 AliasResolution::Any { mut files, .. } => {
415 let mut files: Vec<String> = files.drain().collect();
416 files.sort();
417 files
418 }
419 };
420 holders.retain(|file| {
421 view.const_exports(file)
422 .is_some_and(|names| names.iter().any(|entry| const_export_covers(entry, name)))
423 });
424 ConstHolders::Found(holders)
425}
426
427#[derive(Debug)]
432pub(super) enum ForwardError {
433 Unknown { original: String },
435 Broken {
437 original: String,
438 hop: String,
439 detail: BrokenDetail,
440 },
441 Split { original: String, hops: Vec<String> },
443 Cycle { chain: Vec<String> },
446 HopAmbiguous {
448 alias: String,
449 base: String,
450 files: HashSet<String>,
451 },
452}
453
454#[derive(Debug)]
456pub(super) enum BrokenDetail {
457 UnexportedConst,
459 Let,
461 Absent,
463}
464
465impl std::fmt::Display for ForwardError {
466 fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
467 match self {
468 ForwardError::Unknown { original } => write!(f, "unknown CONST `{original}`"),
469 ForwardError::Broken {
470 original,
471 hop,
472 detail,
473 } => {
474 let base = base_name(hop);
475 let detail = match detail {
476 BrokenDetail::UnexportedConst => format!(
477 "module holds `{base}` as CONST but does not export it: add `EXPORT CONST ${base}`"
478 ),
479 BrokenDetail::Let => format!(
480 "`{base}` is a LET binding and cannot be exported: only CONST bindings cross the module boundary"
481 ),
482 BrokenDetail::Absent => {
483 let (forward, _) = split_qualified(hop).unwrap_or(("", base));
484 format!("no import alias `{forward}` exports `{base}`")
485 }
486 };
487 write!(
488 f,
489 "unknown CONST `{original}`: re-export `{hop}` does not resolve: {detail}"
490 )
491 }
492 ForwardError::Split { original, hops } => write!(
493 f,
494 "ambiguous CONST `{original}`: re-exported from {}; export exactly one source",
495 hops.join(" and ")
496 ),
497 ForwardError::Cycle { chain } => {
498 write!(f, "CONST re-export cycle detected: {}", chain.join(" -> "))
499 }
500 ForwardError::HopAmbiguous { alias, base, files } => write!(
501 f,
502 "{}",
503 ambiguous_alias_message(alias, base, files).replacen("function", "CONST", 1)
504 ),
505 }
506 }
507}
508
509impl std::error::Error for ForwardError {}
510
511pub(super) fn chase_const_forward<S: ModuleGraphView>(
518 view: &S,
519 file: &str,
520 name: &str,
521 original: &str,
522) -> Result<Vec<String>, ForwardError> {
523 let mut terminals: Vec<String> = Vec::new();
524 chase_from(view, file, name, original, &mut Vec::new(), &mut terminals)?;
525 terminals.sort();
526 terminals.dedup();
527 Ok(terminals)
528}
529
530fn chase_from<S: ModuleGraphView>(
531 view: &S,
532 current: &str,
533 name: &str,
534 original: &str,
535 chain: &mut Vec<String>,
536 terminals: &mut Vec<String>,
537) -> Result<(), ForwardError> {
538 let suffix = const_canonical_suffix(name);
539 let covering = |canonical: &str| {
540 canonical
541 .strip_suffix(suffix.as_str())
542 .and_then(|file| view.const_exports(file))
543 .is_some_and(|names| names.iter().any(|entry| const_export_covers(entry, name)))
544 };
545 let mut current = current.to_string();
546 loop {
547 let Some(names) = view.const_exports(current.as_str()) else {
548 return Err(ForwardError::Unknown {
549 original: original.to_string(),
550 });
551 };
552 if names.iter().any(|entry| entry == name) {
553 terminals.push(current);
554 return Ok(());
555 }
556 let mut aliases: Vec<&str> = Vec::new();
557 for entry in names {
558 if let Some((alias, base)) = split_qualified(entry)
559 && base == name
560 && !aliases.contains(&alias)
561 {
562 aliases.push(alias);
563 }
564 }
565 if aliases.is_empty() {
566 if chain.is_empty() {
567 return Err(ForwardError::Unknown {
568 original: original.to_string(),
569 });
570 }
571 let hop = chain.last().expect("chain never empty").clone();
572 let detail = match view.binding(current.as_str(), name) {
573 BindingPresence::Const => BrokenDetail::UnexportedConst,
574 BindingPresence::Let => BrokenDetail::Let,
575 BindingPresence::Absent => BrokenDetail::Absent,
576 };
577 return Err(ForwardError::Broken {
578 original: original.to_string(),
579 hop,
580 detail,
581 });
582 }
583 if aliases.len() > 1 {
584 let mut hops: Vec<String> = aliases.iter().map(|alias| qualify(alias, name)).collect();
585 hops.sort();
586 return Err(ForwardError::Split {
587 original: original.to_string(),
588 hops,
589 });
590 }
591 let forward = aliases[0];
592 let hop = qualify(forward, name);
593 if chain.contains(&hop) {
594 chain.push(hop);
595 return Err(ForwardError::Cycle {
596 chain: chain.clone(),
597 });
598 }
599 chain.push(hop.clone());
600 let targets = view.alias_targets(current.as_str());
601 match classify_alias_call(&targets, &hop, &covering) {
602 AliasResolution::Global | AliasResolution::Unknown => {
603 return Err(ForwardError::Broken {
604 original: original.to_string(),
605 hop,
606 detail: BrokenDetail::Absent,
607 });
608 }
609 AliasResolution::Ambiguous { alias, base, files } => {
610 return Err(ForwardError::HopAmbiguous { alias, base, files });
611 }
612 AliasResolution::Canonical(canonical) => {
613 let Some(next) = canonical.strip_suffix(suffix.as_str()) else {
614 return Err(ForwardError::Unknown {
615 original: original.to_string(),
616 });
617 };
618 current = next.to_string();
619 }
620 AliasResolution::Any { mut files, .. } => {
621 let mut covering: Vec<String> = files
622 .drain()
623 .filter(|file| {
624 view.const_exports(file).is_some_and(|names| {
625 names.iter().any(|entry| const_export_covers(entry, name))
626 })
627 })
628 .collect();
629 covering.sort();
630 match covering.len() {
631 0 => {
632 return Err(ForwardError::Broken {
633 original: original.to_string(),
634 hop,
635 detail: BrokenDetail::Absent,
636 });
637 }
638 1 => {
639 current = covering.into_iter().next().expect("len checked");
640 }
641 _ => {
642 for branch in covering {
643 let mut branch_chain = chain.clone();
644 chase_from(
645 view,
646 branch.as_str(),
647 name,
648 original,
649 &mut branch_chain,
650 terminals,
651 )?;
652 }
653 return Ok(());
654 }
655 }
656 }
657 }
658 }
659}
660pub(super) fn disjoint_template_script_visible(
668 base: &str,
669 files: &HashSet<String>,
670 has_host: bool,
671 exists: &dyn Fn(&str) -> bool,
672) -> bool {
673 !has_host && !files.is_empty() && files.iter().all(|file| exists(&file_func_key(file, base)))
674}
675
676pub(super) fn disjoint_alias_placeholder_miss(
683 module: &str,
684 name: &str,
685 base: &str,
686 files: &HashSet<String>,
687 has_host: bool,
688 is_script: &dyn Fn(&str) -> bool,
689) -> String {
690 let script = disjoint_template_script_visible(base, files, has_host, is_script);
691 describe_placeholder_miss(module, name, script, false, !script)
692 .expect("disjoint miss always renders")
693}
694
695pub(super) fn spellings_for_defining_file(
702 unit_targets: &AliasTargets,
703 defining: &str,
704 base: &str,
705 is_script: &dyn Fn(&str) -> bool,
706) -> (Vec<String>, Vec<(String, HashSet<String>)>) {
707 let mut direct = Vec::new();
708 let mut ambiguous = Vec::new();
709 for (alias, files) in unit_targets {
710 if !files
711 .iter()
712 .any(|(file, _)| file.as_deref() == Some(defining))
713 {
714 continue;
715 }
716 let spelling = qualify(alias, base);
717 match classify_alias_call(unit_targets, &spelling, &|key| {
718 key == file_func_key(defining, base)
719 }) {
720 AliasResolution::Canonical(_) => direct.push(spelling),
721 AliasResolution::Ambiguous { files, .. } => {
722 ambiguous.push((spelling, files));
723 }
724 AliasResolution::Any {
725 base,
726 files,
727 has_host,
728 } => {
729 if disjoint_template_script_visible(&base, &files, has_host, is_script) {
730 direct.push(spelling);
731 }
732 }
733 AliasResolution::Global | AliasResolution::Unknown => {}
734 }
735 }
736 (direct, ambiguous)
737}
738
739impl FuncKind {
740 pub fn label(&self) -> &'static str {
741 match self {
742 FuncKind::Script => "script",
743 FuncKind::HostCtx | FuncKind::HostPure => "host",
744 }
745 }
746}
747
748#[derive(Debug, Clone)]
766pub struct FuncParam {
767 pub name: String,
768 pub param_type: Option<TypeTag>,
769 pub allowed: Option<&'static [&'static str]>,
770 pub docs: &'static str,
771 pub options: Option<&'static [ParamOption]>,
772 pub optional: bool,
773}
774
775pub fn required_arity(params: &[FuncParam]) -> usize {
780 params
781 .iter()
782 .rev()
783 .take_while(|param| param.optional)
784 .fold(params.len(), |count, _| count - 1)
785}
786
787pub fn fill_optional_args(params: &[FuncParam], mut values: Vec<Value>) -> Vec<Value> {
792 assert!(
793 values.len() <= params.len(),
794 "arity gate must run before fill_optional_args"
795 );
796 assert!(
797 values.len() >= required_arity(params),
798 "arity gate must run before fill_optional_args"
799 );
800 while values.len() < params.len() {
801 values.push(Value::map(BTreeMap::new()));
802 }
803 values
804}
805
806#[derive(Debug, Clone)]
813pub struct ParamOption {
814 pub name: &'static str,
815 pub value: TypeTag,
816 pub required: bool,
817 pub default: Option<&'static str>,
818}
819
820#[derive(Debug, Clone)]
826pub struct FuncMeta {
827 pub name: String,
828 pub module: String,
832 pub kind: FuncKind,
833 pub params: Option<Vec<FuncParam>>,
834 pub returns: Option<TypeTag>,
835 pub rpn: bool,
836 pub summary: &'static str,
837 pub docs: &'static str,
838 pub examples: &'static [crate::Example],
844}
845
846pub type PureFn = Arc<dyn Fn(Vec<Value>) -> Result<Value> + Send + Sync>;
849
850pub type NativeFn<P> = Arc<dyn Fn(&mut StepCtx<P>, Vec<Value>) -> Result<Value> + Send + Sync>;
852
853pub trait OxDockFn<P: ProcessManager> {
857 fn registration() -> HostRegistration<P>;
860}
861
862pub enum HostRegistration<P: ProcessManager> {
871 Stateful {
872 name: String,
873 meta: FuncMeta,
874 func: NativeFn<P>,
875 },
876 Pure {
877 name: String,
878 meta: FuncMeta,
879 func: PureFn,
880 },
881 Both {
882 name: String,
883 meta: FuncMeta,
884 func: NativeFn<P>,
885 template: PureFn,
886 },
887}
888
889impl<P: ProcessManager> Clone for HostRegistration<P> {
892 fn clone(&self) -> Self {
893 match self {
894 HostRegistration::Stateful { name, meta, func } => HostRegistration::Stateful {
895 name: name.clone(),
896 meta: meta.clone(),
897 func: Arc::clone(func),
898 },
899 HostRegistration::Pure { name, meta, func } => HostRegistration::Pure {
900 name: name.clone(),
901 meta: meta.clone(),
902 func: Arc::clone(func),
903 },
904 HostRegistration::Both {
905 name,
906 meta,
907 func,
908 template,
909 } => HostRegistration::Both {
910 name: name.clone(),
911 meta: meta.clone(),
912 func: Arc::clone(func),
913 template: Arc::clone(template),
914 },
915 }
916 }
917}
918
919impl<P: ProcessManager> HostRegistration<P> {
920 pub fn meta(&self) -> &FuncMeta {
923 match self {
924 HostRegistration::Stateful { meta, .. } => meta,
925 HostRegistration::Pure { meta, .. } => meta,
926 HostRegistration::Both { meta, .. } => meta,
927 }
928 }
929}
930
931#[derive(Debug, Clone)]
937pub(super) struct FuncDefData {
938 pub(super) params: Vec<(String, TypeTag, bool)>,
939 pub(super) return_type: TypeTag,
940 pub(super) return_spelling: String,
941 pub(super) is_async: bool,
942 pub(super) body: Vec<Step>,
943 pub(super) module: Option<String>,
948 pub(super) def_jail: Option<(WorkspaceSelection, GuardedPath)>,
954}
955
956pub fn optional_zero_value(tag: &TypeTag) -> Result<Value> {
964 match tag {
965 TypeTag::Bool => Ok(Value::bool(false)),
966 TypeTag::String | TypeTag::Any => Ok(Value::string(String::new())),
967 TypeTag::Int => Ok(Value::int(0)),
968 TypeTag::Float => Ok(Value::float(0.0)),
969 TypeTag::List | TypeTag::ListOf(_) => Ok(Value::list(Vec::new())),
970 TypeTag::Map | TypeTag::MapOf(_) => Ok(Value::map(BTreeMap::new())),
971 TypeTag::Record(fields)
972 if fields
973 .iter()
974 .all(|field| field.optional || field.default.is_some()) =>
975 {
976 Ok(Value::map(BTreeMap::new()))
977 }
978 other => anyhow::bail!(
979 "no zero value for {}; omit the `?` or pass the argument explicitly",
980 oxdock_parser::render_structural(other)
981 ),
982 }
983}
984
985pub fn resolve_script_params<P: ProcessManager>(
991 state: &ExecState<P>,
992 func_name: &str,
993 params: &[(String, String, bool)],
994) -> Result<Vec<(String, TypeTag, bool)>> {
995 let mut resolved = Vec::with_capacity(params.len());
996 for (pname, ptype, optional) in params {
997 let clean = pname.trim_start_matches('$').to_string();
998 let tag = state
999 .resolve_tag(ptype)
1000 .map_err(|err| anyhow::anyhow!("function `{func_name}`: {err:#}"))?;
1001 state.check_declaration_tag(&format!("function `{func_name}` param `${clean}`"), &tag)?;
1002 if *optional {
1003 optional_zero_value(&tag).map(|_| ()).map_err(|err| {
1004 anyhow::anyhow!("function `{func_name}` optional param `${clean}`: {err:#}")
1005 })?;
1006 }
1007 resolved.push((clean, tag, *optional));
1008 }
1009 Ok(resolved)
1010}
1011
1012pub fn check_script_param_tags(func_name: &str, params: &[(String, TypeTag, bool)]) -> Result<()> {
1015 for (pname, tag, optional) in params {
1016 if *optional {
1017 optional_zero_value(tag).map(|_| ()).map_err(|err| {
1018 anyhow::anyhow!("function `{func_name}` optional param `${pname}`: {err:#}")
1019 })?;
1020 }
1021 }
1022 Ok(())
1023}
1024
1025pub(super) enum FuncBody<P: ProcessManager> {
1030 Script(FuncDefData),
1031 Pure(PureFn),
1032 Ctx(NativeFn<P>),
1033 Both { pure: PureFn, ctx: NativeFn<P> },
1034}
1035
1036impl<P: ProcessManager> Clone for FuncBody<P> {
1038 fn clone(&self) -> Self {
1039 match self {
1040 FuncBody::Script(def) => FuncBody::Script(def.clone()),
1041 FuncBody::Pure(func) => FuncBody::Pure(Arc::clone(func)),
1042 FuncBody::Ctx(func) => FuncBody::Ctx(Arc::clone(func)),
1043 FuncBody::Both { pure, ctx } => FuncBody::Both {
1044 pure: Arc::clone(pure),
1045 ctx: Arc::clone(ctx),
1046 },
1047 }
1048 }
1049}
1050
1051pub(super) struct FuncEntry<P: ProcessManager> {
1055 pub(super) meta: FuncMeta,
1056 pub(super) body: FuncBody<P>,
1057}
1058
1059impl<P: ProcessManager> Clone for FuncEntry<P> {
1061 fn clone(&self) -> Self {
1062 Self {
1063 meta: self.meta.clone(),
1064 body: self.body.clone(),
1065 }
1066 }
1067}
1068
1069struct ScopeFrame<P: ProcessManager> {
1072 defined: HashSet<String>,
1073 shadowed: Vec<(String, FuncEntry<P>)>,
1074}
1075
1076impl<P: ProcessManager> Clone for ScopeFrame<P> {
1078 fn clone(&self) -> Self {
1079 Self {
1080 defined: self.defined.clone(),
1081 shadowed: self.shadowed.clone(),
1082 }
1083 }
1084}
1085
1086pub type PureTable = HashMap<String, HashMap<String, PureFn>>;
1096
1097pub fn placeholder_resolver(table: Arc<PureTable>) -> oxdock_process::PlaceholderCall {
1106 Arc::new(move |module, func, args| {
1107 let callee = table
1108 .get(module)
1109 .and_then(|entries| entries.get(func))
1110 .ok_or_else(|| {
1111 let mut known: Vec<String> = table
1112 .iter()
1113 .flat_map(|(m, entries)| entries.keys().map(move |f| format!("{m}::{f}")))
1114 .collect();
1115 known.sort();
1116 anyhow::anyhow!(
1117 "unknown placeholder function '{module}::{func}'; known functions: {}",
1118 known.join(", ")
1119 )
1120 })?;
1121 callee(args)
1122 })
1123}
1124
1125pub(super) fn describe_placeholder_miss(
1132 module: &str,
1133 name: &str,
1134 is_script: bool,
1135 is_stateful: bool,
1136 alias_known: bool,
1137) -> Option<String> {
1138 let qualified = qualify(module, name);
1139 if is_script {
1140 let call = if module == SCRIPT_MODULE_NAME {
1141 format!("{name}(...)")
1142 } else {
1143 format!("{qualified}(...)")
1144 };
1145 return Some(format!(
1146 "placeholder function '{qualified}' is a script function and cannot run in {{{{ }}}}; bind the result first with LET $v = {call} then interpolate {{{{ $v }}}}"
1147 ));
1148 }
1149 if is_stateful {
1150 return Some(format!(
1151 "placeholder function '{qualified}' is stateful and cannot run in {{{{ }}}}; capture it first with LET then interpolate {{{{ $v }}}}"
1152 ));
1153 }
1154 if alias_known {
1155 return Some(format!(
1156 "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 }}}}"
1157 ));
1158 }
1159 None
1160}
1161
1162pub(super) struct PlaceholderClasses {
1165 pub script: HashSet<String>,
1166 pub stateful: HashSet<String>,
1167 pub aliases: HashSet<String>,
1168 pub ambiguous: HashMap<String, HashSet<String>>,
1170}
1171
1172impl PlaceholderClasses {
1173 pub(super) fn describe(&self, module: &str, name: &str) -> Option<String> {
1174 let qualified = qualify(module, name);
1175 if let Some(files) = self.ambiguous.get(&qualified) {
1176 return Some(ambiguous_alias_message(module, name, files));
1177 }
1178 describe_placeholder_miss(
1179 module,
1180 name,
1181 self.script.contains(&qualified),
1182 self.stateful.contains(&qualified),
1183 self.aliases.contains(module),
1184 )
1185 }
1186}
1187
1188pub struct FunctionRegistry<P: ProcessManager> {
1189 entries: HashMap<String, FuncEntry<P>>,
1190 scopes: Vec<ScopeFrame<P>>,
1191 pure_shared: Arc<PureTable>,
1192 script_docs: HashMap<String, (String, String)>,
1196}
1197
1198impl<P: ProcessManager> FunctionRegistry<P> {
1199 pub(super) fn with_builtins() -> Self {
1200 let mut reg = Self {
1201 entries: HashMap::new(),
1202 pure_shared: Arc::new(HashMap::new()),
1203 script_docs: HashMap::new(),
1204 scopes: vec![ScopeFrame {
1205 defined: HashSet::new(),
1206 shadowed: Vec::new(),
1207 }],
1208 };
1209 for host in Self::builtin_registrations() {
1213 match host {
1214 HostRegistration::Stateful { name, meta, func } => {
1215 reg.insert_qualified(STD_MODULE_NAME, name, meta, FuncBody::Ctx(func));
1216 }
1217 HostRegistration::Pure { name, meta, func } => {
1218 reg.insert_qualified(STD_MODULE_NAME, name, meta, FuncBody::Pure(func));
1219 }
1220 HostRegistration::Both {
1221 name,
1222 meta,
1223 func,
1224 template,
1225 } => {
1226 reg.insert_qualified(
1227 STD_MODULE_NAME,
1228 name,
1229 meta,
1230 FuncBody::Both {
1231 pure: template,
1232 ctx: func,
1233 },
1234 );
1235 }
1236 }
1237 }
1238 reg
1239 }
1240
1241 pub(super) fn builtin_registrations() -> Vec<HostRegistration<P>> {
1246 vec![
1247 Int::registration(),
1248 Float::registration(),
1249 BoolConvert::registration(),
1250 BoolOr::registration(),
1251 FormatByteCount::registration(),
1252 ParseByteCount::registration(),
1253 FormatDuration::registration(),
1254 ParseDuration::registration(),
1255 Types::registration(),
1256 TypeDescribe::registration(),
1257 Glob::registration(),
1258 LoadToml::registration(),
1259 LoadJson::registration(),
1260 HashSha256::registration(),
1261 Cwd::registration(),
1262 ParseToml::registration(),
1263 ParseJson::registration(),
1264 PathType::registration(),
1265 PathWritable::registration(),
1266 IsExec::registration(),
1267 IsFile::registration(),
1268 IsDir::registration(),
1269 Exists::registration(),
1270 HasKey::registration(),
1271 Get::registration(),
1272 MapSet::registration(),
1273 MergeMaps::registration(),
1274 Base64Encode::registration(),
1275 Base64Decode::registration(),
1276 Rand::registration(),
1277 ToJson::registration(),
1278 TypeOf::registration(),
1279 Functions::registration(),
1280 Describe::registration(),
1281 IsMain::registration(),
1282 IsTerminal::registration(),
1283 Eof::registration(),
1284 TaskPoll::registration(),
1285 Version::registration(),
1286 Interpreter::registration(),
1287 Argv::registration(),
1288 ParseArgs::registration(),
1289 ParseFlags::registration(),
1290 ParsePositionals::registration(),
1291 TextTrim::registration(),
1292 TextTrimPrefix::registration(),
1293 TextTrimSuffix::registration(),
1294 PathJoin::registration(),
1295 PathBase::registration(),
1296 PathRel::registration(),
1297 TextToUpper::registration(),
1298 TextToLower::registration(),
1299 TextReplace::registration(),
1300 TextReplaceRegex::registration(),
1301 TextSplit::registration(),
1302 TextJoin::registration(),
1303 TextLines::registration(),
1304 TextFields::registration(),
1305 TextMatch::registration(),
1306 TextExtract::registration(),
1307 TextStartsWith::registration(),
1308 TextEndsWith::registration(),
1309 Contains::registration(),
1310 Unique::registration(),
1311 Len::registration(),
1312 TextCount::registration(),
1313 TextCountMatches::registration(),
1314 TextGrep::registration(),
1315 TextLinesRange::registration(),
1316 SemaphoreNew::registration(),
1317 SemaphoreTryAcquire::registration(),
1318 SemaphoreAvailable::registration(),
1319 ShellSplitArgs::registration(),
1320 ShellJoinArgs::registration(),
1321 ]
1322 }
1323
1324 pub(super) fn keys(&self) -> HashSet<String> {
1327 self.entries.keys().cloned().collect()
1328 }
1329
1330 pub(super) fn get(&self, name: &str) -> Option<FuncEntry<P>> {
1332 self.entries.get(name).cloned()
1333 }
1334
1335 pub(super) fn scope_depth(&self) -> usize {
1339 self.scopes.len()
1340 }
1341
1342 pub(super) fn get_scoped(&self, base: &str, floor: usize) -> Option<FuncEntry<P>> {
1351 let qualified = qualify(SCRIPT_MODULE_NAME, base);
1352 let len = self.scopes.len();
1353 let start = floor.min(len);
1354 for frame in self.scopes[start..].iter().rev() {
1355 if frame.defined.contains(&qualified) {
1356 return self.entries.get(&qualified).cloned();
1357 }
1358 }
1359 None
1360 }
1361
1362 pub(super) fn describe_unit_placeholder_miss(
1368 &self,
1369 unit_targets: &AliasTargets,
1370 module: &str,
1371 name: &str,
1372 ) -> Option<String> {
1373 let qualified = qualify(module, name);
1374 match classify_alias_call(unit_targets, &qualified, &|key| {
1379 self.entries.contains_key(key)
1380 }) {
1381 AliasResolution::Canonical(canonical) => {
1382 if let Some(entry) = self.entries.get(&canonical) {
1383 if let Some(miss) = Self::placeholder_miss_for_body(module, name, &entry.body) {
1384 return Some(miss);
1385 }
1386 None
1387 } else {
1388 describe_placeholder_miss(module, name, false, false, true)
1389 }
1390 }
1391 AliasResolution::Global => {
1392 if let Some(entry) = self.entries.get(&qualified) {
1393 if let Some(miss) = Self::placeholder_miss_for_body(module, name, &entry.body) {
1397 return Some(miss);
1398 }
1399 }
1400 None
1401 }
1402 AliasResolution::Ambiguous { files, .. } => {
1403 Some(ambiguous_alias_message(module, name, &files))
1404 }
1405 AliasResolution::Unknown => describe_placeholder_miss(module, name, false, false, true),
1406 AliasResolution::Any {
1412 base,
1413 files,
1414 has_host,
1415 } => Some(disjoint_alias_placeholder_miss(
1416 module,
1417 name,
1418 &base,
1419 &files,
1420 has_host,
1421 &|key| matches!(self.entries.get(key), Some(entry) if matches!(entry.body, FuncBody::Script(_))),
1422 )),
1423 }
1424 }
1425
1426 fn placeholder_miss_for_body(module: &str, name: &str, body: &FuncBody<P>) -> Option<String> {
1430 match body {
1431 FuncBody::Script(_) => describe_placeholder_miss(module, name, true, false, false),
1432 FuncBody::Ctx(_) => describe_placeholder_miss(module, name, false, true, false),
1433 FuncBody::Pure(_) | FuncBody::Both { .. } => None,
1434 }
1435 }
1436
1437 pub(super) fn placeholder_snapshot(&self, unit_targets: &AliasTargets) -> PlaceholderClasses {
1441 let mut script = HashSet::new();
1442 let mut stateful = HashSet::new();
1443 let mut ambiguous: HashMap<String, HashSet<String>> = HashMap::new();
1444 for (key, entry) in self.entries.iter() {
1445 let Some((module, base)) = split_qualified(key) else {
1446 continue;
1447 };
1448 match &entry.body {
1449 FuncBody::Script(def) => {
1450 if module == SCRIPT_MODULE_NAME {
1451 script.insert(key.clone());
1453 continue;
1454 }
1455 let defining = def.module.as_deref().unwrap_or(module);
1463 let (direct, ambiguous_here) = spellings_for_defining_file(
1464 unit_targets,
1465 defining,
1466 base,
1467 &|key| matches!(self.entries.get(key), Some(entry) if matches!(entry.body, FuncBody::Script(_))),
1468 );
1469 script.extend(direct);
1470 for (spelling, files) in ambiguous_here {
1471 ambiguous.entry(spelling).or_default().extend(files);
1472 }
1473 }
1474 FuncBody::Ctx(_) => {
1475 stateful.insert(key.clone());
1476 }
1477 FuncBody::Pure(_) | FuncBody::Both { .. } => {}
1478 }
1479 }
1480 let aliases = unit_targets.keys().cloned().collect();
1481 PlaceholderClasses {
1482 script,
1483 stateful,
1484 aliases,
1485 ambiguous,
1486 }
1487 }
1488
1489 fn insert_native(&mut self, name: String, meta: FuncMeta, body: FuncBody<P>) {
1490 self.entries.insert(name, FuncEntry { meta, body });
1491 self.rebuild_pure_shared();
1492 }
1493
1494 fn rebuild_pure_shared(&mut self) {
1500 let mut table: PureTable = HashMap::new();
1501 for (name, entry) in &self.entries {
1502 let func = match &entry.body {
1503 FuncBody::Pure(func) => func,
1504 FuncBody::Both { pure, .. } => pure,
1505 FuncBody::Script(_) | FuncBody::Ctx(_) => continue,
1506 };
1507 if let Some((module, base)) = split_qualified(name) {
1508 table
1509 .entry(module.to_string())
1510 .or_default()
1511 .insert(base.to_string(), Arc::clone(func));
1512 }
1513 }
1514 self.pure_shared = Arc::new(table);
1515 }
1516
1517 fn insert_qualified(
1521 &mut self,
1522 module: &str,
1523 base: String,
1524 mut meta: FuncMeta,
1525 body: FuncBody<P>,
1526 ) {
1527 meta.name = qualify(module, &base);
1528 meta.module = module.to_string();
1529 if self.entries.contains_key(&meta.name) {
1534 panic!("duplicate function registration `{}`", meta.name);
1535 }
1536 self.insert_native(meta.name.clone(), meta, body);
1537 }
1538
1539 pub(super) fn register_host(
1540 &mut self,
1541 module: &str,
1542 name: String,
1543 mut meta: FuncMeta,
1544 func: NativeFn<P>,
1545 ) {
1546 meta.kind = FuncKind::HostCtx;
1547 self.insert_qualified(module, name, meta, FuncBody::Ctx(func));
1548 }
1549
1550 pub(super) fn register_pure_host(
1551 &mut self,
1552 module: &str,
1553 name: String,
1554 mut meta: FuncMeta,
1555 func: PureFn,
1556 ) {
1557 meta.kind = FuncKind::HostPure;
1558 self.insert_qualified(module, name, meta, FuncBody::Pure(func));
1559 }
1560
1561 pub(super) fn register_both_host(
1562 &mut self,
1563 module: &str,
1564 name: String,
1565 mut meta: FuncMeta,
1566 func: NativeFn<P>,
1567 template: PureFn,
1568 ) {
1569 meta.kind = FuncKind::HostCtx;
1570 self.insert_qualified(
1571 module,
1572 name,
1573 meta,
1574 FuncBody::Both {
1575 pure: template,
1576 ctx: func,
1577 },
1578 );
1579 }
1580
1581 #[allow(clippy::too_many_arguments)]
1586 pub(super) fn define_script(
1587 &mut self,
1588 name: &str,
1589 params: &[(String, TypeTag, bool)],
1590 return_type: TypeTag,
1591 return_spelling: &str,
1592 is_async: bool,
1593 body: &[Step],
1594 module: Option<&str>,
1595 def_jail: Option<(WorkspaceSelection, GuardedPath)>,
1596 ) -> Result<()> {
1597 let qualified = qualify(SCRIPT_MODULE_NAME, name);
1598 let shadowable = matches!(
1599 self.entries.get(&qualified).map(|entry| &entry.body),
1600 Some(FuncBody::Script(_))
1601 );
1602 let reserved = self.entries.iter().any(|(key, entry)| {
1607 split_qualified(key).is_some_and(|(_, base)| base == name)
1608 && !matches!(entry.body, FuncBody::Script(_))
1609 });
1610 if reserved && !shadowable {
1611 anyhow::bail!("cannot shadow reserved function `{name}`");
1612 }
1613 if self
1614 .scopes
1615 .last()
1616 .is_some_and(|frame| frame.defined.contains(&qualified))
1617 {
1618 anyhow::bail!("duplicate function `{name}` in same scope");
1619 }
1620 check_script_param_tags(name, params)?;
1621 let old = self.entries.insert(
1622 qualified.clone(),
1623 FuncEntry {
1624 meta: FuncMeta {
1625 name: qualified.clone(),
1626 module: SCRIPT_MODULE_NAME.to_string(),
1627 kind: FuncKind::Script,
1628 params: Some(
1629 params
1630 .iter()
1631 .map(|(pname, param_type, optional)| {
1632 Ok(FuncParam {
1633 name: pname.clone(),
1634 param_type: Some(param_type.clone()),
1635 allowed: None,
1636 docs: "",
1639 options: None,
1640 optional: *optional,
1641 })
1642 })
1643 .collect::<Result<_>>()?,
1644 ),
1645 returns: Some(return_type.clone()),
1646 rpn: false,
1647 summary: "DSL-defined function.",
1648 docs: "Defined via FUNC in script.",
1649 examples: &[],
1650 },
1651 body: FuncBody::Script(FuncDefData {
1652 params: params.to_vec(),
1653 return_type,
1654 return_spelling: return_spelling.to_string(),
1655 is_async,
1656 body: body.to_vec(),
1657 module: module.map(|m| m.to_string()),
1658 def_jail,
1659 }),
1660 },
1661 );
1662 if let Some(frame) = self.scopes.last_mut() {
1663 frame.defined.insert(qualified.clone());
1664 if let Some(old) = old {
1665 frame.shadowed.push((qualified, old));
1666 }
1667 }
1668 Ok(())
1669 }
1670
1671 #[allow(clippy::too_many_arguments)]
1677 pub(super) fn define_file_func(
1678 &mut self,
1679 name: &str,
1680 params: &[(String, TypeTag, bool)],
1681 return_type: TypeTag,
1682 return_spelling: &str,
1683 is_async: bool,
1684 body: &[Step],
1685 defining: &str,
1686 ) -> Result<()> {
1687 let qualified = file_func_key(defining, name);
1691 let shadowable = matches!(
1692 self.entries.get(&qualified).map(|entry| &entry.body),
1693 Some(FuncBody::Script(_))
1694 );
1695 let reserved = self.entries.iter().any(|(key, entry)| {
1699 split_qualified(key).is_some_and(|(_, base)| base == name)
1700 && !matches!(entry.body, FuncBody::Script(_))
1701 });
1702 if reserved && !shadowable {
1703 anyhow::bail!("cannot shadow reserved function `{name}`");
1704 }
1705 let frame_idx = 0;
1709 if self
1710 .scopes
1711 .get(frame_idx)
1712 .is_some_and(|frame| frame.defined.contains(&qualified))
1713 {
1714 anyhow::bail!("duplicate function `{name}` in same scope");
1715 }
1716 check_script_param_tags(name, params)?;
1717 let old = self.entries.insert(
1718 qualified.clone(),
1719 FuncEntry {
1720 meta: FuncMeta {
1721 name: qualified.clone(),
1722 module: defining.to_string(),
1723 kind: FuncKind::Script,
1724 params: Some(
1725 params
1726 .iter()
1727 .map(|(pname, param_type, optional)| {
1728 Ok(FuncParam {
1729 name: pname.clone(),
1730 param_type: Some(param_type.clone()),
1731 allowed: None,
1732 docs: "",
1733 options: None,
1734 optional: *optional,
1735 })
1736 })
1737 .collect::<Result<_>>()?,
1738 ),
1739 returns: Some(return_type.clone()),
1740 rpn: false,
1741 summary: "DSL-defined function.",
1742 docs: "Defined via FUNC in an imported script.",
1743 examples: &[],
1744 },
1745 body: FuncBody::Script(FuncDefData {
1746 params: params.to_vec(),
1747 return_type,
1748 return_spelling: return_spelling.to_string(),
1749 is_async,
1750 body: body.to_vec(),
1751 module: Some(defining.to_string()),
1752 def_jail: None,
1757 }),
1758 },
1759 );
1760 if let Some(frame) = self.scopes.get_mut(frame_idx) {
1761 frame.defined.insert(qualified.clone());
1762 if let Some(old) = old {
1763 frame.shadowed.push((qualified, old));
1764 }
1765 }
1766 Ok(())
1767 }
1768
1769 pub(super) fn seal_canonical_jail(
1777 &mut self,
1778 canonical: &str,
1779 jail: (WorkspaceSelection, GuardedPath),
1780 ) {
1781 if let Some(entry) = self.entries.get_mut(canonical)
1782 && let FuncBody::Script(def) = &mut entry.body
1783 && def.def_jail.is_none()
1784 {
1785 def.def_jail = Some(jail);
1786 }
1787 }
1788
1789 pub(super) fn push_scope(&mut self) {
1792 self.scopes.push(ScopeFrame {
1793 defined: HashSet::new(),
1794 shadowed: Vec::new(),
1795 });
1796 }
1797
1798 pub(super) fn pop_scope(&mut self) {
1801 let Some(frame) = self.scopes.pop() else {
1802 return;
1803 };
1804 for name in frame.defined {
1805 self.entries.remove(&name);
1806 }
1807 for (name, old) in frame.shadowed {
1808 self.entries.insert(name, old);
1809 }
1810 }
1811
1812 pub(super) fn resolve_file_call_key(
1815 &self,
1816 unit_targets: &AliasTargets,
1817 name: &str,
1818 ) -> Result<Option<String>> {
1819 match classify_alias_call(unit_targets, name, &|key| self.entries.contains_key(key)) {
1820 AliasResolution::Global | AliasResolution::Unknown | AliasResolution::Any { .. } => {
1821 Ok(None)
1822 }
1823 AliasResolution::Canonical(key) => Ok(Some(key)),
1824 AliasResolution::Ambiguous { alias, base, files } => Err(anyhow::anyhow!(
1825 "{}",
1826 ambiguous_alias_message(&alias, &base, &files)
1827 )),
1828 }
1829 }
1830
1831 pub(super) fn pure_shared(&self) -> Arc<PureTable> {
1835 Arc::clone(&self.pure_shared)
1836 }
1837
1838 pub(super) fn all_metas(&self) -> Vec<FuncMeta> {
1841 self.entries_metas()
1842 }
1843
1844 fn meta(&self, name: &str) -> Option<FuncMeta> {
1845 self.entries.get(name).map(|entry| entry.meta.clone())
1846 }
1847
1848 fn native_metas(&self) -> Vec<FuncMeta> {
1849 let mut out: Vec<FuncMeta> = Vec::new();
1850 for entry in self.entries.values() {
1851 if !matches!(entry.body, FuncBody::Script(_)) {
1852 out.push(entry.meta.clone());
1853 }
1854 }
1855 out.sort_by(|a, b| a.name.cmp(&b.name));
1856 out
1857 }
1858
1859 pub(super) fn pure_metas(&self) -> Vec<FuncMeta> {
1864 let mut out: Vec<FuncMeta> = Vec::new();
1865 for entry in self.entries.values() {
1866 if matches!(entry.body, FuncBody::Pure(_) | FuncBody::Both { .. }) {
1867 out.push(entry.meta.clone());
1868 }
1869 }
1870 out.sort_by(|a, b| a.name.cmp(&b.name));
1871 out
1872 }
1873
1874 fn entries_metas(&self) -> Vec<FuncMeta> {
1877 let mut out: Vec<FuncMeta> = self
1878 .entries
1879 .values()
1880 .map(|entry| entry.meta.clone())
1881 .collect();
1882 out.sort_by(|a, b| a.name.cmp(&b.name));
1883 out
1884 }
1885
1886 pub fn set_script_docs(&mut self, docs: &HashMap<String, (String, String)>) {
1889 for (base, pair) in docs {
1890 self.script_docs
1891 .insert(qualify(SCRIPT_MODULE_NAME, base), pair.clone());
1892 }
1893 }
1894
1895 pub fn script_doc_for(&self, qualified: &str) -> Option<(String, String)> {
1897 self.script_docs.get(qualified).cloned()
1898 }
1899
1900 pub fn exported_metas(
1905 &self,
1906 func_exports: &[String],
1907 unit_targets: &AliasTargets,
1908 ) -> anyhow::Result<Vec<FuncMeta>> {
1909 let mut out = Vec::with_capacity(func_exports.len());
1910 for name in func_exports {
1911 let qualified = match split_qualified(name) {
1915 None => qualify(SCRIPT_MODULE_NAME, name),
1916 Some(_) => name.clone(),
1917 };
1918 let lookup = self
1919 .resolve_file_call_key(unit_targets, &qualified)?
1920 .unwrap_or_else(|| qualified.clone());
1921 if let Some(entry) = self.entries.get(&lookup) {
1922 let mut meta = entry.meta.clone();
1923 if lookup != qualified {
1924 meta.name = name.clone();
1925 }
1926 out.push(meta);
1927 continue;
1928 }
1929 anyhow::bail!(
1930 "EXPORT `{name}` matches no defined script function or known host function"
1931 );
1932 }
1933 Ok(out)
1934 }
1935}
1936
1937impl<P: ProcessManager> Clone for FunctionRegistry<P> {
1938 fn clone(&self) -> Self {
1939 Self {
1940 entries: self.entries.clone(),
1941 scopes: self.scopes.clone(),
1942 pure_shared: Arc::clone(&self.pure_shared),
1943 script_docs: self.script_docs.clone(),
1944 }
1945 }
1946}
1947
1948pub fn builtin_function_names() -> HashSet<String> {
1955 let mut names = FunctionRegistry::<DefaultProcessManager>::with_builtins().keys();
1956 names.insert(KEYWORD_INSPECT.to_string());
1957 names
1958}
1959
1960pub fn builtin_function_metas() -> Vec<FuncMeta> {
1964 FunctionRegistry::<DefaultProcessManager>::with_builtins().native_metas()
1965}
1966
1967pub fn std_module_table() -> oxdock_parser::ModuleTable {
1972 let func_names: HashSet<String> = builtin_function_metas()
1974 .into_iter()
1975 .map(|meta| base_name(&meta.name).to_string())
1976 .collect();
1977 oxdock_parser::ModuleTable {
1978 modules: HashMap::from([(
1979 STD_MODULE_NAME.to_string(),
1980 Some(oxdock_parser::ModuleFuncs { func_names }),
1981 )]),
1982 }
1983}
1984
1985#[oxdock_func(pure, returns = TypeTag::Int)]
1998#[example(
1999 name = "convert",
2000 code = r###"
2001 IMPORT [STD]
2002 LET $n: INT = INT("42")
2003 ASSERT_EQ $n 42
2004 LET $flag: INT = INT(true)
2005 ASSERT_EQ $flag 1
2006 "###
2007)]
2008fn int(
2009 #[union(Int, Float, String, Bool)]
2011 val: Value,
2012) -> Result<Value> {
2013 super::args::int_from_value(val)
2014}
2015
2016#[oxdock_func(pure, returns = TypeTag::Float)]
2021#[example(
2022 name = "convert",
2023 code = r###"
2024 IMPORT [STD]
2025 LET $f: FLOAT = FLOAT("1.5")
2026 ASSERT_EQ $f 1.5
2027 LET $whole: FLOAT = FLOAT(2)
2028 ASSERT_EQ $whole 2.0
2029 "###
2030)]
2031fn float(
2032 #[union(Float, Int, String)]
2034 val: Value,
2035) -> Result<Value> {
2036 super::args::float_from_value(val)
2037}
2038
2039#[oxdock_func(pure, returns = TypeTag::String)]
2044#[example(
2045 name = "format and round-trip",
2046 code = r###"
2047 # Byte counts render in the largest exact unit.
2048 IMPORT [STD]
2049 LET $pretty: STRING = FORMAT_BYTE_COUNT(1_048_576)
2050 ASSERT_EQ $pretty "1MiB"
2051
2052 # The pair round-trips through the parser.
2053 LET $back: INT = PARSE_BYTE_COUNT($pretty)
2054 ASSERT_EQ $back 1_048_576
2055 "###
2056)]
2057fn format_byte_count(
2058 bytes: i64,
2060) -> Result<Value> {
2061 if bytes < 0 {
2062 return Err(anyhow::anyhow!(
2063 "FORMAT_BYTE_COUNT needs a non-negative byte count, got {bytes}"
2064 ));
2065 }
2066 Ok(Value::string(oxdock_parser::command::format_byte_count(
2067 bytes as u64,
2068 )))
2069}
2070
2071#[oxdock_func(pure, returns = TypeTag::Int)]
2106#[example(
2107 name = "parse",
2108 code = r###"
2109 IMPORT [STD]
2110 LET $n: INT = PARSE_BYTE_COUNT("10KB")
2111 ASSERT_EQ $n 10_000
2112 LET $identity: INT = PARSE_BYTE_COUNT(512)
2113 ASSERT_EQ $identity 512
2114 "###
2115)]
2116fn parse_byte_count(
2117 #[union(Int, Float, String)]
2119 text: Value,
2120) -> Result<Value> {
2121 if let Some(n) = text.as_i64() {
2122 if n < 0 {
2123 return Err(anyhow::anyhow!(
2124 "PARSE_BYTE_COUNT needs a non-negative byte count, got {n}"
2125 ));
2126 }
2127 return Ok(Value::int(n));
2128 }
2129 if let Some(f) = text.as_f64() {
2130 if f.is_finite() && f.fract() == 0.0 && f >= 0.0 && f <= i64::MAX as f64 {
2131 return Ok(Value::int(f as i64));
2132 }
2133 return Err(anyhow::anyhow!(
2134 "PARSE_BYTE_COUNT needs an integral byte count, got {f:?}"
2135 ));
2136 }
2137 let Some(s) = text.as_str() else {
2138 return Err(anyhow::anyhow!(
2139 "PARSE_BYTE_COUNT needs a token or number, found {text:?}"
2140 ));
2141 };
2142 let n = oxdock_parser::command::parse_byte_count(s)?;
2143 let n = i64::try_from(n)
2144 .map_err(|_| anyhow::anyhow!("PARSE_BYTE_COUNT out of INT range: {s:?}"))?;
2145 Ok(Value::int(n))
2146}
2147
2148#[oxdock_func(pure, returns = TypeTag::String)]
2153#[example(
2154 name = "format and round-trip",
2155 code = r###"
2156 # Durations render in the largest exact unit.
2157 IMPORT [STD]
2158 LET $pretty: STRING = FORMAT_DURATION(90_000)
2159 ASSERT_EQ $pretty "90s"
2160
2161 # The pair round-trips through the parser.
2162 LET $back: INT = PARSE_DURATION($pretty)
2163 ASSERT_EQ $back 90_000
2164 "###
2165)]
2166fn format_duration(
2167 millis: i64,
2169) -> Result<Value> {
2170 if millis < 0 {
2171 return Err(anyhow::anyhow!(
2172 "FORMAT_DURATION needs non-negative milliseconds, got {millis}"
2173 ));
2174 }
2175 Ok(Value::string(oxdock_parser::command::format_duration(
2176 &std::time::Duration::from_millis(millis as u64),
2177 )))
2178}
2179
2180#[oxdock_func(pure, returns = TypeTag::Int)]
2186#[example(
2187 name = "parse",
2188 code = r###"
2189 # A bare number means seconds, like TIMEOUT.
2190 IMPORT [STD]
2191 LET $ms: INT = PARSE_DURATION("2m")
2192 ASSERT_EQ $ms 120_000
2193
2194 # Milliseconds stay exact.
2195 LET $exact: INT = PARSE_DURATION("1500ms")
2196 ASSERT_EQ $exact 1_500
2197
2198 # One optional space separates number from unit.
2199 LET $spaced: INT = PARSE_DURATION("1 h")
2200 ASSERT_EQ $spaced 3_600_000
2201 "###
2202)]
2203fn parse_duration(
2204 text: String,
2206) -> Result<Value> {
2207 let duration = oxdock_parser::command::parse_duration(&text)?;
2208 let millis = i64::try_from(duration.as_millis())
2209 .map_err(|_| anyhow::anyhow!("PARSE_DURATION out of INT range: {text:?}"))?;
2210 Ok(Value::int(millis))
2211}
2212
2213#[oxdock_func(rpn, returns = TypeTag::ListOf(std::sync::Arc::new(TypeTag::String)))]
2218#[example(
2219 name = "match",
2220 code = r###"
2221 IMPORT [STD]
2222 WRITE "notes-a.md" "a"
2223 WRITE "notes-b.md" "b"
2224 WRITE "other.txt" "c"
2225 LET $found: LIST<STRING> = GLOB("notes-*.md")
2226 ASSERT_EQ $found.0 "notes-a.md"
2227 ASSERT_EQ $found.1 "notes-b.md"
2228 "###
2229)]
2230fn glob<P: ProcessManager>(
2231 cx: &mut StepCtx<P>,
2232 #[union(String, Path)]
2234 pattern: Value,
2235) -> Result<Value> {
2236 let text = super::args::string_or_path_text(&pattern)?;
2237 super::args::glob_from_value(&[Value::string(text)], cx)
2238}
2239
2240#[oxdock_func(rpn, returns = TypeTag::MapOf(std::sync::Arc::new(TypeTag::Any)))]
2245#[example(
2246 name = "load",
2247 code = r###"
2248 IMPORT [STD]
2249 WRITE "cfg.toml" "title = \"demo\""
2250 LET $cfg: MAP<ANY> = LOAD_TOML("cfg.toml")
2251 ASSERT_EQ $cfg.title "demo"
2252 "###
2253)]
2254fn load_toml<P: ProcessManager>(
2255 cx: &mut StepCtx<P>,
2256 #[union(String, Path)]
2258 path: Value,
2259) -> Result<Value> {
2260 let text = super::args::string_or_path_text(&path)?;
2261 super::args::load_toml_from_value(&[Value::string(text)], cx)
2262}
2263
2264#[oxdock_func(rpn, returns = TypeTag::Any)]
2272#[example(
2273 name = "load",
2274 code = r###"
2275 IMPORT [STD]
2276 WRITE "data.json" "{\"a\": 1}"
2277 LET $doc: MAP<ANY> = LOAD_JSON("data.json")
2278 ASSERT_EQ $doc.a 1
2279 "###
2280)]
2281fn load_json<P: ProcessManager>(
2282 cx: &mut StepCtx<P>,
2283 #[union(String, Path)]
2285 path: Value,
2286) -> Result<Value> {
2287 let text = super::args::string_or_path_text(&path)?;
2288 super::args::load_json_from_value(&[Value::string(text)], cx)
2289}
2290
2291#[oxdock_func(rpn, returns = TypeTag::String)]
2301#[example(
2302 name = "hash",
2303 code = r###"
2304 IMPORT [STD]
2305 WRITE payload.txt hello
2306 LET $digest: STRING = HASH_SHA256("payload.txt")
2307 ASSERT_EQ $digest "2cf24dba5fb0a30e26e83b2ac5b9e29e1b161e5c1fa7425e73043362938b9824"
2308 "###
2309)]
2310fn hash_sha256<P: ProcessManager>(
2311 cx: &mut StepCtx<P>,
2312 #[union(String, Path)]
2314 path: Value,
2315) -> Result<Value> {
2316 use sha2::Digest;
2317
2318 let text = super::args::string_or_path_text(&path)?;
2319 let target = cx.state.fs.resolve_read(&cx.state.cwd, &text)?;
2320 let mut hasher = sha2::Sha256::new();
2321 super::fs_ops::hash_path(cx.state.fs.as_ref(), &target, "", &mut hasher)?;
2322 let digest = hasher.finalize();
2323 let bytes: &[u8] = digest.as_ref();
2324 Ok(Value::string(oxdock_utils::hex_encode(bytes)))
2325}
2326
2327#[oxdock_func(rpn, returns = TypeTag::String)]
2338#[example(
2339 name = "cwd",
2340 code = r###"
2341 IMPORT [STD]
2342 WORKDIR sub
2343 LET $c: STRING = CWD()
2344 ASSERT_CONTAINS $c "sub"
2345 "###
2346)]
2347fn cwd<P: ProcessManager>(cx: &mut StepCtx<P>) -> Result<Value> {
2348 if cx.state.fs.is_snapshot_pending() {
2349 return Ok(Value::string(super::SNAPSHOT_PENDING_DISPLAY.to_string()));
2350 }
2351 let concrete = cx.state.fs.concretize_cwd(&cx.state.cwd);
2352 let real = super::fs_ops::canonical_cwd(cx.state.fs.as_ref(), &concrete)?;
2353 Ok(Value::string(real))
2354}
2355
2356#[oxdock_func(pure, returns = TypeTag::MapOf(std::sync::Arc::new(TypeTag::Any)))]
2362#[example(
2363 name = "parse",
2364 code = r###"
2365 IMPORT [STD]
2366 LET $doc: MAP<ANY> = PARSE_TOML("title = \"demo\"")
2367 ASSERT_EQ $doc.title "demo"
2368 "###
2369)]
2370fn parse_toml(
2371 text: String,
2373) -> Result<Value> {
2374 super::args::parse_toml_from_value(Value::string(text))
2375}
2376
2377#[oxdock_func(pure, returns = TypeTag::Any)]
2386#[example(
2387 name = "parse",
2388 code = r###"
2389 # Parse in-memory JSON text with the same conversion as file loading.
2390 IMPORT [STD]
2391 LET $body: STRING = "{\"a\": 1}"
2392 LET $doc: ANY = PARSE_JSON($body)
2393 ASSERT_EQ $doc.a 1
2394
2395 # Top-level arrays parse to LIST, which is why the return is ANY.
2396 LET $items: LIST<ANY> = PARSE_JSON("[1, 2]")
2397 ASSERT_EQ $items.0 1
2398 ASSERT_EQ $items.1 2
2399 "###
2400)]
2401fn parse_json(
2402 text: String,
2404) -> Result<Value> {
2405 super::args::parse_json_from_value(Value::string(text))
2406}
2407
2408#[oxdock_func(returns = TypeTag::String)]
2414#[example(
2415 name = "describe",
2416 code = r###"
2417 IMPORT [STD]
2418 WRITE "entry.txt" "words"
2419 LET $kind: STRING = PATH_TYPE("entry.txt")
2420 ASSERT_EQ $kind "file"
2421 LET $missing: STRING = PATH_TYPE("no-such-entry.txt")
2422 ASSERT_EQ $missing "absent"
2423 "###
2424)]
2425fn path_type<P: ProcessManager>(
2426 cx: &mut StepCtx<P>,
2427 #[union(String, Path)]
2429 path: Value,
2430) -> Result<Value> {
2431 let text = super::args::string_or_path_text(&path)?;
2432 super::args::path_type_from_value(&[Value::string(text)], cx)
2433}
2434
2435#[oxdock_func(returns = TypeTag::Bool)]
2444#[example(
2445 name = "probe",
2446 code = r###"
2447 # An absent nested path is writable when its ancestor is.
2448 IMPORT [STD]
2449 LET $fresh: BOOL = PATH_WRITABLE("probe-check/nested/file.txt")
2450 ASSERT_EQ $fresh true
2451
2452 # The empty string never aliases the working directory.
2453 LET $empty: BOOL = PATH_WRITABLE("")
2454 ASSERT_EQ $empty false
2455 "###
2456)]
2457fn path_writable<P: ProcessManager>(
2458 cx: &mut StepCtx<P>,
2459 #[union(String, Path)]
2461 path: Value,
2462) -> Result<Value> {
2463 let text = super::args::string_or_path_text(&path)?;
2464 super::args::path_writable_from_value(&[Value::string(text)], cx)
2465}
2466
2467#[oxdock_func(returns = TypeTag::Bool)]
2480#[example(
2481 name = "probe",
2482 code = r###"
2483 # Missing tools read false instead of failing the run.
2484 IMPORT [STD]
2485 LET $missing: BOOL = IS_EXEC("no-such-tool-xyz")
2486 ASSERT_EQ $missing false
2487
2488 # Plain files are not executable on any platform.
2489 WRITE tool.txt payload
2490 LET $plain: BOOL = IS_EXEC("tool.txt")
2491 ASSERT_EQ $plain false
2492 "###
2493)]
2494fn is_exec<P: ProcessManager>(
2495 cx: &mut StepCtx<P>,
2496 #[union(String, Path)]
2498 name: Value,
2499) -> Result<Value> {
2500 let text = super::args::string_or_path_text(&name)?;
2501 super::args::is_exec_from_value(&[Value::string(text)], cx)
2502}
2503
2504#[oxdock_func(returns = TypeTag::Bool)]
2512#[example(
2513 name = "probe",
2514 code = r###"
2515 # Ordinary files read true; missing paths read false.
2516 IMPORT [STD]
2517 WRITE "entry.txt" "words"
2518 LET $hit: BOOL = IS_FILE("entry.txt")
2519 ASSERT_EQ $hit true
2520 LET $miss: BOOL = IS_FILE("no-such-entry.txt")
2521 ASSERT_EQ $miss false
2522 "###
2523)]
2524fn is_file<P: ProcessManager>(
2525 cx: &mut StepCtx<P>,
2526 #[union(String, Path)]
2528 path: Value,
2529) -> Result<Value> {
2530 let text = super::args::string_or_path_text(&path)?;
2531 Ok(Value::bool(super::args::path_is_file(cx, &text)))
2532}
2533
2534#[oxdock_func(returns = TypeTag::Bool)]
2542#[example(
2543 name = "probe",
2544 code = r###"
2545 # Directories read true; files read false.
2546 IMPORT [STD]
2547 LET $hit: BOOL = IS_DIR(".")
2548 ASSERT_EQ $hit true
2549 WRITE "entry.txt" "words"
2550 LET $miss: BOOL = IS_DIR("entry.txt")
2551 ASSERT_EQ $miss false
2552 "###
2553)]
2554fn is_dir<P: ProcessManager>(
2555 cx: &mut StepCtx<P>,
2556 #[union(String, Path)]
2558 path: Value,
2559) -> Result<Value> {
2560 let text = super::args::string_or_path_text(&path)?;
2561 Ok(Value::bool(super::args::path_is_dir(cx, &text)))
2562}
2563
2564#[oxdock_func(returns = TypeTag::Bool)]
2571#[example(
2572 name = "probe",
2573 code = r###"
2574 # Present entries read true; absent paths read false.
2575 IMPORT [STD]
2576 WRITE "entry.txt" "words"
2577 LET $hit: BOOL = EXISTS("entry.txt")
2578 ASSERT_EQ $hit true
2579 LET $miss: BOOL = EXISTS("no-such-entry.txt")
2580 ASSERT_EQ $miss false
2581 "###
2582)]
2583fn exists<P: ProcessManager>(
2584 cx: &mut StepCtx<P>,
2585 #[union(String, Path)]
2587 path: Value,
2588) -> Result<Value> {
2589 let text = super::args::string_or_path_text(&path)?;
2590 Ok(Value::bool(super::args::path_exists(cx, &text)))
2591}
2592
2593#[oxdock_func(pure, returns = TypeTag::Bool)]
2599#[example(
2600 name = "probe",
2601 code = r###"
2602 IMPORT [STD]
2603 LET $m: MAP<ANY> = PARSE_JSON("{\"a\": 1}")
2604 LET $hit: BOOL = HAS_KEY($m, "a")
2605 ASSERT_EQ $hit true
2606 LET $miss: BOOL = HAS_KEY($m, "b")
2607 ASSERT_EQ $miss false
2608 "###
2609)]
2610fn has_key(
2611 map: BTreeMap<String, Value>,
2613 key: String,
2615) -> Result<Value> {
2616 super::args::has_key_from_value(Value::map(map), &key)
2617}
2618
2619#[oxdock_func(pure, returns = TypeTag::Any)]
2625#[example(
2626 name = "present and absent",
2627 code = r###"
2628 IMPORT [STD]
2629 LET $m: MAP<ANY> = PARSE_JSON("{\"a\": 1}")
2630 LET $hit: INT = GET($m, "a", 0)
2631 ASSERT_EQ $hit 1
2632 LET $miss: INT = GET($m, "b", 0)
2633 ASSERT_EQ $miss 0
2634 "###
2635)]
2636fn get(
2637 map: BTreeMap<String, Value>,
2639 key: String,
2641 default: Value,
2643) -> Result<Value> {
2644 Ok(map.get(&key).cloned().unwrap_or(default))
2645}
2646
2647#[oxdock_func(pure, returns = TypeTag::MapOf(std::sync::Arc::new(TypeTag::Any)))]
2657#[example(
2658 name = "insert",
2659 code = r###"
2660 IMPORT [STD]
2661 LET $m: MAP<ANY> = MAP_SET({seed: 0}, "a", 1)
2662 ASSERT_EQ $m.a 1
2663 "###
2664)]
2665fn map_set(
2666 #[reject_frozen]
2668 map: BTreeMap<String, Value>,
2669 key: String,
2671 value: Value,
2673) -> Result<Value> {
2674 super::args::map_set_from_value(Value::map(map), key, value)
2675}
2676
2677#[oxdock_func(returns = TypeTag::Float, summary = "Draw a random FLOAT uniformly from [0, 1), optionally seeded.")]
2685#[example(
2686 name = "seeded draw",
2687 code = r###"
2688 # A seed draws the same value on every run.
2689 IMPORT [STD]
2690 LET $one: FLOAT = RAND({seed: 7})
2691 LET $two: FLOAT = RAND({seed: 7})
2692 ASSERT_EQ $one $two
2693 "###
2694)]
2695#[example(
2696 name = "unseeded draw",
2697 code = r###"
2698 # Scale a unit draw into a backoff delay between 1 and 11 seconds.
2699 IMPORT [STD]
2700 LET $draw: FLOAT = RAND()
2701 LET $delay: FLOAT = 1.0 + $draw * 10.0
2702 IF $delay < 1.0 {
2703 FAIL "trap: RAND draw below range"
2704 }
2705 IF $delay >= 11.0 {
2706 FAIL "trap: RAND draw above range"
2707 }
2708 ECHO "retrying in {{ $delay }}s"
2709 "###
2710)]
2711fn rand<P: ProcessManager>(
2712 cx: &mut StepCtx<P>,
2713 #[options("seed?: INT")]
2715 #[optional]
2716 options: BTreeMap<String, Value>,
2717) -> Result<Value> {
2718 let _ = cx;
2719 let seed = options
2722 .get("seed")
2723 .map(|value| value.as_i64().expect("check_options verified INT"));
2724 super::args::rand_float_from_value(seed)
2725}
2726
2727#[oxdock_func(pure, returns = TypeTag::String)]
2733#[example(
2734 name = "encode",
2735 code = r###"
2736 # Encode text to standard base64.
2737 IMPORT [STD]
2738 LET $encoded: STRING = BASE64_ENCODE("hello")
2739 ASSERT_EQ $encoded "aGVsbG8="
2740 "###
2741)]
2742fn base64_encode(
2743 text: String,
2745) -> Result<Value> {
2746 super::args::base64_encode_from_value(Value::string(text))
2747}
2748
2749#[oxdock_func(pure, returns = TypeTag::String)]
2756#[example(
2757 name = "decode",
2758 code = r###"
2759 # Decode standard base64 back to text.
2760 IMPORT [STD]
2761 LET $decoded: STRING = BASE64_DECODE("aGVsbG8=")
2762 ASSERT_EQ $decoded "hello"
2763 "###
2764)]
2765fn base64_decode(
2766 text: String,
2768) -> Result<Value> {
2769 super::args::base64_decode_from_value(Value::string(text))
2770}
2771
2772#[oxdock_func(pure, returns = TypeTag::String)]
2779#[example(
2780 name = "encode",
2781 code = r###"
2782 IMPORT [STD]
2783 LET $json: STRING = TO_JSON({a: 1})
2784 ASSERT_EQ $json "{\"a\":1}\n"
2785 "###
2786)]
2787fn to_json(
2788 #[union(String, Int, Float, Bool, List, Map)]
2790 value: Value,
2791) -> Result<Value> {
2792 super::args::to_json_from_value(value)
2793}
2794
2795#[oxdock_func(pure, returns = TypeTag::String)]
2803#[example(
2804 name = "name the word",
2805 code = r###"
2806 IMPORT [STD]
2807 LET $word: STRING = TYPE_OF(42)
2808 ASSERT_EQ $word "INT"
2809 "###
2810)]
2811fn type_of(
2812 value: Value,
2814) -> Result<Value> {
2815 super::args::type_of_from_value(value)
2816}
2817
2818#[oxdock_func(pure, returns = TypeTag::MapOf(std::sync::Arc::new(TypeTag::Any)))]
2830#[example(
2831 name = "merge",
2832 code = r###"
2833 IMPORT [STD]
2834 LET $m: MAP<ANY> = MERGE_MAPS([{a: 1}, {b: 2}], "overwrite")
2835 ASSERT_EQ $m.a 1
2836 ASSERT_EQ $m.b 2
2837 "###
2838)]
2839fn merge_maps(
2840 #[reject_frozen]
2842 maps: Vec<BTreeMap<String, Value>>,
2843 #[values("fail_on_duplicate", "overwrite")]
2845 policy: String,
2846) -> Result<Value> {
2847 super::args::merge_maps_from_value(
2848 Value::list(maps.into_iter().map(Value::map).collect()),
2849 policy,
2850 )
2851}
2852
2853#[oxdock_func(pure, returns = TypeTag::String)]
2858#[example(
2859 name = "report",
2860 code = r###"
2861 # The engine reports its own build version as a dotted string.
2862 IMPORT [STD]
2863 LET $v: STRING = VERSION()
2864 ASSERT_CONTAINS $v "."
2865 "###
2866)]
2867fn version() -> Result<Value> {
2868 Ok(Value::string(env!("CARGO_PKG_VERSION").to_string()))
2869}
2870
2871#[oxdock_func(returns = TypeTag::ListOf(std::sync::Arc::new(TypeTag::String)))]
2876#[example(
2877 name = "list",
2878 code = r###"
2879 IMPORT [STD]
2880 LET $names: LIST<STRING> = FUNCTIONS()
2881 ASSERT_CONTAINS $names "STD::INT"
2882 "###
2883)]
2884fn functions<P: ProcessManager>(cx: &mut StepCtx<P>) -> Result<Value> {
2885 let mut names: Vec<String> = cx
2886 .state
2887 .list_functions()
2888 .into_iter()
2889 .map(|meta| meta.name)
2890 .collect();
2891 names.sort();
2892 names.dedup();
2893 Ok(Value::list(names.into_iter().map(Value::string).collect()))
2894}
2895
2896#[oxdock_func(returns = TypeTag::ListOf(std::sync::Arc::new(TypeTag::String)))]
2903#[example(
2904 name = "empty",
2905 code = r###"
2906 # With no staged args the list is empty.
2907 IMPORT [STD]
2908 LET $args: LIST<STRING> = ARGV()
2909 LET $n: INT = LEN($args)
2910 ASSERT_EQ $n 0
2911 "###
2912)]
2913fn argv<P: ProcessManager>(cx: &mut StepCtx<P>) -> Result<Value> {
2914 Ok(Value::list(
2915 cx.state
2916 .io
2917 .script_args()
2918 .iter()
2919 .cloned()
2920 .map(Value::string)
2921 .collect(),
2922 ))
2923}
2924
2925pub struct ParseArgs;
2945
2946impl<P: ProcessManager> OxDockFn<P> for ParseArgs {
2947 fn registration() -> HostRegistration<P> {
2948 let func: NativeFn<P> = Arc::new(|cx: &mut StepCtx<P>, values: Vec<Value>| {
2949 if values.len() != 1 {
2950 anyhow::bail!("PARSE_ARGS() expects 1 argument, got {}", values.len());
2951 }
2952 let mut iter = values.into_iter();
2953 let args_val = iter.next().expect("arity checked above");
2954 let args = string_list_arg(&args_val, "PARSE_ARGS() argument `$args`")?;
2955 let specs = resolve_flags_specs(cx)?;
2956 let (raw, positionals) = tokenize_raw_args(args)?;
2957 let coerced = coerce_flags(&specs, &raw)?;
2958 let mut out = BTreeMap::new();
2959 out.insert("flags".to_string(), Value::map(coerced));
2960 if !positionals.is_empty() {
2961 out.insert("positionals".to_string(), Value::list(positionals));
2962 }
2963 Ok(Value::map(out))
2964 });
2965 HostRegistration::Stateful {
2966 name: "PARSE_ARGS".to_string(),
2967 meta: FuncMeta {
2968 name: "PARSE_ARGS".to_string(),
2969 module: String::new(),
2970 kind: FuncKind::HostPure,
2971 params: Some(vec![FuncParam {
2972 name: "args".to_string(),
2973 param_type: Some(TypeTag::ListOf(Arc::new(TypeTag::String))),
2974 allowed: None,
2975 docs: "Argv tail to parse, usually from `STD::ARGV()`.",
2976 options: None,
2977 optional: false,
2978 }]),
2979 returns: Some(TypeTag::Record(Arc::from([
2980 Field {
2981 name: "flags".to_string(),
2982 ty: TypeTag::Map,
2983 docs: "Flags coerced to `TYPE FLAGS`.",
2984 optional: false,
2985 default: None,
2986
2987 alias: None,
2988 },
2989 Field {
2990 name: "positionals".to_string(),
2991 ty: TypeTag::ListOf(Arc::new(TypeTag::String)),
2992 docs: "Trailing values and entries after the first double dash. Omitted when empty.",
2993 optional: true,
2994 default: None,
2995
2996 alias: None,
2997 },
2998 ]))),
2999 rpn: true,
3000 summary: "Parse an argv tail against TYPE FLAGS.",
3001 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.",
3002 examples: &[
3003 crate::Example {
3004 name: "flags and positionals",
3005 fence_meta: None,
3006 code: indoc::indoc! {r#"
3007 IMPORT [STD]
3008 # One schema TYPE drives coercion; the pair binds both slots.
3009 TYPE FLAGS = MAP<model: STRING, verbose?: BOOL>
3010 TYPE POSITIONS = LIST<STRING>
3011 TYPE PARSED = MAP<flags: FLAGS, positionals?: POSITIONS>
3012 LET $parsed: PARSED = PARSE_ARGS(["--model=gpt-4", "--verbose", "serve"])
3013 LET $flags: FLAGS = $parsed.flags
3014 ASSERT_EQ $flags.model "gpt-4"
3015 ASSERT_EQ $flags.verbose true
3016 ASSERT_EQ $parsed.positionals.0 "serve"
3017 "#},
3018 },
3019 crate::Example {
3020 name: "optional stays absent",
3021 fence_meta: None,
3022 code: indoc::indoc! {r#"
3023 IMPORT [STD]
3024 # Absent optionals stay absent; read them with a typed GET default.
3025 TYPE FLAGS = MAP<model: STRING, propose?: BOOL>
3026 TYPE POSITIONS = LIST<STRING>
3027 TYPE PARSED = MAP<flags: FLAGS, positionals?: POSITIONS>
3028 LET $parsed: PARSED = PARSE_ARGS(["--model=x"])
3029 LET $flags: FLAGS = $parsed.flags
3030 LET $propose: BOOL = GET($flags, "propose", false)
3031 ASSERT_EQ $propose false
3032 "#},
3033 },
3034 crate::Example {
3035 name: "flags only omits positionals",
3036 fence_meta: None,
3037 code: indoc::indoc! {r#"
3038 IMPORT [STD]
3039 # Empty positionals are omitted, so a flags only shape binds clean.
3040 TYPE FLAGS = MAP<model: STRING>
3041 TYPE PARSED = MAP<flags: FLAGS>
3042 LET $parsed: PARSED = PARSE_ARGS(["--model=x"])
3043 LET $flags: FLAGS = $parsed.flags
3044 ASSERT_EQ $flags.model "x"
3045 "#},
3046 },
3047 crate::Example {
3048 name: "literal defaults",
3049 fence_meta: None,
3050 code: indoc::indoc! {r#"
3051 IMPORT [STD]
3052 # Defaults are literals only: INT, FLOAT, BOOL,
3053 # and double-quoted STRING fill absent flags.
3054 TYPE FLAGS = MAP<retries: INT = 2, ratio: FLOAT = 2.5, verbose: BOOL = true, model: STRING = "gpt-4">
3055 TYPE PARSED = MAP<flags: FLAGS>
3056 LET $parsed: PARSED = PARSE_ARGS([])
3057 LET $flags: FLAGS = $parsed.flags
3058 ASSERT_EQ $flags.retries 2
3059 ASSERT_EQ $flags.verbose true
3060 ASSERT_EQ $flags.model "gpt-4"
3061 LET $ratio_ok: BOOL = $flags.ratio == 2.5
3062 ASSERT_EQ $ratio_ok true
3063 "#},
3064 },
3065 crate::Example {
3066 name: "variable default fails",
3067 fence_meta: Some("expect_error:\"expected default literal\""),
3068 code: indoc::indoc! {r#"
3069 IMPORT [STD]
3070 # Defaults are literals: a variable in place
3071 # of a literal fails instead of evaluating.
3072 TYPE FLAGS = MAP<n: INT = $x>
3073 TYPE PARSED = MAP<flags: FLAGS>
3074 LET $p: PARSED = PARSE_ARGS([])
3075 "#},
3076 },
3077 crate::Example {
3078 name: "missing required",
3079 fence_meta: Some("expect_error:\"missing required flag\""),
3080 code: indoc::indoc! {r#"
3081 IMPORT [STD]
3082 # Absent required flags fail naming the flag.
3083 TYPE FLAGS = MAP<model: STRING>
3084 TYPE PARSED = MAP<flags: FLAGS>
3085 LET $parsed: PARSED = PARSE_ARGS([])
3086 "#},
3087 },
3088 crate::Example {
3089 name: "unknown flag",
3090 fence_meta: Some("expect_error:\"unknown flag\""),
3091 code: indoc::indoc! {r#"
3092 IMPORT [STD]
3093 # Undeclared flags fail instead of passing through.
3094 TYPE FLAGS = MAP<model: STRING>
3095 TYPE PARSED = MAP<flags: FLAGS>
3096 LET $parsed: PARSED = PARSE_ARGS(["--model=x", "--nope=1"])
3097 "#},
3098 },
3099 crate::Example {
3100 name: "alias accepted",
3101 fence_meta: None,
3102 code: indoc::indoc! {r#"
3103 IMPORT [STD]
3104 # One canonical key binds both spellings; the
3105 # alias never appears as a separate key.
3106 TYPE FLAGS = MAP<h: BOOL ALIAS help>
3107 TYPE PARSED = MAP<flags: FLAGS>
3108 LET $a: PARSED = PARSE_ARGS(["--help"])
3109 ASSERT_EQ $a.flags.h true
3110 LET $b: PARSED = PARSE_ARGS(["--h"])
3111 ASSERT_EQ $b.flags.h true
3112 "#},
3113 },
3114 crate::Example {
3115 name: "alias duplicate fails",
3116 fence_meta: Some("expect_error:\"duplicate flag\""),
3117 code: indoc::indoc! {r#"
3118 IMPORT [STD]
3119 # Canonical and alias together fail naming both.
3120 TYPE FLAGS = MAP<h: BOOL ALIAS help>
3121 TYPE PARSED = MAP<flags: FLAGS>
3122 LET $p: PARSED = PARSE_ARGS(["--h", "--help"])
3123 "#},
3124 },
3125 crate::Example {
3126 name: "alias missing names both",
3127 fence_meta: Some("expect_error:\"--h/--help\""),
3128 code: indoc::indoc! {r#"
3129 IMPORT [STD]
3130 # Missing required flags name both spellings.
3131 TYPE FLAGS = MAP<h: BOOL ALIAS help>
3132 TYPE PARSED = MAP<flags: FLAGS>
3133 LET $p: PARSED = PARSE_ARGS([])
3134 "#},
3135 },
3136 ],
3137 },
3138 func,
3139 }
3140 }
3141}
3142
3143#[derive(Debug, Clone, Copy, PartialEq, Eq)]
3147enum CliType {
3148 String,
3149 Bool,
3150 Int,
3151 Float,
3152}
3153
3154fn coerce_cli_flag(target: CliType, flag: &str, raw: Value) -> Result<Value> {
3159 match target {
3160 CliType::Bool => {
3161 if let Some(b) = raw.as_bool() {
3162 return Ok(Value::bool(b));
3163 }
3164 if let Some(s) = raw.as_str() {
3165 match super::args::parse_bool_str(s) {
3166 Some(b) => return Ok(Value::bool(b)),
3167 None => anyhow::bail!(
3168 "PARSE_ARGS flag --{flag} expects BOOL (true/false, 1/0, yes/no, on/off), got {s:?}"
3169 ),
3170 }
3171 }
3172 anyhow::bail!(
3173 "PARSE_ARGS flag --{flag} expects BOOL, got {}",
3174 raw.type_name()
3175 )
3176 }
3177 CliType::String => {
3178 if let Some(s) = raw.as_str() {
3179 return Ok(Value::string(s.to_string()));
3180 }
3181 anyhow::bail!("PARSE_ARGS flag --{flag} needs a value: use --{flag}=<value>");
3182 }
3183 CliType::Int => {
3184 if raw.as_bool().is_some() {
3185 anyhow::bail!("PARSE_ARGS flag --{flag} needs a value: use --{flag}=<value>");
3186 }
3187 super::args::int_from_value(raw)
3188 .map_err(|_| anyhow::anyhow!("PARSE_ARGS flag --{flag} expects INT"))
3189 }
3190 CliType::Float => {
3191 if raw.as_bool().is_some() {
3192 anyhow::bail!("PARSE_ARGS flag --{flag} needs a value: use --{flag}=<value>");
3193 }
3194 super::args::float_from_value(raw)
3195 .map_err(|_| anyhow::anyhow!("PARSE_ARGS flag --{flag} expects FLOAT"))
3196 }
3197 }
3198}
3199
3200#[derive(Debug, Clone)]
3204struct CliSpec {
3205 target: CliType,
3206 required: bool,
3207 default: Option<Value>,
3208 alias: Option<String>,
3209}
3210
3211type CliSpecs = BTreeMap<String, CliSpec>;
3213
3214fn string_list_arg(val: &Value, what: &str) -> Result<Vec<String>> {
3217 crate::check_value_at(&TypeTag::ListOf(Arc::new(TypeTag::String)), val, what)?;
3218 Ok(val
3219 .as_list()
3220 .expect("check_value_at enforces LIST")
3221 .iter()
3222 .map(|v| {
3223 v.as_str()
3224 .expect("check_value_at enforces STRING")
3225 .to_string()
3226 })
3227 .collect())
3228}
3229
3230fn tokenize_raw_args(args: Vec<String>) -> Result<(BTreeMap<String, Value>, Vec<Value>)> {
3234 use lexopt::Arg::{Long, Short, Value as ArgValue};
3235 let mut parser = lexopt::Parser::from_args(args);
3236 let mut flags: BTreeMap<String, Value> = BTreeMap::new();
3237 let mut positionals: Vec<Value> = Vec::new();
3238 let utf8 = |value: std::ffi::OsString| -> Result<String> {
3239 value
3240 .into_string()
3241 .map_err(|_| anyhow::anyhow!("PARSE_ARGS: argument must be UTF-8"))
3242 };
3243 loop {
3244 match parser.next() {
3245 Ok(None) => break,
3246 Ok(Some(Long(name))) => {
3247 let key = name.to_owned();
3248 if let Some(raw) = parser.optional_value() {
3249 flags.insert(key, Value::string(utf8(raw)?));
3250 } else {
3251 flags.insert(key, Value::bool(true));
3252 }
3253 }
3254 Ok(Some(Short(ch))) => {
3255 flags.insert(ch.to_string(), Value::bool(true));
3256 }
3257 Ok(Some(ArgValue(raw))) => {
3258 positionals.push(Value::string(utf8(raw)?));
3259 }
3260 Err(lexopt::Error::UnexpectedValue { option, value }) => {
3261 let key = option
3262 .strip_prefix("--")
3263 .or_else(|| option.strip_prefix('-'))
3264 .unwrap_or(option.as_str());
3265 flags.insert(key.to_string(), Value::string(utf8(value)?));
3266 }
3267 Err(err) => anyhow::bail!("PARSE_ARGS: {err}"),
3268 }
3269 }
3270 Ok((flags, positionals))
3271}
3272
3273fn coerce_flags(
3281 specs: &CliSpecs,
3282 raw: &BTreeMap<String, Value>,
3283) -> Result<BTreeMap<String, Value>> {
3284 let mut alias_to_canonical: BTreeMap<&str, &str> = BTreeMap::new();
3287 for (canonical, spec) in specs.iter() {
3288 if let Some(alias) = spec.alias.as_ref() {
3289 alias_to_canonical.insert(alias.as_str(), canonical.as_str());
3290 }
3291 }
3292 let mut coerced: BTreeMap<String, Value> = BTreeMap::new();
3293 for (flag, spec) in specs.iter() {
3294 if flag.is_empty() {
3295 anyhow::bail!("PARSE_ARGS schema flag names must be non-empty");
3296 }
3297 let canonical_raw = raw.get(flag);
3298 let alias_raw = spec.alias.as_ref().and_then(|alias| raw.get(alias));
3299 let display = match spec.alias.as_ref() {
3301 Some(alias) => format!("--{flag}/--{alias}"),
3302 None => format!("--{flag}"),
3303 };
3304 if canonical_raw.is_some() && alias_raw.is_some() {
3305 anyhow::bail!("PARSE_ARGS duplicate flag {display}");
3306 }
3307 if let Some(raw_val) = canonical_raw.or(alias_raw) {
3308 coerced.insert(
3309 flag.clone(),
3310 coerce_cli_flag(spec.target, flag, raw_val.clone())?,
3311 );
3312 } else if let Some(d) = spec.default.as_ref() {
3313 coerced.insert(flag.clone(), d.clone());
3314 } else if spec.required {
3315 anyhow::bail!("PARSE_ARGS missing required flag {display}");
3316 }
3317 }
3318 for flag in raw.keys() {
3319 if !specs.contains_key(flag) && !alias_to_canonical.contains_key(flag.as_str()) {
3320 anyhow::bail!("PARSE_ARGS unknown flag --{flag}");
3321 }
3322 }
3323 Ok(coerced)
3324}
3325
3326fn resolve_flags_specs<P: ProcessManager>(cx: &mut StepCtx<P>) -> Result<CliSpecs> {
3333 let name = "FLAGS";
3334 let tag = cx
3335 .state
3336 .resolve_tag(name)
3337 .map_err(|err| anyhow::anyhow!("PARSE_ARGS schema type {name:?}: {err:#}"))?;
3338 let TypeTag::Record(fields) = tag else {
3339 anyhow::bail!("PARSE_ARGS schema type {name:?} must be a MAP shape with scalar fields");
3340 };
3341 let mut specs = BTreeMap::new();
3342 for field in fields.iter() {
3343 let target = match field.ty {
3344 TypeTag::String => CliType::String,
3345 TypeTag::Bool => CliType::Bool,
3346 TypeTag::Int => CliType::Int,
3347 TypeTag::Float => CliType::Float,
3348 _ => anyhow::bail!(
3349 "PARSE_ARGS schema for --{}: type must be one of STRING, BOOL, INT, or FLOAT, got {}",
3350 field.name,
3351 field.ty.name(),
3352 ),
3353 };
3354 specs.insert(
3355 field.name.clone(),
3356 CliSpec {
3357 target,
3358 required: !field.optional && field.default.is_none(),
3359 default: field.default.clone(),
3360 alias: field.alias.clone(),
3361 },
3362 );
3363 }
3364 Ok(specs)
3365}
3366
3367pub struct ParseFlags;
3375
3376impl<P: ProcessManager> OxDockFn<P> for ParseFlags {
3377 fn registration() -> HostRegistration<P> {
3378 let func: NativeFn<P> = Arc::new(|cx: &mut StepCtx<P>, values: Vec<Value>| {
3379 if values.len() != 1 {
3380 anyhow::bail!("PARSE_FLAGS() expects 1 argument, got {}", values.len());
3381 }
3382 let mut iter = values.into_iter();
3383 let args_val = iter.next().expect("arity checked above");
3384 let args = string_list_arg(&args_val, "PARSE_FLAGS() argument `$args`")?;
3385 let specs = resolve_flags_specs(cx)?;
3386 let (raw, positionals) = tokenize_raw_args(args)?;
3387 if !positionals.is_empty() {
3388 let shown: Vec<String> = positionals.iter().map(|pos| pos.to_string()).collect();
3389 anyhow::bail!(
3390 "PARSE_FLAGS() does not accept positional arguments; found {}",
3391 shown.join(", ")
3392 );
3393 }
3394 Ok(Value::map(coerce_flags(&specs, &raw)?))
3395 });
3396 HostRegistration::Stateful {
3397 name: "PARSE_FLAGS".to_string(),
3398 meta: FuncMeta {
3399 name: "PARSE_FLAGS".to_string(),
3400 module: String::new(),
3401 kind: FuncKind::HostPure,
3402 params: Some(vec![FuncParam {
3403 name: "args".to_string(),
3404 param_type: Some(TypeTag::ListOf(Arc::new(TypeTag::String))),
3405 allowed: None,
3406 docs: "Argv tail to parse, usually from `STD::ARGV()`.",
3407 options: None,
3408 optional: false,
3409 }]),
3410 returns: Some(TypeTag::Map),
3411 rpn: true,
3412 summary: "Parse flags against TYPE FLAGS.",
3413 docs: "Consumes a `LIST<STRING>` and coerces flags through `TYPE FLAGS`. Returns the flags `MAP` directly; positional arguments fail.",
3414 examples: &[crate::Example {
3415 name: "flags only",
3416 fence_meta: None,
3417 code: indoc::indoc! {r#"
3418 IMPORT [STD]
3419 # Flags only returns the flags MAP directly.
3420 TYPE FLAGS = MAP<model: STRING, retries: INT = 2>
3421 LET $flags: FLAGS = PARSE_FLAGS(["--model=x"])
3422 ASSERT_EQ $flags.model "x"
3423 ASSERT_EQ $flags.retries 2
3424 "#},
3425 }],
3426 },
3427 func,
3428 }
3429 }
3430}
3431
3432pub struct ParsePositionals;
3437
3438impl<P: ProcessManager> OxDockFn<P> for ParsePositionals {
3439 fn registration() -> HostRegistration<P> {
3440 let func: NativeFn<P> = Arc::new(|_: &mut StepCtx<P>, values: Vec<Value>| {
3441 if values.len() != 1 {
3442 anyhow::bail!(
3443 "PARSE_POSITIONALS() expects 1 argument, got {}",
3444 values.len()
3445 );
3446 }
3447 let mut iter = values.into_iter();
3448 let args_val = iter.next().expect("arity checked above");
3449 let args = string_list_arg(&args_val, "PARSE_POSITIONALS() argument `$args`")?;
3450 let (_raw, positionals) = tokenize_raw_args(args)?;
3451 Ok(Value::list(positionals))
3452 });
3453 HostRegistration::Stateful {
3454 name: "PARSE_POSITIONALS".to_string(),
3455 meta: FuncMeta {
3456 name: "PARSE_POSITIONALS".to_string(),
3457 module: String::new(),
3458 kind: FuncKind::HostPure,
3459 params: Some(vec![FuncParam {
3460 name: "args".to_string(),
3461 param_type: Some(TypeTag::ListOf(Arc::new(TypeTag::String))),
3462 allowed: None,
3463 docs: "Argv tail to parse, usually from `STD::ARGV()`.",
3464 options: None,
3465 optional: false,
3466 }]),
3467 returns: Some(TypeTag::ListOf(Arc::new(TypeTag::String))),
3468 rpn: true,
3469 summary: "Parse positionals in argv order.",
3470 docs: "Consumes a `LIST<STRING>` and returns positionals in argv order with no schema.",
3471 examples: &[crate::Example {
3472 name: "positionals only",
3473 fence_meta: None,
3474 code: indoc::indoc! {r#"
3475 IMPORT [STD]
3476 # No schema needed: positionals are always strings in order.
3477 TYPE POSITIONS = LIST<STRING>
3478 LET $pos: POSITIONS = PARSE_POSITIONALS(["serve", "--", "--not-a-flag"])
3479 ASSERT_EQ $pos.0 "serve"
3480 ASSERT_EQ $pos.1 "--not-a-flag"
3481 "#},
3482 }],
3483 },
3484 func,
3485 }
3486 }
3487}
3488
3489#[oxdock_func(
3504 returns = TypeTag::Record(std::sync::Arc::from([Field {
3505 name: "name".to_string(),
3506 ty: TypeTag::String,
3507 docs: "Qualified function name.",
3508 optional: false,
3509 default: None,
3510
3511 alias: None,}, Field {
3512 name: "module".to_string(),
3513 ty: TypeTag::String,
3514 docs: "Owning module.",
3515 optional: false,
3516 default: None,
3517
3518 alias: None,}, Field {
3519 name: "kind".to_string(),
3520 ty: TypeTag::String,
3521 docs: "Origin label (`host` or `script`).",
3522 optional: false,
3523 default: None,
3524
3525 alias: None,}, Field {
3526 name: "params".to_string(),
3527 ty: TypeTag::ListOf(std::sync::Arc::new(TypeTag::MapOf(std::sync::Arc::new(
3528 TypeTag::Any,
3529 )))),
3530 docs: "Parameter entries (empty for parameterless functions).",
3531 optional: false,
3532 default: None,
3533
3534 alias: None,}, Field {
3535 name: "returns".to_string(),
3536 ty: TypeTag::String,
3537 docs: "Structural return shape (empty when untagged).",
3538 optional: false,
3539 default: None,
3540
3541 alias: None,}, Field {
3542 name: "rpn".to_string(),
3543 ty: TypeTag::Bool,
3544 docs: "True when callable in RPN position.",
3545 optional: false,
3546 default: None,
3547
3548 alias: None,}, Field {
3549 name: "summary".to_string(),
3550 ty: TypeTag::String,
3551 docs: "One-line description.",
3552 optional: false,
3553 default: None,
3554
3555 alias: None,}]))
3556 summary = "Describe one function by qualified name."
3557)]
3558#[example(
3559 name = "describe",
3560 code = r###"
3561 IMPORT [STD]
3562 LET $info: MAP<ANY> = DESCRIBE("STD::INT")
3563 ASSERT_EQ $info.name "STD::INT"
3564 ASSERT_EQ $info.returns "INT"
3565 "###
3566)]
3567fn describe<P: ProcessManager>(
3568 cx: &mut StepCtx<P>,
3569 name: String,
3571) -> Result<Value> {
3572 if split_qualified(&name).is_none() && name != KEYWORD_INSPECT {
3573 anyhow::bail!(
3574 "unknown function `{name}`: DESCRIBE requires a qualified name (e.g. `STD::{name}`)"
3575 );
3576 }
3577 cx.state
3578 .describe_function(&name)
3579 .ok_or_else(|| anyhow::anyhow!("unknown function {name}"))
3580}
3581
3582#[oxdock_func(returns = TypeTag::ListOf(std::sync::Arc::new(TypeTag::String)))]
3588#[example(
3589 name = "list",
3590 code = r###"
3591 IMPORT [STD]
3592 LET $names: LIST<STRING> = TYPES()
3593 ASSERT_CONTAINS $names "STRING"
3594 "###
3595)]
3596fn types<P: ProcessManager>(cx: &mut StepCtx<P>) -> Result<Value> {
3597 Ok(Value::list(
3598 cx.state
3599 .type_names()
3600 .into_iter()
3601 .map(Value::string)
3602 .collect(),
3603 ))
3604}
3605
3606#[oxdock_func(returns = TypeTag::Record(std::sync::Arc::from([Field {
3612 name: "name".to_string(),
3613 ty: TypeTag::String,
3614 docs: "Queried type name.",
3615 optional: false,
3616 default: None,
3617
3618 alias: None,}, Field {
3619 name: "summary".to_string(),
3620 ty: TypeTag::String,
3621 docs: "One-line description.",
3622 optional: false,
3623 default: None,
3624
3625 alias: None,}, Field {
3626 name: "docs".to_string(),
3627 ty: TypeTag::String,
3628 docs: "Full documentation text.",
3629 optional: false,
3630 default: None,
3631
3632 alias: None,}])))]
3633#[example(
3634 name = "describe",
3635 code = r###"
3636 IMPORT [STD]
3637 LET $info: MAP<ANY> = TYPE_DESCRIBE("STRING")
3638 ASSERT_EQ $info.name "STRING"
3639 "###
3640)]
3641fn type_describe<P: ProcessManager>(
3642 cx: &mut StepCtx<P>,
3643 name: String,
3645) -> Result<Value> {
3646 if let Some(descriptor) = cx.state.describe_type(&name) {
3647 let mut map = BTreeMap::new();
3648 map.insert(
3649 "name".to_string(),
3650 Value::string(descriptor.name.to_string()),
3651 );
3652 map.insert(
3653 "summary".to_string(),
3654 Value::string(descriptor.summary.to_string()),
3655 );
3656 map.insert(
3657 "docs".to_string(),
3658 Value::string(descriptor.docs.to_string()),
3659 );
3660 return Ok(Value::map(map));
3661 }
3662 if let Some(target) = cx.state.alias_target(&name) {
3665 let mut map = BTreeMap::new();
3666 map.insert("name".to_string(), Value::string(name.clone()));
3667 map.insert(
3668 "summary".to_string(),
3669 Value::string(format!("Script type alias for {target}.")),
3670 );
3671 map.insert(
3672 "docs".to_string(),
3673 Value::string(format!(
3674 "Declared with TYPE {name} = {target}. The alias expands structurally at every declaration."
3675 )),
3676 );
3677 return Ok(Value::map(map));
3678 }
3679 Err(anyhow::anyhow!("unknown type {name}"))
3680}
3681
3682#[oxdock_func(returns = TypeTag::String)]
3696#[example(
3697 name = "self",
3698 code = r###"
3699 # The running interpreter resolves to a non-empty path.
3700 IMPORT [STD]
3701 LET $exe: STRING = INTERPRETER()
3702 LET $nonempty: BOOL = $exe != ""
3703 ASSERT_EQ $nonempty true
3704 "###
3705)]
3706#[example(
3707 name = "dynamic assembly",
3708 code = r###"
3709 # Assemble the child script dynamically: the parent interpolates
3710 # its own bindings into the pipe, then runs the interpreter on it.
3711 # Unescaped {{ }} bakes in at render time; \{{ }} stays literal
3712 # so the child expands it with its own bindings.
3713 # The pipe delivers EOF when the producer step ends, so the child
3714 # reads exactly one script.
3715 IMPORT [STD]
3716 LET $exe: STRING = INTERPRETER()
3717 LET $who: STRING = "Ada"
3718 LET $child: PIPE
3719 WITH_IO [stdout=$child] ECHO """
3720 ECHO "hello {{ $who }}!"
3721 LET $who: STRING = "Grace"
3722 ECHO "child sees \{{ $who }}!"
3723 """
3724 LET $out: STRING = WITH_IO [stdin=$child] RUN [$exe]
3725 ASSERT_CONTAINS $out "hello Ada!"
3726 ASSERT_CONTAINS $out "child sees Grace!"
3727 "###
3728)]
3729fn interpreter<P: ProcessManager>(cx: &mut StepCtx<P>) -> Result<Value> {
3730 if let Some(staged) = cx.state.io.interpreter_override() {
3731 return Ok(Value::string(staged));
3732 }
3733 Ok(Value::string(oxdock_process::interpreter_exe()?))
3734}
3735
3736#[oxdock_func(returns = TypeTag::Bool)]
3744#[example(
3745 name = "main",
3746 code = r###"
3747 # Entry top level runs as main.
3748 IMPORT [STD]
3749 LET $m: BOOL = IS_MAIN()
3750 ASSERT_EQ $m true
3751 "###
3752)]
3753#[example(
3754 name = "library doubles as demo",
3755 fence_meta = "roots:unified",
3756 code = r###"
3757 # A library doubles as a runnable demo: guard the demo with
3758 # IF IS_MAIN() so importing it stays side effect free. The
3759 # parent writes both files, then runs each in a fresh
3760 # interpreter: direct execution prints the demo, importing
3761 # it does not. Unified roots: the child inherits one
3762 # workspace, so parent and child see the same files. The
3763 # exact stdout match proves the demo line stays out of the
3764 # importing run.
3765 IMPORT [STD]
3766
3767 # The library under test: demo guarded by IS_MAIN.
3768 WRITE lib.oxfile """
3769 IMPORT [STD]
3770 FUNC GREET($x: STRING): STRING { RETURN "hi \{{ $x }}" }
3771 EXPORT GREET
3772 IF IS_MAIN() {
3773 ECHO "demo: hi Ada"
3774 }
3775 """
3776
3777 # The importer: calls the library, prints only its own line.
3778 WRITE main.oxfile """
3779 IMPORT ["lib.oxfile" AS LIB]
3780 LET $g: STRING = LIB::GREET("Bo")
3781 ECHO "imported: \{{ $g }}"
3782 """
3783
3784 # Direct run executes the demo.
3785 LET $exe: STRING = INTERPRETER()
3786 LET $direct: STRING = RUN [$exe, "lib.oxfile"]
3787 ASSERT_CONTAINS $direct "demo: hi Ada"
3788
3789 # Importing run stays silent apart from its own line.
3790 LET $via: STRING = RUN [$exe, "main.oxfile"]
3791 ASSERT_EQ $via "imported: hi Bo\n"
3792 "###
3793)]
3794fn is_main<P: ProcessManager>(cx: &mut StepCtx<P>) -> Result<Value> {
3795 let main = match cx.state.module_stack.last() {
3796 None | Some(None) => true,
3797 Some(Some(_)) => false,
3798 };
3799 Ok(Value::bool(main))
3800}
3801
3802#[oxdock_func(returns = TypeTag::Bool)]
3816#[example(
3817 name = "null stdin",
3818 code = r###"
3819 # A null stdin is never a terminal, in every harness.
3820 IMPORT [STD]
3821 LET $term: BOOL = IS_TERMINAL("stdin")
3822 ASSERT_EQ $term false
3823 "###
3824)]
3825fn is_terminal<P: ProcessManager>(
3826 cx: &mut StepCtx<P>,
3827 #[values("stdin", "stdout", "stderr")]
3829 stream_name: String,
3830) -> Result<Value> {
3831 use std::io::IsTerminal;
3832 let terminal = match stream_name.as_str() {
3833 "stdin" => {
3834 if cx.stdin_pipe.is_some() {
3839 false
3840 } else {
3841 match &cx.stdin {
3842 CommandStdin::Null => false,
3843 #[cfg(not(miri))]
3844 CommandStdin::OsPipe(_) => false,
3845 CommandStdin::Stream(_) => false,
3846 CommandStdin::Inherit => std::io::stdin().is_terminal(),
3847 }
3848 }
3849 }
3850 "stdout" => {
3851 if cx.out_pipe.is_some() {
3852 false
3854 } else if cx.state.io.stdout().is_some() {
3855 false
3858 } else {
3859 match &cx.out {
3860 None => std::io::stdout().is_terminal(),
3862 #[cfg(not(miri))]
3864 Some(StreamHandle::Os(_)) => false,
3865 Some(StreamHandle::Stream(_)) => std::io::stdout().is_terminal(),
3875 }
3876 }
3877 }
3878 "stderr" => {
3879 if cx.state.io.stderr().is_some() {
3880 false
3882 } else {
3883 match &cx.err {
3884 None => std::io::stderr().is_terminal(),
3886 #[cfg(not(miri))]
3888 Some(StreamHandle::Os(_)) => false,
3889 Some(StreamHandle::Stream(_)) => false,
3892 }
3893 }
3894 }
3895 _ => anyhow::bail!(
3896 "IS_TERMINAL expects \"stdin\", \"stdout\", or \"stderr\", got {stream_name:?}"
3901 ),
3902 };
3903 Ok(Value::bool(terminal))
3904}
3905
3906#[oxdock_func(returns = TypeTag::Semaphore)]
3914#[example(
3915 name = "mint",
3916 code = r###"
3917 # Mint a semaphore admitting at most two holders.
3918 IMPORT [STD]
3919 LET $sem: SEMAPHORE = SEMAPHORE_NEW(2)
3920
3921 # A fresh semaphore reports its full cap as available.
3922 LET $free: INT = SEMAPHORE_AVAILABLE($sem)
3923 ASSERT_EQ $free 2
3924 "###
3925)]
3926fn semaphore_new<P: ProcessManager>(
3927 cx: &mut StepCtx<P>,
3928 max: i64,
3930) -> Result<Value> {
3931 let _ = cx;
3932 if max <= 0 {
3933 return Err(anyhow::anyhow!(
3934 "SEMAPHORE_NEW() requires a positive max, got {max}"
3935 ));
3936 }
3937 Ok(Value::semaphore(max as usize))
3938}
3939
3940#[oxdock_func(returns = TypeTag::Record(std::sync::Arc::from([Field {
3949 name: "held".to_string(),
3950 ty: TypeTag::Bool,
3951 docs: "`true` with the permit under `permit`, `false` with no `permit` key.",
3952 optional: false,
3953 default: None,
3954
3955 alias: None,}, Field {
3956 name: "permit".to_string(),
3957 ty: TypeTag::Permit,
3958 docs: "Permit handle; read only when `held`.",
3959 optional: true,
3960 default: None,
3961
3962 alias: None,}])))]
3963#[example(
3964 name = "acquire",
3965 code = r###"
3966 # First acquire holds with a permit to bind.
3967 IMPORT [STD]
3968 LET $sem: SEMAPHORE = SEMAPHORE_NEW(1)
3969 LET $first: MAP<held: BOOL, permit?: PERMIT> = SEMAPHORE_TRY_ACQUIRE($sem)
3970 ASSERT_EQ $first.held true
3971 LET $permit: PERMIT = $first.permit
3972
3973 # A capped semaphore answers held false with no permit key.
3974 LET $second: MAP<held: BOOL, permit?: PERMIT> = SEMAPHORE_TRY_ACQUIRE($sem)
3975 ASSERT_EQ $second.held false
3976 LET $has_permit: BOOL = HAS_KEY($second, "permit")
3977 ASSERT_EQ $has_permit false
3978 "###
3979)]
3980fn semaphore_try_acquire<P: ProcessManager>(
3981 cx: &mut StepCtx<P>,
3982 sem: Arc<SemaphoreState>,
3984) -> Result<Value> {
3985 let _ = cx;
3986 let mut map = BTreeMap::new();
3987 if sem.try_acquire() {
3988 map.insert("held".to_string(), Value::bool(true));
3989 map.insert("permit".to_string(), Value::permit(&sem));
3990 } else {
3991 map.insert("held".to_string(), Value::bool(false));
3992 }
3993 Ok(Value::map(map))
3994}
3995
3996#[oxdock_func(pure, returns = TypeTag::Int)]
4003#[example(
4004 name = "readout",
4005 code = r###"
4006 # Hold one permit on a cap of two.
4007 IMPORT [STD]
4008 LET $sem: SEMAPHORE = SEMAPHORE_NEW(2)
4009 LET $acq: MAP<held: BOOL, permit?: PERMIT> = SEMAPHORE_TRY_ACQUIRE($sem)
4010 ASSERT_EQ $acq.held true
4011
4012 # One held permit leaves exactly one free.
4013 LET $free: INT = SEMAPHORE_AVAILABLE($sem)
4014 ASSERT_EQ $free 1
4015 "###
4016)]
4017fn semaphore_available(
4018 sem: Arc<SemaphoreState>,
4020) -> Result<Value> {
4021 Ok(Value::int(sem.available() as i64))
4022}
4023
4024#[oxdock_func(
4033 rpn,
4034 returns = TypeTag::union(vec![TypeTag::String, TypeTag::Pipe]),
4035 template = text_trim_string
4036)]
4037#[example(
4038 name = "trim",
4039 code = r###"
4040 # Leading and trailing whitespace falls away.
4041 IMPORT [STD]
4042 LET $clean: STRING = TEXT_TRIM(" hello ")
4043 ASSERT_EQ $clean "hello"
4044 "###
4045)]
4046#[example(
4047 name = "trim pipe mirrors",
4048 code = r###"
4049 # Pipe input mints pipe output with the same transform.
4050 IMPORT [STD]
4051 LET $cap: PIPE
4052 WITH_IO [stdout=$cap] {
4053 ECHO " hello "
4054 }
4055 LET $out: PIPE = TEXT_TRIM($cap)
4056 WITH_IO [stdin=$out] READ_LINE $line
4057 ASSERT_EQ $line "hello"
4058 "###
4059)]
4060#[example(
4061 name = "trim template",
4062 code = r###"
4063 # String inputs run inside placeholders too.
4064 IMPORT [STD]
4065 LET $msg: STRING = 'clean:{{ STD::TEXT_TRIM(" hello ") }}'
4066 ASSERT_EQ $msg "clean:hello"
4067 "###
4068)]
4069#[example(
4070 name = "trim file template",
4071 code = r###"
4072 # EXPAND templates resolve the same registry.
4073 IMPORT [STD]
4074 WRITE "tpl.txt" "clean:\{{ STD::TEXT_TRIM(\" hello \") }}"
4075 LET $out: STRING = EXPAND "tpl.txt"
4076 ASSERT_EQ $out "clean:hello"
4077 "###
4078)]
4079fn text_trim<P: ProcessManager>(
4080 cx: &mut StepCtx<P>,
4081 #[union(String, Pipe)]
4083 text: Value,
4084) -> Result<Value> {
4085 super::args::mirror_stream(cx, "TEXT_TRIM", &text, super::args::TextPump::Trim)
4086}
4087
4088fn text_trim_string(text: Value) -> Result<Value> {
4091 super::args::mirror_string("TEXT_TRIM", &text, super::args::TextPump::Trim)
4092}
4093
4094#[oxdock_func(
4103 rpn,
4104 returns = TypeTag::union(vec![TypeTag::String, TypeTag::Pipe]),
4105 template = text_trim_prefix_string
4106)]
4107#[example(
4108 name = "strip prefix",
4109 code = r###"
4110 # A present prefix falls away; absence returns the input unchanged.
4111 IMPORT [STD]
4112 LET $bare: STRING = TEXT_TRIM_PREFIX("v1.2.3", "v")
4113 ASSERT_EQ $bare "1.2.3"
4114
4115 # Missing prefixes pass through untouched.
4116 LET $same: STRING = TEXT_TRIM_PREFIX("1.2.3", "v")
4117 ASSERT_EQ $same "1.2.3"
4118 "###
4119)]
4120#[example(
4121 name = "strip prefix pipe mirrors",
4122 code = r###"
4123 # Pipe input mints pipe output with the same strip.
4124 IMPORT [STD]
4125 LET $cap: PIPE
4126 WITH_IO [stdout=$cap] {
4127 ECHO "v1.2.3"
4128 }
4129 LET $trimmed: PIPE = TEXT_TRIM($cap)
4130 LET $out: PIPE = TEXT_TRIM_PREFIX($trimmed, "v")
4131 WITH_IO [stdin=$out] READ_LINE $line
4132 ASSERT_EQ $line "1.2.3"
4133 "###
4134)]
4135#[example(
4136 name = "strip prefix template",
4137 code = r###"
4138 # String inputs run inside placeholders too.
4139 IMPORT [STD]
4140 LET $msg: STRING = 'bare:{{ STD::TEXT_TRIM_PREFIX("v1.2.3", "v") }}'
4141 ASSERT_EQ $msg "bare:1.2.3"
4142 "###
4143)]
4144fn text_trim_prefix<P: ProcessManager>(
4145 cx: &mut StepCtx<P>,
4146 #[union(String, Pipe)]
4148 text: Value,
4149 prefix: String,
4151) -> Result<Value> {
4152 super::args::mirror_stream(
4153 cx,
4154 "TEXT_TRIM_PREFIX",
4155 &text,
4156 super::args::TextPump::TrimPrefix(prefix),
4157 )
4158}
4159
4160fn text_trim_prefix_string(text: Value, prefix: String) -> Result<Value> {
4163 super::args::mirror_string(
4164 "TEXT_TRIM_PREFIX",
4165 &text,
4166 super::args::TextPump::TrimPrefix(prefix),
4167 )
4168}
4169
4170#[oxdock_func(
4177 rpn,
4178 returns = TypeTag::union(vec![TypeTag::String, TypeTag::Pipe]),
4179 template = text_trim_suffix_string
4180)]
4181#[example(
4182 name = "strip suffix",
4183 code = r###"
4184 # A present suffix falls away; absence returns the input unchanged.
4185 IMPORT [STD]
4186 LET $bare: STRING = TEXT_TRIM_SUFFIX("archive.tar.gz", ".gz")
4187 ASSERT_EQ $bare "archive.tar"
4188
4189 # Missing suffixes pass through untouched.
4190 LET $same: STRING = TEXT_TRIM_SUFFIX("archive.tar", ".gz")
4191 ASSERT_EQ $same "archive.tar"
4192 "###
4193)]
4194#[example(
4195 name = "strip suffix pipe mirrors",
4196 code = r###"
4197 # Pipe input mints pipe output with the same strip.
4198 IMPORT [STD]
4199 LET $cap: PIPE
4200 WITH_IO [stdout=$cap] {
4201 ECHO "archive.tar.gz"
4202 }
4203 LET $trimmed: PIPE = TEXT_TRIM($cap)
4204 LET $out: PIPE = TEXT_TRIM_SUFFIX($trimmed, ".gz")
4205 WITH_IO [stdin=$out] READ_LINE $line
4206 ASSERT_EQ $line "archive.tar"
4207 "###
4208)]
4209#[example(
4210 name = "strip suffix template",
4211 code = r###"
4212 # String inputs run inside placeholders too.
4213 IMPORT [STD]
4214 LET $msg: STRING = 'bare:{{ STD::TEXT_TRIM_SUFFIX("archive.tar.gz", ".gz") }}'
4215 ASSERT_EQ $msg "bare:archive.tar"
4216 "###
4217)]
4218fn text_trim_suffix<P: ProcessManager>(
4219 cx: &mut StepCtx<P>,
4220 #[union(String, Pipe)]
4222 text: Value,
4223 suffix: String,
4225) -> Result<Value> {
4226 super::args::mirror_stream(
4227 cx,
4228 "TEXT_TRIM_SUFFIX",
4229 &text,
4230 super::args::TextPump::TrimSuffix(suffix),
4231 )
4232}
4233
4234fn text_trim_suffix_string(text: Value, suffix: String) -> Result<Value> {
4237 super::args::mirror_string(
4238 "TEXT_TRIM_SUFFIX",
4239 &text,
4240 super::args::TextPump::TrimSuffix(suffix),
4241 )
4242}
4243
4244#[oxdock_func(returns = TypeTag::String)]
4255#[example(
4256 name = "join path",
4257 code = r###"
4258 # Directory and file stem join with the native separator.
4259 # Source `\\` is one backslash at runtime; `/` works on Windows
4260 # too, native just reads better there.
4261 IMPORT [STD]
4262 LET $p: STRING = PATH_JOIN("some-dir", "some-file")
4263 [family:unix] ASSERT_EQ $p "some-dir/some-file"
4264 [family:windows] ASSERT_EQ $p "some-dir\\some-file"
4265 "###
4266)]
4267fn path_join<P: ProcessManager>(
4268 _cx: &mut StepCtx<P>,
4269 #[union(String, Path)]
4271 dir: Value,
4272 #[union(String, Path)]
4274 name: Value,
4275) -> Result<Value> {
4276 let d = super::args::string_or_path_text(&dir)?;
4277 let n = super::args::string_or_path_text(&name)?;
4278 Ok(Value::string(oxdock_fs::join_native(&d, &n)))
4279}
4280
4281#[oxdock_func(pure, returns = TypeTag::String)]
4289#[example(
4290 name = "base",
4291 code = r###"
4292 # Final segments bind without filesystem access.
4293 IMPORT [STD]
4294 LET $b: STRING = PATH_BASE("some-dir/some-file")
4295 ASSERT_EQ $b "some-file"
4296
4297 # Trailing slashes trim before the split.
4298 LET $d: STRING = PATH_BASE("some-dir/")
4299 ASSERT_EQ $d "some-dir"
4300 "###
4301)]
4302fn path_base(
4303 #[union(String, Path)]
4305 path: Value,
4306) -> Result<Value> {
4307 let text = super::args::string_or_path_text(&path)?;
4308 let base = oxdock_fs::path_base(&text).map_err(|e| anyhow::anyhow!("PATH_BASE: {e:#}"))?;
4309 Ok(Value::string(base))
4310}
4311
4312#[oxdock_func(pure, returns = TypeTag::String)]
4322#[example(
4323 name = "relativize",
4324 code = r###"
4325 # Prefix bases strip to their remainder.
4326 IMPORT [STD]
4327 LET $r: STRING = PATH_REL("some-dir", "some-dir/some-file")
4328 ASSERT_EQ $r "some-file"
4329
4330 # Equal paths bind dot.
4331 LET $dot: STRING = PATH_REL("some-dir", "some-dir")
4332 ASSERT_EQ $dot "."
4333 "###
4334)]
4335fn path_rel(
4336 #[union(String, Path)]
4338 base: Value,
4339 #[union(String, Path)]
4341 path: Value,
4342) -> Result<Value> {
4343 let b = super::args::string_or_path_text(&base)?;
4344 let p = super::args::string_or_path_text(&path)?;
4345 let rel = oxdock_fs::path_rel(&b, &p).map_err(|e| anyhow::anyhow!("PATH_REL: {e:#}"))?;
4346 Ok(Value::string(rel))
4347}
4348
4349#[oxdock_func(
4356 rpn,
4357 returns = TypeTag::union(vec![TypeTag::String, TypeTag::Pipe]),
4358 template = text_to_upper_string
4359)]
4360#[example(
4361 name = "uppercase",
4362 code = r###"
4363 # Text folds to uppercase.
4364 IMPORT [STD]
4365 LET $loud: STRING = TEXT_TO_UPPER("hello")
4366 ASSERT_EQ $loud "HELLO"
4367 "###
4368)]
4369#[example(
4370 name = "uppercase pipe mirrors",
4371 code = r###"
4372 # Pipe input mints pipe output with the same fold.
4373 IMPORT [STD]
4374 LET $cap: PIPE
4375 WITH_IO [stdout=$cap] {
4376 ECHO "hello"
4377 }
4378 LET $out: PIPE = TEXT_TO_UPPER($cap)
4379 WITH_IO [stdin=$out] READ_LINE $line
4380 ASSERT_EQ $line "HELLO"
4381 "###
4382)]
4383#[example(
4384 name = "uppercase template",
4385 code = r###"
4386 # String inputs run inside placeholders too.
4387 IMPORT [STD]
4388 LET $msg: STRING = 'loud:{{ STD::TEXT_TO_UPPER("hello") }}'
4389 ASSERT_EQ $msg "loud:HELLO"
4390 "###
4391)]
4392fn text_to_upper<P: ProcessManager>(
4393 cx: &mut StepCtx<P>,
4394 #[union(String, Pipe)]
4396 text: Value,
4397) -> Result<Value> {
4398 super::args::mirror_stream(cx, "TEXT_TO_UPPER", &text, super::args::TextPump::ToUpper)
4399}
4400
4401fn text_to_upper_string(text: Value) -> Result<Value> {
4404 super::args::mirror_string("TEXT_TO_UPPER", &text, super::args::TextPump::ToUpper)
4405}
4406
4407#[oxdock_func(
4414 rpn,
4415 returns = TypeTag::union(vec![TypeTag::String, TypeTag::Pipe]),
4416 template = text_to_lower_string
4417)]
4418#[example(
4419 name = "lowercase",
4420 code = r###"
4421 # Text folds to lowercase.
4422 IMPORT [STD]
4423 LET $quiet: STRING = TEXT_TO_LOWER("HELLO")
4424 ASSERT_EQ $quiet "hello"
4425 "###
4426)]
4427#[example(
4428 name = "lowercase pipe mirrors",
4429 code = r###"
4430 # Pipe input mints pipe output with the same fold.
4431 IMPORT [STD]
4432 LET $cap: PIPE
4433 WITH_IO [stdout=$cap] {
4434 ECHO "HELLO"
4435 }
4436 LET $out: PIPE = TEXT_TO_LOWER($cap)
4437 WITH_IO [stdin=$out] READ_LINE $line
4438 ASSERT_EQ $line "hello"
4439 "###
4440)]
4441#[example(
4442 name = "lowercase template",
4443 code = r###"
4444 # String inputs run inside placeholders too.
4445 IMPORT [STD]
4446 LET $msg: STRING = 'quiet:{{ STD::TEXT_TO_LOWER("HELLO") }}'
4447 ASSERT_EQ $msg "quiet:hello"
4448 "###
4449)]
4450fn text_to_lower<P: ProcessManager>(
4451 cx: &mut StepCtx<P>,
4452 #[union(String, Pipe)]
4454 text: Value,
4455) -> Result<Value> {
4456 super::args::mirror_stream(cx, "TEXT_TO_LOWER", &text, super::args::TextPump::ToLower)
4457}
4458
4459fn text_to_lower_string(text: Value) -> Result<Value> {
4462 super::args::mirror_string("TEXT_TO_LOWER", &text, super::args::TextPump::ToLower)
4463}
4464
4465#[oxdock_func(
4476 rpn,
4477 returns = TypeTag::union(vec![TypeTag::String, TypeTag::Pipe]),
4478 template = text_replace_string
4479)]
4480#[example(
4481 name = "replace",
4482 code = r###"
4483 # Every literal occurrence rewrites in place.
4484 IMPORT [STD]
4485 LET $fixed: STRING = TEXT_REPLACE("hello world", "world", "there")
4486 ASSERT_EQ $fixed "hello there"
4487 "###
4488)]
4489#[example(
4490 name = "replace pipe mirrors",
4491 code = r###"
4492 # Pipe input mints pipe output with the same rewrite.
4493 IMPORT [STD]
4494 LET $cap: PIPE
4495 WITH_IO [stdout=$cap] {
4496 ECHO "hello world"
4497 }
4498 LET $trimmed: PIPE = TEXT_TRIM($cap)
4499 LET $out: PIPE = TEXT_REPLACE($trimmed, "world", "there")
4500 WITH_IO [stdin=$out] READ_LINE $line
4501 ASSERT_EQ $line "hello there"
4502 "###
4503)]
4504#[example(
4505 name = "replace template",
4506 code = r###"
4507 # String inputs run inside placeholders too.
4508 IMPORT [STD]
4509 LET $msg: STRING = 'fixed:{{ STD::TEXT_REPLACE("hello world", "world", "there") }}'
4510 ASSERT_EQ $msg "fixed:hello there"
4511 "###
4512)]
4513fn text_replace<P: ProcessManager>(
4514 cx: &mut StepCtx<P>,
4515 #[union(String, Pipe)]
4517 text: Value,
4518 from: String,
4520 to: String,
4522) -> Result<Value> {
4523 super::args::mirror_stream(
4524 cx,
4525 "TEXT_REPLACE",
4526 &text,
4527 super::args::TextPump::ReplaceLiteral { from, to },
4528 )
4529}
4530
4531fn text_replace_string(text: Value, from: String, to: String) -> Result<Value> {
4534 super::args::mirror_string(
4535 "TEXT_REPLACE",
4536 &text,
4537 super::args::TextPump::ReplaceLiteral { from, to },
4538 )
4539}
4540
4541#[oxdock_func(
4553 rpn,
4554 returns = TypeTag::union(vec![TypeTag::String, TypeTag::Pipe]),
4555 template = text_replace_regex_string
4556)]
4557#[example(
4558 name = "replace with captures",
4559 code = r###"
4560 # Capture groups expand in the replacement.
4561 IMPORT [STD]
4562 LET $swapped: STRING = TEXT_REPLACE_REGEX("2026-10-13", "(\\d+)-(\\d+)-(\\d+)", "$3/$2/$1")
4563 ASSERT_EQ $swapped "13/10/2026"
4564 "###
4565)]
4566#[example(
4567 name = "replace regex pipe mirrors",
4568 code = r###"
4569 # Pipe input mints pipe output with the same rewrite.
4570 IMPORT [STD]
4571 LET $cap: PIPE
4572 WITH_IO [stdout=$cap] {
4573 ECHO "2026-10-13"
4574 }
4575 LET $trimmed: PIPE = TEXT_TRIM($cap)
4576 LET $out: PIPE = TEXT_REPLACE_REGEX($trimmed, "(\\d+)-(\\d+)-(\\d+)", "$3/$2/$1")
4577 WITH_IO [stdin=$out] READ_LINE $line
4578 ASSERT_EQ $line "13/10/2026"
4579 "###
4580)]
4581#[example(
4582 name = "replace regex template",
4583 code = r###"
4584 # String inputs run inside placeholders too.
4585 IMPORT [STD]
4586 LET $msg: STRING = 'swapped:{{ STD::TEXT_REPLACE_REGEX("2026-10-13", "(\\d+)-(\\d+)-(\\d+)", "$3/$2/$1") }}'
4587 ASSERT_EQ $msg "swapped:13/10/2026"
4588 "###
4589)]
4590fn text_replace_regex<P: ProcessManager>(
4591 cx: &mut StepCtx<P>,
4592 #[union(String, Pipe)]
4594 text: Value,
4595 pattern: String,
4597 replacement: String,
4599) -> Result<Value> {
4600 if let Some(s) = text.as_str() {
4601 let out =
4602 super::args::text_replace_regex_str(s, &pattern, &replacement, "TEXT_REPLACE_REGEX")?;
4603 return Ok(Value::string(out));
4604 }
4605 let content = super::args::read_pipe_eager(cx, "TEXT_REPLACE_REGEX", &text)?;
4606 let out = super::args::text_replace_regex_str(
4607 &content,
4608 &pattern,
4609 &replacement,
4610 "TEXT_REPLACE_REGEX",
4611 )?;
4612 super::args::write_completed_pipe(cx, "TEXT_REPLACE_REGEX", out)
4613}
4614
4615fn text_replace_regex_string(text: Value, pattern: String, replacement: String) -> Result<Value> {
4618 let Some(s) = text.as_str() else {
4619 return Err(super::args::pipe_needs_step_io("TEXT_REPLACE_REGEX"));
4620 };
4621 let out = super::args::text_replace_regex_str(s, &pattern, &replacement, "TEXT_REPLACE_REGEX")?;
4622 Ok(Value::string(out))
4623}
4624
4625#[oxdock_func(pure, returns = TypeTag::ListOf(std::sync::Arc::new(TypeTag::String)))]
4633#[example(
4634 name = "split",
4635 code = r###"
4636 # Delimiters split into list items.
4637 IMPORT [STD]
4638 LET $parts: LIST<STRING> = TEXT_SPLIT("a,b,c", ",")
4639 ASSERT_EQ $parts.0 "a"
4640 ASSERT_EQ $parts.1 "b"
4641 ASSERT_EQ $parts.2 "c"
4642 "###
4643)]
4644fn text_split(
4645 text: String,
4647 delimiter: String,
4649) -> Result<Value> {
4650 Ok(super::args::text_list_value(super::args::text_split_str(
4651 &text, &delimiter,
4652 )))
4653}
4654
4655#[oxdock_func(pure, returns = TypeTag::String)]
4658#[example(
4659 name = "join",
4660 code = r###"
4661 # List items join with the separator between them.
4662 IMPORT [STD]
4663 LET $joined: STRING = TEXT_JOIN(["a", "b", "c"], ",")
4664 ASSERT_EQ $joined "a,b,c"
4665 "###
4666)]
4667fn text_join(
4668 elements: Vec<String>,
4670 delimiter: String,
4672) -> Result<Value> {
4673 Ok(Value::string(elements.join(delimiter.as_str())))
4674}
4675
4676#[oxdock_func(pure, returns = TypeTag::ListOf(std::sync::Arc::new(TypeTag::String)))]
4688#[example(
4689 name = "split args",
4690 code = r###"
4691 # Quoted segments stay one word.
4692 IMPORT [STD]
4693 LET $argv: LIST<STRING> = SHELL_SPLIT_ARGS("gh issue comment 153 --body-file notes.md")
4694 ASSERT_EQ $argv.0 "gh"
4695 ASSERT_EQ $argv.3 "153"
4696 ASSERT_EQ $argv.5 "notes.md"
4697
4698 # Quotes and escapes parse the shell way.
4699 LET $quoted: LIST<STRING> = SHELL_SPLIT_ARGS("say \"hi there\" 'a b'")
4700 ASSERT_EQ $quoted.0 "say"
4701 ASSERT_EQ $quoted.1 "hi there"
4702 ASSERT_EQ $quoted.2 "a b"
4703 "###
4704)]
4705fn shell_split_args(
4706 command: String,
4708) -> Result<Value> {
4709 match shell_words::split(&command) {
4710 Ok(words) => Ok(super::args::text_list_value(words)),
4711 Err(err) => anyhow::bail!("SHELL_SPLIT_ARGS: {err}"),
4712 }
4713}
4714
4715#[oxdock_func(pure, returns = TypeTag::String)]
4723#[example(
4724 name = "join args",
4725 code = r###"
4726 # Plain words join with spaces and no quoting.
4727 IMPORT [STD]
4728 LET $plain: STRING = SHELL_JOIN_ARGS(["gh", "issue", "list"])
4729 ASSERT_EQ $plain "gh issue list"
4730
4731 # Words with spaces quote, and the round trip is exact.
4732 LET $words: LIST<STRING> = ["say", "hi there", "a'b"]
4733 LET $joined: STRING = SHELL_JOIN_ARGS($words)
4734 LET $back: LIST<STRING> = SHELL_SPLIT_ARGS($joined)
4735 ASSERT_EQ $back.0 "say"
4736 ASSERT_EQ $back.1 "hi there"
4737 ASSERT_EQ $back.2 "a'b"
4738 "###
4739)]
4740fn shell_join_args(
4741 words: Vec<String>,
4743) -> Result<Value> {
4744 Ok(Value::string(shell_words::join(&words)))
4745}
4746
4747#[oxdock_func(pure, returns = TypeTag::ListOf(std::sync::Arc::new(TypeTag::String)))]
4755#[example(
4756 name = "lines",
4757 code = r###"
4758 # Newlines split into line items.
4759 IMPORT [STD]
4760 LET $lines: LIST<STRING> = TEXT_LINES("one\ntwo\nthree")
4761 ASSERT_EQ $lines.0 "one"
4762 ASSERT_EQ $lines.1 "two"
4763 ASSERT_EQ $lines.2 "three"
4764
4765 # Windows endings split the same way after normalization.
4766 LET $crlf: LIST<STRING> = TEXT_LINES("one\r\ntwo\r\nthree")
4767 ASSERT_EQ $crlf.0 "one"
4768 ASSERT_EQ $crlf.1 "two"
4769 ASSERT_EQ $crlf.2 "three"
4770
4771 # Old Mac endings split too, and mixed endings split together because the input normalizes to LF before splitting.
4772 LET $mixed: LIST<STRING> = TEXT_LINES("a\r\nb\nc\rd")
4773 ASSERT_EQ $mixed.0 "a"
4774 ASSERT_EQ $mixed.1 "b"
4775 ASSERT_EQ $mixed.2 "c"
4776 ASSERT_EQ $mixed.3 "d"
4777 "###
4778)]
4779fn text_lines(
4780 text: String,
4782) -> Result<Value> {
4783 Ok(super::args::text_list_value(super::args::text_lines_str(
4784 &text,
4785 )))
4786}
4787
4788#[oxdock_func(pure, returns = TypeTag::ListOf(std::sync::Arc::new(TypeTag::String)))]
4794#[example(
4795 name = "fields",
4796 code = r###"
4797 # Runs of whitespace separate fields; empties never appear.
4798 IMPORT [STD]
4799 LET $fields: LIST<STRING> = TEXT_FIELDS(" abc def ")
4800 ASSERT_EQ $fields.0 "abc"
4801 ASSERT_EQ $fields.1 "def"
4802 "###
4803)]
4804fn text_fields(
4805 text: String,
4807) -> Result<Value> {
4808 Ok(super::args::text_list_value(super::args::text_fields_str(
4809 &text,
4810 )))
4811}
4812
4813#[oxdock_func(pure, returns = TypeTag::ListOf(std::sync::Arc::new(TypeTag::String)))]
4822#[example(
4823 name = "line range",
4824 code = r###"
4825 # Lines 2 through 3 come back as a list, 1-based inclusive.
4826 IMPORT [STD]
4827 LET $window: LIST<STRING> = TEXT_LINES_RANGE("one\ntwo\nthree\nfour", 2, 3)
4828 ASSERT_EQ $window.0 "two"
4829 ASSERT_EQ $window.1 "three"
4830
4831 # Ranges past the end clamp instead of failing.
4832 LET $tail: LIST<STRING> = TEXT_LINES_RANGE("one\ntwo", 2, 9)
4833 ASSERT_EQ $tail.0 "two"
4834 "###
4835)]
4836fn text_lines_range(
4837 text: String,
4839 from: i64,
4841 to: i64,
4843) -> Result<Value> {
4844 Ok(super::args::text_list_value(
4845 super::args::text_lines_range_str(&text, from, to, "TEXT_LINES_RANGE")?,
4846 ))
4847}
4848
4849#[oxdock_func(pure, returns = TypeTag::Bool)]
4857#[example(
4858 name = "match",
4859 code = r###"
4860 # Regex matches report true; misses report false.
4861 IMPORT [STD]
4862 LET $hit: BOOL = TEXT_MATCH("abc123", "\\d+")
4863 ASSERT_EQ $hit true
4864
4865 # A miss is false, not a failure.
4866 LET $miss: BOOL = TEXT_MATCH("abc", "^\\d+$")
4867 ASSERT_EQ $miss false
4868 "###
4869)]
4870fn text_match(
4871 text: String,
4873 pattern: String,
4875) -> Result<Value> {
4876 let re = super::args::text_compile_pattern("TEXT_MATCH", &pattern)?;
4877 Ok(Value::bool(re.is_match(&text)))
4878}
4879
4880#[oxdock_func(pure, name = "BOOL", returns = TypeTag::Bool)]
4889#[example(
4890 name = "convert",
4891 code = r###"
4892 IMPORT [STD]
4893 LET $n: BOOL = BOOL("yes")
4894 ASSERT_EQ $n true
4895 LET $f: BOOL = BOOL("0")
4896 ASSERT_EQ $f false
4897 "###
4898)]
4899fn bool_convert(
4900 #[union(Bool, String)]
4902 val: Value,
4903) -> Result<Value> {
4904 if let Some(b) = val.as_bool() {
4905 return Ok(Value::bool(b));
4906 }
4907 let Some(s) = val.as_str() else {
4908 return Err(anyhow::anyhow!(
4909 "BOOL needs a Bool or String, found {val:?}"
4910 ));
4911 };
4912 match super::args::parse_bool_str(s) {
4913 Some(b) => Ok(Value::bool(b)),
4914 None => anyhow::bail!("BOOL cannot coerce {s:?} to BOOL"),
4915 }
4916}
4917
4918#[oxdock_func(pure, returns = TypeTag::Bool)]
4928#[example(
4929 name = "absent-default",
4930 code = r###"
4931 # Absent names read empty; the default settles the polarity.
4932 IMPORT [STD]
4933 INHERIT_ENV [OXDOCK_TEST_ABSENT_FLAG]
4934 LET $dry: BOOL = BOOL_OR("{{ env:OXDOCK_TEST_ABSENT_FLAG }}", true)
4935 ASSERT_EQ $dry true
4936
4937 # Present values coerce strictly, ignoring the default.
4938 LET $off: BOOL = BOOL_OR("false", true)
4939 ASSERT_EQ $off false
4940 "###
4941)]
4942fn bool_or(
4943 text: String,
4945 default: bool,
4947) -> Result<Value> {
4948 if text.trim().is_empty() {
4949 return Ok(Value::bool(default));
4950 }
4951 match super::args::parse_bool_str(&text) {
4952 Some(b) => Ok(Value::bool(b)),
4953 None => anyhow::bail!("BOOL_OR cannot coerce {text:?} to BOOL"),
4954 }
4955}
4956
4957#[oxdock_func(pure, returns = TypeTag::ListOf(std::sync::Arc::new(TypeTag::String)))]
4966#[example(
4967 name = "extract",
4968 code = r###"
4969 # Index zero is the full match; groups follow in order.
4970 IMPORT [STD]
4971 LET $caps: LIST<STRING> = TEXT_EXTRACT("abc123", "([a-z]+)(\\d+)")
4972 ASSERT_EQ $caps.0 "abc123"
4973 ASSERT_EQ $caps.1 "abc"
4974 ASSERT_EQ $caps.2 "123"
4975 "###
4976)]
4977fn text_extract(
4978 text: String,
4980 pattern: String,
4982) -> Result<Value> {
4983 let groups = super::args::text_extract_str(&text, &pattern, "TEXT_EXTRACT")?;
4984 Ok(super::args::text_list_value(groups))
4985}
4986
4987#[oxdock_func(pure, returns = TypeTag::Bool)]
4994#[example(
4995 name = "starts with",
4996 code = r###"
4997 # Present prefixes report true; misses report false.
4998 IMPORT [STD]
4999 LET $hit: BOOL = TEXT_STARTS_WITH("linux-musl-x64", "linux")
5000 ASSERT_EQ $hit true
5001
5002 # A miss is false, not a failure.
5003 LET $miss: BOOL = TEXT_STARTS_WITH("macos-arm", "linux")
5004 ASSERT_EQ $miss false
5005 "###
5006)]
5007fn text_starts_with(
5008 text: String,
5010 prefix: String,
5012) -> Result<Value> {
5013 Ok(Value::bool(text.starts_with(prefix.as_str())))
5014}
5015
5016#[oxdock_func(pure, returns = TypeTag::Bool)]
5023#[example(
5024 name = "ends with",
5025 code = r###"
5026 # Present suffixes report true; misses report false.
5027 IMPORT [STD]
5028 LET $hit: BOOL = TEXT_ENDS_WITH("x86_64-linux-musl", "linux-musl")
5029 ASSERT_EQ $hit true
5030
5031 # A miss is false, not a failure.
5032 LET $miss: BOOL = TEXT_ENDS_WITH("x86_64-linux-gnu", "linux-musl")
5033 ASSERT_EQ $miss false
5034 "###
5035)]
5036fn text_ends_with(
5037 text: String,
5039 suffix: String,
5041) -> Result<Value> {
5042 Ok(Value::bool(text.ends_with(suffix.as_str())))
5043}
5044
5045#[oxdock_func(pure, returns = TypeTag::Bool)]
5055#[example(
5056 name = "contains",
5057 code = r###"
5058 # Present needles report true; misses report false.
5059 IMPORT [STD]
5060 LET $hit: BOOL = CONTAINS("x86_64-linux-musl", "musl")
5061 ASSERT_EQ $hit true
5062
5063 # A miss is false, not a failure.
5064 LET $miss: BOOL = CONTAINS("x86_64-linux-gnu", "musl")
5065 ASSERT_EQ $miss false
5066 "###
5067)]
5068#[example(
5069 name = "contains list",
5070 code = r###"
5071 # List membership uses strict equality across any element type.
5072 IMPORT [STD]
5073 LET $hit: BOOL = CONTAINS(["a", "b", "c"], "b")
5074 ASSERT_EQ $hit true
5075 LET $miss: BOOL = CONTAINS(["a", "b", "c"], "z")
5076 ASSERT_EQ $miss false
5077 LET $num: BOOL = CONTAINS([1, 2, 3], 2.0)
5078 ASSERT_EQ $num true
5079
5080 # Stringified numbers never coerce to integers.
5081 LET $strnum: BOOL = CONTAINS(["1", "2", "3"], 2)
5082 ASSERT_EQ $strnum false
5083
5084 # Boolean lists match true and miss false with no coercion.
5085 LET $bools: LIST<BOOL> = [true]
5086 LET $bhit: BOOL = CONTAINS($bools, true)
5087 ASSERT_EQ $bhit true
5088 LET $bmiss: BOOL = CONTAINS($bools, false)
5089 ASSERT_EQ $bmiss false
5090 LET $nocoerce: BOOL = CONTAINS($bools, 1)
5091 ASSERT_EQ $nocoerce false
5092 "###
5093)]
5094fn contains(
5095 #[union(String, List)]
5097 haystack: Value,
5098 needle: Value,
5100) -> Result<Value> {
5101 if let Some(text) = haystack.as_str() {
5102 let Some(n) = needle.as_str() else {
5103 return Err(anyhow::anyhow!(
5104 "CONTAINS needs a STRING needle for a STRING haystack, found {}",
5105 needle.type_name()
5106 ));
5107 };
5108 return Ok(Value::bool(text.contains(n)));
5109 }
5110 if let Some(items) = haystack.as_list() {
5111 for item in items {
5112 if super::args::values_equal(item, &needle) {
5113 return Ok(Value::bool(true));
5114 }
5115 }
5116 return Ok(Value::bool(false));
5117 }
5118 Err(anyhow::anyhow!(
5119 "CONTAINS needs a STRING or LIST haystack, found {}",
5120 haystack.type_name()
5121 ))
5122}
5123
5124#[oxdock_func(pure, returns = TypeTag::List)]
5132#[example(
5133 name = "deduplicate",
5134 code = r###"
5135 # First occurrences win, later repeats drop.
5136 IMPORT [STD]
5137 LET $seen: LIST<STRING> = UNIQUE(["a", "b", "a", "c", "b"])
5138 ASSERT_EQ $seen.0 "a"
5139 ASSERT_EQ $seen.1 "b"
5140 ASSERT_EQ $seen.2 "c"
5141 ASSERT_EQ LEN($seen) 3
5142
5143 # The empty list stays empty.
5144 LET $empty: LIST<STRING> = UNIQUE([])
5145 ASSERT_EQ LEN($empty) 0
5146 "###
5147)]
5148#[example(
5149 name = "strict membership",
5150 code = r###"
5151 # Numerics collapse across INT and FLOAT like CONTAINS.
5152 IMPORT [STD]
5153 LET $nums: LIST<ANY> = UNIQUE([1, 2.0, 1, 3])
5154 ASSERT_EQ $nums.0 1
5155 ASSERT_EQ $nums.1 2.0
5156 ASSERT_EQ $nums.2 3
5157 ASSERT_EQ LEN($nums) 3
5158
5159 # Stringified numbers never coerce to integers.
5160 LET $mixed: LIST<ANY> = UNIQUE(["1", 1])
5161 ASSERT_EQ $mixed.0 "1"
5162 ASSERT_EQ $mixed.1 1
5163 ASSERT_EQ LEN($mixed) 2
5164 "###
5165)]
5166fn unique(
5167 items: Vec<Value>,
5169) -> Result<Value> {
5170 let mut out: Vec<Value> = Vec::with_capacity(items.len());
5171 for item in items {
5172 if !out
5173 .iter()
5174 .any(|seen| super::args::values_equal(seen, &item))
5175 {
5176 out.push(item);
5177 }
5178 }
5179 Ok(Value::list(out))
5180}
5181
5182#[oxdock_func(pure, returns = TypeTag::Int)]
5191#[example(
5192 name = "length",
5193 code = r###"
5194 # Plain text counts one per character.
5195 IMPORT [STD]
5196 LET $n: INT = LEN("hello")
5197 ASSERT_EQ $n 5
5198
5199 # Multibyte characters count once each, not per byte.
5200 LET $wide: INT = LEN("héllo")
5201 ASSERT_EQ $wide 5
5202
5203 # Lists count elements, maps count entries.
5204 LET $items: LIST<STRING> = ["a", "b", "c"]
5205 LET $nitems: INT = LEN($items)
5206 ASSERT_EQ $nitems 3
5207 LET $row: MAP<name: STRING> = {name: "ada"}
5208 LET $nkeys: INT = LEN($row)
5209 ASSERT_EQ $nkeys 1
5210 LET $empty: INT = LEN([])
5211 ASSERT_EQ $empty 0
5212 "###
5213)]
5214fn len(
5215 #[union(String, List, Map)]
5217 value: Value,
5218) -> Result<Value> {
5219 if let Some(text) = value.as_str() {
5220 return Ok(Value::int(text.chars().count() as i64));
5221 }
5222 if let Some(items) = value.as_list() {
5223 return Ok(Value::int(items.len() as i64));
5224 }
5225 if let Some(entries) = value.as_map() {
5226 return Ok(Value::int(entries.len() as i64));
5227 }
5228 Err(anyhow::anyhow!(
5229 "LEN needs a STRING, LIST, or MAP value, got {}",
5230 value.type_name()
5231 ))
5232}
5233
5234#[oxdock_func(pure, returns = TypeTag::Int)]
5242#[example(
5243 name = "count",
5244 code = r###"
5245 # Every non-overlapping occurrence counts once.
5246 IMPORT [STD]
5247 LET $n: INT = TEXT_COUNT("hello world", "o")
5248 ASSERT_EQ $n 2
5249
5250 # Overlapping candidates never double count.
5251 LET $once: INT = TEXT_COUNT("aaa", "aa")
5252 ASSERT_EQ $once 1
5253 "###
5254)]
5255fn text_count(
5256 text: String,
5258 needle: String,
5260) -> Result<Value> {
5261 let n = super::args::text_count_str(&text, &needle, "TEXT_COUNT")?;
5262 Ok(Value::int(n))
5263}
5264
5265#[oxdock_func(pure, returns = TypeTag::Int)]
5275#[example(
5276 name = "count matches",
5277 code = r###"
5278 # One line matches once no matter how many times it hits.
5279 IMPORT [STD]
5280 LET $n: INT = TEXT_COUNT_MATCHES("test a: test\ntest b: nope\ntest c: test", ": test")
5281 ASSERT_EQ $n 2
5282
5283 # A miss binds zero, never an error.
5284 LET $none: INT = TEXT_COUNT_MATCHES("test b: nope", ": test$")
5285 ASSERT_EQ $none 0
5286 "###
5287)]
5288fn text_count_matches(
5289 text: String,
5291 pattern: String,
5293) -> Result<Value> {
5294 let n = super::args::text_count_matches_str(&text, &pattern, "TEXT_COUNT_MATCHES")?;
5295 Ok(Value::int(n))
5296}
5297
5298#[oxdock_func(pure, returns = TypeTag::ListOf(std::sync::Arc::new(TypeTag::String)))]
5311#[example(
5312 name = "grep",
5313 code = r###"
5314 # Matching lines come back as a list, in order.
5315 IMPORT [STD]
5316 LET $hits: LIST<STRING> = TEXT_GREP("one\ntwo\none more", "^one")
5317 ASSERT_EQ $hits.0 "one"
5318 ASSERT_EQ $hits.1 "one more"
5319
5320 # A miss binds an empty list, never an error.
5321 LET $miss: LIST<STRING> = TEXT_GREP("one\ntwo", "^z")
5322 LET $joined: STRING = TEXT_JOIN($miss, ",")
5323 ASSERT_EQ $joined ""
5324
5325 # The (?i) flag ignores case, so uppercase lines match too.
5326 LET $folded: LIST<STRING> = TEXT_GREP("One\ntwo\nONE more", "(?i)^one")
5327 ASSERT_EQ $folded.0 "One"
5328 ASSERT_EQ $folded.1 "ONE more"
5329 "###
5330)]
5331#[example(
5332 name = "grep invert",
5333 code = r###"
5334 # The invert option keeps every non-matching line instead.
5335 IMPORT [STD]
5336 LET $kept: LIST<STRING> = TEXT_GREP("one\ntwo\none more", "^one", {invert: true})
5337 ASSERT_EQ $kept.0 "two"
5338
5339 # A pattern matching every line binds an empty list, never an error.
5340 LET $none: LIST<STRING> = TEXT_GREP("one\ntwo", "^", {invert: true})
5341 LET $joined: STRING = TEXT_JOIN($none, ",")
5342 ASSERT_EQ $joined ""
5343
5344 # Options ride into placeholders as MAP literals. Placeholder
5345 # strings unescape only backslash and quote, so multiline text
5346 # arrives through a variable.
5347 LET $two_lines: STRING = "one\ntwo"
5348 LET $msg: STRING = 'kept:{{ STD::TEXT_GREP($two_lines, "^one", {invert: true}) }}'
5349 ASSERT_EQ $msg "kept:two"
5350 "###
5351)]
5352fn text_grep(
5353 text: String,
5355 pattern: String,
5357 #[options("invert?: BOOL")]
5359 #[optional]
5360 options: BTreeMap<String, Value>,
5361) -> Result<Value> {
5362 let invert = super::args::text_invert_flag(&options);
5365 Ok(super::args::text_list_value(super::args::text_grep_str(
5366 &text,
5367 &pattern,
5368 invert,
5369 "TEXT_GREP",
5370 )?))
5371}
5372
5373#[oxdock_func(returns = TypeTag::Bool)]
5384#[example(
5385 name = "drain to end",
5386 code = r###"
5387 # Capture two lines, then drain to end of stream with no sentinel line.
5388 IMPORT [STD]
5389 LET $cap: PIPE
5390 WITH_IO [stdout=$cap] {
5391 ECHO "one"
5392 ECHO "two"
5393 }
5394
5395 # The loop exits on close, and the count proves both lines drained.
5396 LET $n: INT = 0
5397 WHILE !EOF($cap) {
5398 WITH_IO [stdin=$cap] READ_LINE $line
5399 $n = $n + 1
5400 }
5401 ASSERT_EQ $n 2
5402 "###
5403)]
5404fn eof<P: ProcessManager>(
5405 cx: &mut StepCtx<P>,
5406 pipe: PipeHandle,
5408) -> Result<Value> {
5409 let info = cx.state.io.inspect_pipe(&pipe);
5410 Ok(Value::bool(info.closed && info.buffered == 0))
5411}
5412
5413fn task_poll_result_fields() -> Arc<[Field]> {
5417 Arc::from(vec![
5418 Field {
5419 name: "state".to_string(),
5420 ty: TypeTag::String,
5421 docs: "Task phase: `running` or `finished`.",
5422 optional: false,
5423 default: None,
5424
5425 alias: None,
5426 },
5427 Field {
5428 name: "ok".to_string(),
5429 ty: TypeTag::Bool,
5430 docs: "True unless the task failed.",
5431 optional: false,
5432 default: None,
5433
5434 alias: None,
5435 },
5436 Field {
5437 name: "stdout_tail".to_string(),
5438 ty: TypeTag::String,
5439 docs: "Bounded stdout tail, live while running.",
5440 optional: false,
5441 default: None,
5442
5443 alias: None,
5444 },
5445 Field {
5446 name: "stderr_tail".to_string(),
5447 ty: TypeTag::String,
5448 docs: "Bounded stderr tail, live while running.",
5449 optional: false,
5450 default: None,
5451
5452 alias: None,
5453 },
5454 Field {
5455 name: "truncated_bytes".to_string(),
5456 ty: TypeTag::Int,
5457 docs: "Dropped head bytes past the per-stream cap.",
5458 optional: false,
5459 default: None,
5460
5461 alias: None,
5462 },
5463 Field {
5464 name: "exit_code".to_string(),
5465 ty: TypeTag::Int,
5466 docs: "Process exit code, present once finished.",
5467 optional: true,
5468 default: None,
5469
5470 alias: None,
5471 },
5472 Field {
5473 name: "result".to_string(),
5474 ty: TypeTag::Any,
5475 docs: "Task `RETURN` value, present on clean finish.",
5476 optional: true,
5477 default: None,
5478
5479 alias: None,
5480 },
5481 Field {
5482 name: "error".to_string(),
5483 ty: TypeTag::String,
5484 docs: "Failure text, present on failed finish.",
5485 optional: true,
5486 default: None,
5487
5488 alias: None,
5489 },
5490 ])
5491}
5492
5493#[oxdock_func(returns = TypeTag::Record(task_poll_result_fields()))]
5506#[example(
5507 name = "running poll",
5508 code = r###"
5509 # A sleeping task is still running on the first poll.
5510 IMPORT [STD]
5511 LET $t: HANDLE<STRING> = ASYNC { SLEEP 30s; RETURN "done" }
5512 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)
5513 ASSERT_EQ $m.state "running"
5514 ASSERT_EQ $m.ok true
5515 # Clean up the sleeper so the run ends promptly.
5516 CANCEL $t
5517 "###
5518)]
5519#[example(
5520 name = "finished poll",
5521 code = r###"
5522 # A finished task reports its value and final tails, then still awaits.
5523 IMPORT [STD]
5524 LET $t: HANDLE<STRING> = ASYNC { ECHO "hi"; SLEEP 1s; RETURN "done" }
5525 # Do other work while the task runs; poll once it should be done.
5526 SLEEP 2s
5527 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)
5528 ASSERT_EQ $m.state "finished"
5529 ASSERT_EQ $m.result "done"
5530 LET $o: STRING = AWAIT $t
5531 ASSERT_EQ $o "done"
5532 "###
5533)]
5534fn task_poll<P: ProcessManager>(
5535 cx: &mut StepCtx<P>,
5536 task: HandleValue,
5538) -> Result<Value> {
5539 let entry =
5540 super::handlers::resolve_task_entry_by_id(task.0, &format!("TASK_POLL({})", task.0), cx)?;
5541 let obs = entry.observe_completion();
5542 let (stdout_tail, stderr_tail, dropped) = entry.snapshot_tails();
5543 let mut out = BTreeMap::new();
5544 out.insert(
5545 "state".to_string(),
5546 Value::string(if obs.running { "running" } else { "finished" }.to_string()),
5547 );
5548 out.insert("ok".to_string(), Value::bool(obs.ok));
5549 if !obs.running {
5550 out.insert("exit_code".to_string(), Value::int(obs.exit_code));
5551 }
5552 if let Some(result) = obs.result {
5553 out.insert("result".to_string(), result);
5554 }
5555 if !obs.error.is_empty() {
5556 out.insert("error".to_string(), Value::string(obs.error));
5557 }
5558 out.insert("stdout_tail".to_string(), Value::string(stdout_tail));
5559 out.insert("stderr_tail".to_string(), Value::string(stderr_tail));
5560 out.insert(
5561 "truncated_bytes".to_string(),
5562 Value::int(dropped.min(i64::MAX as u64) as i64),
5563 );
5564 Ok(Value::map(out))
5565}
5566
5567fn meta_to_value(meta: &FuncMeta) -> Value {
5568 let mut map = BTreeMap::new();
5569 map.insert("name".to_string(), Value::string(meta.name.clone()));
5570 map.insert("module".to_string(), Value::string(meta.module.clone()));
5571 map.insert(
5572 "kind".to_string(),
5573 Value::string(meta.kind.label().to_string()),
5574 );
5575 let params = match &meta.params {
5576 Some(params) => Value::list(
5577 params
5578 .iter()
5579 .map(|p| {
5580 let mut entry = BTreeMap::new();
5581 entry.insert("name".to_string(), Value::string(p.name.clone()));
5582 entry.insert(
5583 "param_type".to_string(),
5584 Value::string(
5585 p.param_type
5586 .as_ref()
5587 .map(render_structural)
5588 .unwrap_or_default(),
5589 ),
5590 );
5591 entry.insert(
5592 "allowed".to_string(),
5593 Value::string(
5594 p.allowed
5595 .map(|values| values.join(", "))
5596 .unwrap_or_default(),
5597 ),
5598 );
5599 entry.insert("docs".to_string(), Value::string(String::new()));
5600 entry.insert("optional".to_string(), Value::bool(p.optional));
5601 entry.insert(
5602 "options".to_string(),
5603 match p.options {
5604 Some(keys) => Value::list(
5605 keys.iter()
5606 .map(|key| {
5607 let mut option = BTreeMap::new();
5608 option.insert(
5609 "name".to_string(),
5610 Value::string(key.name.to_string()),
5611 );
5612 option.insert(
5613 "value_type".to_string(),
5614 Value::string(render_structural(&key.value)),
5615 );
5616 option.insert(
5617 "required".to_string(),
5618 Value::bool(key.required),
5619 );
5620 option.insert(
5621 "default".to_string(),
5622 Value::string(
5623 key.default.unwrap_or_default().to_string(),
5624 ),
5625 );
5626 Value::map(option)
5627 })
5628 .collect(),
5629 ),
5630 None => Value::string(String::new()),
5631 },
5632 );
5633 Value::map(entry)
5634 })
5635 .collect(),
5636 ),
5637 None => Value::list(Vec::new()),
5641 };
5642 map.insert("params".to_string(), params);
5643 map.insert(
5644 "returns".to_string(),
5645 Value::string(
5646 meta.returns
5647 .as_ref()
5648 .map(render_structural)
5649 .unwrap_or_default(),
5650 ),
5651 );
5652 map.insert("rpn".to_string(), Value::bool(meta.rpn));
5653 map.insert(
5654 "summary".to_string(),
5655 Value::string(meta.summary.to_string()),
5656 );
5657 Value::map(map)
5658}
5659
5660#[derive(Debug, Clone)]
5664pub struct RecordSchema {
5665 pub name: &'static str,
5666 pub fields: std::sync::Arc<[Field]>,
5667}
5668
5669#[derive(Clone)]
5673pub struct HostModule<P: ProcessManager> {
5674 pub name: String,
5675 pub funcs: Vec<HostRegistration<P>>,
5676 pub types: Vec<&'static TypeDescriptor>,
5677 pub record_schemas: Vec<RecordSchema>,
5678 pub states: Vec<ModuleState>,
5685}
5686
5687#[derive(Clone)]
5691pub struct ModuleState {
5692 id: std::any::TypeId,
5693 state: std::sync::Arc<dyn std::any::Any + Send + Sync>,
5694}
5695
5696pub type PreRunInspector = dyn Fn(&[Step]) -> Result<()> + Send + Sync;
5700
5701#[derive(Clone)]
5707pub struct PreRunCheck {
5708 check: Arc<PreRunInspector>,
5709}
5710
5711impl PreRunCheck {
5712 pub fn new(check: impl Fn(&[Step]) -> Result<()> + Send + Sync + 'static) -> Self {
5714 Self {
5715 check: Arc::new(check),
5716 }
5717 }
5718
5719 pub fn run(&self, steps: &[Step]) -> Result<()> {
5721 (self.check)(steps)
5722 }
5723}
5724
5725impl<P: ProcessManager> HostModule<P> {
5726 pub fn with_state<T: Send + Sync + 'static>(mut self, state: std::sync::Arc<T>) -> Self {
5729 self.states.push(ModuleState {
5730 id: std::any::TypeId::of::<T>(),
5731 state,
5732 });
5733 self
5734 }
5735
5736 pub fn check_pre_run(&self, steps: &[Step]) -> Result<()> {
5740 for state in &self.states {
5741 if let Some(check) = state.state.downcast_ref::<PreRunCheck>() {
5742 check.run(steps)?;
5743 }
5744 }
5745 Ok(())
5746 }
5747}
5748
5749impl<P: ProcessManager> ExecState<P> {
5750 pub fn register_module(&mut self, module: HostModule<P>) {
5753 for registration in module.funcs {
5754 match registration {
5755 HostRegistration::Stateful { name, meta, func } => {
5756 self.functions.register_host(&module.name, name, meta, func);
5757 }
5758 HostRegistration::Pure { name, meta, func } => {
5759 self.functions
5760 .register_pure_host(&module.name, name, meta, func);
5761 }
5762 HostRegistration::Both {
5763 name,
5764 meta,
5765 func,
5766 template,
5767 } => {
5768 self.functions
5769 .register_both_host(&module.name, name, meta, func, template);
5770 }
5771 }
5772 }
5773 for descriptor in module.types {
5774 self.register_type(descriptor);
5775 }
5776 for schema in module.record_schemas {
5777 self.register_record_schema(schema.name, schema.fields);
5778 }
5779 for state in module.states {
5780 self.module_states
5781 .insert((module.name.clone(), state.id), state.state);
5782 }
5783 }
5784
5785 pub fn list_functions(&self) -> Vec<FuncMeta> {
5787 let mut out: Vec<FuncMeta> = self.functions.entries_metas().into_iter().collect();
5788 if !out.iter().any(|m| m.name == KEYWORD_INSPECT) {
5790 out.push(FuncMeta {
5791 name: KEYWORD_INSPECT.to_string(),
5792 module: STD_MODULE_NAME.to_string(),
5793 kind: FuncKind::HostCtx,
5794 params: None,
5795 returns: Some(TypeTag::Map),
5796 rpn: false,
5797 summary: "Inspect a variable binding.",
5798 docs: "INSPECT($var): dedicated AST node taking a variable, not a value.",
5799 examples: &[],
5800 });
5801 }
5802 out.sort_by(|a, b| a.name.cmp(&b.name));
5803 out
5804 }
5805
5806 pub fn describe_function(&self, name: &str) -> Option<Value> {
5808 if let Some(meta) = self.functions.meta(name) {
5809 return Some(meta_to_value(&meta));
5810 }
5811 if name == KEYWORD_INSPECT {
5813 return Some(meta_to_value(&FuncMeta {
5814 name: KEYWORD_INSPECT.to_string(),
5815 module: STD_MODULE_NAME.to_string(),
5816 kind: FuncKind::HostCtx,
5817 params: None,
5818 returns: Some(TypeTag::Map),
5819 rpn: false,
5820 summary: "Inspect a variable binding.",
5821 docs: "INSPECT($var): dedicated AST node taking a variable, not a value.",
5822 examples: &[],
5823 }));
5824 }
5825 None
5826 }
5827
5828 pub fn pure_function_table(&self) -> Arc<PureTable> {
5833 self.functions.pure_shared()
5834 }
5835}
5836
5837#[cfg(test)]
5838mod tests {
5839 use super::*;
5840
5841 #[test]
5842 fn placeholder_resolver_dispatches_table_entries() {
5843 let echo: PureFn = Arc::new(|args| {
5847 args.into_iter()
5848 .next()
5849 .ok_or_else(|| anyhow::anyhow!("ECHO needs 1 arg"))
5850 });
5851 let mut entries = HashMap::new();
5852 entries.insert("ECHO".to_string(), echo);
5853 let mut table = PureTable::new();
5854 table.insert("T".to_string(), entries);
5855 let resolve = placeholder_resolver(Arc::new(table));
5856 let out = resolve("T", "ECHO", vec![Value::string("hi".to_string())]).expect("dispatch");
5857 assert_eq!(out.as_str().expect("string"), "hi");
5858 let err = format!(
5859 "{:#}",
5860 resolve("T", "NOPE", vec![]).expect_err("unknown must fail")
5861 );
5862 assert!(
5863 err.contains("unknown placeholder function 'T::NOPE'"),
5864 "names the call: {err}"
5865 );
5866 assert!(
5867 err.contains("known functions: T::ECHO"),
5868 "lists known names: {err}"
5869 );
5870 }
5871
5872 #[test]
5873 fn describe_entry_renders_union_spellings() {
5874 let union = oxdock_parser::union_tag!(String, Pipe);
5880 let meta = FuncMeta {
5881 name: "T::F".to_string(),
5882 module: "T".to_string(),
5883 kind: FuncKind::HostPure,
5884 params: Some(vec![FuncParam {
5885 name: "text".to_string(),
5886 param_type: Some(union.clone()),
5887 allowed: None,
5888 docs: "",
5889 options: None,
5890 optional: false,
5891 }]),
5892 returns: Some(union),
5893 rpn: false,
5894 summary: "test-only",
5895 docs: "test-only",
5896 examples: &[],
5897 };
5898 let value = meta_to_value(&meta);
5899 let map = value.as_map().expect("describe value is a map");
5900 let params = map
5901 .get("params")
5902 .expect("params key")
5903 .as_list()
5904 .expect("params is a list");
5905 let first = params[0].as_map().expect("entry is a map");
5906 assert_eq!(
5907 first.get("param_type").and_then(Value::as_str),
5908 Some("STRING|PIPE"),
5909 "param renders the set"
5910 );
5911 assert_eq!(
5912 map.get("returns").and_then(Value::as_str),
5913 Some("STRING|PIPE"),
5914 "returns render the set"
5915 );
5916 }
5917
5918 #[test]
5919 fn describe_entry_renders_handle_payload() {
5920 let meta = FuncMeta {
5924 name: "SCRIPT::FETCH".to_string(),
5925 module: "SCRIPT".to_string(),
5926 kind: FuncKind::Script,
5927 params: Some(vec![]),
5928 returns: Some(TypeTag::HandleOf(std::sync::Arc::new(TypeTag::String))),
5929 rpn: false,
5930 summary: "test-only",
5931 docs: "test-only",
5932 examples: &[],
5933 };
5934 let value = meta_to_value(&meta);
5935 let map = value.as_map().expect("describe value is a map");
5936 assert_eq!(
5937 map.get("returns").and_then(Value::as_str),
5938 Some("HANDLE<STRING>"),
5939 "returns render the payload"
5940 );
5941 }
5942
5943 #[test]
5944 fn describe_entry_carries_optional_flag() {
5945 let meta = FuncMeta {
5949 name: "T::F".to_string(),
5950 module: "T".to_string(),
5951 kind: FuncKind::HostPure,
5952 params: Some(vec![
5953 FuncParam {
5954 name: "url".to_string(),
5955 param_type: Some(TypeTag::String),
5956 allowed: None,
5957 docs: "",
5958 options: None,
5959 optional: false,
5960 },
5961 FuncParam {
5962 name: "options".to_string(),
5963 param_type: Some(TypeTag::Map),
5964 allowed: None,
5965 docs: "",
5966 options: None,
5967 optional: true,
5968 },
5969 ]),
5970 returns: Some(TypeTag::String),
5971 rpn: false,
5972 summary: "test-only",
5973 docs: "test-only",
5974 examples: &[],
5975 };
5976 let value = meta_to_value(&meta);
5977 let map = value.as_map().expect("describe value is a map");
5978 let params = map
5979 .get("params")
5980 .expect("params key")
5981 .as_list()
5982 .expect("params is a list");
5983 assert_eq!(params.len(), 2);
5984 let first = params[0].as_map().expect("entry is a map");
5985 let second = params[1].as_map().expect("entry is a map");
5986 assert_eq!(
5987 first.get("optional").and_then(Value::as_bool),
5988 Some(false),
5989 "required param must read false"
5990 );
5991 assert_eq!(
5992 second.get("optional").and_then(Value::as_bool),
5993 Some(true),
5994 "omittable param must read true"
5995 );
5996 }
5997
5998 #[test]
5999 fn template_twins_mirror_string_paths_and_refuse_pipes() {
6000 let pipe = Value::pipe_fresh();
6006 type TwinCase = (&'static str, Box<dyn Fn() -> Result<Value>>);
6007 let cases: Vec<TwinCase> = vec![
6008 (
6009 "TEXT_TRIM",
6010 Box::new(|| text_trim_string(Value::string(" hello ".to_string()))),
6011 ),
6012 (
6013 "TEXT_TRIM_PREFIX",
6014 Box::new(|| {
6015 text_trim_prefix_string(Value::string("v1".to_string()), "v".to_string())
6016 }),
6017 ),
6018 (
6019 "TEXT_TRIM_SUFFIX",
6020 Box::new(|| {
6021 text_trim_suffix_string(Value::string("a.gz".to_string()), "x".to_string())
6022 }),
6023 ),
6024 (
6025 "TEXT_TO_UPPER",
6026 Box::new(|| text_to_upper_string(Value::string("hi".to_string()))),
6027 ),
6028 (
6029 "TEXT_TO_LOWER",
6030 Box::new(|| text_to_lower_string(Value::string("HI".to_string()))),
6031 ),
6032 (
6033 "TEXT_REPLACE",
6034 Box::new(|| {
6035 text_replace_string(
6036 Value::string("ab".to_string()),
6037 "b".to_string(),
6038 "c".to_string(),
6039 )
6040 }),
6041 ),
6042 (
6043 "TEXT_REPLACE_REGEX",
6044 Box::new(|| {
6045 text_replace_regex_string(
6046 Value::string("ab".to_string()),
6047 "b".to_string(),
6048 "c".to_string(),
6049 )
6050 }),
6051 ),
6052 ];
6053 assert_eq!(cases.len(), 7, "every mirror op needs a twin row");
6054 for (name, run) in &cases {
6055 let value = run().unwrap_or_else(|e| panic!("{name} twin must answer strings: {e:#}"));
6056 assert!(
6057 value.as_str().is_some(),
6058 "{name} twin must answer STRING, got {}",
6059 value.type_name()
6060 );
6061 }
6062 assert_eq!(
6063 text_trim_string(Value::string(" hello ".to_string()))
6064 .expect("trim twin")
6065 .as_str(),
6066 Some("hello")
6067 );
6068 let pipe_cases: Vec<(&str, Result<Value>)> = vec![
6070 ("TEXT_TRIM", text_trim_string(pipe.clone())),
6071 (
6072 "TEXT_TRIM_PREFIX",
6073 text_trim_prefix_string(pipe.clone(), "v".to_string()),
6074 ),
6075 (
6076 "TEXT_TRIM_SUFFIX",
6077 text_trim_suffix_string(pipe.clone(), ".gz".to_string()),
6078 ),
6079 ("TEXT_TO_UPPER", text_to_upper_string(pipe.clone())),
6080 ("TEXT_TO_LOWER", text_to_lower_string(pipe.clone())),
6081 (
6082 "TEXT_REPLACE",
6083 text_replace_string(pipe.clone(), "a".to_string(), "b".to_string()),
6084 ),
6085 (
6086 "TEXT_REPLACE_REGEX",
6087 text_replace_regex_string(pipe.clone(), "a".to_string(), "b".to_string()),
6088 ),
6089 ];
6090 for (name, result) in pipe_cases {
6091 let err = result.expect_err(&format!("{name} twin must refuse PIPE"));
6092 assert!(
6093 format!("{err:#}").contains("step IO"),
6094 "{name} refusal names the missing context: {err:#}"
6095 );
6096 }
6097 }
6098
6099 #[test]
6100 fn shell_words_join_split_round_trip() {
6101 let words = vec![
6105 "gh".to_string(),
6106 "issue".to_string(),
6107 "comment".to_string(),
6108 "with spaces".to_string(),
6109 "it's".to_string(),
6110 "say \"hi\"".to_string(),
6111 "$HOME".to_string(),
6112 "$(whoami)".to_string(),
6113 "C:\\path\\to".to_string(),
6114 "naïve café".to_string(),
6115 "".to_string(),
6116 ];
6117 let joined = shell_words::join(&words);
6118 let back = shell_words::split(&joined).expect("join output must parse");
6119 assert_eq!(back, words);
6120 assert!(shell_words::split("unbalanced \"quote").is_err());
6121 }
6122
6123 struct FakeView {
6127 exports: HashMap<String, Vec<String>>,
6128 targets: HashMap<String, AliasTargets>,
6129 bindings: HashMap<String, HashMap<String, bool>>,
6130 }
6131
6132 impl ModuleGraphView for FakeView {
6133 fn const_exports(&self, file: &str) -> Option<&[String]> {
6134 self.exports.get(file).map(Vec::as_slice)
6135 }
6136
6137 fn alias_targets(&self, file: &str) -> AliasTargets {
6138 self.targets.get(file).cloned().unwrap_or_default()
6139 }
6140
6141 fn binding(&self, file: &str, name: &str) -> BindingPresence {
6142 match self.bindings.get(file).and_then(|names| names.get(name)) {
6143 Some(true) => BindingPresence::Const,
6144 Some(false) => BindingPresence::Let,
6145 None => BindingPresence::Absent,
6146 }
6147 }
6148 }
6149
6150 fn fake_targets(pairs: &[(&str, &str)]) -> AliasTargets {
6151 let mut targets = AliasTargets::new();
6152 for (alias, file) in pairs {
6153 targets
6154 .entry((*alias).to_string())
6155 .or_default()
6156 .push((Some((*file).to_string()), None));
6157 }
6158 targets
6159 }
6160
6161 fn os_guard(os: &str) -> GuardExpr {
6162 GuardExpr::Predicate(oxdock_parser::Guard::Attr {
6163 ns: oxdock_parser::Ns::Os,
6164 key: None,
6165 val: Some(os.to_string()),
6166 })
6167 }
6168
6169 #[test]
6170 fn chase_resolves_bare_and_single_forward() {
6171 let mut view = FakeView {
6174 exports: HashMap::from([
6175 ("a".to_string(), vec!["N".to_string()]),
6176 ("b".to_string(), vec!["A::N".to_string()]),
6177 ("c".to_string(), vec!["B::N".to_string()]),
6178 ]),
6179 targets: HashMap::from([
6180 ("u".to_string(), fake_targets(&[("B", "b")])),
6181 ("b".to_string(), fake_targets(&[("A", "a")])),
6182 ("c".to_string(), fake_targets(&[("B", "b")])),
6183 ]),
6184 bindings: HashMap::new(),
6185 };
6186 assert_eq!(
6187 chase_const_forward(&view, "a", "N", "U::N").expect("bare"),
6188 vec!["a".to_string()]
6189 );
6190 assert_eq!(
6191 chase_const_forward(&view, "b", "N", "U::N").expect("forward"),
6192 vec!["a".to_string()]
6193 );
6194 view.targets
6195 .insert("u".to_string(), fake_targets(&[("C", "c")]));
6196 assert_eq!(
6197 chase_const_forward(&view, "c", "N", "U::N").expect("chain"),
6198 vec!["a".to_string()]
6199 );
6200 }
6201
6202 #[test]
6203 fn chase_prefers_bare_over_forwards() {
6204 let view = FakeView {
6207 exports: HashMap::from([("b".to_string(), vec!["N".to_string(), "A::N".to_string()])]),
6208 targets: HashMap::from([("b".to_string(), fake_targets(&[("A", "a")]))]),
6209 bindings: HashMap::new(),
6210 };
6211 assert_eq!(
6212 chase_const_forward(&view, "b", "N", "U::N").expect("bare wins"),
6213 vec!["b".to_string()]
6214 );
6215 }
6216
6217 #[test]
6218 fn chase_rejects_split_forwards() {
6219 let view = FakeView {
6222 exports: HashMap::from([(
6223 "b".to_string(),
6224 vec!["A::N".to_string(), "C::N".to_string()],
6225 )]),
6226 targets: HashMap::new(),
6227 bindings: HashMap::new(),
6228 };
6229 let err = format!(
6230 "{}",
6231 chase_const_forward(&view, "b", "N", "U::N").expect_err("split must fail")
6232 );
6233 assert!(err.contains("ambiguous CONST `U::N`"), "{err}");
6234 assert!(err.contains("A::N") && err.contains("C::N"), "{err}");
6235 }
6236
6237 #[test]
6238 fn chase_names_broken_link_detail() {
6239 let view = FakeView {
6242 exports: HashMap::from([
6243 ("b".to_string(), vec!["A::M".to_string()]),
6244 ("c".to_string(), vec!["A::P".to_string()]),
6245 ("d".to_string(), vec!["A::Q".to_string()]),
6246 ("a".to_string(), Vec::new()),
6247 ]),
6248 targets: HashMap::from([
6249 ("b".to_string(), fake_targets(&[("A", "a")])),
6250 ("c".to_string(), fake_targets(&[("A", "a")])),
6251 ("d".to_string(), fake_targets(&[("A", "a")])),
6252 ]),
6253 bindings: HashMap::from([(
6254 "a".to_string(),
6255 HashMap::from([("P".to_string(), true), ("Q".to_string(), false)]),
6256 )]),
6257 };
6258 let err = format!(
6259 "{}",
6260 chase_const_forward(&view, "b", "M", "U::M").expect_err("missing must fail")
6261 );
6262 assert!(err.contains("does not resolve"), "{err}");
6263 assert!(err.contains("no import alias `A` exports `M`"), "{err}");
6264 let err = format!(
6265 "{}",
6266 chase_const_forward(&view, "c", "P", "U::P").expect_err("unexported must fail")
6267 );
6268 assert!(
6269 err.contains("holds `P` as CONST but does not export it"),
6270 "{err}"
6271 );
6272 let err = format!(
6273 "{}",
6274 chase_const_forward(&view, "d", "Q", "U::Q").expect_err("LET must fail")
6275 );
6276 assert!(
6277 err.contains("is a LET binding and cannot be exported"),
6278 "{err}"
6279 );
6280 }
6281
6282 #[test]
6283 fn chase_rejects_cycles() {
6284 let view = FakeView {
6287 exports: HashMap::from([
6288 ("a".to_string(), vec!["B::N".to_string()]),
6289 ("b".to_string(), vec!["A::N".to_string()]),
6290 ]),
6291 targets: HashMap::from([
6292 ("a".to_string(), fake_targets(&[("B", "b")])),
6293 ("b".to_string(), fake_targets(&[("A", "a")])),
6294 ]),
6295 bindings: HashMap::new(),
6296 };
6297 let err = format!(
6298 "{}",
6299 chase_const_forward(&view, "a", "N", "U::N").expect_err("cycle must fail")
6300 );
6301 assert!(err.contains("re-export cycle"), "{err}");
6302 }
6303
6304 #[test]
6305 fn chase_unions_disjoint_guard_branches() {
6306 let mut guarded = AliasTargets::new();
6309 guarded.insert(
6310 "A".to_string(),
6311 vec![
6312 (Some("lin".to_string()), Some(os_guard("linux"))),
6313 (Some("mac".to_string()), Some(os_guard("macos"))),
6314 ],
6315 );
6316 let view = FakeView {
6317 exports: HashMap::from([
6318 ("b".to_string(), vec!["A::N".to_string()]),
6319 ("lin".to_string(), vec!["N".to_string()]),
6320 ("mac".to_string(), vec!["N".to_string()]),
6321 ]),
6322 targets: HashMap::from([("b".to_string(), guarded)]),
6323 bindings: HashMap::new(),
6324 };
6325 assert_eq!(
6326 chase_const_forward(&view, "b", "N", "U::N").expect("disjoint branches"),
6327 vec!["lin".to_string(), "mac".to_string()]
6328 );
6329 }
6330
6331 #[test]
6332 fn holder_classification_sorts_and_rejects() {
6333 let view = FakeView {
6336 exports: HashMap::from([
6337 ("b".to_string(), vec!["N".to_string()]),
6338 ("c".to_string(), vec!["N".to_string()]),
6339 ]),
6340 targets: HashMap::new(),
6341 bindings: HashMap::new(),
6342 };
6343 let unit = fake_targets(&[("B", "b"), ("B", "c")]);
6344 match const_holder_files(&view, &unit, "B", "N") {
6345 ConstHolders::Ambiguous { .. } => {}
6346 other => panic!("overlapping holders must be ambiguous, got {other:?}"),
6347 }
6348 match const_holder_files(&view, &unit, "Z", "N") {
6349 ConstHolders::NoAlias => {}
6350 other => panic!("unknown alias must report NoAlias, got {other:?}"),
6351 }
6352 let unit = fake_targets(&[("B", "b")]);
6353 match const_holder_files(&view, &unit, "B", "N") {
6354 ConstHolders::Found(files) => assert_eq!(files, vec!["b".to_string()]),
6355 other => panic!("single holder must be found, got {other:?}"),
6356 }
6357 }
6358}