1use std::collections::{BTreeMap, HashMap, HashSet};
2use std::sync::Arc;
3
4use anyhow::Result;
5use oxdock_diagnostics::{Diagnostic, DiagnosticResult};
6use oxdock_fs::to_forward_slashes;
7use oxdock_fs::{GuardedPath, WorkspaceSelection};
8use oxdock_func_macro::oxdock_func;
9use oxdock_parser::value::HandleValue;
10use oxdock_parser::{
11 Field, GuardExpr, KEYWORD_CONST, KEYWORD_EXPORT, KEYWORD_FROM, KEYWORD_FUNC, KEYWORD_IMPORT,
12 KEYWORD_INSPECT, KEYWORD_LET, KEYWORD_TYPE, MODULE_SEPARATOR, SCRIPT_MODULE_NAME,
13 STD_MODULE_NAME, SemaphoreState, Step, TypeTag, Value, base_name, guards_overlap, qualify,
14 render_structural, split_qualified,
15};
16use oxdock_pipe::PipeHandle;
17use oxdock_process::{CommandStdin, DefaultProcessManager, ProcessManager};
18
19use super::diagnostics as std_diag;
20use super::function_names::{
21 FUNC_BOOL, FUNC_BOOL_OR, FUNC_PARSE_ARGS, FUNC_PARSE_FLAGS, FUNC_PARSE_POSITIONALS,
22 FUNC_TEXT_COUNT, FUNC_TEXT_COUNT_MATCHES, FUNC_TEXT_EXTRACT, FUNC_TEXT_GREP,
23 FUNC_TEXT_LINES_RANGE, FUNC_TEXT_MATCH, FUNC_TEXT_REPLACE, FUNC_TEXT_REPLACE_REGEX,
24};
25use super::io::StreamHandle;
26use super::state::ExecState;
27use super::steps::StepCtx;
28use super::typing::TypeDescriptor;
29
30#[derive(Debug, Clone, Copy, PartialEq, Eq)]
36pub enum FuncKind {
37 Script,
38 HostCtx,
39 HostPure,
40}
41
42pub(super) fn file_func_key(defining_file: &str, name: &str) -> String {
46 qualify(defining_file, name)
47}
48
49pub(super) fn ambiguous_alias_message(alias: &str, name: &str, files: &HashSet<String>) -> String {
52 let mut files: Vec<&str> = files.iter().map(|file| file.as_str()).collect();
53 files.sort();
54 format!(
55 "function `{alias}::{name}` is ambiguous: alias `{alias}` is imported from multiple files ({})",
56 files.join(", ")
57 )
58}
59
60pub(super) enum AliasResolution {
66 Global,
68 Canonical(String),
70 Unknown,
72 Ambiguous {
75 alias: String,
76 base: String,
77 files: HashSet<String>,
78 },
79 Any {
86 base: String,
87 files: HashSet<String>,
88 has_host: bool,
89 },
90}
91
92pub(super) type AliasTargets = HashMap<String, Vec<(Option<String>, Option<GuardExpr>)>>;
99
100pub(super) trait FuncFrameView {
106 type Hit;
108 fn find_nested(&self, base: &str) -> Option<Self::Hit>;
110 fn find_home(&self, unit: &str, base: &str) -> Option<Self::Hit>;
112 fn find_harvest(&self, unit: &str, base: &str) -> Option<Self::Hit>;
114 fn walk(&self, unit: &str, base: &str) -> Option<Self::Hit> {
116 self.find_nested(base)
117 .or_else(|| self.find_home(unit, base))
118 .or_else(|| self.find_harvest(unit, base))
119 }
120}
121
122pub(super) fn classify_alias_call(
128 unit_targets: &AliasTargets,
129 name: &str,
130 exists: &dyn Fn(&str) -> bool,
131) -> AliasResolution {
132 let Some((alias, base)) = split_qualified(name) else {
133 return AliasResolution::Global;
134 };
135 if alias == SCRIPT_MODULE_NAME {
136 return AliasResolution::Global;
137 }
138 let Some(entries) = unit_targets.get(alias) else {
139 return AliasResolution::Global;
140 };
141 if entries.is_empty() {
142 return AliasResolution::Unknown;
143 }
144 let mut files: Vec<(&str, Vec<Option<&GuardExpr>>)> = Vec::new();
147 let mut host_guards: Vec<Option<&GuardExpr>> = Vec::new();
148 for (file, guard) in entries {
149 match file {
150 Some(path) => match files.iter_mut().find(|(known, _)| *known == path) {
151 Some((_, guards)) => guards.push(guard.as_ref()),
152 None => files.push((path, vec![guard.as_ref()])),
153 },
154 None => host_guards.push(guard.as_ref()),
155 }
156 }
157 if files.is_empty() {
158 return AliasResolution::Unknown;
159 }
160 let overlaps = |left: &[Option<&GuardExpr>], right: &[Option<&GuardExpr>]| {
161 left.iter()
162 .any(|a| right.iter().any(|b| guards_overlap(*a, *b)))
163 };
164 if files.len() == 1 {
165 let disjoint_host = host_guards
169 .iter()
170 .any(|host| !overlaps(&files[0].1, &[*host]));
171 if !disjoint_host {
172 return AliasResolution::Canonical(file_func_key(files[0].0, base));
173 }
174 let mut all = HashSet::new();
175 all.insert(files[0].0.to_string());
176 return AliasResolution::Any {
177 base: base.to_string(),
178 files: all,
179 has_host: true,
180 };
181 }
182 let mut ambiguous = HashSet::new();
183 for (i, (file, guards)) in files.iter().enumerate() {
184 for (other, other_guards) in files.iter().skip(i + 1) {
185 if overlaps(guards, other_guards)
186 && (exists(&file_func_key(file, base)) || exists(&file_func_key(other, base)))
187 {
188 ambiguous.insert((*file).to_string());
189 ambiguous.insert((*other).to_string());
190 }
191 }
192 }
193 if !ambiguous.is_empty() {
194 return AliasResolution::Ambiguous {
195 alias: alias.to_string(),
196 base: base.to_string(),
197 files: ambiguous,
198 };
199 }
200 let all: HashSet<String> = files.iter().map(|(file, _)| (*file).to_string()).collect();
201 if all.iter().any(|file| exists(&file_func_key(file, base))) {
202 return AliasResolution::Any {
203 base: base.to_string(),
204 files: all,
205 has_host: !host_guards.is_empty(),
206 };
207 }
208 AliasResolution::Unknown
209}
210
211pub(super) fn missing_import_hint<'a>(
221 files: impl IntoIterator<Item = (&'a str, &'a [String])>,
222 unit_targets: &AliasTargets,
223 name: &str,
224) -> Option<String> {
225 let base = match split_qualified(name) {
226 Some((_, base)) => base,
227 None => name,
228 };
229 if base.is_empty() {
230 return None;
231 }
232 let mut exporters: Vec<&str> = files
233 .into_iter()
234 .filter(|(_, exports)| exports.iter().any(|exported| exported == base))
235 .map(|(file, _)| file)
236 .collect();
237 exporters.sort();
238 exporters.dedup();
239 if exporters.is_empty() {
240 return None;
241 }
242 let imported_as = |file: &str| {
244 let mut aliases: Vec<&str> = unit_targets
245 .iter()
246 .filter(|(_, targets)| {
247 targets
248 .iter()
249 .any(|(target, _)| target.as_deref() == Some(file))
250 })
251 .map(|(alias, _)| alias.as_str())
252 .collect();
253 aliases.sort();
254 aliases
255 };
256 if exporters.len() == 1 {
257 let file = exporters[0];
258 let aliases = imported_as(file);
259 let import_alias = aliases
264 .iter()
265 .find(|alias| qualify(alias, base) != name)
266 .or(aliases.first())
267 .copied();
268 let suggestion = match import_alias {
269 Some(import_alias) => {
270 let spelling = qualify(import_alias, base);
271 if spelling == name {
272 format!(
275 "file \"{file}\" exports `{base}` but the `{import_alias}` view does not resolve it here"
276 )
277 } else {
278 format!("did you mean `{spelling}`? (file \"{file}\" exports `{base}`)")
279 }
280 }
281 None => {
282 let path = to_forward_slashes(file);
285 format!(
286 "file \"{file}\" exports `{base}`: add `[{KEYWORD_FUNC} {base} {KEYWORD_FROM} \"{path}\"]` to an {KEYWORD_IMPORT}"
287 )
288 }
289 };
290 return Some(format!("; {suggestion}"));
291 }
292 let mut files = exporters.join("\", \"");
293 files.insert(0, '"');
294 files.push('"');
295 Some(format!(
296 "; files {files} export `{base}`: qualify the call with the importing alias"
297 ))
298}
299
300pub(super) fn const_export_covers(entry: &str, name: &str) -> bool {
305 base_name(entry) == name
306}
307
308pub(super) enum BindingPresence {
311 Const,
312 Let,
313 Absent,
314}
315
316pub(super) fn missing_const_hint<S: ModuleGraphView>(
323 view: &S,
324 targets: &AliasTargets,
325 alias: &str,
326 name: &str,
327) -> Option<String> {
328 targets
329 .get(alias)
330 .map(|entries| {
331 entries
332 .iter()
333 .filter_map(|(file, _)| file.as_ref())
334 .collect::<Vec<_>>()
335 })
336 .unwrap_or_default()
337 .iter()
338 .find_map(|file| match view.binding(file, name) {
339 BindingPresence::Const => Some(format!(
340 "module holds `{name}` as {KEYWORD_CONST} but does not export it: add `{KEYWORD_EXPORT} {KEYWORD_CONST} ${name}`"
341 )),
342 BindingPresence::Let => Some(format!(
343 "`{name}` is a {KEYWORD_LET} binding and cannot be exported: only {KEYWORD_CONST} bindings cross the module boundary"
344 )),
345 BindingPresence::Absent => None,
346 })
347}
348
349pub(super) trait ModuleGraphView {
356 fn const_exports(&self, file: &str) -> Option<&[String]>;
358 fn alias_targets(&self, file: &str) -> AliasTargets;
361 fn binding(&self, file: &str, name: &str) -> BindingPresence;
363}
364
365#[derive(Debug)]
371pub(super) enum ConstHolders {
372 Found(Vec<String>),
375 NoAlias,
377 Ambiguous {
379 alias: String,
380 base: String,
381 files: HashSet<String>,
382 },
383}
384
385fn const_canonical_suffix(name: &str) -> String {
390 format!("{MODULE_SEPARATOR}{name}")
391}
392
393pub(super) fn const_holder_files<S: ModuleGraphView>(
395 view: &S,
396 unit_targets: &AliasTargets,
397 alias: &str,
398 name: &str,
399) -> ConstHolders {
400 let qualified = qualify(alias, name);
401 let suffix = const_canonical_suffix(name);
402 let exports = |canonical: &str| {
406 canonical
407 .strip_suffix(suffix.as_str())
408 .and_then(|file| view.const_exports(file))
409 .is_some_and(|names| names.iter().any(|entry| const_export_covers(entry, name)))
410 };
411 let mut holders = match classify_alias_call(unit_targets, &qualified, &exports) {
412 AliasResolution::Global | AliasResolution::Unknown => return ConstHolders::NoAlias,
413 AliasResolution::Ambiguous { alias, base, files } => {
414 return ConstHolders::Ambiguous { alias, base, files };
415 }
416 AliasResolution::Canonical(canonical) => {
417 let Some(file) = canonical.strip_suffix(suffix.as_str()) else {
418 return ConstHolders::NoAlias;
419 };
420 vec![file.to_string()]
421 }
422 AliasResolution::Any { mut files, .. } => {
423 let mut files: Vec<String> = files.drain().collect();
424 files.sort();
425 files
426 }
427 };
428 holders.retain(|file| {
429 view.const_exports(file)
430 .is_some_and(|names| names.iter().any(|entry| const_export_covers(entry, name)))
431 });
432 ConstHolders::Found(holders)
433}
434
435#[derive(Debug)]
444pub(super) enum ForwardError {
445 Unknown { original: String },
447 Broken {
449 original: String,
450 hop: String,
451 detail: BrokenDetail,
452 },
453 Split { original: String, hops: Vec<String> },
455 Cycle { chain: Vec<String> },
458 HopAmbiguous {
460 alias: String,
461 base: String,
462 files: HashSet<String>,
463 },
464}
465
466#[derive(Debug)]
468pub(super) enum BrokenDetail {
469 UnexportedConst,
471 Let,
473 Absent,
475}
476
477impl std::fmt::Display for ForwardError {
478 fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
479 match self {
480 ForwardError::Unknown { original } => write!(f, "unknown {KEYWORD_CONST} `{original}`"),
481 ForwardError::Broken {
482 original,
483 hop,
484 detail,
485 } => {
486 let base = base_name(hop);
487 let detail = match detail {
488 BrokenDetail::UnexportedConst => format!(
489 "module holds `{base}` as {KEYWORD_CONST} but does not export it: add `{KEYWORD_EXPORT} {KEYWORD_CONST} ${base}`"
490 ),
491 BrokenDetail::Let => format!(
492 "`{base}` is a {KEYWORD_LET} binding and cannot be exported: only {KEYWORD_CONST} bindings cross the module boundary"
493 ),
494 BrokenDetail::Absent => {
495 let (forward, _) = split_qualified(hop).unwrap_or(("", base));
496 format!("no import alias `{forward}` exports `{base}`")
497 }
498 };
499 write!(
500 f,
501 "unknown {KEYWORD_CONST} `{original}`: re-export `{hop}` does not resolve: {detail}"
502 )
503 }
504 ForwardError::Split { original, hops } => write!(
505 f,
506 "ambiguous {KEYWORD_CONST} `{original}`: re-exported from {}; export exactly one source",
507 hops.join(" and ")
508 ),
509 ForwardError::Cycle { chain } => {
510 write!(
511 f,
512 "{KEYWORD_CONST} re-export cycle detected: {}",
513 chain.join(" -> ")
514 )
515 }
516 ForwardError::HopAmbiguous { alias, base, files } => write!(
517 f,
518 "{}",
519 ambiguous_alias_message(alias, base, files).replacen("function", KEYWORD_CONST, 1)
520 ),
521 }
522 }
523}
524
525fn forward_failed(err: ForwardError) -> Diagnostic {
530 std_diag::import_const_forward_failed(&err.to_string())
531}
532
533pub(super) fn chase_const_forward<S: ModuleGraphView>(
540 view: &S,
541 file: &str,
542 name: &str,
543 original: &str,
544) -> DiagnosticResult<Vec<String>> {
545 let mut terminals: Vec<String> = Vec::new();
546 chase_from(view, file, name, original, &mut Vec::new(), &mut terminals)?;
547 terminals.sort();
548 terminals.dedup();
549 Ok(terminals)
550}
551
552fn chase_from<S: ModuleGraphView>(
553 view: &S,
554 current: &str,
555 name: &str,
556 original: &str,
557 chain: &mut Vec<String>,
558 terminals: &mut Vec<String>,
559) -> DiagnosticResult<()> {
560 let suffix = const_canonical_suffix(name);
561 let covering = |canonical: &str| {
562 canonical
563 .strip_suffix(suffix.as_str())
564 .and_then(|file| view.const_exports(file))
565 .is_some_and(|names| names.iter().any(|entry| const_export_covers(entry, name)))
566 };
567 let mut current = current.to_string();
568 loop {
569 let Some(names) = view.const_exports(current.as_str()) else {
570 return Err(forward_failed(ForwardError::Unknown {
571 original: original.to_string(),
572 }));
573 };
574 if names.iter().any(|entry| entry == name) {
575 terminals.push(current);
576 return Ok(());
577 }
578 let mut aliases: Vec<&str> = Vec::new();
579 for entry in names {
580 if let Some((alias, base)) = split_qualified(entry)
581 && base == name
582 && !aliases.contains(&alias)
583 {
584 aliases.push(alias);
585 }
586 }
587 if aliases.is_empty() {
588 if chain.is_empty() {
589 return Err(forward_failed(ForwardError::Unknown {
590 original: original.to_string(),
591 }));
592 }
593 let hop = chain.last().expect("chain never empty").clone();
594 let detail = match view.binding(current.as_str(), name) {
595 BindingPresence::Const => BrokenDetail::UnexportedConst,
596 BindingPresence::Let => BrokenDetail::Let,
597 BindingPresence::Absent => BrokenDetail::Absent,
598 };
599 return Err(forward_failed(ForwardError::Broken {
600 original: original.to_string(),
601 hop,
602 detail,
603 }));
604 }
605 if aliases.len() > 1 {
606 let mut hops: Vec<String> = aliases.iter().map(|alias| qualify(alias, name)).collect();
607 hops.sort();
608 return Err(forward_failed(ForwardError::Split {
609 original: original.to_string(),
610 hops,
611 }));
612 }
613 let forward = aliases[0];
614 let hop = qualify(forward, name);
615 if chain.contains(&hop) {
616 chain.push(hop);
617 return Err(forward_failed(ForwardError::Cycle {
618 chain: chain.clone(),
619 }));
620 }
621 chain.push(hop.clone());
622 let targets = view.alias_targets(current.as_str());
623 match classify_alias_call(&targets, &hop, &covering) {
624 AliasResolution::Global | AliasResolution::Unknown => {
625 return Err(forward_failed(ForwardError::Broken {
626 original: original.to_string(),
627 hop,
628 detail: BrokenDetail::Absent,
629 }));
630 }
631 AliasResolution::Ambiguous { alias, base, files } => {
632 return Err(forward_failed(ForwardError::HopAmbiguous {
633 alias,
634 base,
635 files,
636 }));
637 }
638 AliasResolution::Canonical(canonical) => {
639 let Some(next) = canonical.strip_suffix(suffix.as_str()) else {
640 return Err(forward_failed(ForwardError::Unknown {
641 original: original.to_string(),
642 }));
643 };
644 current = next.to_string();
645 }
646 AliasResolution::Any { mut files, .. } => {
647 let mut covering: Vec<String> = files
648 .drain()
649 .filter(|file| {
650 view.const_exports(file).is_some_and(|names| {
651 names.iter().any(|entry| const_export_covers(entry, name))
652 })
653 })
654 .collect();
655 covering.sort();
656 match covering.len() {
657 0 => {
658 return Err(forward_failed(ForwardError::Broken {
659 original: original.to_string(),
660 hop,
661 detail: BrokenDetail::Absent,
662 }));
663 }
664 1 => {
665 current = covering.into_iter().next().expect("len checked");
666 }
667 _ => {
668 for branch in covering {
669 let mut branch_chain = chain.clone();
670 chase_from(
671 view,
672 branch.as_str(),
673 name,
674 original,
675 &mut branch_chain,
676 terminals,
677 )?;
678 }
679 return Ok(());
680 }
681 }
682 }
683 }
684 }
685}
686pub(super) fn disjoint_template_script_visible(
694 base: &str,
695 files: &HashSet<String>,
696 has_host: bool,
697 exists: &dyn Fn(&str) -> bool,
698) -> bool {
699 !has_host && !files.is_empty() && files.iter().all(|file| exists(&file_func_key(file, base)))
700}
701
702pub(super) fn disjoint_alias_placeholder_miss(
709 module: &str,
710 name: &str,
711 base: &str,
712 files: &HashSet<String>,
713 has_host: bool,
714 is_script: &dyn Fn(&str) -> bool,
715) -> String {
716 let script = disjoint_template_script_visible(base, files, has_host, is_script);
717 describe_placeholder_miss(module, name, script, false, !script)
718 .expect("disjoint miss always renders")
719}
720
721pub(super) fn spellings_for_defining_file(
728 unit_targets: &AliasTargets,
729 defining: &str,
730 base: &str,
731 is_script: &dyn Fn(&str) -> bool,
732) -> (Vec<String>, Vec<(String, HashSet<String>)>) {
733 let mut direct = Vec::new();
734 let mut ambiguous = Vec::new();
735 for (alias, files) in unit_targets {
736 if !files
737 .iter()
738 .any(|(file, _)| file.as_deref() == Some(defining))
739 {
740 continue;
741 }
742 let spelling = qualify(alias, base);
743 match classify_alias_call(unit_targets, &spelling, &|key| {
744 key == file_func_key(defining, base)
745 }) {
746 AliasResolution::Canonical(_) => direct.push(spelling),
747 AliasResolution::Ambiguous { files, .. } => {
748 ambiguous.push((spelling, files));
749 }
750 AliasResolution::Any {
751 base,
752 files,
753 has_host,
754 } => {
755 if disjoint_template_script_visible(&base, &files, has_host, is_script) {
756 direct.push(spelling);
757 }
758 }
759 AliasResolution::Global | AliasResolution::Unknown => {}
760 }
761 }
762 (direct, ambiguous)
763}
764
765impl FuncKind {
766 pub fn label(&self) -> &'static str {
767 match self {
768 FuncKind::Script => "script",
769 FuncKind::HostCtx | FuncKind::HostPure => "host",
770 }
771 }
772}
773
774#[derive(Debug, Clone)]
792pub struct FuncParam {
793 pub name: String,
794 pub param_type: Option<TypeTag>,
795 pub allowed: Option<&'static [&'static str]>,
796 pub docs: &'static str,
797 pub options: Option<&'static [ParamOption]>,
798 pub optional: bool,
799}
800
801pub fn required_arity(params: &[FuncParam]) -> usize {
806 params
807 .iter()
808 .rev()
809 .take_while(|param| param.optional)
810 .fold(params.len(), |count, _| count - 1)
811}
812
813pub fn fill_optional_args(params: &[FuncParam], mut values: Vec<Value>) -> Vec<Value> {
818 assert!(
819 values.len() <= params.len(),
820 "arity gate must run before fill_optional_args"
821 );
822 assert!(
823 values.len() >= required_arity(params),
824 "arity gate must run before fill_optional_args"
825 );
826 while values.len() < params.len() {
827 values.push(Value::map(BTreeMap::new()));
828 }
829 values
830}
831
832#[derive(Debug, Clone)]
839pub struct ParamOption {
840 pub name: &'static str,
841 pub value: TypeTag,
842 pub required: bool,
843 pub default: Option<&'static str>,
844}
845
846#[derive(Debug, Clone)]
852pub struct FuncMeta {
853 pub name: String,
854 pub module: String,
858 pub kind: FuncKind,
859 pub params: Option<Vec<FuncParam>>,
860 pub returns: Option<TypeTag>,
861 pub rpn: bool,
862 pub summary: &'static str,
863 pub docs: &'static str,
864 pub examples: &'static [crate::Example],
870}
871
872pub type PureFn = Arc<dyn Fn(Vec<Value>) -> Result<Value> + Send + Sync>;
875
876pub type NativeFn<P> = Arc<dyn Fn(&mut StepCtx<P>, Vec<Value>) -> Result<Value> + Send + Sync>;
878
879pub trait OxDockFn<P: ProcessManager> {
883 fn registration() -> HostRegistration<P>;
886}
887
888pub enum HostRegistration<P: ProcessManager> {
897 Stateful {
898 name: String,
899 meta: FuncMeta,
900 func: NativeFn<P>,
901 },
902 Pure {
903 name: String,
904 meta: FuncMeta,
905 func: PureFn,
906 },
907 Both {
908 name: String,
909 meta: FuncMeta,
910 func: NativeFn<P>,
911 template: PureFn,
912 },
913}
914
915impl<P: ProcessManager> Clone for HostRegistration<P> {
918 fn clone(&self) -> Self {
919 match self {
920 HostRegistration::Stateful { name, meta, func } => HostRegistration::Stateful {
921 name: name.clone(),
922 meta: meta.clone(),
923 func: Arc::clone(func),
924 },
925 HostRegistration::Pure { name, meta, func } => HostRegistration::Pure {
926 name: name.clone(),
927 meta: meta.clone(),
928 func: Arc::clone(func),
929 },
930 HostRegistration::Both {
931 name,
932 meta,
933 func,
934 template,
935 } => HostRegistration::Both {
936 name: name.clone(),
937 meta: meta.clone(),
938 func: Arc::clone(func),
939 template: Arc::clone(template),
940 },
941 }
942 }
943}
944
945impl<P: ProcessManager> HostRegistration<P> {
946 pub fn name(&self) -> &str {
952 match self {
953 HostRegistration::Stateful { name, .. } => name,
954 HostRegistration::Pure { name, .. } => name,
955 HostRegistration::Both { name, .. } => name,
956 }
957 }
958
959 pub fn meta(&self) -> &FuncMeta {
962 match self {
963 HostRegistration::Stateful { meta, .. } => meta,
964 HostRegistration::Pure { meta, .. } => meta,
965 HostRegistration::Both { meta, .. } => meta,
966 }
967 }
968}
969
970#[derive(Debug, Clone)]
976pub(super) struct FuncDefData {
977 pub(super) params: Vec<(String, TypeTag, bool)>,
978 pub(super) return_type: TypeTag,
979 pub(super) return_spelling: String,
980 pub(super) is_async: bool,
981 pub(super) body: Vec<Step>,
982 pub(super) module: Option<String>,
987 pub(super) def_jail: Option<(WorkspaceSelection, GuardedPath)>,
993}
994
995pub fn optional_zero_value(tag: &TypeTag) -> DiagnosticResult<Value> {
1003 match tag {
1004 TypeTag::Bool => Ok(Value::bool(false)),
1005 TypeTag::String | TypeTag::Any => Ok(Value::string(String::new())),
1006 TypeTag::Int => Ok(Value::int(0)),
1007 TypeTag::Float => Ok(Value::float(0.0)),
1008 TypeTag::List | TypeTag::ListOf(_) => Ok(Value::list(Vec::new())),
1009 TypeTag::Map | TypeTag::MapOf(_) => Ok(Value::map(BTreeMap::new())),
1010 TypeTag::Record(fields)
1011 if fields
1012 .iter()
1013 .all(|field| field.optional || field.default.is_some()) =>
1014 {
1015 Ok(Value::map(BTreeMap::new()))
1016 }
1017 other => Err(std_diag::func_zero_value_missing(
1018 &oxdock_parser::render_structural(other),
1019 )),
1020 }
1021}
1022
1023pub fn resolve_script_params<P: ProcessManager>(
1029 state: &ExecState<P>,
1030 func_name: &str,
1031 params: &[(String, String, bool)],
1032) -> DiagnosticResult<Vec<(String, TypeTag, bool)>> {
1033 let mut resolved = Vec::with_capacity(params.len());
1034 for (pname, ptype, optional) in params {
1035 let clean = pname.trim_start_matches('$').to_string();
1036 let tag = state
1037 .resolve_tag(ptype)
1038 .map_err(|err| std_diag::func_param_type(func_name, err))?;
1039 state.check_declaration_tag(&format!("function `{func_name}` param `${clean}`"), &tag)?;
1040 if *optional {
1041 optional_zero_value(&tag)
1042 .map(|_| ())
1043 .map_err(|err| std_diag::func_optional_param(func_name, &clean, err))?;
1044 }
1045 resolved.push((clean, tag, *optional));
1046 }
1047 Ok(resolved)
1048}
1049
1050pub fn check_script_param_tags(
1053 func_name: &str,
1054 params: &[(String, TypeTag, bool)],
1055) -> DiagnosticResult<()> {
1056 for (pname, tag, optional) in params {
1057 if *optional {
1058 optional_zero_value(tag)
1059 .map(|_| ())
1060 .map_err(|err| std_diag::func_optional_param(func_name, pname, err))?;
1061 }
1062 }
1063 Ok(())
1064}
1065
1066pub(super) enum FuncBody<P: ProcessManager> {
1071 Script(FuncDefData),
1072 Pure(PureFn),
1073 Ctx(NativeFn<P>),
1074 Both { pure: PureFn, ctx: NativeFn<P> },
1075}
1076
1077impl<P: ProcessManager> Clone for FuncBody<P> {
1079 fn clone(&self) -> Self {
1080 match self {
1081 FuncBody::Script(def) => FuncBody::Script(def.clone()),
1082 FuncBody::Pure(func) => FuncBody::Pure(Arc::clone(func)),
1083 FuncBody::Ctx(func) => FuncBody::Ctx(Arc::clone(func)),
1084 FuncBody::Both { pure, ctx } => FuncBody::Both {
1085 pure: Arc::clone(pure),
1086 ctx: Arc::clone(ctx),
1087 },
1088 }
1089 }
1090}
1091
1092pub(super) struct FuncEntry<P: ProcessManager> {
1096 pub(super) meta: FuncMeta,
1097 pub(super) body: FuncBody<P>,
1098}
1099
1100impl<P: ProcessManager> Clone for FuncEntry<P> {
1102 fn clone(&self) -> Self {
1103 Self {
1104 meta: self.meta.clone(),
1105 body: self.body.clone(),
1106 }
1107 }
1108}
1109
1110struct ScopeFrame<P: ProcessManager> {
1113 defined: HashSet<String>,
1114 shadowed: Vec<(String, FuncEntry<P>)>,
1115}
1116
1117impl<P: ProcessManager> Clone for ScopeFrame<P> {
1119 fn clone(&self) -> Self {
1120 Self {
1121 defined: self.defined.clone(),
1122 shadowed: self.shadowed.clone(),
1123 }
1124 }
1125}
1126
1127pub type PureTable = HashMap<String, HashMap<String, PureFn>>;
1137
1138pub fn placeholder_resolver(table: Arc<PureTable>) -> oxdock_process::PlaceholderCall {
1147 Arc::new(move |module, func, args| {
1148 let callee = table
1149 .get(module)
1150 .and_then(|entries| entries.get(func))
1151 .ok_or_else(|| {
1152 let mut known: Vec<String> = table
1153 .iter()
1154 .flat_map(|(m, entries)| entries.keys().map(move |f| format!("{m}::{f}")))
1155 .collect();
1156 known.sort();
1157 anyhow::Error::new(std_diag::func_placeholder_unknown(module, func, &known))
1158 })?;
1159 callee(args)
1160 })
1161}
1162
1163pub(super) fn describe_placeholder_miss(
1170 module: &str,
1171 name: &str,
1172 is_script: bool,
1173 is_stateful: bool,
1174 alias_known: bool,
1175) -> Option<String> {
1176 let qualified = qualify(module, name);
1177 if is_script {
1178 let call = if module == SCRIPT_MODULE_NAME {
1179 format!("{name}(...)")
1180 } else {
1181 format!("{qualified}(...)")
1182 };
1183 return Some(format!(
1184 "placeholder function '{qualified}' is a script function and cannot run in {{{{ }}}}; bind the result first with {KEYWORD_LET} $v = {call} then interpolate {{{{ $v }}}}"
1185 ));
1186 }
1187 if is_stateful {
1188 return Some(format!(
1189 "placeholder function '{qualified}' is stateful and cannot run in {{{{ }}}}; capture it first with {KEYWORD_LET} then interpolate {{{{ $v }}}}"
1190 ));
1191 }
1192 if alias_known {
1193 return Some(format!(
1194 "placeholder function '{qualified}': no function '{name}' under file alias '{module}'; check the file's {KEYWORD_EXPORT} list and the {KEYWORD_IMPORT} harvest, or bind a known function first with {KEYWORD_LET} then interpolate {{{{ $v }}}}"
1195 ));
1196 }
1197 None
1198}
1199
1200pub(super) struct PlaceholderClasses {
1203 pub script: HashSet<String>,
1204 pub stateful: HashSet<String>,
1205 pub aliases: HashSet<String>,
1206 pub ambiguous: HashMap<String, HashSet<String>>,
1208}
1209
1210impl PlaceholderClasses {
1211 pub(super) fn describe(&self, module: &str, name: &str) -> Option<String> {
1212 let qualified = qualify(module, name);
1213 if let Some(files) = self.ambiguous.get(&qualified) {
1214 return Some(ambiguous_alias_message(module, name, files));
1215 }
1216 describe_placeholder_miss(
1217 module,
1218 name,
1219 self.script.contains(&qualified),
1220 self.stateful.contains(&qualified),
1221 self.aliases.contains(module),
1222 )
1223 }
1224}
1225
1226pub struct FunctionRegistry<P: ProcessManager> {
1227 entries: HashMap<String, FuncEntry<P>>,
1228 scopes: Vec<ScopeFrame<P>>,
1229 pure_shared: Arc<PureTable>,
1230 script_docs: HashMap<String, (String, String)>,
1234}
1235
1236impl<P: ProcessManager> FunctionRegistry<P> {
1237 pub(super) fn with_builtins() -> Self {
1238 let mut reg = Self {
1239 entries: HashMap::new(),
1240 pure_shared: Arc::new(HashMap::new()),
1241 script_docs: HashMap::new(),
1242 scopes: vec![ScopeFrame {
1243 defined: HashSet::new(),
1244 shadowed: Vec::new(),
1245 }],
1246 };
1247 for host in Self::builtin_registrations() {
1251 match host {
1252 HostRegistration::Stateful { name, meta, func } => {
1253 reg.insert_qualified(STD_MODULE_NAME, name, meta, FuncBody::Ctx(func));
1254 }
1255 HostRegistration::Pure { name, meta, func } => {
1256 reg.insert_qualified(STD_MODULE_NAME, name, meta, FuncBody::Pure(func));
1257 }
1258 HostRegistration::Both {
1259 name,
1260 meta,
1261 func,
1262 template,
1263 } => {
1264 reg.insert_qualified(
1265 STD_MODULE_NAME,
1266 name,
1267 meta,
1268 FuncBody::Both {
1269 pure: template,
1270 ctx: func,
1271 },
1272 );
1273 }
1274 }
1275 }
1276 reg
1277 }
1278
1279 pub(super) fn builtin_registrations() -> Vec<HostRegistration<P>> {
1284 vec![
1285 Int::registration(),
1286 Float::registration(),
1287 BoolConvert::registration(),
1288 BoolOr::registration(),
1289 FormatByteCount::registration(),
1290 ParseByteCount::registration(),
1291 FormatDuration::registration(),
1292 ParseDuration::registration(),
1293 Types::registration(),
1294 TypeDescribe::registration(),
1295 Glob::registration(),
1296 LoadToml::registration(),
1297 LoadJson::registration(),
1298 HashSha256::registration(),
1299 Cwd::registration(),
1300 ParseToml::registration(),
1301 ParseJson::registration(),
1302 PathType::registration(),
1303 PathWritable::registration(),
1304 IsExec::registration(),
1305 IsFile::registration(),
1306 IsDir::registration(),
1307 Exists::registration(),
1308 HasKey::registration(),
1309 Get::registration(),
1310 MapSet::registration(),
1311 MergeMaps::registration(),
1312 Base64Encode::registration(),
1313 Base64Decode::registration(),
1314 Rand::registration(),
1315 ToJson::registration(),
1316 TypeOf::registration(),
1317 Functions::registration(),
1318 Describe::registration(),
1319 IsMain::registration(),
1320 IsTerminal::registration(),
1321 Eof::registration(),
1322 TaskPoll::registration(),
1323 Version::registration(),
1324 Interpreter::registration(),
1325 Argv::registration(),
1326 ParseArgs::registration(),
1327 ParseFlags::registration(),
1328 ParsePositionals::registration(),
1329 TextTrim::registration(),
1330 TextTrimPrefix::registration(),
1331 TextTrimSuffix::registration(),
1332 PathJoin::registration(),
1333 PathBase::registration(),
1334 PathRel::registration(),
1335 TextToUpper::registration(),
1336 TextToLower::registration(),
1337 TextReplace::registration(),
1338 TextReplaceRegex::registration(),
1339 TextSplit::registration(),
1340 TextJoin::registration(),
1341 TextLines::registration(),
1342 TextFields::registration(),
1343 TextMatch::registration(),
1344 TextExtract::registration(),
1345 TextStartsWith::registration(),
1346 TextEndsWith::registration(),
1347 Contains::registration(),
1348 Unique::registration(),
1349 Len::registration(),
1350 TextCount::registration(),
1351 TextCountMatches::registration(),
1352 TextGrep::registration(),
1353 TextLinesRange::registration(),
1354 SemaphoreNew::registration(),
1355 SemaphoreTryAcquire::registration(),
1356 SemaphoreAvailable::registration(),
1357 ShellSplitArgs::registration(),
1358 ShellJoinArgs::registration(),
1359 ]
1360 }
1361
1362 pub(super) fn keys(&self) -> HashSet<String> {
1365 self.entries.keys().cloned().collect()
1366 }
1367
1368 pub(super) fn get(&self, name: &str) -> Option<FuncEntry<P>> {
1370 self.entries.get(name).cloned()
1371 }
1372
1373 pub(super) fn scope_depth(&self) -> usize {
1377 self.scopes.len()
1378 }
1379
1380 pub(super) fn get_scoped(&self, base: &str, floor: usize) -> Option<FuncEntry<P>> {
1389 let qualified = qualify(SCRIPT_MODULE_NAME, base);
1390 let len = self.scopes.len();
1391 let start = floor.min(len);
1392 for frame in self.scopes[start..].iter().rev() {
1393 if frame.defined.contains(&qualified) {
1394 return self.entries.get(&qualified).cloned();
1395 }
1396 }
1397 None
1398 }
1399
1400 pub(super) fn describe_unit_placeholder_miss(
1406 &self,
1407 unit_targets: &AliasTargets,
1408 module: &str,
1409 name: &str,
1410 ) -> Option<String> {
1411 let qualified = qualify(module, name);
1412 match classify_alias_call(unit_targets, &qualified, &|key| {
1417 self.entries.contains_key(key)
1418 }) {
1419 AliasResolution::Canonical(canonical) => {
1420 if let Some(entry) = self.entries.get(&canonical) {
1421 if let Some(miss) = Self::placeholder_miss_for_body(module, name, &entry.body) {
1422 return Some(miss);
1423 }
1424 None
1425 } else {
1426 describe_placeholder_miss(module, name, false, false, true)
1427 }
1428 }
1429 AliasResolution::Global => {
1430 if let Some(entry) = self.entries.get(&qualified) {
1431 if let Some(miss) = Self::placeholder_miss_for_body(module, name, &entry.body) {
1435 return Some(miss);
1436 }
1437 }
1438 None
1439 }
1440 AliasResolution::Ambiguous { files, .. } => {
1441 Some(ambiguous_alias_message(module, name, &files))
1442 }
1443 AliasResolution::Unknown => describe_placeholder_miss(module, name, false, false, true),
1444 AliasResolution::Any {
1450 base,
1451 files,
1452 has_host,
1453 } => Some(disjoint_alias_placeholder_miss(
1454 module,
1455 name,
1456 &base,
1457 &files,
1458 has_host,
1459 &|key| matches!(self.entries.get(key), Some(entry) if matches!(entry.body, FuncBody::Script(_))),
1460 )),
1461 }
1462 }
1463
1464 fn placeholder_miss_for_body(module: &str, name: &str, body: &FuncBody<P>) -> Option<String> {
1468 match body {
1469 FuncBody::Script(_) => describe_placeholder_miss(module, name, true, false, false),
1470 FuncBody::Ctx(_) => describe_placeholder_miss(module, name, false, true, false),
1471 FuncBody::Pure(_) | FuncBody::Both { .. } => None,
1472 }
1473 }
1474
1475 pub(super) fn placeholder_snapshot(&self, unit_targets: &AliasTargets) -> PlaceholderClasses {
1479 let mut script = HashSet::new();
1480 let mut stateful = HashSet::new();
1481 let mut ambiguous: HashMap<String, HashSet<String>> = HashMap::new();
1482 for (key, entry) in self.entries.iter() {
1483 let Some((module, base)) = split_qualified(key) else {
1484 continue;
1485 };
1486 match &entry.body {
1487 FuncBody::Script(def) => {
1488 if module == SCRIPT_MODULE_NAME {
1489 script.insert(key.clone());
1491 continue;
1492 }
1493 let defining = def.module.as_deref().unwrap_or(module);
1501 let (direct, ambiguous_here) = spellings_for_defining_file(
1502 unit_targets,
1503 defining,
1504 base,
1505 &|key| matches!(self.entries.get(key), Some(entry) if matches!(entry.body, FuncBody::Script(_))),
1506 );
1507 script.extend(direct);
1508 for (spelling, files) in ambiguous_here {
1509 ambiguous.entry(spelling).or_default().extend(files);
1510 }
1511 }
1512 FuncBody::Ctx(_) => {
1513 stateful.insert(key.clone());
1514 }
1515 FuncBody::Pure(_) | FuncBody::Both { .. } => {}
1516 }
1517 }
1518 let aliases = unit_targets.keys().cloned().collect();
1519 PlaceholderClasses {
1520 script,
1521 stateful,
1522 aliases,
1523 ambiguous,
1524 }
1525 }
1526
1527 fn insert_native(&mut self, name: String, meta: FuncMeta, body: FuncBody<P>) {
1528 self.entries.insert(name, FuncEntry { meta, body });
1529 self.rebuild_pure_shared();
1530 }
1531
1532 fn rebuild_pure_shared(&mut self) {
1538 let mut table: PureTable = HashMap::new();
1539 for (name, entry) in &self.entries {
1540 let func = match &entry.body {
1541 FuncBody::Pure(func) => func,
1542 FuncBody::Both { pure, .. } => pure,
1543 FuncBody::Script(_) | FuncBody::Ctx(_) => continue,
1544 };
1545 if let Some((module, base)) = split_qualified(name) {
1546 table
1547 .entry(module.to_string())
1548 .or_default()
1549 .insert(base.to_string(), Arc::clone(func));
1550 }
1551 }
1552 self.pure_shared = Arc::new(table);
1553 }
1554
1555 fn insert_qualified(
1559 &mut self,
1560 module: &str,
1561 base: String,
1562 mut meta: FuncMeta,
1563 body: FuncBody<P>,
1564 ) {
1565 meta.name = qualify(module, &base);
1566 meta.module = module.to_string();
1567 if self.entries.contains_key(&meta.name) {
1572 panic!("duplicate function registration `{}`", meta.name);
1573 }
1574 self.insert_native(meta.name.clone(), meta, body);
1575 }
1576
1577 pub(super) fn register_host(
1578 &mut self,
1579 module: &str,
1580 name: String,
1581 mut meta: FuncMeta,
1582 func: NativeFn<P>,
1583 ) {
1584 meta.kind = FuncKind::HostCtx;
1585 self.insert_qualified(module, name, meta, FuncBody::Ctx(func));
1586 }
1587
1588 pub(super) fn register_pure_host(
1589 &mut self,
1590 module: &str,
1591 name: String,
1592 mut meta: FuncMeta,
1593 func: PureFn,
1594 ) {
1595 meta.kind = FuncKind::HostPure;
1596 self.insert_qualified(module, name, meta, FuncBody::Pure(func));
1597 }
1598
1599 pub(super) fn register_both_host(
1600 &mut self,
1601 module: &str,
1602 name: String,
1603 mut meta: FuncMeta,
1604 func: NativeFn<P>,
1605 template: PureFn,
1606 ) {
1607 meta.kind = FuncKind::HostCtx;
1608 self.insert_qualified(
1609 module,
1610 name,
1611 meta,
1612 FuncBody::Both {
1613 pure: template,
1614 ctx: func,
1615 },
1616 );
1617 }
1618
1619 #[allow(clippy::too_many_arguments)]
1624 pub(super) fn define_script(
1625 &mut self,
1626 name: &str,
1627 params: &[(String, TypeTag, bool)],
1628 return_type: TypeTag,
1629 return_spelling: &str,
1630 is_async: bool,
1631 body: &[Step],
1632 module: Option<&str>,
1633 def_jail: Option<(WorkspaceSelection, GuardedPath)>,
1634 ) -> DiagnosticResult<()> {
1635 let qualified = qualify(SCRIPT_MODULE_NAME, name);
1636 let shadowable = matches!(
1637 self.entries.get(&qualified).map(|entry| &entry.body),
1638 Some(FuncBody::Script(_))
1639 );
1640 let reserved = self.entries.iter().any(|(key, entry)| {
1645 split_qualified(key).is_some_and(|(_, base)| base == name)
1646 && !matches!(entry.body, FuncBody::Script(_))
1647 });
1648 if reserved && !shadowable {
1649 return Err(std_diag::func_shadow_reserved(name));
1650 }
1651 if self
1652 .scopes
1653 .last()
1654 .is_some_and(|frame| frame.defined.contains(&qualified))
1655 {
1656 return Err(std_diag::func_duplicate_in_scope(name));
1657 }
1658 check_script_param_tags(name, params)?;
1659 let old = self.entries.insert(
1660 qualified.clone(),
1661 FuncEntry {
1662 meta: FuncMeta {
1663 name: qualified.clone(),
1664 module: SCRIPT_MODULE_NAME.to_string(),
1665 kind: FuncKind::Script,
1666 params: Some(
1667 params
1668 .iter()
1669 .map(|(pname, param_type, optional)| {
1670 Ok(FuncParam {
1671 name: pname.clone(),
1672 param_type: Some(param_type.clone()),
1673 allowed: None,
1674 docs: "",
1677 options: None,
1678 optional: *optional,
1679 })
1680 })
1681 .collect::<DiagnosticResult<_>>()?,
1682 ),
1683 returns: Some(return_type.clone()),
1684 rpn: false,
1685 summary: "DSL-defined function.",
1686 docs: "Defined via FUNC in script.",
1687 examples: &[],
1688 },
1689 body: FuncBody::Script(FuncDefData {
1690 params: params.to_vec(),
1691 return_type,
1692 return_spelling: return_spelling.to_string(),
1693 is_async,
1694 body: body.to_vec(),
1695 module: module.map(|m| m.to_string()),
1696 def_jail,
1697 }),
1698 },
1699 );
1700 if let Some(frame) = self.scopes.last_mut() {
1701 frame.defined.insert(qualified.clone());
1702 if let Some(old) = old {
1703 frame.shadowed.push((qualified, old));
1704 }
1705 }
1706 Ok(())
1707 }
1708
1709 #[allow(clippy::too_many_arguments)]
1715 pub(super) fn define_file_func(
1716 &mut self,
1717 name: &str,
1718 params: &[(String, TypeTag, bool)],
1719 return_type: TypeTag,
1720 return_spelling: &str,
1721 is_async: bool,
1722 body: &[Step],
1723 defining: &str,
1724 ) -> DiagnosticResult<()> {
1725 let qualified = file_func_key(defining, name);
1729 let shadowable = matches!(
1730 self.entries.get(&qualified).map(|entry| &entry.body),
1731 Some(FuncBody::Script(_))
1732 );
1733 let reserved = self.entries.iter().any(|(key, entry)| {
1737 split_qualified(key).is_some_and(|(_, base)| base == name)
1738 && !matches!(entry.body, FuncBody::Script(_))
1739 });
1740 if reserved && !shadowable {
1741 return Err(std_diag::func_shadow_reserved(name));
1742 }
1743 let frame_idx = 0;
1747 if self
1748 .scopes
1749 .get(frame_idx)
1750 .is_some_and(|frame| frame.defined.contains(&qualified))
1751 {
1752 return Err(std_diag::func_duplicate_in_scope(name));
1753 }
1754 check_script_param_tags(name, params)?;
1755 let old = self.entries.insert(
1756 qualified.clone(),
1757 FuncEntry {
1758 meta: FuncMeta {
1759 name: qualified.clone(),
1760 module: defining.to_string(),
1761 kind: FuncKind::Script,
1762 params: Some(
1763 params
1764 .iter()
1765 .map(|(pname, param_type, optional)| {
1766 Ok(FuncParam {
1767 name: pname.clone(),
1768 param_type: Some(param_type.clone()),
1769 allowed: None,
1770 docs: "",
1771 options: None,
1772 optional: *optional,
1773 })
1774 })
1775 .collect::<DiagnosticResult<_>>()?,
1776 ),
1777 returns: Some(return_type.clone()),
1778 rpn: false,
1779 summary: "DSL-defined function.",
1780 docs: "Defined via FUNC in an imported script.",
1781 examples: &[],
1782 },
1783 body: FuncBody::Script(FuncDefData {
1784 params: params.to_vec(),
1785 return_type,
1786 return_spelling: return_spelling.to_string(),
1787 is_async,
1788 body: body.to_vec(),
1789 module: Some(defining.to_string()),
1790 def_jail: None,
1795 }),
1796 },
1797 );
1798 if let Some(frame) = self.scopes.get_mut(frame_idx) {
1799 frame.defined.insert(qualified.clone());
1800 if let Some(old) = old {
1801 frame.shadowed.push((qualified, old));
1802 }
1803 }
1804 Ok(())
1805 }
1806
1807 pub(super) fn seal_canonical_jail(
1815 &mut self,
1816 canonical: &str,
1817 jail: (WorkspaceSelection, GuardedPath),
1818 ) {
1819 if let Some(entry) = self.entries.get_mut(canonical)
1820 && let FuncBody::Script(def) = &mut entry.body
1821 && def.def_jail.is_none()
1822 {
1823 def.def_jail = Some(jail);
1824 }
1825 }
1826
1827 pub(super) fn push_scope(&mut self) {
1830 self.scopes.push(ScopeFrame {
1831 defined: HashSet::new(),
1832 shadowed: Vec::new(),
1833 });
1834 }
1835
1836 pub(super) fn pop_scope(&mut self) {
1839 let Some(frame) = self.scopes.pop() else {
1840 return;
1841 };
1842 for name in frame.defined {
1843 self.entries.remove(&name);
1844 }
1845 for (name, old) in frame.shadowed {
1846 self.entries.insert(name, old);
1847 }
1848 }
1849
1850 pub(super) fn resolve_file_call_key(
1853 &self,
1854 unit_targets: &AliasTargets,
1855 name: &str,
1856 ) -> DiagnosticResult<Option<String>> {
1857 match classify_alias_call(unit_targets, name, &|key| self.entries.contains_key(key)) {
1858 AliasResolution::Global | AliasResolution::Unknown | AliasResolution::Any { .. } => {
1859 Ok(None)
1860 }
1861 AliasResolution::Canonical(key) => Ok(Some(key)),
1862 AliasResolution::Ambiguous { alias, base, files } => {
1863 Err(std_diag::func_ambiguous_alias(&alias, &base, &files))
1864 }
1865 }
1866 }
1867
1868 pub(super) fn pure_shared(&self) -> Arc<PureTable> {
1872 Arc::clone(&self.pure_shared)
1873 }
1874
1875 pub(super) fn all_metas(&self) -> Vec<FuncMeta> {
1878 self.entries_metas()
1879 }
1880
1881 fn meta(&self, name: &str) -> Option<FuncMeta> {
1882 self.entries.get(name).map(|entry| entry.meta.clone())
1883 }
1884
1885 fn native_metas(&self) -> Vec<FuncMeta> {
1886 let mut out: Vec<FuncMeta> = Vec::new();
1887 for entry in self.entries.values() {
1888 if !matches!(entry.body, FuncBody::Script(_)) {
1889 out.push(entry.meta.clone());
1890 }
1891 }
1892 out.sort_by(|a, b| a.name.cmp(&b.name));
1893 out
1894 }
1895
1896 pub(super) fn pure_metas(&self) -> Vec<FuncMeta> {
1901 let mut out: Vec<FuncMeta> = Vec::new();
1902 for entry in self.entries.values() {
1903 if matches!(entry.body, FuncBody::Pure(_) | FuncBody::Both { .. }) {
1904 out.push(entry.meta.clone());
1905 }
1906 }
1907 out.sort_by(|a, b| a.name.cmp(&b.name));
1908 out
1909 }
1910
1911 fn entries_metas(&self) -> Vec<FuncMeta> {
1914 let mut out: Vec<FuncMeta> = self
1915 .entries
1916 .values()
1917 .map(|entry| entry.meta.clone())
1918 .collect();
1919 out.sort_by(|a, b| a.name.cmp(&b.name));
1920 out
1921 }
1922
1923 pub fn set_script_docs(&mut self, docs: &HashMap<String, (String, String)>) {
1926 for (base, pair) in docs {
1927 self.script_docs
1928 .insert(qualify(SCRIPT_MODULE_NAME, base), pair.clone());
1929 }
1930 }
1931
1932 pub fn script_doc_for(&self, qualified: &str) -> Option<(String, String)> {
1934 self.script_docs.get(qualified).cloned()
1935 }
1936
1937 pub fn exported_metas(
1942 &self,
1943 func_exports: &[String],
1944 unit_targets: &AliasTargets,
1945 ) -> DiagnosticResult<Vec<FuncMeta>> {
1946 let mut out = Vec::with_capacity(func_exports.len());
1947 for name in func_exports {
1948 let qualified = match split_qualified(name) {
1952 None => qualify(SCRIPT_MODULE_NAME, name),
1953 Some(_) => name.clone(),
1954 };
1955 let lookup = self
1956 .resolve_file_call_key(unit_targets, &qualified)?
1957 .unwrap_or_else(|| qualified.clone());
1958 if let Some(entry) = self.entries.get(&lookup) {
1959 let mut meta = entry.meta.clone();
1960 if lookup != qualified {
1961 meta.name = name.clone();
1962 }
1963 out.push(meta);
1964 continue;
1965 }
1966 return Err(std_diag::func_export_unknown(name));
1967 }
1968 Ok(out)
1969 }
1970}
1971
1972impl<P: ProcessManager> Clone for FunctionRegistry<P> {
1973 fn clone(&self) -> Self {
1974 Self {
1975 entries: self.entries.clone(),
1976 scopes: self.scopes.clone(),
1977 pure_shared: Arc::clone(&self.pure_shared),
1978 script_docs: self.script_docs.clone(),
1979 }
1980 }
1981}
1982
1983pub fn builtin_function_names() -> HashSet<String> {
1990 let mut names = FunctionRegistry::<DefaultProcessManager>::with_builtins().keys();
1991 names.insert(KEYWORD_INSPECT.to_string());
1992 names
1993}
1994
1995pub fn builtin_function_metas() -> Vec<FuncMeta> {
1999 FunctionRegistry::<DefaultProcessManager>::with_builtins().native_metas()
2000}
2001
2002pub fn std_module_table() -> oxdock_parser::ModuleTable {
2007 let func_names: HashSet<String> = builtin_function_metas()
2009 .into_iter()
2010 .map(|meta| base_name(&meta.name).to_string())
2011 .collect();
2012 oxdock_parser::ModuleTable {
2013 modules: HashMap::from([(
2014 STD_MODULE_NAME.to_string(),
2015 Some(oxdock_parser::ModuleFuncs { func_names }),
2016 )]),
2017 }
2018}
2019
2020#[oxdock_func(pure, returns = TypeTag::Int)]
2033#[example(
2034 name = "convert",
2035 code = r###"
2036 IMPORT [STD]
2037 LET $n: INT = INT("42")
2038 ASSERT_EQ $n 42
2039 LET $flag: INT = INT(true)
2040 ASSERT_EQ $flag 1
2041 "###
2042)]
2043fn int(
2044 #[union(Int, Float, String, Bool)]
2046 val: Value,
2047) -> Result<Value> {
2048 Ok(super::args::int_from_value(val)?)
2049}
2050
2051#[oxdock_func(pure, returns = TypeTag::Float)]
2056#[example(
2057 name = "convert",
2058 code = r###"
2059 IMPORT [STD]
2060 LET $f: FLOAT = FLOAT("1.5")
2061 ASSERT_EQ $f 1.5
2062 LET $whole: FLOAT = FLOAT(2)
2063 ASSERT_EQ $whole 2.0
2064 "###
2065)]
2066fn float(
2067 #[union(Float, Int, String)]
2069 val: Value,
2070) -> Result<Value> {
2071 Ok(super::args::float_from_value(val)?)
2072}
2073
2074#[oxdock_func(pure, returns = TypeTag::String)]
2079#[example(
2080 name = "format and round-trip",
2081 code = r###"
2082 # Byte counts render in the largest exact unit.
2083 IMPORT [STD]
2084 LET $pretty: STRING = FORMAT_BYTE_COUNT(1_048_576)
2085 ASSERT_EQ $pretty "1MiB"
2086
2087 # The pair round-trips through the parser.
2088 LET $back: INT = PARSE_BYTE_COUNT($pretty)
2089 ASSERT_EQ $back 1_048_576
2090 "###
2091)]
2092fn format_byte_count(
2093 bytes: i64,
2095) -> Result<Value> {
2096 if bytes < 0 {
2097 return Err(anyhow::Error::new(
2098 std_diag::std_format_byte_count_negative(bytes),
2099 ));
2100 }
2101 Ok(Value::string(oxdock_parser::command::format_byte_count(
2102 bytes as u64,
2103 )))
2104}
2105
2106#[oxdock_func(pure, returns = TypeTag::Int)]
2141#[example(
2142 name = "parse",
2143 code = r###"
2144 IMPORT [STD]
2145 LET $n: INT = PARSE_BYTE_COUNT("10KB")
2146 ASSERT_EQ $n 10_000
2147 LET $identity: INT = PARSE_BYTE_COUNT(512)
2148 ASSERT_EQ $identity 512
2149 "###
2150)]
2151fn parse_byte_count(
2152 #[union(Int, Float, String)]
2154 text: Value,
2155) -> Result<Value> {
2156 if let Some(n) = text.as_i64() {
2157 if n < 0 {
2158 return Err(anyhow::Error::new(std_diag::std_parse_byte_count_negative(
2159 n,
2160 )));
2161 }
2162 return Ok(Value::int(n));
2163 }
2164 if let Some(f) = text.as_f64() {
2165 if f.is_finite() && f.fract() == 0.0 && f >= 0.0 && f <= i64::MAX as f64 {
2166 return Ok(Value::int(f as i64));
2167 }
2168 return Err(anyhow::Error::new(std_diag::std_parse_byte_count_integral(
2169 f,
2170 )));
2171 }
2172 let Some(s) = text.as_str() else {
2173 return Err(anyhow::Error::new(std_diag::std_parse_byte_count_shape(
2174 &text,
2175 )));
2176 };
2177 let n = oxdock_parser::command::parse_byte_count(s)?;
2178 let n = i64::try_from(n)
2179 .map_err(|_| anyhow::Error::new(std_diag::std_parse_byte_count_range(s)))?;
2180 Ok(Value::int(n))
2181}
2182
2183#[oxdock_func(pure, returns = TypeTag::String)]
2188#[example(
2189 name = "format and round-trip",
2190 code = r###"
2191 # Durations render in the largest exact unit.
2192 IMPORT [STD]
2193 LET $pretty: STRING = FORMAT_DURATION(90_000)
2194 ASSERT_EQ $pretty "90s"
2195
2196 # The pair round-trips through the parser.
2197 LET $back: INT = PARSE_DURATION($pretty)
2198 ASSERT_EQ $back 90_000
2199 "###
2200)]
2201fn format_duration(
2202 millis: i64,
2204) -> Result<Value> {
2205 if millis < 0 {
2206 return Err(anyhow::Error::new(std_diag::std_format_duration_negative(
2207 millis,
2208 )));
2209 }
2210 Ok(Value::string(oxdock_parser::command::format_duration(
2211 &std::time::Duration::from_millis(millis as u64),
2212 )))
2213}
2214
2215#[oxdock_func(pure, returns = TypeTag::Int)]
2221#[example(
2222 name = "parse",
2223 code = r###"
2224 # A bare number means seconds, like TIMEOUT.
2225 IMPORT [STD]
2226 LET $ms: INT = PARSE_DURATION("2m")
2227 ASSERT_EQ $ms 120_000
2228
2229 # Milliseconds stay exact.
2230 LET $exact: INT = PARSE_DURATION("1500ms")
2231 ASSERT_EQ $exact 1_500
2232
2233 # One optional space separates number from unit.
2234 LET $spaced: INT = PARSE_DURATION("1 h")
2235 ASSERT_EQ $spaced 3_600_000
2236 "###
2237)]
2238fn parse_duration(
2239 text: String,
2241) -> Result<Value> {
2242 let duration = oxdock_parser::command::parse_duration(&text)?;
2243 let millis = i64::try_from(duration.as_millis())
2244 .map_err(|_| anyhow::Error::new(std_diag::std_parse_duration_range(&text)))?;
2245 Ok(Value::int(millis))
2246}
2247
2248#[oxdock_func(rpn, returns = TypeTag::ListOf(std::sync::Arc::new(TypeTag::String)))]
2253#[example(
2254 name = "match",
2255 code = r###"
2256 IMPORT [STD]
2257 WRITE "notes-a.md" "a"
2258 WRITE "notes-b.md" "b"
2259 WRITE "other.txt" "c"
2260 LET $found: LIST<STRING> = GLOB("notes-*.md")
2261 ASSERT_EQ $found.0 "notes-a.md"
2262 ASSERT_EQ $found.1 "notes-b.md"
2263 "###
2264)]
2265fn glob<P: ProcessManager>(
2266 cx: &mut StepCtx<P>,
2267 #[union(String, Path)]
2269 pattern: Value,
2270) -> Result<Value> {
2271 let text = super::args::string_or_path_text(&pattern)?;
2272 Ok(super::args::glob_from_value(&[Value::string(text)], cx)?)
2273}
2274
2275#[oxdock_func(rpn, returns = TypeTag::MapOf(std::sync::Arc::new(TypeTag::Any)))]
2280#[example(
2281 name = "load",
2282 code = r###"
2283 IMPORT [STD]
2284 WRITE "cfg.toml" "title = \"demo\""
2285 LET $cfg: MAP<ANY> = LOAD_TOML("cfg.toml")
2286 ASSERT_EQ $cfg.title "demo"
2287 "###
2288)]
2289fn load_toml<P: ProcessManager>(
2290 cx: &mut StepCtx<P>,
2291 #[union(String, Path)]
2293 path: Value,
2294) -> Result<Value> {
2295 let text = super::args::string_or_path_text(&path)?;
2296 Ok(super::args::load_toml_from_value(
2297 &[Value::string(text)],
2298 cx,
2299 )?)
2300}
2301
2302#[oxdock_func(rpn, returns = TypeTag::Any)]
2310#[example(
2311 name = "load",
2312 code = r###"
2313 IMPORT [STD]
2314 WRITE "data.json" "{\"a\": 1}"
2315 LET $doc: MAP<ANY> = LOAD_JSON("data.json")
2316 ASSERT_EQ $doc.a 1
2317 "###
2318)]
2319fn load_json<P: ProcessManager>(
2320 cx: &mut StepCtx<P>,
2321 #[union(String, Path)]
2323 path: Value,
2324) -> Result<Value> {
2325 let text = super::args::string_or_path_text(&path)?;
2326 Ok(super::args::load_json_from_value(
2327 &[Value::string(text)],
2328 cx,
2329 )?)
2330}
2331
2332#[oxdock_func(rpn, returns = TypeTag::String)]
2342#[example(
2343 name = "hash",
2344 code = r###"
2345 IMPORT [STD]
2346 WRITE payload.txt hello
2347 LET $digest: STRING = HASH_SHA256("payload.txt")
2348 ASSERT_EQ $digest "2cf24dba5fb0a30e26e83b2ac5b9e29e1b161e5c1fa7425e73043362938b9824"
2349 "###
2350)]
2351fn hash_sha256<P: ProcessManager>(
2352 cx: &mut StepCtx<P>,
2353 #[union(String, Path)]
2355 path: Value,
2356) -> Result<Value> {
2357 use sha2::Digest;
2358
2359 let text = super::args::string_or_path_text(&path)?;
2360 let target = cx.state.fs.resolve_read(&cx.state.cwd, &text)?;
2361 let mut hasher = sha2::Sha256::new();
2362 super::fs_ops::hash_path(cx.state.fs.as_ref(), &target, "", &mut hasher)?;
2363 let digest = hasher.finalize();
2364 let bytes: &[u8] = digest.as_ref();
2365 Ok(Value::string(oxdock_utils::hex_encode(bytes)))
2366}
2367
2368#[oxdock_func(rpn, returns = TypeTag::String)]
2379#[example(
2380 name = "cwd",
2381 code = r###"
2382 IMPORT [STD]
2383 WORKDIR sub
2384 LET $c: STRING = CWD()
2385 ASSERT_CONTAINS $c "sub"
2386 "###
2387)]
2388fn cwd<P: ProcessManager>(cx: &mut StepCtx<P>) -> Result<Value> {
2389 if cx.state.fs.is_snapshot_pending() {
2390 return Ok(Value::string(super::SNAPSHOT_PENDING_DISPLAY.to_string()));
2391 }
2392 let concrete = cx.state.fs.concretize_cwd(&cx.state.cwd);
2393 let real = super::fs_ops::canonical_cwd(cx.state.fs.as_ref(), &concrete)?;
2394 Ok(Value::string(real))
2395}
2396
2397#[oxdock_func(pure, returns = TypeTag::MapOf(std::sync::Arc::new(TypeTag::Any)))]
2403#[example(
2404 name = "parse",
2405 code = r###"
2406 IMPORT [STD]
2407 LET $doc: MAP<ANY> = PARSE_TOML("title = \"demo\"")
2408 ASSERT_EQ $doc.title "demo"
2409 "###
2410)]
2411fn parse_toml(
2412 text: String,
2414) -> Result<Value> {
2415 Ok(super::args::parse_toml_from_value(Value::string(text))?)
2416}
2417
2418#[oxdock_func(pure, returns = TypeTag::Any)]
2427#[example(
2428 name = "parse",
2429 code = r###"
2430 # Parse in-memory JSON text with the same conversion as file loading.
2431 IMPORT [STD]
2432 LET $body: STRING = "{\"a\": 1}"
2433 LET $doc: ANY = PARSE_JSON($body)
2434 ASSERT_EQ $doc.a 1
2435
2436 # Top-level arrays parse to LIST, which is why the return is ANY.
2437 LET $items: LIST<ANY> = PARSE_JSON("[1, 2]")
2438 ASSERT_EQ $items.0 1
2439 ASSERT_EQ $items.1 2
2440 "###
2441)]
2442fn parse_json(
2443 text: String,
2445) -> Result<Value> {
2446 Ok(super::args::parse_json_from_value(Value::string(text))?)
2447}
2448
2449#[oxdock_func(returns = TypeTag::String)]
2455#[example(
2456 name = "describe",
2457 code = r###"
2458 IMPORT [STD]
2459 WRITE "entry.txt" "words"
2460 LET $kind: STRING = PATH_TYPE("entry.txt")
2461 ASSERT_EQ $kind "file"
2462 LET $missing: STRING = PATH_TYPE("no-such-entry.txt")
2463 ASSERT_EQ $missing "absent"
2464 "###
2465)]
2466fn path_type<P: ProcessManager>(
2467 cx: &mut StepCtx<P>,
2468 #[union(String, Path)]
2470 path: Value,
2471) -> Result<Value> {
2472 let text = super::args::string_or_path_text(&path)?;
2473 Ok(super::args::path_type_from_value(
2474 &[Value::string(text)],
2475 cx,
2476 )?)
2477}
2478
2479#[oxdock_func(returns = TypeTag::Bool)]
2488#[example(
2489 name = "probe",
2490 code = r###"
2491 # An absent nested path is writable when its ancestor is.
2492 IMPORT [STD]
2493 LET $fresh: BOOL = PATH_WRITABLE("probe-check/nested/file.txt")
2494 ASSERT_EQ $fresh true
2495
2496 # The empty string never aliases the working directory.
2497 LET $empty: BOOL = PATH_WRITABLE("")
2498 ASSERT_EQ $empty false
2499 "###
2500)]
2501fn path_writable<P: ProcessManager>(
2502 cx: &mut StepCtx<P>,
2503 #[union(String, Path)]
2505 path: Value,
2506) -> Result<Value> {
2507 let text = super::args::string_or_path_text(&path)?;
2508 Ok(super::args::path_writable_from_value(
2509 &[Value::string(text)],
2510 cx,
2511 )?)
2512}
2513
2514#[oxdock_func(returns = TypeTag::Bool)]
2527#[example(
2528 name = "probe",
2529 code = r###"
2530 # Missing tools read false instead of failing the run.
2531 IMPORT [STD]
2532 LET $missing: BOOL = IS_EXEC("no-such-tool-xyz")
2533 ASSERT_EQ $missing false
2534
2535 # Plain files are not executable on any platform.
2536 WRITE tool.txt payload
2537 LET $plain: BOOL = IS_EXEC("tool.txt")
2538 ASSERT_EQ $plain false
2539 "###
2540)]
2541fn is_exec<P: ProcessManager>(
2542 cx: &mut StepCtx<P>,
2543 #[union(String, Path)]
2545 name: Value,
2546) -> Result<Value> {
2547 let text = super::args::string_or_path_text(&name)?;
2548 Ok(super::args::is_exec_from_value(&[Value::string(text)], cx)?)
2549}
2550
2551#[oxdock_func(returns = TypeTag::Bool)]
2559#[example(
2560 name = "probe",
2561 code = r###"
2562 # Ordinary files read true; missing paths read false.
2563 IMPORT [STD]
2564 WRITE "entry.txt" "words"
2565 LET $hit: BOOL = IS_FILE("entry.txt")
2566 ASSERT_EQ $hit true
2567 LET $miss: BOOL = IS_FILE("no-such-entry.txt")
2568 ASSERT_EQ $miss false
2569 "###
2570)]
2571fn is_file<P: ProcessManager>(
2572 cx: &mut StepCtx<P>,
2573 #[union(String, Path)]
2575 path: Value,
2576) -> Result<Value> {
2577 let text = super::args::string_or_path_text(&path)?;
2578 Ok(Value::bool(super::args::path_is_file(cx, &text)))
2579}
2580
2581#[oxdock_func(returns = TypeTag::Bool)]
2589#[example(
2590 name = "probe",
2591 code = r###"
2592 # Directories read true; files read false.
2593 IMPORT [STD]
2594 LET $hit: BOOL = IS_DIR(".")
2595 ASSERT_EQ $hit true
2596 WRITE "entry.txt" "words"
2597 LET $miss: BOOL = IS_DIR("entry.txt")
2598 ASSERT_EQ $miss false
2599 "###
2600)]
2601fn is_dir<P: ProcessManager>(
2602 cx: &mut StepCtx<P>,
2603 #[union(String, Path)]
2605 path: Value,
2606) -> Result<Value> {
2607 let text = super::args::string_or_path_text(&path)?;
2608 Ok(Value::bool(super::args::path_is_dir(cx, &text)))
2609}
2610
2611#[oxdock_func(returns = TypeTag::Bool)]
2618#[example(
2619 name = "probe",
2620 code = r###"
2621 # Present entries read true; absent paths read false.
2622 IMPORT [STD]
2623 WRITE "entry.txt" "words"
2624 LET $hit: BOOL = EXISTS("entry.txt")
2625 ASSERT_EQ $hit true
2626 LET $miss: BOOL = EXISTS("no-such-entry.txt")
2627 ASSERT_EQ $miss false
2628 "###
2629)]
2630fn exists<P: ProcessManager>(
2631 cx: &mut StepCtx<P>,
2632 #[union(String, Path)]
2634 path: Value,
2635) -> Result<Value> {
2636 let text = super::args::string_or_path_text(&path)?;
2637 Ok(Value::bool(super::args::path_exists(cx, &text)))
2638}
2639
2640#[oxdock_func(pure, returns = TypeTag::Bool)]
2646#[example(
2647 name = "probe",
2648 code = r###"
2649 IMPORT [STD]
2650 LET $m: MAP<ANY> = PARSE_JSON("{\"a\": 1}")
2651 LET $hit: BOOL = HAS_KEY($m, "a")
2652 ASSERT_EQ $hit true
2653 LET $miss: BOOL = HAS_KEY($m, "b")
2654 ASSERT_EQ $miss false
2655 "###
2656)]
2657fn has_key(
2658 map: BTreeMap<String, Value>,
2660 key: String,
2662) -> Result<Value> {
2663 Ok(super::args::has_key_from_value(Value::map(map), &key)?)
2664}
2665
2666#[oxdock_func(pure, returns = TypeTag::Any)]
2672#[example(
2673 name = "present and absent",
2674 code = r###"
2675 IMPORT [STD]
2676 LET $m: MAP<ANY> = PARSE_JSON("{\"a\": 1}")
2677 LET $hit: INT = GET($m, "a", 0)
2678 ASSERT_EQ $hit 1
2679 LET $miss: INT = GET($m, "b", 0)
2680 ASSERT_EQ $miss 0
2681 "###
2682)]
2683fn get(
2684 map: BTreeMap<String, Value>,
2686 key: String,
2688 default: Value,
2690) -> Result<Value> {
2691 Ok(map.get(&key).cloned().unwrap_or(default))
2692}
2693
2694#[oxdock_func(pure, returns = TypeTag::MapOf(std::sync::Arc::new(TypeTag::Any)))]
2704#[example(
2705 name = "insert",
2706 code = r###"
2707 IMPORT [STD]
2708 LET $m: MAP<ANY> = MAP_SET({seed: 0}, "a", 1)
2709 ASSERT_EQ $m.a 1
2710 "###
2711)]
2712fn map_set(
2713 #[reject_frozen]
2715 map: BTreeMap<String, Value>,
2716 key: String,
2718 value: Value,
2720) -> Result<Value> {
2721 Ok(super::args::map_set_from_value(
2722 Value::map(map),
2723 key,
2724 value,
2725 )?)
2726}
2727
2728#[oxdock_func(returns = TypeTag::Float, summary = "Draw a random FLOAT uniformly from [0, 1), optionally seeded.")]
2736#[example(
2737 name = "seeded draw",
2738 code = r###"
2739 # A seed draws the same value on every run.
2740 IMPORT [STD]
2741 LET $one: FLOAT = RAND({seed: 7})
2742 LET $two: FLOAT = RAND({seed: 7})
2743 ASSERT_EQ $one $two
2744 "###
2745)]
2746#[example(
2747 name = "unseeded draw",
2748 code = r###"
2749 # Scale a unit draw into a backoff delay between 1 and 11 seconds.
2750 IMPORT [STD]
2751 LET $draw: FLOAT = RAND()
2752 LET $delay: FLOAT = 1.0 + $draw * 10.0
2753 IF $delay < 1.0 {
2754 FAIL "trap: RAND draw below range"
2755 }
2756 IF $delay >= 11.0 {
2757 FAIL "trap: RAND draw above range"
2758 }
2759 ECHO "retrying in {{ $delay }}s"
2760 "###
2761)]
2762fn rand<P: ProcessManager>(
2763 cx: &mut StepCtx<P>,
2764 #[options("seed?: INT")]
2766 #[optional]
2767 options: BTreeMap<String, Value>,
2768) -> Result<Value> {
2769 let _ = cx;
2770 let seed = options
2773 .get("seed")
2774 .map(|value| value.as_i64().expect("check_options verified INT"));
2775 Ok(super::args::rand_float_from_value(seed)?)
2776}
2777
2778#[oxdock_func(pure, returns = TypeTag::String)]
2784#[example(
2785 name = "encode",
2786 code = r###"
2787 # Encode text to standard base64.
2788 IMPORT [STD]
2789 LET $encoded: STRING = BASE64_ENCODE("hello")
2790 ASSERT_EQ $encoded "aGVsbG8="
2791 "###
2792)]
2793fn base64_encode(
2794 text: String,
2796) -> Result<Value> {
2797 Ok(super::args::base64_encode_from_value(Value::string(text))?)
2798}
2799
2800#[oxdock_func(pure, returns = TypeTag::String)]
2807#[example(
2808 name = "decode",
2809 code = r###"
2810 # Decode standard base64 back to text.
2811 IMPORT [STD]
2812 LET $decoded: STRING = BASE64_DECODE("aGVsbG8=")
2813 ASSERT_EQ $decoded "hello"
2814 "###
2815)]
2816fn base64_decode(
2817 text: String,
2819) -> Result<Value> {
2820 Ok(super::args::base64_decode_from_value(Value::string(text))?)
2821}
2822
2823#[oxdock_func(pure, returns = TypeTag::String)]
2830#[example(
2831 name = "encode",
2832 code = r###"
2833 IMPORT [STD]
2834 LET $json: STRING = TO_JSON({a: 1})
2835 ASSERT_EQ $json "{\"a\":1}\n"
2836 "###
2837)]
2838fn to_json(
2839 #[union(String, Int, Float, Bool, List, Map)]
2841 value: Value,
2842) -> Result<Value> {
2843 Ok(super::args::to_json_from_value(value)?)
2844}
2845
2846#[oxdock_func(pure, returns = TypeTag::String)]
2854#[example(
2855 name = "name the word",
2856 code = r###"
2857 IMPORT [STD]
2858 LET $word: STRING = TYPE_OF(42)
2859 ASSERT_EQ $word "INT"
2860 "###
2861)]
2862fn type_of(
2863 value: Value,
2865) -> Result<Value> {
2866 Ok(super::args::type_of_from_value(value)?)
2867}
2868
2869#[oxdock_func(pure, returns = TypeTag::MapOf(std::sync::Arc::new(TypeTag::Any)))]
2881#[example(
2882 name = "merge",
2883 code = r###"
2884 IMPORT [STD]
2885 LET $m: MAP<ANY> = MERGE_MAPS([{a: 1}, {b: 2}], "overwrite")
2886 ASSERT_EQ $m.a 1
2887 ASSERT_EQ $m.b 2
2888 "###
2889)]
2890fn merge_maps(
2891 #[reject_frozen]
2893 maps: Vec<BTreeMap<String, Value>>,
2894 #[values("fail_on_duplicate", "overwrite")]
2896 policy: String,
2897) -> Result<Value> {
2898 Ok(super::args::merge_maps_from_value(
2899 Value::list(maps.into_iter().map(Value::map).collect()),
2900 policy,
2901 )?)
2902}
2903
2904#[oxdock_func(pure, returns = TypeTag::String)]
2909#[example(
2910 name = "report",
2911 code = r###"
2912 # The engine reports its own build version as a dotted string.
2913 IMPORT [STD]
2914 LET $v: STRING = VERSION()
2915 ASSERT_CONTAINS $v "."
2916 "###
2917)]
2918fn version() -> Result<Value> {
2919 Ok(Value::string(env!("CARGO_PKG_VERSION").to_string()))
2920}
2921
2922#[oxdock_func(returns = TypeTag::ListOf(std::sync::Arc::new(TypeTag::String)))]
2927#[example(
2928 name = "list",
2929 code = r###"
2930 IMPORT [STD]
2931 LET $names: LIST<STRING> = FUNCTIONS()
2932 ASSERT_CONTAINS $names "STD::INT"
2933 "###
2934)]
2935fn functions<P: ProcessManager>(cx: &mut StepCtx<P>) -> Result<Value> {
2936 let mut names: Vec<String> = cx
2937 .state
2938 .list_functions()
2939 .into_iter()
2940 .map(|meta| meta.name)
2941 .collect();
2942 names.sort();
2943 names.dedup();
2944 Ok(Value::list(names.into_iter().map(Value::string).collect()))
2945}
2946
2947#[oxdock_func(returns = TypeTag::ListOf(std::sync::Arc::new(TypeTag::String)))]
2954#[example(
2955 name = "empty",
2956 code = r###"
2957 # With no staged args the list is empty.
2958 IMPORT [STD]
2959 LET $args: LIST<STRING> = ARGV()
2960 LET $n: INT = LEN($args)
2961 ASSERT_EQ $n 0
2962 "###
2963)]
2964fn argv<P: ProcessManager>(cx: &mut StepCtx<P>) -> Result<Value> {
2965 Ok(Value::list(
2966 cx.state
2967 .io
2968 .script_args()
2969 .iter()
2970 .cloned()
2971 .map(Value::string)
2972 .collect(),
2973 ))
2974}
2975
2976pub struct ParseArgs;
2996
2997impl<P: ProcessManager> OxDockFn<P> for ParseArgs {
2998 fn registration() -> HostRegistration<P> {
2999 let func: NativeFn<P> = Arc::new(|cx: &mut StepCtx<P>, values: Vec<Value>| {
3000 if values.len() != 1 {
3001 return Err(anyhow::Error::new(std_diag::std_parse_args_arity(
3002 values.len(),
3003 )));
3004 }
3005 let mut iter = values.into_iter();
3006 let args_val = iter.next().expect("arity checked above");
3007 let args =
3008 string_list_arg(&args_val, &format!("{FUNC_PARSE_ARGS}() argument `$args`"))?;
3009 let specs = resolve_flags_specs(cx)?;
3010 let (raw, positionals) = tokenize_raw_args(args)?;
3011 let coerced = coerce_flags(&specs, &raw)?;
3012 let mut out = BTreeMap::new();
3013 out.insert("flags".to_string(), Value::map(coerced));
3014 if !positionals.is_empty() {
3015 out.insert("positionals".to_string(), Value::list(positionals));
3016 }
3017 Ok(Value::map(out))
3018 });
3019 HostRegistration::Stateful {
3020 name: FUNC_PARSE_ARGS.to_string(),
3021 meta: FuncMeta {
3022 name: FUNC_PARSE_ARGS.to_string(),
3023 module: String::new(),
3024 kind: FuncKind::HostPure,
3025 params: Some(vec![FuncParam {
3026 name: "args".to_string(),
3027 param_type: Some(TypeTag::ListOf(Arc::new(TypeTag::String))),
3028 allowed: None,
3029 docs: "Argv tail to parse, usually from `STD::ARGV()`.",
3030 options: None,
3031 optional: false,
3032 }]),
3033 returns: Some(TypeTag::Record(Arc::from([
3034 Field {
3035 name: "flags".to_string(),
3036 ty: TypeTag::Map,
3037 docs: "Flags coerced to `TYPE FLAGS`.",
3038 optional: false,
3039 default: None,
3040
3041 alias: None,
3042 },
3043 Field {
3044 name: "positionals".to_string(),
3045 ty: TypeTag::ListOf(Arc::new(TypeTag::String)),
3046 docs: "Trailing values and entries after the first double dash. Omitted when empty.",
3047 optional: true,
3048 default: None,
3049
3050 alias: None,
3051 },
3052 ]))),
3053 rpn: true,
3054 summary: "Parse an argv tail against TYPE FLAGS.",
3055 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.",
3056 examples: &[
3057 crate::Example {
3058 name: "flags and positionals",
3059 fence_meta: None,
3060 code: indoc::indoc! {r#"
3061 IMPORT [STD]
3062 # One schema TYPE drives coercion; the pair binds both slots.
3063 TYPE FLAGS = MAP<model: STRING, verbose?: BOOL>
3064 TYPE POSITIONS = LIST<STRING>
3065 TYPE PARSED = MAP<flags: FLAGS, positionals?: POSITIONS>
3066 LET $parsed: PARSED = PARSE_ARGS(["--model=gpt-4", "--verbose", "serve"])
3067 LET $flags: FLAGS = $parsed.flags
3068 ASSERT_EQ $flags.model "gpt-4"
3069 ASSERT_EQ $flags.verbose true
3070 ASSERT_EQ $parsed.positionals.0 "serve"
3071 "#},
3072 },
3073 crate::Example {
3074 name: "optional stays absent",
3075 fence_meta: None,
3076 code: indoc::indoc! {r#"
3077 IMPORT [STD]
3078 # Absent optionals stay absent; read them with a typed GET default.
3079 TYPE FLAGS = MAP<model: STRING, propose?: BOOL>
3080 TYPE POSITIONS = LIST<STRING>
3081 TYPE PARSED = MAP<flags: FLAGS, positionals?: POSITIONS>
3082 LET $parsed: PARSED = PARSE_ARGS(["--model=x"])
3083 LET $flags: FLAGS = $parsed.flags
3084 LET $propose: BOOL = GET($flags, "propose", false)
3085 ASSERT_EQ $propose false
3086 "#},
3087 },
3088 crate::Example {
3089 name: "flags only omits positionals",
3090 fence_meta: None,
3091 code: indoc::indoc! {r#"
3092 IMPORT [STD]
3093 # Empty positionals are omitted, so a flags only shape binds clean.
3094 TYPE FLAGS = MAP<model: STRING>
3095 TYPE PARSED = MAP<flags: FLAGS>
3096 LET $parsed: PARSED = PARSE_ARGS(["--model=x"])
3097 LET $flags: FLAGS = $parsed.flags
3098 ASSERT_EQ $flags.model "x"
3099 "#},
3100 },
3101 crate::Example {
3102 name: "literal defaults",
3103 fence_meta: None,
3104 code: indoc::indoc! {r#"
3105 IMPORT [STD]
3106 # Defaults are literals only: INT, FLOAT, BOOL,
3107 # and double-quoted STRING fill absent flags.
3108 TYPE FLAGS = MAP<retries: INT = 2, ratio: FLOAT = 2.5, verbose: BOOL = true, model: STRING = "gpt-4">
3109 TYPE PARSED = MAP<flags: FLAGS>
3110 LET $parsed: PARSED = PARSE_ARGS([])
3111 LET $flags: FLAGS = $parsed.flags
3112 ASSERT_EQ $flags.retries 2
3113 ASSERT_EQ $flags.verbose true
3114 ASSERT_EQ $flags.model "gpt-4"
3115 LET $ratio_ok: BOOL = $flags.ratio == 2.5
3116 ASSERT_EQ $ratio_ok true
3117 "#},
3118 },
3119 crate::Example {
3120 name: "variable default fails",
3121 fence_meta: Some("expect_error:\"expected default literal\""),
3122 code: indoc::indoc! {r#"
3123 IMPORT [STD]
3124 # Defaults are literals: a variable in place
3125 # of a literal fails instead of evaluating.
3126 TYPE FLAGS = MAP<n: INT = $x>
3127 TYPE PARSED = MAP<flags: FLAGS>
3128 LET $p: PARSED = PARSE_ARGS([])
3129 "#},
3130 },
3131 crate::Example {
3132 name: "missing required",
3133 fence_meta: Some("expect_error:\"missing required flag\""),
3134 code: indoc::indoc! {r#"
3135 IMPORT [STD]
3136 # Absent required flags fail naming the flag.
3137 TYPE FLAGS = MAP<model: STRING>
3138 TYPE PARSED = MAP<flags: FLAGS>
3139 LET $parsed: PARSED = PARSE_ARGS([])
3140 "#},
3141 },
3142 crate::Example {
3143 name: "unknown flag",
3144 fence_meta: Some("expect_error:\"unknown flag\""),
3145 code: indoc::indoc! {r#"
3146 IMPORT [STD]
3147 # Undeclared flags fail instead of passing through.
3148 TYPE FLAGS = MAP<model: STRING>
3149 TYPE PARSED = MAP<flags: FLAGS>
3150 LET $parsed: PARSED = PARSE_ARGS(["--model=x", "--nope=1"])
3151 "#},
3152 },
3153 crate::Example {
3154 name: "alias accepted",
3155 fence_meta: None,
3156 code: indoc::indoc! {r#"
3157 IMPORT [STD]
3158 # One canonical key binds both spellings; the
3159 # alias never appears as a separate key.
3160 TYPE FLAGS = MAP<h: BOOL ALIAS help>
3161 TYPE PARSED = MAP<flags: FLAGS>
3162 LET $a: PARSED = PARSE_ARGS(["--help"])
3163 ASSERT_EQ $a.flags.h true
3164 LET $b: PARSED = PARSE_ARGS(["--h"])
3165 ASSERT_EQ $b.flags.h true
3166 "#},
3167 },
3168 crate::Example {
3169 name: "alias duplicate fails",
3170 fence_meta: Some("expect_error:\"duplicate flag\""),
3171 code: indoc::indoc! {r#"
3172 IMPORT [STD]
3173 # Canonical and alias together fail naming both.
3174 TYPE FLAGS = MAP<h: BOOL ALIAS help>
3175 TYPE PARSED = MAP<flags: FLAGS>
3176 LET $p: PARSED = PARSE_ARGS(["--h", "--help"])
3177 "#},
3178 },
3179 crate::Example {
3180 name: "alias missing names both",
3181 fence_meta: Some("expect_error:\"--h/--help\""),
3182 code: indoc::indoc! {r#"
3183 IMPORT [STD]
3184 # Missing required flags name both spellings.
3185 TYPE FLAGS = MAP<h: BOOL ALIAS help>
3186 TYPE PARSED = MAP<flags: FLAGS>
3187 LET $p: PARSED = PARSE_ARGS([])
3188 "#},
3189 },
3190 ],
3191 },
3192 func,
3193 }
3194 }
3195}
3196
3197#[derive(Debug, Clone, Copy, PartialEq, Eq)]
3201enum CliType {
3202 String,
3203 Bool,
3204 Int,
3205 Float,
3206}
3207
3208fn coerce_cli_flag(target: CliType, flag: &str, raw: Value) -> DiagnosticResult<Value> {
3213 match target {
3214 CliType::Bool => {
3215 if let Some(b) = raw.as_bool() {
3216 return Ok(Value::bool(b));
3217 }
3218 if let Some(s) = raw.as_str() {
3219 match super::args::parse_bool_str(s) {
3220 Some(b) => return Ok(Value::bool(b)),
3221 None => {
3222 return Err(std_diag::std_parse_args_bool_flag(flag, s));
3223 }
3224 }
3225 }
3226 Err(std_diag::std_parse_args_bool_type(flag, raw.type_name()))
3227 }
3228 CliType::String => {
3229 if let Some(s) = raw.as_str() {
3230 return Ok(Value::string(s.to_string()));
3231 }
3232 Err(std_diag::std_parse_args_needs_value(flag))
3233 }
3234 CliType::Int => {
3235 if raw.as_bool().is_some() {
3236 return Err(std_diag::std_parse_args_needs_value(flag));
3237 }
3238 super::args::int_from_value(raw).map_err(|_| std_diag::std_parse_args_expects_int(flag))
3239 }
3240 CliType::Float => {
3241 if raw.as_bool().is_some() {
3242 return Err(std_diag::std_parse_args_needs_value(flag));
3243 }
3244 super::args::float_from_value(raw)
3245 .map_err(|_| std_diag::std_parse_args_expects_float(flag))
3246 }
3247 }
3248}
3249
3250#[derive(Debug, Clone)]
3254struct CliSpec {
3255 target: CliType,
3256 required: bool,
3257 default: Option<Value>,
3258 alias: Option<String>,
3259}
3260
3261type CliSpecs = BTreeMap<String, CliSpec>;
3263
3264fn string_list_arg(val: &Value, what: &str) -> DiagnosticResult<Vec<String>> {
3267 crate::check_value_at(&TypeTag::ListOf(Arc::new(TypeTag::String)), val, what)
3268 .map_err(|err| std_diag::std_parse_args_arg_shape(&err))?;
3269 Ok(val
3270 .as_list()
3271 .expect("check_value_at enforces LIST")
3272 .iter()
3273 .map(|v| {
3274 v.as_str()
3275 .expect("check_value_at enforces STRING")
3276 .to_string()
3277 })
3278 .collect())
3279}
3280
3281fn tokenize_raw_args(args: Vec<String>) -> DiagnosticResult<(BTreeMap<String, Value>, Vec<Value>)> {
3285 use lexopt::Arg::{Long, Short, Value as ArgValue};
3286 let mut parser = lexopt::Parser::from_args(args);
3287 let mut flags: BTreeMap<String, Value> = BTreeMap::new();
3288 let mut positionals: Vec<Value> = Vec::new();
3289 let utf8 = |value: std::ffi::OsString| -> DiagnosticResult<String> {
3290 value
3291 .into_string()
3292 .map_err(|_| std_diag::std_parse_args_not_utf8())
3293 };
3294 loop {
3295 match parser.next() {
3296 Ok(None) => break,
3297 Ok(Some(Long(name))) => {
3298 let key = name.to_owned();
3299 if let Some(raw) = parser.optional_value() {
3300 flags.insert(key, Value::string(utf8(raw)?));
3301 } else {
3302 flags.insert(key, Value::bool(true));
3303 }
3304 }
3305 Ok(Some(Short(ch))) => {
3306 flags.insert(ch.to_string(), Value::bool(true));
3307 }
3308 Ok(Some(ArgValue(raw))) => {
3309 positionals.push(Value::string(utf8(raw)?));
3310 }
3311 Err(lexopt::Error::UnexpectedValue { option, value }) => {
3312 let key = option
3313 .strip_prefix("--")
3314 .or_else(|| option.strip_prefix('-'))
3315 .unwrap_or(option.as_str());
3316 flags.insert(key.to_string(), Value::string(utf8(value)?));
3317 }
3318 Err(err) => return Err(std_diag::std_parse_args_lex_error(&err)),
3319 }
3320 }
3321 Ok((flags, positionals))
3322}
3323
3324fn coerce_flags(
3332 specs: &CliSpecs,
3333 raw: &BTreeMap<String, Value>,
3334) -> DiagnosticResult<BTreeMap<String, Value>> {
3335 let mut alias_to_canonical: BTreeMap<&str, &str> = BTreeMap::new();
3338 for (canonical, spec) in specs.iter() {
3339 if let Some(alias) = spec.alias.as_ref() {
3340 alias_to_canonical.insert(alias.as_str(), canonical.as_str());
3341 }
3342 }
3343 let mut coerced: BTreeMap<String, Value> = BTreeMap::new();
3344 for (flag, spec) in specs.iter() {
3345 if flag.is_empty() {
3346 return Err(std_diag::std_parse_args_schema_flag_empty());
3347 }
3348 let canonical_raw = raw.get(flag);
3349 let alias_raw = spec.alias.as_ref().and_then(|alias| raw.get(alias));
3350 if canonical_raw.is_some() && alias_raw.is_some() {
3351 return Err(std_diag::std_parse_args_duplicate_flag(
3352 flag,
3353 spec.alias.as_deref(),
3354 ));
3355 }
3356 if let Some(raw_val) = canonical_raw.or(alias_raw) {
3357 coerced.insert(
3358 flag.clone(),
3359 coerce_cli_flag(spec.target, flag, raw_val.clone())?,
3360 );
3361 } else if let Some(d) = spec.default.as_ref() {
3362 coerced.insert(flag.clone(), d.clone());
3363 } else if spec.required {
3364 return Err(std_diag::std_parse_args_missing_flag(
3365 flag,
3366 spec.alias.as_deref(),
3367 ));
3368 }
3369 }
3370 for flag in raw.keys() {
3371 if !specs.contains_key(flag) && !alias_to_canonical.contains_key(flag.as_str()) {
3372 return Err(std_diag::std_parse_args_unknown_flag(flag));
3373 }
3374 }
3375 Ok(coerced)
3376}
3377
3378fn resolve_flags_specs<P: ProcessManager>(cx: &mut StepCtx<P>) -> DiagnosticResult<CliSpecs> {
3385 let name = "FLAGS";
3386 let tag = cx
3387 .state
3388 .resolve_tag(name)
3389 .map_err(|err| std_diag::std_parse_args_schema_type(name, &err))?;
3390 let TypeTag::Record(fields) = tag else {
3391 return Err(std_diag::std_parse_args_schema_shape(name));
3392 };
3393 let mut specs = BTreeMap::new();
3394 for field in fields.iter() {
3395 let target = match field.ty {
3396 TypeTag::String => CliType::String,
3397 TypeTag::Bool => CliType::Bool,
3398 TypeTag::Int => CliType::Int,
3399 TypeTag::Float => CliType::Float,
3400 _ => {
3401 return Err(std_diag::std_parse_args_schema_field_type(
3402 &field.name,
3403 field.ty.name(),
3404 ));
3405 }
3406 };
3407 specs.insert(
3408 field.name.clone(),
3409 CliSpec {
3410 target,
3411 required: !field.optional && field.default.is_none(),
3412 default: field.default.clone(),
3413 alias: field.alias.clone(),
3414 },
3415 );
3416 }
3417 Ok(specs)
3418}
3419
3420pub struct ParseFlags;
3428
3429impl<P: ProcessManager> OxDockFn<P> for ParseFlags {
3430 fn registration() -> HostRegistration<P> {
3431 let func: NativeFn<P> = Arc::new(|cx: &mut StepCtx<P>, values: Vec<Value>| {
3432 if values.len() != 1 {
3433 return Err(anyhow::Error::new(std_diag::std_parse_flags_arity(
3434 values.len(),
3435 )));
3436 }
3437 let mut iter = values.into_iter();
3438 let args_val = iter.next().expect("arity checked above");
3439 let args = string_list_arg(&args_val, "{FUNC_PARSE_FLAGS}() argument `$args`")?;
3440 let specs = resolve_flags_specs(cx)?;
3441 let (raw, positionals) = tokenize_raw_args(args)?;
3442 if !positionals.is_empty() {
3443 return Err(anyhow::Error::new(std_diag::std_parse_flags_positional(
3444 &positionals
3445 .iter()
3446 .map(|pos| pos.to_string())
3447 .collect::<Vec<_>>(),
3448 )));
3449 }
3450 Ok(Value::map(coerce_flags(&specs, &raw)?))
3451 });
3452 HostRegistration::Stateful {
3453 name: FUNC_PARSE_FLAGS.to_string(),
3454 meta: FuncMeta {
3455 name: FUNC_PARSE_FLAGS.to_string(),
3456 module: String::new(),
3457 kind: FuncKind::HostPure,
3458 params: Some(vec![FuncParam {
3459 name: "args".to_string(),
3460 param_type: Some(TypeTag::ListOf(Arc::new(TypeTag::String))),
3461 allowed: None,
3462 docs: "Argv tail to parse, usually from `STD::ARGV()`.",
3463 options: None,
3464 optional: false,
3465 }]),
3466 returns: Some(TypeTag::Map),
3467 rpn: true,
3468 summary: "Parse flags against TYPE FLAGS.",
3469 docs: "Consumes a `LIST<STRING>` and coerces flags through `TYPE FLAGS`. Returns the flags `MAP` directly; positional arguments fail.",
3470 examples: &[crate::Example {
3471 name: "flags only",
3472 fence_meta: None,
3473 code: indoc::indoc! {r#"
3474 IMPORT [STD]
3475 # Flags only returns the flags MAP directly.
3476 TYPE FLAGS = MAP<model: STRING, retries: INT = 2>
3477 LET $flags: FLAGS = PARSE_FLAGS(["--model=x"])
3478 ASSERT_EQ $flags.model "x"
3479 ASSERT_EQ $flags.retries 2
3480 "#},
3481 }],
3482 },
3483 func,
3484 }
3485 }
3486}
3487
3488pub struct ParsePositionals;
3493
3494impl<P: ProcessManager> OxDockFn<P> for ParsePositionals {
3495 fn registration() -> HostRegistration<P> {
3496 let func: NativeFn<P> = Arc::new(|_: &mut StepCtx<P>, values: Vec<Value>| {
3497 if values.len() != 1 {
3498 return Err(anyhow::Error::new(std_diag::std_parse_positionals_arity(
3499 values.len(),
3500 )));
3501 }
3502 let mut iter = values.into_iter();
3503 let args_val = iter.next().expect("arity checked above");
3504 let args = string_list_arg(
3505 &args_val,
3506 &format!("{FUNC_PARSE_POSITIONALS}() argument `$args`"),
3507 )?;
3508 let (_raw, positionals) = tokenize_raw_args(args)?;
3509 Ok(Value::list(positionals))
3510 });
3511 HostRegistration::Stateful {
3512 name: FUNC_PARSE_POSITIONALS.to_string(),
3513 meta: FuncMeta {
3514 name: FUNC_PARSE_POSITIONALS.to_string(),
3515 module: String::new(),
3516 kind: FuncKind::HostPure,
3517 params: Some(vec![FuncParam {
3518 name: "args".to_string(),
3519 param_type: Some(TypeTag::ListOf(Arc::new(TypeTag::String))),
3520 allowed: None,
3521 docs: "Argv tail to parse, usually from `STD::ARGV()`.",
3522 options: None,
3523 optional: false,
3524 }]),
3525 returns: Some(TypeTag::ListOf(Arc::new(TypeTag::String))),
3526 rpn: true,
3527 summary: "Parse positionals in argv order.",
3528 docs: "Consumes a `LIST<STRING>` and returns positionals in argv order with no schema.",
3529 examples: &[crate::Example {
3530 name: "positionals only",
3531 fence_meta: None,
3532 code: indoc::indoc! {r#"
3533 IMPORT [STD]
3534 # No schema needed: positionals are always strings in order.
3535 TYPE POSITIONS = LIST<STRING>
3536 LET $pos: POSITIONS = PARSE_POSITIONALS(["serve", "--", "--not-a-flag"])
3537 ASSERT_EQ $pos.0 "serve"
3538 ASSERT_EQ $pos.1 "--not-a-flag"
3539 "#},
3540 }],
3541 },
3542 func,
3543 }
3544 }
3545}
3546
3547#[oxdock_func(
3562 returns = TypeTag::Record(std::sync::Arc::from([Field {
3563 name: "name".to_string(),
3564 ty: TypeTag::String,
3565 docs: "Qualified function name.",
3566 optional: false,
3567 default: None,
3568
3569 alias: None,}, Field {
3570 name: "module".to_string(),
3571 ty: TypeTag::String,
3572 docs: "Owning module.",
3573 optional: false,
3574 default: None,
3575
3576 alias: None,}, Field {
3577 name: "kind".to_string(),
3578 ty: TypeTag::String,
3579 docs: "Origin label (`host` or `script`).",
3580 optional: false,
3581 default: None,
3582
3583 alias: None,}, Field {
3584 name: "params".to_string(),
3585 ty: TypeTag::ListOf(std::sync::Arc::new(TypeTag::MapOf(std::sync::Arc::new(
3586 TypeTag::Any,
3587 )))),
3588 docs: "Parameter entries (empty for parameterless functions).",
3589 optional: false,
3590 default: None,
3591
3592 alias: None,}, Field {
3593 name: "returns".to_string(),
3594 ty: TypeTag::String,
3595 docs: "Structural return shape (empty when untagged).",
3596 optional: false,
3597 default: None,
3598
3599 alias: None,}, Field {
3600 name: "rpn".to_string(),
3601 ty: TypeTag::Bool,
3602 docs: "True when callable in RPN position.",
3603 optional: false,
3604 default: None,
3605
3606 alias: None,}, Field {
3607 name: "summary".to_string(),
3608 ty: TypeTag::String,
3609 docs: "One-line description.",
3610 optional: false,
3611 default: None,
3612
3613 alias: None,}]))
3614 summary = "Describe one function by qualified name."
3615)]
3616#[example(
3617 name = "describe",
3618 code = r###"
3619 IMPORT [STD]
3620 LET $info: MAP<ANY> = DESCRIBE("STD::INT")
3621 ASSERT_EQ $info.name "STD::INT"
3622 ASSERT_EQ $info.returns "INT"
3623 "###
3624)]
3625fn describe<P: ProcessManager>(
3626 cx: &mut StepCtx<P>,
3627 name: String,
3629) -> Result<Value> {
3630 if split_qualified(&name).is_none() && name != KEYWORD_INSPECT {
3631 return Err(anyhow::Error::new(std_diag::func_describe_unqualified(
3632 &name,
3633 )));
3634 }
3635 cx.state
3636 .describe_function(&name)
3637 .ok_or_else(|| anyhow::Error::new(std_diag::func_unknown(&name)))
3638}
3639
3640#[oxdock_func(returns = TypeTag::ListOf(std::sync::Arc::new(TypeTag::String)))]
3646#[example(
3647 name = "list",
3648 code = r###"
3649 IMPORT [STD]
3650 LET $names: LIST<STRING> = TYPES()
3651 ASSERT_CONTAINS $names "STRING"
3652 "###
3653)]
3654fn types<P: ProcessManager>(cx: &mut StepCtx<P>) -> Result<Value> {
3655 Ok(Value::list(
3656 cx.state
3657 .type_names()
3658 .into_iter()
3659 .map(Value::string)
3660 .collect(),
3661 ))
3662}
3663
3664#[oxdock_func(returns = TypeTag::Record(std::sync::Arc::from([Field {
3670 name: "name".to_string(),
3671 ty: TypeTag::String,
3672 docs: "Queried type name.",
3673 optional: false,
3674 default: None,
3675
3676 alias: None,}, Field {
3677 name: "summary".to_string(),
3678 ty: TypeTag::String,
3679 docs: "One-line description.",
3680 optional: false,
3681 default: None,
3682
3683 alias: None,}, Field {
3684 name: "docs".to_string(),
3685 ty: TypeTag::String,
3686 docs: "Full documentation text.",
3687 optional: false,
3688 default: None,
3689
3690 alias: None,}])))]
3691#[example(
3692 name = "describe",
3693 code = r###"
3694 IMPORT [STD]
3695 LET $info: MAP<ANY> = TYPE_DESCRIBE("STRING")
3696 ASSERT_EQ $info.name "STRING"
3697 "###
3698)]
3699fn type_describe<P: ProcessManager>(
3700 cx: &mut StepCtx<P>,
3701 name: String,
3703) -> Result<Value> {
3704 if let Some(descriptor) = cx.state.describe_type(&name) {
3705 let mut map = BTreeMap::new();
3706 map.insert(
3707 "name".to_string(),
3708 Value::string(descriptor.name.to_string()),
3709 );
3710 map.insert(
3711 "summary".to_string(),
3712 Value::string(descriptor.summary.to_string()),
3713 );
3714 map.insert(
3715 "docs".to_string(),
3716 Value::string(descriptor.docs.to_string()),
3717 );
3718 return Ok(Value::map(map));
3719 }
3720 if let Some(target) = cx.state.alias_target(&name) {
3723 let mut map = BTreeMap::new();
3724 map.insert("name".to_string(), Value::string(name.clone()));
3725 map.insert(
3726 "summary".to_string(),
3727 Value::string(format!("Script type alias for {target}.")),
3728 );
3729 map.insert(
3730 "docs".to_string(),
3731 Value::string(format!(
3732 "Declared with {KEYWORD_TYPE} {name} = {target}. The alias expands structurally at every declaration."
3733 )),
3734 );
3735 return Ok(Value::map(map));
3736 }
3737 Err(anyhow::Error::new(std_diag::std_unknown_type(&name)))
3738}
3739
3740#[oxdock_func(returns = TypeTag::String)]
3754#[example(
3755 name = "self",
3756 code = r###"
3757 # The running interpreter resolves to a non-empty path.
3758 IMPORT [STD]
3759 LET $exe: STRING = INTERPRETER()
3760 LET $nonempty: BOOL = $exe != ""
3761 ASSERT_EQ $nonempty true
3762 "###
3763)]
3764#[example(
3765 name = "dynamic assembly",
3766 code = r###"
3767 # Assemble the child script dynamically: the parent interpolates
3768 # its own bindings into the pipe, then runs the interpreter on it.
3769 # Unescaped {{ }} bakes in at render time; \{{ }} stays literal
3770 # so the child expands it with its own bindings.
3771 # The pipe delivers EOF when the producer step ends, so the child
3772 # reads exactly one script.
3773 IMPORT [STD]
3774 LET $exe: STRING = INTERPRETER()
3775 LET $who: STRING = "Ada"
3776 LET $child: PIPE
3777 WITH_IO [stdout=$child] ECHO """
3778 ECHO "hello {{ $who }}!"
3779 LET $who: STRING = "Grace"
3780 ECHO "child sees \{{ $who }}!"
3781 """
3782 LET $out: STRING = WITH_IO [stdin=$child] RUN [$exe]
3783 ASSERT_CONTAINS $out "hello Ada!"
3784 ASSERT_CONTAINS $out "child sees Grace!"
3785 "###
3786)]
3787fn interpreter<P: ProcessManager>(cx: &mut StepCtx<P>) -> Result<Value> {
3788 if let Some(staged) = cx.state.io.interpreter_override() {
3789 return Ok(Value::string(staged));
3790 }
3791 Ok(Value::string(oxdock_process::interpreter_exe()?))
3792}
3793
3794#[oxdock_func(returns = TypeTag::Bool)]
3802#[example(
3803 name = "main",
3804 code = r###"
3805 # Entry top level runs as main.
3806 IMPORT [STD]
3807 LET $m: BOOL = IS_MAIN()
3808 ASSERT_EQ $m true
3809 "###
3810)]
3811#[example(
3812 name = "library doubles as demo",
3813 fence_meta = "roots:unified",
3814 code = r###"
3815 # A library doubles as a runnable demo: guard the demo with
3816 # IF IS_MAIN() so importing it stays side effect free. The
3817 # parent writes both files, then runs each in a fresh
3818 # interpreter: direct execution prints the demo, importing
3819 # it does not. Unified roots: the child inherits one
3820 # workspace, so parent and child see the same files. The
3821 # exact stdout match proves the demo line stays out of the
3822 # importing run.
3823 IMPORT [STD]
3824
3825 # The library under test: demo guarded by IS_MAIN.
3826 WRITE lib.oxfile """
3827 IMPORT [STD]
3828 FUNC GREET($x: STRING): STRING { RETURN "hi \{{ $x }}" }
3829 EXPORT GREET
3830 IF IS_MAIN() {
3831 ECHO "demo: hi Ada"
3832 }
3833 """
3834
3835 # The importer: calls the library, prints only its own line.
3836 WRITE main.oxfile """
3837 IMPORT ["lib.oxfile" AS LIB]
3838 LET $g: STRING = LIB::GREET("Bo")
3839 ECHO "imported: \{{ $g }}"
3840 """
3841
3842 # Direct run executes the demo.
3843 LET $exe: STRING = INTERPRETER()
3844 LET $direct: STRING = RUN [$exe, "lib.oxfile"]
3845 ASSERT_CONTAINS $direct "demo: hi Ada"
3846
3847 # Importing run stays silent apart from its own line.
3848 LET $via: STRING = RUN [$exe, "main.oxfile"]
3849 ASSERT_EQ $via "imported: hi Bo\n"
3850 "###
3851)]
3852fn is_main<P: ProcessManager>(cx: &mut StepCtx<P>) -> Result<Value> {
3853 let main = match cx.state.module_stack.last() {
3854 None | Some(None) => true,
3855 Some(Some(_)) => false,
3856 };
3857 Ok(Value::bool(main))
3858}
3859
3860#[oxdock_func(returns = TypeTag::Bool)]
3874#[example(
3875 name = "null stdin",
3876 code = r###"
3877 # A null stdin is never a terminal, in every harness.
3878 IMPORT [STD]
3879 LET $term: BOOL = IS_TERMINAL("stdin")
3880 ASSERT_EQ $term false
3881 "###
3882)]
3883fn is_terminal<P: ProcessManager>(
3884 cx: &mut StepCtx<P>,
3885 #[values("stdin", "stdout", "stderr")]
3887 stream_name: String,
3888) -> Result<Value> {
3889 use std::io::IsTerminal;
3890 let terminal = match stream_name.as_str() {
3891 "stdin" => {
3892 if cx.stdin_pipe.is_some() {
3897 false
3898 } else {
3899 match &cx.stdin {
3900 CommandStdin::Null => false,
3901 #[cfg(not(miri))]
3902 CommandStdin::OsPipe(_) => false,
3903 CommandStdin::Stream(_) => false,
3904 CommandStdin::Inherit => std::io::stdin().is_terminal(),
3905 }
3906 }
3907 }
3908 "stdout" => {
3909 if cx.out_pipe.is_some() {
3910 false
3912 } else if cx.state.io.stdout().is_some() {
3913 false
3916 } else {
3917 match &cx.out {
3918 None => std::io::stdout().is_terminal(),
3920 #[cfg(not(miri))]
3922 Some(StreamHandle::Os(_)) => false,
3923 Some(StreamHandle::Stream(_)) => std::io::stdout().is_terminal(),
3933 }
3934 }
3935 }
3936 "stderr" => {
3937 if cx.state.io.stderr().is_some() {
3938 false
3940 } else {
3941 match &cx.err {
3942 None => std::io::stderr().is_terminal(),
3944 #[cfg(not(miri))]
3946 Some(StreamHandle::Os(_)) => false,
3947 Some(StreamHandle::Stream(_)) => false,
3950 }
3951 }
3952 }
3953 _ => {
3954 return Err(anyhow::Error::new(std_diag::std_is_terminal_expected(
3955 &stream_name,
3956 )));
3957 }
3958 };
3959 Ok(Value::bool(terminal))
3960}
3961
3962#[oxdock_func(returns = TypeTag::Semaphore)]
3970#[example(
3971 name = "mint",
3972 code = r###"
3973 # Mint a semaphore admitting at most two holders.
3974 IMPORT [STD]
3975 LET $sem: SEMAPHORE = SEMAPHORE_NEW(2)
3976
3977 # A fresh semaphore reports its full cap as available.
3978 LET $free: INT = SEMAPHORE_AVAILABLE($sem)
3979 ASSERT_EQ $free 2
3980 "###
3981)]
3982fn semaphore_new<P: ProcessManager>(
3983 cx: &mut StepCtx<P>,
3984 max: i64,
3986) -> Result<Value> {
3987 let _ = cx;
3988 if max <= 0 {
3989 return Err(anyhow::Error::new(std_diag::std_semaphore_needs_positive(
3990 max,
3991 )));
3992 }
3993 Ok(Value::semaphore(max as usize))
3994}
3995
3996#[oxdock_func(returns = TypeTag::Record(std::sync::Arc::from([Field {
4005 name: "held".to_string(),
4006 ty: TypeTag::Bool,
4007 docs: "`true` with the permit under `permit`, `false` with no `permit` key.",
4008 optional: false,
4009 default: None,
4010
4011 alias: None,}, Field {
4012 name: "permit".to_string(),
4013 ty: TypeTag::Permit,
4014 docs: "Permit handle; read only when `held`.",
4015 optional: true,
4016 default: None,
4017
4018 alias: None,}])))]
4019#[example(
4020 name = "acquire",
4021 code = r###"
4022 # First acquire holds with a permit to bind.
4023 IMPORT [STD]
4024 LET $sem: SEMAPHORE = SEMAPHORE_NEW(1)
4025 LET $first: MAP<held: BOOL, permit?: PERMIT> = SEMAPHORE_TRY_ACQUIRE($sem)
4026 ASSERT_EQ $first.held true
4027 LET $permit: PERMIT = $first.permit
4028
4029 # A capped semaphore answers held false with no permit key.
4030 LET $second: MAP<held: BOOL, permit?: PERMIT> = SEMAPHORE_TRY_ACQUIRE($sem)
4031 ASSERT_EQ $second.held false
4032 LET $has_permit: BOOL = HAS_KEY($second, "permit")
4033 ASSERT_EQ $has_permit false
4034 "###
4035)]
4036fn semaphore_try_acquire<P: ProcessManager>(
4037 cx: &mut StepCtx<P>,
4038 sem: Arc<SemaphoreState>,
4040) -> Result<Value> {
4041 let _ = cx;
4042 let mut map = BTreeMap::new();
4043 if sem.try_acquire() {
4044 map.insert("held".to_string(), Value::bool(true));
4045 map.insert("permit".to_string(), Value::permit(&sem));
4046 } else {
4047 map.insert("held".to_string(), Value::bool(false));
4048 }
4049 Ok(Value::map(map))
4050}
4051
4052#[oxdock_func(pure, returns = TypeTag::Int)]
4059#[example(
4060 name = "readout",
4061 code = r###"
4062 # Hold one permit on a cap of two.
4063 IMPORT [STD]
4064 LET $sem: SEMAPHORE = SEMAPHORE_NEW(2)
4065 LET $acq: MAP<held: BOOL, permit?: PERMIT> = SEMAPHORE_TRY_ACQUIRE($sem)
4066 ASSERT_EQ $acq.held true
4067
4068 # One held permit leaves exactly one free.
4069 LET $free: INT = SEMAPHORE_AVAILABLE($sem)
4070 ASSERT_EQ $free 1
4071 "###
4072)]
4073fn semaphore_available(
4074 sem: Arc<SemaphoreState>,
4076) -> Result<Value> {
4077 Ok(Value::int(sem.available() as i64))
4078}
4079
4080#[oxdock_func(
4089 rpn,
4090 returns = TypeTag::union(vec![TypeTag::String, TypeTag::Pipe]),
4091 template = text_trim_string
4092)]
4093#[example(
4094 name = "trim",
4095 code = r###"
4096 # Leading and trailing whitespace falls away.
4097 IMPORT [STD]
4098 LET $clean: STRING = TEXT_TRIM(" hello ")
4099 ASSERT_EQ $clean "hello"
4100 "###
4101)]
4102#[example(
4103 name = "trim pipe mirrors",
4104 code = r###"
4105 # Pipe input mints pipe output with the same transform.
4106 IMPORT [STD]
4107 LET $cap: PIPE
4108 WITH_IO [stdout=$cap] {
4109 ECHO " hello "
4110 }
4111 LET $out: PIPE = TEXT_TRIM($cap)
4112 WITH_IO [stdin=$out] READ_LINE $line
4113 ASSERT_EQ $line "hello"
4114 "###
4115)]
4116#[example(
4117 name = "trim template",
4118 code = r###"
4119 # String inputs run inside placeholders too.
4120 IMPORT [STD]
4121 LET $msg: STRING = 'clean:{{ STD::TEXT_TRIM(" hello ") }}'
4122 ASSERT_EQ $msg "clean:hello"
4123 "###
4124)]
4125#[example(
4126 name = "trim file template",
4127 code = r###"
4128 # EXPAND templates resolve the same registry.
4129 IMPORT [STD]
4130 WRITE "tpl.txt" "clean:\{{ STD::TEXT_TRIM(\" hello \") }}"
4131 LET $out: STRING = EXPAND "tpl.txt"
4132 ASSERT_EQ $out "clean:hello"
4133 "###
4134)]
4135fn text_trim<P: ProcessManager>(
4136 cx: &mut StepCtx<P>,
4137 #[union(String, Pipe)]
4139 text: Value,
4140) -> Result<Value> {
4141 Ok(super::args::mirror_stream(
4142 cx,
4143 "TEXT_TRIM",
4144 &text,
4145 super::args::TextPump::Trim,
4146 )?)
4147}
4148
4149fn text_trim_string(text: Value) -> Result<Value> {
4152 Ok(super::args::mirror_string(
4153 "TEXT_TRIM",
4154 &text,
4155 super::args::TextPump::Trim,
4156 )?)
4157}
4158
4159#[oxdock_func(
4168 rpn,
4169 returns = TypeTag::union(vec![TypeTag::String, TypeTag::Pipe]),
4170 template = text_trim_prefix_string
4171)]
4172#[example(
4173 name = "strip prefix",
4174 code = r###"
4175 # A present prefix falls away; absence returns the input unchanged.
4176 IMPORT [STD]
4177 LET $bare: STRING = TEXT_TRIM_PREFIX("v1.2.3", "v")
4178 ASSERT_EQ $bare "1.2.3"
4179
4180 # Missing prefixes pass through untouched.
4181 LET $same: STRING = TEXT_TRIM_PREFIX("1.2.3", "v")
4182 ASSERT_EQ $same "1.2.3"
4183 "###
4184)]
4185#[example(
4186 name = "strip prefix pipe mirrors",
4187 code = r###"
4188 # Pipe input mints pipe output with the same strip.
4189 IMPORT [STD]
4190 LET $cap: PIPE
4191 WITH_IO [stdout=$cap] {
4192 ECHO "v1.2.3"
4193 }
4194 LET $trimmed: PIPE = TEXT_TRIM($cap)
4195 LET $out: PIPE = TEXT_TRIM_PREFIX($trimmed, "v")
4196 WITH_IO [stdin=$out] READ_LINE $line
4197 ASSERT_EQ $line "1.2.3"
4198 "###
4199)]
4200#[example(
4201 name = "strip prefix template",
4202 code = r###"
4203 # String inputs run inside placeholders too.
4204 IMPORT [STD]
4205 LET $msg: STRING = 'bare:{{ STD::TEXT_TRIM_PREFIX("v1.2.3", "v") }}'
4206 ASSERT_EQ $msg "bare:1.2.3"
4207 "###
4208)]
4209fn text_trim_prefix<P: ProcessManager>(
4210 cx: &mut StepCtx<P>,
4211 #[union(String, Pipe)]
4213 text: Value,
4214 prefix: String,
4216) -> Result<Value> {
4217 Ok(super::args::mirror_stream(
4218 cx,
4219 "TEXT_TRIM_PREFIX",
4220 &text,
4221 super::args::TextPump::TrimPrefix(prefix),
4222 )?)
4223}
4224
4225fn text_trim_prefix_string(text: Value, prefix: String) -> Result<Value> {
4228 Ok(super::args::mirror_string(
4229 "TEXT_TRIM_PREFIX",
4230 &text,
4231 super::args::TextPump::TrimPrefix(prefix),
4232 )?)
4233}
4234
4235#[oxdock_func(
4242 rpn,
4243 returns = TypeTag::union(vec![TypeTag::String, TypeTag::Pipe]),
4244 template = text_trim_suffix_string
4245)]
4246#[example(
4247 name = "strip suffix",
4248 code = r###"
4249 # A present suffix falls away; absence returns the input unchanged.
4250 IMPORT [STD]
4251 LET $bare: STRING = TEXT_TRIM_SUFFIX("archive.tar.gz", ".gz")
4252 ASSERT_EQ $bare "archive.tar"
4253
4254 # Missing suffixes pass through untouched.
4255 LET $same: STRING = TEXT_TRIM_SUFFIX("archive.tar", ".gz")
4256 ASSERT_EQ $same "archive.tar"
4257 "###
4258)]
4259#[example(
4260 name = "strip suffix pipe mirrors",
4261 code = r###"
4262 # Pipe input mints pipe output with the same strip.
4263 IMPORT [STD]
4264 LET $cap: PIPE
4265 WITH_IO [stdout=$cap] {
4266 ECHO "archive.tar.gz"
4267 }
4268 LET $trimmed: PIPE = TEXT_TRIM($cap)
4269 LET $out: PIPE = TEXT_TRIM_SUFFIX($trimmed, ".gz")
4270 WITH_IO [stdin=$out] READ_LINE $line
4271 ASSERT_EQ $line "archive.tar"
4272 "###
4273)]
4274#[example(
4275 name = "strip suffix template",
4276 code = r###"
4277 # String inputs run inside placeholders too.
4278 IMPORT [STD]
4279 LET $msg: STRING = 'bare:{{ STD::TEXT_TRIM_SUFFIX("archive.tar.gz", ".gz") }}'
4280 ASSERT_EQ $msg "bare:archive.tar"
4281 "###
4282)]
4283fn text_trim_suffix<P: ProcessManager>(
4284 cx: &mut StepCtx<P>,
4285 #[union(String, Pipe)]
4287 text: Value,
4288 suffix: String,
4290) -> Result<Value> {
4291 Ok(super::args::mirror_stream(
4292 cx,
4293 "TEXT_TRIM_SUFFIX",
4294 &text,
4295 super::args::TextPump::TrimSuffix(suffix),
4296 )?)
4297}
4298
4299fn text_trim_suffix_string(text: Value, suffix: String) -> Result<Value> {
4302 Ok(super::args::mirror_string(
4303 "TEXT_TRIM_SUFFIX",
4304 &text,
4305 super::args::TextPump::TrimSuffix(suffix),
4306 )?)
4307}
4308
4309#[oxdock_func(returns = TypeTag::String)]
4320#[example(
4321 name = "join path",
4322 code = r###"
4323 # Directory and file stem join with the native separator.
4324 # Source `\\` is one backslash at runtime; `/` works on Windows
4325 # too, native just reads better there.
4326 IMPORT [STD]
4327 LET $p: STRING = PATH_JOIN("some-dir", "some-file")
4328 [family:unix] ASSERT_EQ $p "some-dir/some-file"
4329 [family:windows] ASSERT_EQ $p "some-dir\\some-file"
4330 "###
4331)]
4332fn path_join<P: ProcessManager>(
4333 _cx: &mut StepCtx<P>,
4334 #[union(String, Path)]
4336 dir: Value,
4337 #[union(String, Path)]
4339 name: Value,
4340) -> Result<Value> {
4341 let d = super::args::string_or_path_text(&dir)?;
4342 let n = super::args::string_or_path_text(&name)?;
4343 Ok(Value::string(oxdock_fs::join_native(&d, &n)))
4344}
4345
4346#[oxdock_func(pure, returns = TypeTag::String)]
4354#[example(
4355 name = "base",
4356 code = r###"
4357 # Final segments bind without filesystem access.
4358 IMPORT [STD]
4359 LET $b: STRING = PATH_BASE("some-dir/some-file")
4360 ASSERT_EQ $b "some-file"
4361
4362 # Trailing slashes trim before the split.
4363 LET $d: STRING = PATH_BASE("some-dir/")
4364 ASSERT_EQ $d "some-dir"
4365 "###
4366)]
4367fn path_base(
4368 #[union(String, Path)]
4370 path: Value,
4371) -> Result<Value> {
4372 let text = super::args::string_or_path_text(&path)?;
4373 let base = oxdock_fs::path_base(&text)
4374 .map_err(|e| anyhow::Error::new(std_diag::std_path_base_failed(&e)))?;
4375 Ok(Value::string(base))
4376}
4377
4378#[oxdock_func(pure, returns = TypeTag::String)]
4388#[example(
4389 name = "relativize",
4390 code = r###"
4391 # Prefix bases strip to their remainder.
4392 IMPORT [STD]
4393 LET $r: STRING = PATH_REL("some-dir", "some-dir/some-file")
4394 ASSERT_EQ $r "some-file"
4395
4396 # Equal paths bind dot.
4397 LET $dot: STRING = PATH_REL("some-dir", "some-dir")
4398 ASSERT_EQ $dot "."
4399 "###
4400)]
4401fn path_rel(
4402 #[union(String, Path)]
4404 base: Value,
4405 #[union(String, Path)]
4407 path: Value,
4408) -> Result<Value> {
4409 let b = super::args::string_or_path_text(&base)?;
4410 let p = super::args::string_or_path_text(&path)?;
4411 let rel = oxdock_fs::path_rel(&b, &p)
4412 .map_err(|e| anyhow::Error::new(std_diag::std_path_rel_failed(&e)))?;
4413 Ok(Value::string(rel))
4414}
4415
4416#[oxdock_func(
4423 rpn,
4424 returns = TypeTag::union(vec![TypeTag::String, TypeTag::Pipe]),
4425 template = text_to_upper_string
4426)]
4427#[example(
4428 name = "uppercase",
4429 code = r###"
4430 # Text folds to uppercase.
4431 IMPORT [STD]
4432 LET $loud: STRING = TEXT_TO_UPPER("hello")
4433 ASSERT_EQ $loud "HELLO"
4434 "###
4435)]
4436#[example(
4437 name = "uppercase pipe mirrors",
4438 code = r###"
4439 # Pipe input mints pipe output with the same fold.
4440 IMPORT [STD]
4441 LET $cap: PIPE
4442 WITH_IO [stdout=$cap] {
4443 ECHO "hello"
4444 }
4445 LET $out: PIPE = TEXT_TO_UPPER($cap)
4446 WITH_IO [stdin=$out] READ_LINE $line
4447 ASSERT_EQ $line "HELLO"
4448 "###
4449)]
4450#[example(
4451 name = "uppercase template",
4452 code = r###"
4453 # String inputs run inside placeholders too.
4454 IMPORT [STD]
4455 LET $msg: STRING = 'loud:{{ STD::TEXT_TO_UPPER("hello") }}'
4456 ASSERT_EQ $msg "loud:HELLO"
4457 "###
4458)]
4459fn text_to_upper<P: ProcessManager>(
4460 cx: &mut StepCtx<P>,
4461 #[union(String, Pipe)]
4463 text: Value,
4464) -> Result<Value> {
4465 Ok(super::args::mirror_stream(
4466 cx,
4467 "TEXT_TO_UPPER",
4468 &text,
4469 super::args::TextPump::ToUpper,
4470 )?)
4471}
4472
4473fn text_to_upper_string(text: Value) -> Result<Value> {
4476 Ok(super::args::mirror_string(
4477 "TEXT_TO_UPPER",
4478 &text,
4479 super::args::TextPump::ToUpper,
4480 )?)
4481}
4482
4483#[oxdock_func(
4490 rpn,
4491 returns = TypeTag::union(vec![TypeTag::String, TypeTag::Pipe]),
4492 template = text_to_lower_string
4493)]
4494#[example(
4495 name = "lowercase",
4496 code = r###"
4497 # Text folds to lowercase.
4498 IMPORT [STD]
4499 LET $quiet: STRING = TEXT_TO_LOWER("HELLO")
4500 ASSERT_EQ $quiet "hello"
4501 "###
4502)]
4503#[example(
4504 name = "lowercase pipe mirrors",
4505 code = r###"
4506 # Pipe input mints pipe output with the same fold.
4507 IMPORT [STD]
4508 LET $cap: PIPE
4509 WITH_IO [stdout=$cap] {
4510 ECHO "HELLO"
4511 }
4512 LET $out: PIPE = TEXT_TO_LOWER($cap)
4513 WITH_IO [stdin=$out] READ_LINE $line
4514 ASSERT_EQ $line "hello"
4515 "###
4516)]
4517#[example(
4518 name = "lowercase template",
4519 code = r###"
4520 # String inputs run inside placeholders too.
4521 IMPORT [STD]
4522 LET $msg: STRING = 'quiet:{{ STD::TEXT_TO_LOWER("HELLO") }}'
4523 ASSERT_EQ $msg "quiet:hello"
4524 "###
4525)]
4526fn text_to_lower<P: ProcessManager>(
4527 cx: &mut StepCtx<P>,
4528 #[union(String, Pipe)]
4530 text: Value,
4531) -> Result<Value> {
4532 Ok(super::args::mirror_stream(
4533 cx,
4534 "TEXT_TO_LOWER",
4535 &text,
4536 super::args::TextPump::ToLower,
4537 )?)
4538}
4539
4540fn text_to_lower_string(text: Value) -> Result<Value> {
4543 Ok(super::args::mirror_string(
4544 "TEXT_TO_LOWER",
4545 &text,
4546 super::args::TextPump::ToLower,
4547 )?)
4548}
4549
4550#[oxdock_func(
4561 rpn,
4562 returns = TypeTag::union(vec![TypeTag::String, TypeTag::Pipe]),
4563 template = text_replace_string
4564)]
4565#[example(
4566 name = "replace",
4567 code = r###"
4568 # Every literal occurrence rewrites in place.
4569 IMPORT [STD]
4570 LET $fixed: STRING = TEXT_REPLACE("hello world", "world", "there")
4571 ASSERT_EQ $fixed "hello there"
4572 "###
4573)]
4574#[example(
4575 name = "replace pipe mirrors",
4576 code = r###"
4577 # Pipe input mints pipe output with the same rewrite.
4578 IMPORT [STD]
4579 LET $cap: PIPE
4580 WITH_IO [stdout=$cap] {
4581 ECHO "hello world"
4582 }
4583 LET $trimmed: PIPE = TEXT_TRIM($cap)
4584 LET $out: PIPE = TEXT_REPLACE($trimmed, "world", "there")
4585 WITH_IO [stdin=$out] READ_LINE $line
4586 ASSERT_EQ $line "hello there"
4587 "###
4588)]
4589#[example(
4590 name = "replace template",
4591 code = r###"
4592 # String inputs run inside placeholders too.
4593 IMPORT [STD]
4594 LET $msg: STRING = 'fixed:{{ STD::TEXT_REPLACE("hello world", "world", "there") }}'
4595 ASSERT_EQ $msg "fixed:hello there"
4596 "###
4597)]
4598fn text_replace<P: ProcessManager>(
4599 cx: &mut StepCtx<P>,
4600 #[union(String, Pipe)]
4602 text: Value,
4603 from: String,
4605 to: String,
4607) -> Result<Value> {
4608 Ok(super::args::mirror_stream(
4609 cx,
4610 FUNC_TEXT_REPLACE,
4611 &text,
4612 super::args::TextPump::ReplaceLiteral { from, to },
4613 )?)
4614}
4615
4616fn text_replace_string(text: Value, from: String, to: String) -> Result<Value> {
4619 Ok(super::args::mirror_string(
4620 FUNC_TEXT_REPLACE,
4621 &text,
4622 super::args::TextPump::ReplaceLiteral { from, to },
4623 )?)
4624}
4625
4626#[oxdock_func(
4638 rpn,
4639 returns = TypeTag::union(vec![TypeTag::String, TypeTag::Pipe]),
4640 template = text_replace_regex_string
4641)]
4642#[example(
4643 name = "replace with captures",
4644 code = r###"
4645 # Capture groups expand in the replacement.
4646 IMPORT [STD]
4647 LET $swapped: STRING = TEXT_REPLACE_REGEX("2026-10-13", "(\\d+)-(\\d+)-(\\d+)", "$3/$2/$1")
4648 ASSERT_EQ $swapped "13/10/2026"
4649 "###
4650)]
4651#[example(
4652 name = "replace regex pipe mirrors",
4653 code = r###"
4654 # Pipe input mints pipe output with the same rewrite.
4655 IMPORT [STD]
4656 LET $cap: PIPE
4657 WITH_IO [stdout=$cap] {
4658 ECHO "2026-10-13"
4659 }
4660 LET $trimmed: PIPE = TEXT_TRIM($cap)
4661 LET $out: PIPE = TEXT_REPLACE_REGEX($trimmed, "(\\d+)-(\\d+)-(\\d+)", "$3/$2/$1")
4662 WITH_IO [stdin=$out] READ_LINE $line
4663 ASSERT_EQ $line "13/10/2026"
4664 "###
4665)]
4666#[example(
4667 name = "replace regex template",
4668 code = r###"
4669 # String inputs run inside placeholders too.
4670 IMPORT [STD]
4671 LET $msg: STRING = 'swapped:{{ STD::TEXT_REPLACE_REGEX("2026-10-13", "(\\d+)-(\\d+)-(\\d+)", "$3/$2/$1") }}'
4672 ASSERT_EQ $msg "swapped:13/10/2026"
4673 "###
4674)]
4675fn text_replace_regex<P: ProcessManager>(
4676 cx: &mut StepCtx<P>,
4677 #[union(String, Pipe)]
4679 text: Value,
4680 pattern: String,
4682 replacement: String,
4684) -> Result<Value> {
4685 if let Some(s) = text.as_str() {
4686 let out = super::args::text_replace_regex_str(
4687 s,
4688 &pattern,
4689 &replacement,
4690 FUNC_TEXT_REPLACE_REGEX,
4691 )?;
4692 return Ok(Value::string(out));
4693 }
4694 let content = super::args::read_pipe_eager(cx, FUNC_TEXT_REPLACE_REGEX, &text)?;
4695 let out = super::args::text_replace_regex_str(
4696 &content,
4697 &pattern,
4698 &replacement,
4699 FUNC_TEXT_REPLACE_REGEX,
4700 )?;
4701 Ok(super::args::write_completed_pipe(
4702 cx,
4703 FUNC_TEXT_REPLACE_REGEX,
4704 out,
4705 )?)
4706}
4707
4708fn text_replace_regex_string(text: Value, pattern: String, replacement: String) -> Result<Value> {
4711 let Some(s) = text.as_str() else {
4712 return Err(std_diag::std_pipe_needs_step_io(FUNC_TEXT_REPLACE_REGEX).into());
4713 };
4714 let out =
4715 super::args::text_replace_regex_str(s, &pattern, &replacement, FUNC_TEXT_REPLACE_REGEX)?;
4716 Ok(Value::string(out))
4717}
4718
4719#[oxdock_func(pure, returns = TypeTag::ListOf(std::sync::Arc::new(TypeTag::String)))]
4727#[example(
4728 name = "split",
4729 code = r###"
4730 # Delimiters split into list items.
4731 IMPORT [STD]
4732 LET $parts: LIST<STRING> = TEXT_SPLIT("a,b,c", ",")
4733 ASSERT_EQ $parts.0 "a"
4734 ASSERT_EQ $parts.1 "b"
4735 ASSERT_EQ $parts.2 "c"
4736 "###
4737)]
4738fn text_split(
4739 text: String,
4741 delimiter: String,
4743) -> Result<Value> {
4744 Ok(super::args::text_list_value(super::args::text_split_str(
4745 &text, &delimiter,
4746 )))
4747}
4748
4749#[oxdock_func(pure, returns = TypeTag::String)]
4752#[example(
4753 name = "join",
4754 code = r###"
4755 # List items join with the separator between them.
4756 IMPORT [STD]
4757 LET $joined: STRING = TEXT_JOIN(["a", "b", "c"], ",")
4758 ASSERT_EQ $joined "a,b,c"
4759 "###
4760)]
4761fn text_join(
4762 elements: Vec<String>,
4764 delimiter: String,
4766) -> Result<Value> {
4767 Ok(Value::string(elements.join(delimiter.as_str())))
4768}
4769
4770#[oxdock_func(pure, returns = TypeTag::ListOf(std::sync::Arc::new(TypeTag::String)))]
4782#[example(
4783 name = "split args",
4784 code = r###"
4785 # Quoted segments stay one word.
4786 IMPORT [STD]
4787 LET $argv: LIST<STRING> = SHELL_SPLIT_ARGS("gh issue comment 153 --body-file notes.md")
4788 ASSERT_EQ $argv.0 "gh"
4789 ASSERT_EQ $argv.3 "153"
4790 ASSERT_EQ $argv.5 "notes.md"
4791
4792 # Quotes and escapes parse the shell way.
4793 LET $quoted: LIST<STRING> = SHELL_SPLIT_ARGS("say \"hi there\" 'a b'")
4794 ASSERT_EQ $quoted.0 "say"
4795 ASSERT_EQ $quoted.1 "hi there"
4796 ASSERT_EQ $quoted.2 "a b"
4797 "###
4798)]
4799fn shell_split_args(
4800 command: String,
4802) -> Result<Value> {
4803 match shell_words::split(&command) {
4804 Ok(words) => Ok(super::args::text_list_value(words)),
4805 Err(err) => Err(anyhow::Error::new(std_diag::std_shell_split_failed(&err))),
4806 }
4807}
4808
4809#[oxdock_func(pure, returns = TypeTag::String)]
4817#[example(
4818 name = "join args",
4819 code = r###"
4820 # Plain words join with spaces and no quoting.
4821 IMPORT [STD]
4822 LET $plain: STRING = SHELL_JOIN_ARGS(["gh", "issue", "list"])
4823 ASSERT_EQ $plain "gh issue list"
4824
4825 # Words with spaces quote, and the round trip is exact.
4826 LET $words: LIST<STRING> = ["say", "hi there", "a'b"]
4827 LET $joined: STRING = SHELL_JOIN_ARGS($words)
4828 LET $back: LIST<STRING> = SHELL_SPLIT_ARGS($joined)
4829 ASSERT_EQ $back.0 "say"
4830 ASSERT_EQ $back.1 "hi there"
4831 ASSERT_EQ $back.2 "a'b"
4832 "###
4833)]
4834fn shell_join_args(
4835 words: Vec<String>,
4837) -> Result<Value> {
4838 Ok(Value::string(shell_words::join(&words)))
4839}
4840
4841#[oxdock_func(pure, returns = TypeTag::ListOf(std::sync::Arc::new(TypeTag::String)))]
4849#[example(
4850 name = "lines",
4851 code = r###"
4852 # Newlines split into line items.
4853 IMPORT [STD]
4854 LET $lines: LIST<STRING> = TEXT_LINES("one\ntwo\nthree")
4855 ASSERT_EQ $lines.0 "one"
4856 ASSERT_EQ $lines.1 "two"
4857 ASSERT_EQ $lines.2 "three"
4858
4859 # Windows endings split the same way after normalization.
4860 LET $crlf: LIST<STRING> = TEXT_LINES("one\r\ntwo\r\nthree")
4861 ASSERT_EQ $crlf.0 "one"
4862 ASSERT_EQ $crlf.1 "two"
4863 ASSERT_EQ $crlf.2 "three"
4864
4865 # Old Mac endings split too, and mixed endings split together because the input normalizes to LF before splitting.
4866 LET $mixed: LIST<STRING> = TEXT_LINES("a\r\nb\nc\rd")
4867 ASSERT_EQ $mixed.0 "a"
4868 ASSERT_EQ $mixed.1 "b"
4869 ASSERT_EQ $mixed.2 "c"
4870 ASSERT_EQ $mixed.3 "d"
4871 "###
4872)]
4873fn text_lines(
4874 text: String,
4876) -> Result<Value> {
4877 Ok(super::args::text_list_value(super::args::text_lines_str(
4878 &text,
4879 )))
4880}
4881
4882#[oxdock_func(pure, returns = TypeTag::ListOf(std::sync::Arc::new(TypeTag::String)))]
4888#[example(
4889 name = "fields",
4890 code = r###"
4891 # Runs of whitespace separate fields; empties never appear.
4892 IMPORT [STD]
4893 LET $fields: LIST<STRING> = TEXT_FIELDS(" abc def ")
4894 ASSERT_EQ $fields.0 "abc"
4895 ASSERT_EQ $fields.1 "def"
4896 "###
4897)]
4898fn text_fields(
4899 text: String,
4901) -> Result<Value> {
4902 Ok(super::args::text_list_value(super::args::text_fields_str(
4903 &text,
4904 )))
4905}
4906
4907#[oxdock_func(pure, returns = TypeTag::ListOf(std::sync::Arc::new(TypeTag::String)))]
4916#[example(
4917 name = "line range",
4918 code = r###"
4919 # Lines 2 through 3 come back as a list, 1-based inclusive.
4920 IMPORT [STD]
4921 LET $window: LIST<STRING> = TEXT_LINES_RANGE("one\ntwo\nthree\nfour", 2, 3)
4922 ASSERT_EQ $window.0 "two"
4923 ASSERT_EQ $window.1 "three"
4924
4925 # Ranges past the end clamp instead of failing.
4926 LET $tail: LIST<STRING> = TEXT_LINES_RANGE("one\ntwo", 2, 9)
4927 ASSERT_EQ $tail.0 "two"
4928 "###
4929)]
4930fn text_lines_range(
4931 text: String,
4933 from: i64,
4935 to: i64,
4937) -> Result<Value> {
4938 Ok(super::args::text_list_value(
4939 super::args::text_lines_range_str(&text, from, to, FUNC_TEXT_LINES_RANGE)?,
4940 ))
4941}
4942
4943#[oxdock_func(pure, returns = TypeTag::Bool)]
4951#[example(
4952 name = "match",
4953 code = r###"
4954 # Regex matches report true; misses report false.
4955 IMPORT [STD]
4956 LET $hit: BOOL = TEXT_MATCH("abc123", "\\d+")
4957 ASSERT_EQ $hit true
4958
4959 # A miss is false, not a failure.
4960 LET $miss: BOOL = TEXT_MATCH("abc", "^\\d+$")
4961 ASSERT_EQ $miss false
4962 "###
4963)]
4964fn text_match(
4965 text: String,
4967 pattern: String,
4969) -> Result<Value> {
4970 let re = super::args::text_compile_pattern(FUNC_TEXT_MATCH, &pattern)?;
4971 Ok(Value::bool(re.is_match(&text)))
4972}
4973
4974#[oxdock_func(pure, name = "BOOL", returns = TypeTag::Bool)]
4983#[example(
4984 name = "convert",
4985 code = r###"
4986 IMPORT [STD]
4987 LET $n: BOOL = BOOL("yes")
4988 ASSERT_EQ $n true
4989 LET $f: BOOL = BOOL("0")
4990 ASSERT_EQ $f false
4991 "###
4992)]
4993fn bool_convert(
4994 #[union(Bool, String)]
4996 val: Value,
4997) -> Result<Value> {
4998 if let Some(b) = val.as_bool() {
4999 return Ok(Value::bool(b));
5000 }
5001 let Some(s) = val.as_str() else {
5002 return Err(anyhow::Error::new(std_diag::std_bool_needs_bool_or_string(
5003 &val,
5004 )));
5005 };
5006 match super::args::parse_bool_str(s) {
5007 Some(b) => Ok(Value::bool(b)),
5008 None => Err(anyhow::Error::new(std_diag::std_bool_cannot_coerce(
5009 FUNC_BOOL, s,
5010 ))),
5011 }
5012}
5013
5014#[oxdock_func(pure, returns = TypeTag::Bool)]
5024#[example(
5025 name = "absent-default",
5026 code = r###"
5027 # Absent names read empty; the default settles the polarity.
5028 IMPORT [STD]
5029 INHERIT_ENV [OXDOCK_TEST_ABSENT_FLAG]
5030 LET $dry: BOOL = BOOL_OR("{{ env:OXDOCK_TEST_ABSENT_FLAG }}", true)
5031 ASSERT_EQ $dry true
5032
5033 # Present values coerce strictly, ignoring the default.
5034 LET $off: BOOL = BOOL_OR("false", true)
5035 ASSERT_EQ $off false
5036 "###
5037)]
5038fn bool_or(
5039 text: String,
5041 default: bool,
5043) -> Result<Value> {
5044 if text.trim().is_empty() {
5045 return Ok(Value::bool(default));
5046 }
5047 match super::args::parse_bool_str(&text) {
5048 Some(b) => Ok(Value::bool(b)),
5049 None => Err(anyhow::Error::new(std_diag::std_bool_cannot_coerce(
5050 FUNC_BOOL_OR,
5051 &text,
5052 ))),
5053 }
5054}
5055
5056#[oxdock_func(pure, returns = TypeTag::ListOf(std::sync::Arc::new(TypeTag::String)))]
5065#[example(
5066 name = "extract",
5067 code = r###"
5068 # Index zero is the full match; groups follow in order.
5069 IMPORT [STD]
5070 LET $caps: LIST<STRING> = TEXT_EXTRACT("abc123", "([a-z]+)(\\d+)")
5071 ASSERT_EQ $caps.0 "abc123"
5072 ASSERT_EQ $caps.1 "abc"
5073 ASSERT_EQ $caps.2 "123"
5074 "###
5075)]
5076fn text_extract(
5077 text: String,
5079 pattern: String,
5081) -> Result<Value> {
5082 let groups = super::args::text_extract_str(&text, &pattern, FUNC_TEXT_EXTRACT)?;
5083 Ok(super::args::text_list_value(groups))
5084}
5085
5086#[oxdock_func(pure, returns = TypeTag::Bool)]
5093#[example(
5094 name = "starts with",
5095 code = r###"
5096 # Present prefixes report true; misses report false.
5097 IMPORT [STD]
5098 LET $hit: BOOL = TEXT_STARTS_WITH("linux-musl-x64", "linux")
5099 ASSERT_EQ $hit true
5100
5101 # A miss is false, not a failure.
5102 LET $miss: BOOL = TEXT_STARTS_WITH("macos-arm", "linux")
5103 ASSERT_EQ $miss false
5104 "###
5105)]
5106fn text_starts_with(
5107 text: String,
5109 prefix: String,
5111) -> Result<Value> {
5112 Ok(Value::bool(text.starts_with(prefix.as_str())))
5113}
5114
5115#[oxdock_func(pure, returns = TypeTag::Bool)]
5122#[example(
5123 name = "ends with",
5124 code = r###"
5125 # Present suffixes report true; misses report false.
5126 IMPORT [STD]
5127 LET $hit: BOOL = TEXT_ENDS_WITH("x86_64-linux-musl", "linux-musl")
5128 ASSERT_EQ $hit true
5129
5130 # A miss is false, not a failure.
5131 LET $miss: BOOL = TEXT_ENDS_WITH("x86_64-linux-gnu", "linux-musl")
5132 ASSERT_EQ $miss false
5133 "###
5134)]
5135fn text_ends_with(
5136 text: String,
5138 suffix: String,
5140) -> Result<Value> {
5141 Ok(Value::bool(text.ends_with(suffix.as_str())))
5142}
5143
5144#[oxdock_func(pure, returns = TypeTag::Bool)]
5154#[example(
5155 name = "contains",
5156 code = r###"
5157 # Present needles report true; misses report false.
5158 IMPORT [STD]
5159 LET $hit: BOOL = CONTAINS("x86_64-linux-musl", "musl")
5160 ASSERT_EQ $hit true
5161
5162 # A miss is false, not a failure.
5163 LET $miss: BOOL = CONTAINS("x86_64-linux-gnu", "musl")
5164 ASSERT_EQ $miss false
5165 "###
5166)]
5167#[example(
5168 name = "contains list",
5169 code = r###"
5170 # List membership uses strict equality across any element type.
5171 IMPORT [STD]
5172 LET $hit: BOOL = CONTAINS(["a", "b", "c"], "b")
5173 ASSERT_EQ $hit true
5174 LET $miss: BOOL = CONTAINS(["a", "b", "c"], "z")
5175 ASSERT_EQ $miss false
5176 LET $num: BOOL = CONTAINS([1, 2, 3], 2.0)
5177 ASSERT_EQ $num true
5178
5179 # Stringified numbers never coerce to integers.
5180 LET $strnum: BOOL = CONTAINS(["1", "2", "3"], 2)
5181 ASSERT_EQ $strnum false
5182
5183 # Boolean lists match true and miss false with no coercion.
5184 LET $bools: LIST<BOOL> = [true]
5185 LET $bhit: BOOL = CONTAINS($bools, true)
5186 ASSERT_EQ $bhit true
5187 LET $bmiss: BOOL = CONTAINS($bools, false)
5188 ASSERT_EQ $bmiss false
5189 LET $nocoerce: BOOL = CONTAINS($bools, 1)
5190 ASSERT_EQ $nocoerce false
5191 "###
5192)]
5193fn contains(
5194 #[union(String, List)]
5196 haystack: Value,
5197 needle: Value,
5199) -> Result<Value> {
5200 if let Some(text) = haystack.as_str() {
5201 let Some(n) = needle.as_str() else {
5202 return Err(anyhow::Error::new(std_diag::std_contains_needle_type(
5203 needle.type_name(),
5204 )));
5205 };
5206 return Ok(Value::bool(text.contains(n)));
5207 }
5208 if let Some(items) = haystack.as_list() {
5209 for item in items {
5210 if super::args::values_equal(item, &needle) {
5211 return Ok(Value::bool(true));
5212 }
5213 }
5214 return Ok(Value::bool(false));
5215 }
5216 Err(anyhow::Error::new(std_diag::std_contains_haystack_type(
5217 haystack.type_name(),
5218 )))
5219}
5220
5221#[oxdock_func(pure, returns = TypeTag::List)]
5229#[example(
5230 name = "deduplicate",
5231 code = r###"
5232 # First occurrences win, later repeats drop.
5233 IMPORT [STD]
5234 LET $seen: LIST<STRING> = UNIQUE(["a", "b", "a", "c", "b"])
5235 ASSERT_EQ $seen.0 "a"
5236 ASSERT_EQ $seen.1 "b"
5237 ASSERT_EQ $seen.2 "c"
5238 ASSERT_EQ LEN($seen) 3
5239
5240 # The empty list stays empty.
5241 LET $empty: LIST<STRING> = UNIQUE([])
5242 ASSERT_EQ LEN($empty) 0
5243 "###
5244)]
5245#[example(
5246 name = "strict membership",
5247 code = r###"
5248 # Numerics collapse across INT and FLOAT like CONTAINS.
5249 IMPORT [STD]
5250 LET $nums: LIST<ANY> = UNIQUE([1, 2.0, 1, 3])
5251 ASSERT_EQ $nums.0 1
5252 ASSERT_EQ $nums.1 2.0
5253 ASSERT_EQ $nums.2 3
5254 ASSERT_EQ LEN($nums) 3
5255
5256 # Stringified numbers never coerce to integers.
5257 LET $mixed: LIST<ANY> = UNIQUE(["1", 1])
5258 ASSERT_EQ $mixed.0 "1"
5259 ASSERT_EQ $mixed.1 1
5260 ASSERT_EQ LEN($mixed) 2
5261 "###
5262)]
5263fn unique(
5264 items: Vec<Value>,
5266) -> Result<Value> {
5267 let mut out: Vec<Value> = Vec::with_capacity(items.len());
5268 for item in items {
5269 if !out
5270 .iter()
5271 .any(|seen| super::args::values_equal(seen, &item))
5272 {
5273 out.push(item);
5274 }
5275 }
5276 Ok(Value::list(out))
5277}
5278
5279#[oxdock_func(pure, returns = TypeTag::Int)]
5288#[example(
5289 name = "length",
5290 code = r###"
5291 # Plain text counts one per character.
5292 IMPORT [STD]
5293 LET $n: INT = LEN("hello")
5294 ASSERT_EQ $n 5
5295
5296 # Multibyte characters count once each, not per byte.
5297 LET $wide: INT = LEN("héllo")
5298 ASSERT_EQ $wide 5
5299
5300 # Lists count elements, maps count entries.
5301 LET $items: LIST<STRING> = ["a", "b", "c"]
5302 LET $nitems: INT = LEN($items)
5303 ASSERT_EQ $nitems 3
5304 LET $row: MAP<name: STRING> = {name: "ada"}
5305 LET $nkeys: INT = LEN($row)
5306 ASSERT_EQ $nkeys 1
5307 LET $empty: INT = LEN([])
5308 ASSERT_EQ $empty 0
5309 "###
5310)]
5311fn len(
5312 #[union(String, List, Map)]
5314 value: Value,
5315) -> Result<Value> {
5316 if let Some(text) = value.as_str() {
5317 return Ok(Value::int(text.chars().count() as i64));
5318 }
5319 if let Some(items) = value.as_list() {
5320 return Ok(Value::int(items.len() as i64));
5321 }
5322 if let Some(entries) = value.as_map() {
5323 return Ok(Value::int(entries.len() as i64));
5324 }
5325 Err(anyhow::Error::new(std_diag::std_len_unexpected_type(
5326 value.type_name(),
5327 )))
5328}
5329
5330#[oxdock_func(pure, returns = TypeTag::Int)]
5338#[example(
5339 name = "count",
5340 code = r###"
5341 # Every non-overlapping occurrence counts once.
5342 IMPORT [STD]
5343 LET $n: INT = TEXT_COUNT("hello world", "o")
5344 ASSERT_EQ $n 2
5345
5346 # Overlapping candidates never double count.
5347 LET $once: INT = TEXT_COUNT("aaa", "aa")
5348 ASSERT_EQ $once 1
5349 "###
5350)]
5351fn text_count(
5352 text: String,
5354 needle: String,
5356) -> Result<Value> {
5357 let n = super::args::text_count_str(&text, &needle, FUNC_TEXT_COUNT)?;
5358 Ok(Value::int(n))
5359}
5360
5361#[oxdock_func(pure, returns = TypeTag::Int)]
5371#[example(
5372 name = "count matches",
5373 code = r###"
5374 # One line matches once no matter how many times it hits.
5375 IMPORT [STD]
5376 LET $n: INT = TEXT_COUNT_MATCHES("test a: test\ntest b: nope\ntest c: test", ": test")
5377 ASSERT_EQ $n 2
5378
5379 # A miss binds zero, never an error.
5380 LET $none: INT = TEXT_COUNT_MATCHES("test b: nope", ": test$")
5381 ASSERT_EQ $none 0
5382 "###
5383)]
5384fn text_count_matches(
5385 text: String,
5387 pattern: String,
5389) -> Result<Value> {
5390 let n = super::args::text_count_matches_str(&text, &pattern, FUNC_TEXT_COUNT_MATCHES)?;
5391 Ok(Value::int(n))
5392}
5393
5394#[oxdock_func(pure, returns = TypeTag::ListOf(std::sync::Arc::new(TypeTag::String)))]
5407#[example(
5408 name = "grep",
5409 code = r###"
5410 # Matching lines come back as a list, in order.
5411 IMPORT [STD]
5412 LET $hits: LIST<STRING> = TEXT_GREP("one\ntwo\none more", "^one")
5413 ASSERT_EQ $hits.0 "one"
5414 ASSERT_EQ $hits.1 "one more"
5415
5416 # A miss binds an empty list, never an error.
5417 LET $miss: LIST<STRING> = TEXT_GREP("one\ntwo", "^z")
5418 LET $joined: STRING = TEXT_JOIN($miss, ",")
5419 ASSERT_EQ $joined ""
5420
5421 # The (?i) flag ignores case, so uppercase lines match too.
5422 LET $folded: LIST<STRING> = TEXT_GREP("One\ntwo\nONE more", "(?i)^one")
5423 ASSERT_EQ $folded.0 "One"
5424 ASSERT_EQ $folded.1 "ONE more"
5425 "###
5426)]
5427#[example(
5428 name = "grep invert",
5429 code = r###"
5430 # The invert option keeps every non-matching line instead.
5431 IMPORT [STD]
5432 LET $kept: LIST<STRING> = TEXT_GREP("one\ntwo\none more", "^one", {invert: true})
5433 ASSERT_EQ $kept.0 "two"
5434
5435 # A pattern matching every line binds an empty list, never an error.
5436 LET $none: LIST<STRING> = TEXT_GREP("one\ntwo", "^", {invert: true})
5437 LET $joined: STRING = TEXT_JOIN($none, ",")
5438 ASSERT_EQ $joined ""
5439
5440 # Options ride into placeholders as MAP literals. Placeholder
5441 # strings unescape only backslash and quote, so multiline text
5442 # arrives through a variable.
5443 LET $two_lines: STRING = "one\ntwo"
5444 LET $msg: STRING = 'kept:{{ STD::TEXT_GREP($two_lines, "^one", {invert: true}) }}'
5445 ASSERT_EQ $msg "kept:two"
5446 "###
5447)]
5448fn text_grep(
5449 text: String,
5451 pattern: String,
5453 #[options("invert?: BOOL")]
5455 #[optional]
5456 options: BTreeMap<String, Value>,
5457) -> Result<Value> {
5458 let invert = super::args::text_invert_flag(&options);
5461 Ok(super::args::text_list_value(super::args::text_grep_str(
5462 &text,
5463 &pattern,
5464 invert,
5465 FUNC_TEXT_GREP,
5466 )?))
5467}
5468
5469#[oxdock_func(returns = TypeTag::Bool)]
5480#[example(
5481 name = "drain to end",
5482 code = r###"
5483 # Capture two lines, then drain to end of stream with no sentinel line.
5484 IMPORT [STD]
5485 LET $cap: PIPE
5486 WITH_IO [stdout=$cap] {
5487 ECHO "one"
5488 ECHO "two"
5489 }
5490
5491 # The loop exits on close, and the count proves both lines drained.
5492 LET $n: INT = 0
5493 WHILE !EOF($cap) {
5494 WITH_IO [stdin=$cap] READ_LINE $line
5495 $n = $n + 1
5496 }
5497 ASSERT_EQ $n 2
5498 "###
5499)]
5500fn eof<P: ProcessManager>(
5501 cx: &mut StepCtx<P>,
5502 pipe: PipeHandle,
5504) -> Result<Value> {
5505 let info = cx.state.io.inspect_pipe(&pipe);
5506 Ok(Value::bool(info.closed && info.buffered == 0))
5507}
5508
5509fn task_poll_result_fields() -> Arc<[Field]> {
5513 Arc::from(vec![
5514 Field {
5515 name: "state".to_string(),
5516 ty: TypeTag::String,
5517 docs: "Task phase: `running` or `finished`.",
5518 optional: false,
5519 default: None,
5520
5521 alias: None,
5522 },
5523 Field {
5524 name: "ok".to_string(),
5525 ty: TypeTag::Bool,
5526 docs: "True unless the task failed.",
5527 optional: false,
5528 default: None,
5529
5530 alias: None,
5531 },
5532 Field {
5533 name: "stdout_tail".to_string(),
5534 ty: TypeTag::String,
5535 docs: "Bounded stdout tail, live while running.",
5536 optional: false,
5537 default: None,
5538
5539 alias: None,
5540 },
5541 Field {
5542 name: "stderr_tail".to_string(),
5543 ty: TypeTag::String,
5544 docs: "Bounded stderr tail, live while running.",
5545 optional: false,
5546 default: None,
5547
5548 alias: None,
5549 },
5550 Field {
5551 name: "truncated_bytes".to_string(),
5552 ty: TypeTag::Int,
5553 docs: "Dropped head bytes past the per-stream cap.",
5554 optional: false,
5555 default: None,
5556
5557 alias: None,
5558 },
5559 Field {
5560 name: "exit_code".to_string(),
5561 ty: TypeTag::Int,
5562 docs: "Process exit code, present once finished.",
5563 optional: true,
5564 default: None,
5565
5566 alias: None,
5567 },
5568 Field {
5569 name: "result".to_string(),
5570 ty: TypeTag::Any,
5571 docs: "Task `RETURN` value, present on clean finish.",
5572 optional: true,
5573 default: None,
5574
5575 alias: None,
5576 },
5577 Field {
5578 name: "error".to_string(),
5579 ty: TypeTag::String,
5580 docs: "Failure text, present on failed finish.",
5581 optional: true,
5582 default: None,
5583
5584 alias: None,
5585 },
5586 ])
5587}
5588
5589#[oxdock_func(returns = TypeTag::Record(task_poll_result_fields()))]
5602#[example(
5603 name = "running poll",
5604 code = r###"
5605 # A sleeping task is still running on the first poll.
5606 IMPORT [STD]
5607 LET $t: HANDLE<STRING> = ASYNC { SLEEP 30s; RETURN "done" }
5608 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)
5609 ASSERT_EQ $m.state "running"
5610 ASSERT_EQ $m.ok true
5611 # Clean up the sleeper so the run ends promptly.
5612 CANCEL $t
5613 "###
5614)]
5615#[example(
5616 name = "finished poll",
5617 code = r###"
5618 # A finished task reports its value and final tails, then still awaits.
5619 IMPORT [STD]
5620 LET $t: HANDLE<STRING> = ASYNC { ECHO "hi"; SLEEP 1s; RETURN "done" }
5621 # Do other work while the task runs; poll once it should be done.
5622 SLEEP 2s
5623 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)
5624 ASSERT_EQ $m.state "finished"
5625 ASSERT_EQ $m.result "done"
5626 LET $o: STRING = AWAIT $t
5627 ASSERT_EQ $o "done"
5628 "###
5629)]
5630fn task_poll<P: ProcessManager>(
5631 cx: &mut StepCtx<P>,
5632 task: HandleValue,
5634) -> Result<Value> {
5635 let entry =
5636 super::handlers::resolve_task_entry_by_id(task.0, &format!("TASK_POLL({})", task.0), cx)?;
5637 let obs = entry.observe_completion();
5638 let (stdout_tail, stderr_tail, dropped) = entry.snapshot_tails();
5639 let mut out = BTreeMap::new();
5640 out.insert(
5641 "state".to_string(),
5642 Value::string(if obs.running { "running" } else { "finished" }.to_string()),
5643 );
5644 out.insert("ok".to_string(), Value::bool(obs.ok));
5645 if !obs.running {
5646 out.insert("exit_code".to_string(), Value::int(obs.exit_code));
5647 }
5648 if let Some(result) = obs.result {
5649 out.insert("result".to_string(), result);
5650 }
5651 if !obs.error.is_empty() {
5652 out.insert("error".to_string(), Value::string(obs.error));
5653 }
5654 out.insert("stdout_tail".to_string(), Value::string(stdout_tail));
5655 out.insert("stderr_tail".to_string(), Value::string(stderr_tail));
5656 out.insert(
5657 "truncated_bytes".to_string(),
5658 Value::int(dropped.min(i64::MAX as u64) as i64),
5659 );
5660 Ok(Value::map(out))
5661}
5662
5663fn meta_to_value(meta: &FuncMeta) -> Value {
5664 let mut map = BTreeMap::new();
5665 map.insert("name".to_string(), Value::string(meta.name.clone()));
5666 map.insert("module".to_string(), Value::string(meta.module.clone()));
5667 map.insert(
5668 "kind".to_string(),
5669 Value::string(meta.kind.label().to_string()),
5670 );
5671 let params = match &meta.params {
5672 Some(params) => Value::list(
5673 params
5674 .iter()
5675 .map(|p| {
5676 let mut entry = BTreeMap::new();
5677 entry.insert("name".to_string(), Value::string(p.name.clone()));
5678 entry.insert(
5679 "param_type".to_string(),
5680 Value::string(
5681 p.param_type
5682 .as_ref()
5683 .map(render_structural)
5684 .unwrap_or_default(),
5685 ),
5686 );
5687 entry.insert(
5688 "allowed".to_string(),
5689 Value::string(
5690 p.allowed
5691 .map(|values| values.join(", "))
5692 .unwrap_or_default(),
5693 ),
5694 );
5695 entry.insert("docs".to_string(), Value::string(String::new()));
5696 entry.insert("optional".to_string(), Value::bool(p.optional));
5697 entry.insert(
5698 "options".to_string(),
5699 match p.options {
5700 Some(keys) => Value::list(
5701 keys.iter()
5702 .map(|key| {
5703 let mut option = BTreeMap::new();
5704 option.insert(
5705 "name".to_string(),
5706 Value::string(key.name.to_string()),
5707 );
5708 option.insert(
5709 "value_type".to_string(),
5710 Value::string(render_structural(&key.value)),
5711 );
5712 option.insert(
5713 "required".to_string(),
5714 Value::bool(key.required),
5715 );
5716 option.insert(
5717 "default".to_string(),
5718 Value::string(
5719 key.default.unwrap_or_default().to_string(),
5720 ),
5721 );
5722 Value::map(option)
5723 })
5724 .collect(),
5725 ),
5726 None => Value::string(String::new()),
5727 },
5728 );
5729 Value::map(entry)
5730 })
5731 .collect(),
5732 ),
5733 None => Value::list(Vec::new()),
5737 };
5738 map.insert("params".to_string(), params);
5739 map.insert(
5740 "returns".to_string(),
5741 Value::string(
5742 meta.returns
5743 .as_ref()
5744 .map(render_structural)
5745 .unwrap_or_default(),
5746 ),
5747 );
5748 map.insert("rpn".to_string(), Value::bool(meta.rpn));
5749 map.insert(
5750 "summary".to_string(),
5751 Value::string(meta.summary.to_string()),
5752 );
5753 Value::map(map)
5754}
5755
5756#[derive(Debug, Clone)]
5760pub struct RecordSchema {
5761 pub name: &'static str,
5762 pub fields: std::sync::Arc<[Field]>,
5763}
5764
5765#[derive(Clone)]
5769pub struct HostModule<P: ProcessManager> {
5770 pub name: String,
5771 pub funcs: Vec<HostRegistration<P>>,
5772 pub types: Vec<&'static TypeDescriptor>,
5773 pub record_schemas: Vec<RecordSchema>,
5774 pub states: Vec<ModuleState>,
5781}
5782
5783#[derive(Clone)]
5787pub struct ModuleState {
5788 id: std::any::TypeId,
5789 state: std::sync::Arc<dyn std::any::Any + Send + Sync>,
5790}
5791
5792pub type PreRunInspector = dyn Fn(&[Step]) -> DiagnosticResult<()> + Send + Sync;
5796
5797#[derive(Clone)]
5803pub struct PreRunCheck {
5804 check: Arc<PreRunInspector>,
5805}
5806
5807impl PreRunCheck {
5808 pub fn new(check: impl Fn(&[Step]) -> DiagnosticResult<()> + Send + Sync + 'static) -> Self {
5810 Self {
5811 check: Arc::new(check),
5812 }
5813 }
5814
5815 pub fn run(&self, steps: &[Step]) -> DiagnosticResult<()> {
5817 (self.check)(steps)
5818 }
5819}
5820
5821impl<P: ProcessManager> HostModule<P> {
5822 pub fn with_state<T: Send + Sync + 'static>(mut self, state: std::sync::Arc<T>) -> Self {
5825 self.states.push(ModuleState {
5826 id: std::any::TypeId::of::<T>(),
5827 state,
5828 });
5829 self
5830 }
5831
5832 pub fn check_pre_run(&self, steps: &[Step]) -> DiagnosticResult<()> {
5836 for state in &self.states {
5837 if let Some(check) = state.state.downcast_ref::<PreRunCheck>() {
5838 check.run(steps)?;
5839 }
5840 }
5841 Ok(())
5842 }
5843}
5844
5845impl<P: ProcessManager> ExecState<P> {
5846 pub fn register_module(&mut self, module: HostModule<P>) {
5849 for registration in module.funcs {
5850 match registration {
5851 HostRegistration::Stateful { name, meta, func } => {
5852 self.functions.register_host(&module.name, name, meta, func);
5853 }
5854 HostRegistration::Pure { name, meta, func } => {
5855 self.functions
5856 .register_pure_host(&module.name, name, meta, func);
5857 }
5858 HostRegistration::Both {
5859 name,
5860 meta,
5861 func,
5862 template,
5863 } => {
5864 self.functions
5865 .register_both_host(&module.name, name, meta, func, template);
5866 }
5867 }
5868 }
5869 for descriptor in module.types {
5870 self.register_type(descriptor);
5871 }
5872 for schema in module.record_schemas {
5873 self.register_record_schema(schema.name, schema.fields);
5874 }
5875 for state in module.states {
5876 self.module_states
5877 .insert((module.name.clone(), state.id), state.state);
5878 }
5879 }
5880
5881 pub fn list_functions(&self) -> Vec<FuncMeta> {
5883 let mut out: Vec<FuncMeta> = self.functions.entries_metas().into_iter().collect();
5884 if !out.iter().any(|m| m.name == KEYWORD_INSPECT) {
5886 out.push(FuncMeta {
5887 name: KEYWORD_INSPECT.to_string(),
5888 module: STD_MODULE_NAME.to_string(),
5889 kind: FuncKind::HostCtx,
5890 params: None,
5891 returns: Some(TypeTag::Map),
5892 rpn: false,
5893 summary: "Inspect a variable binding.",
5894 docs: "INSPECT($var): dedicated AST node taking a variable, not a value.",
5895 examples: &[],
5896 });
5897 }
5898 out.sort_by(|a, b| a.name.cmp(&b.name));
5899 out
5900 }
5901
5902 pub fn describe_function(&self, name: &str) -> Option<Value> {
5904 if let Some(meta) = self.functions.meta(name) {
5905 return Some(meta_to_value(&meta));
5906 }
5907 if name == KEYWORD_INSPECT {
5909 return Some(meta_to_value(&FuncMeta {
5910 name: KEYWORD_INSPECT.to_string(),
5911 module: STD_MODULE_NAME.to_string(),
5912 kind: FuncKind::HostCtx,
5913 params: None,
5914 returns: Some(TypeTag::Map),
5915 rpn: false,
5916 summary: "Inspect a variable binding.",
5917 docs: "INSPECT($var): dedicated AST node taking a variable, not a value.",
5918 examples: &[],
5919 }));
5920 }
5921 None
5922 }
5923
5924 pub fn pure_function_table(&self) -> Arc<PureTable> {
5929 self.functions.pure_shared()
5930 }
5931}
5932
5933#[cfg(test)]
5934mod tests {
5935 use super::*;
5936
5937 #[test]
5938 fn placeholder_resolver_dispatches_table_entries() {
5939 let echo: PureFn = Arc::new(|args| {
5943 args.into_iter()
5944 .next()
5945 .ok_or_else(|| anyhow::anyhow!("ECHO needs 1 arg"))
5946 });
5947 let mut entries = HashMap::new();
5948 entries.insert("ECHO".to_string(), echo);
5949 let mut table = PureTable::new();
5950 table.insert("T".to_string(), entries);
5951 let resolve = placeholder_resolver(Arc::new(table));
5952 let out = resolve("T", "ECHO", vec![Value::string("hi".to_string())]).expect("dispatch");
5953 assert_eq!(out.as_str().expect("string"), "hi");
5954 let err = format!(
5955 "{:#}",
5956 resolve("T", "NOPE", vec![]).expect_err("unknown must fail")
5957 );
5958 assert!(
5959 err.contains("unknown placeholder function `T::NOPE`"),
5960 "names the call: {err}"
5961 );
5962 assert!(
5963 err.contains("known functions: T::ECHO"),
5964 "lists known names: {err}"
5965 );
5966 }
5967
5968 #[test]
5969 fn describe_entry_renders_union_spellings() {
5970 let union = oxdock_parser::union_tag!(String, Pipe);
5976 let meta = FuncMeta {
5977 name: "T::F".to_string(),
5978 module: "T".to_string(),
5979 kind: FuncKind::HostPure,
5980 params: Some(vec![FuncParam {
5981 name: "text".to_string(),
5982 param_type: Some(union.clone()),
5983 allowed: None,
5984 docs: "",
5985 options: None,
5986 optional: false,
5987 }]),
5988 returns: Some(union),
5989 rpn: false,
5990 summary: "test-only",
5991 docs: "test-only",
5992 examples: &[],
5993 };
5994 let value = meta_to_value(&meta);
5995 let map = value.as_map().expect("describe value is a map");
5996 let params = map
5997 .get("params")
5998 .expect("params key")
5999 .as_list()
6000 .expect("params is a list");
6001 let first = params[0].as_map().expect("entry is a map");
6002 assert_eq!(
6003 first.get("param_type").and_then(Value::as_str),
6004 Some("STRING|PIPE"),
6005 "param renders the set"
6006 );
6007 assert_eq!(
6008 map.get("returns").and_then(Value::as_str),
6009 Some("STRING|PIPE"),
6010 "returns render the set"
6011 );
6012 }
6013
6014 #[test]
6015 fn describe_entry_renders_handle_payload() {
6016 let meta = FuncMeta {
6020 name: "SCRIPT::FETCH".to_string(),
6021 module: "SCRIPT".to_string(),
6022 kind: FuncKind::Script,
6023 params: Some(vec![]),
6024 returns: Some(TypeTag::HandleOf(std::sync::Arc::new(TypeTag::String))),
6025 rpn: false,
6026 summary: "test-only",
6027 docs: "test-only",
6028 examples: &[],
6029 };
6030 let value = meta_to_value(&meta);
6031 let map = value.as_map().expect("describe value is a map");
6032 assert_eq!(
6033 map.get("returns").and_then(Value::as_str),
6034 Some("HANDLE<STRING>"),
6035 "returns render the payload"
6036 );
6037 }
6038
6039 #[test]
6040 fn describe_entry_carries_optional_flag() {
6041 let meta = FuncMeta {
6045 name: "T::F".to_string(),
6046 module: "T".to_string(),
6047 kind: FuncKind::HostPure,
6048 params: Some(vec![
6049 FuncParam {
6050 name: "url".to_string(),
6051 param_type: Some(TypeTag::String),
6052 allowed: None,
6053 docs: "",
6054 options: None,
6055 optional: false,
6056 },
6057 FuncParam {
6058 name: "options".to_string(),
6059 param_type: Some(TypeTag::Map),
6060 allowed: None,
6061 docs: "",
6062 options: None,
6063 optional: true,
6064 },
6065 ]),
6066 returns: Some(TypeTag::String),
6067 rpn: false,
6068 summary: "test-only",
6069 docs: "test-only",
6070 examples: &[],
6071 };
6072 let value = meta_to_value(&meta);
6073 let map = value.as_map().expect("describe value is a map");
6074 let params = map
6075 .get("params")
6076 .expect("params key")
6077 .as_list()
6078 .expect("params is a list");
6079 assert_eq!(params.len(), 2);
6080 let first = params[0].as_map().expect("entry is a map");
6081 let second = params[1].as_map().expect("entry is a map");
6082 assert_eq!(
6083 first.get("optional").and_then(Value::as_bool),
6084 Some(false),
6085 "required param must read false"
6086 );
6087 assert_eq!(
6088 second.get("optional").and_then(Value::as_bool),
6089 Some(true),
6090 "omittable param must read true"
6091 );
6092 }
6093
6094 #[test]
6095 fn template_twins_mirror_string_paths_and_refuse_pipes() {
6096 let pipe = Value::pipe_fresh();
6102 type TwinCase = (&'static str, Box<dyn Fn() -> Result<Value>>);
6103 let cases: Vec<TwinCase> = vec![
6104 (
6105 "TEXT_TRIM",
6106 Box::new(|| text_trim_string(Value::string(" hello ".to_string()))),
6107 ),
6108 (
6109 "TEXT_TRIM_PREFIX",
6110 Box::new(|| {
6111 text_trim_prefix_string(Value::string("v1".to_string()), "v".to_string())
6112 }),
6113 ),
6114 (
6115 "TEXT_TRIM_SUFFIX",
6116 Box::new(|| {
6117 text_trim_suffix_string(Value::string("a.gz".to_string()), "x".to_string())
6118 }),
6119 ),
6120 (
6121 "TEXT_TO_UPPER",
6122 Box::new(|| text_to_upper_string(Value::string("hi".to_string()))),
6123 ),
6124 (
6125 "TEXT_TO_LOWER",
6126 Box::new(|| text_to_lower_string(Value::string("HI".to_string()))),
6127 ),
6128 (
6129 "TEXT_REPLACE",
6130 Box::new(|| {
6131 text_replace_string(
6132 Value::string("ab".to_string()),
6133 "b".to_string(),
6134 "c".to_string(),
6135 )
6136 }),
6137 ),
6138 (
6139 "TEXT_REPLACE_REGEX",
6140 Box::new(|| {
6141 text_replace_regex_string(
6142 Value::string("ab".to_string()),
6143 "b".to_string(),
6144 "c".to_string(),
6145 )
6146 }),
6147 ),
6148 ];
6149 assert_eq!(cases.len(), 7, "every mirror op needs a twin row");
6150 for (name, run) in &cases {
6151 let value = run().unwrap_or_else(|e| panic!("{name} twin must answer strings: {e:#}"));
6152 assert!(
6153 value.as_str().is_some(),
6154 "{name} twin must answer STRING, got {}",
6155 value.type_name()
6156 );
6157 }
6158 assert_eq!(
6159 text_trim_string(Value::string(" hello ".to_string()))
6160 .expect("trim twin")
6161 .as_str(),
6162 Some("hello")
6163 );
6164 let pipe_cases: Vec<(&str, Result<Value>)> = vec![
6166 ("TEXT_TRIM", text_trim_string(pipe.clone())),
6167 (
6168 "TEXT_TRIM_PREFIX",
6169 text_trim_prefix_string(pipe.clone(), "v".to_string()),
6170 ),
6171 (
6172 "TEXT_TRIM_SUFFIX",
6173 text_trim_suffix_string(pipe.clone(), ".gz".to_string()),
6174 ),
6175 ("TEXT_TO_UPPER", text_to_upper_string(pipe.clone())),
6176 ("TEXT_TO_LOWER", text_to_lower_string(pipe.clone())),
6177 (
6178 "TEXT_REPLACE",
6179 text_replace_string(pipe.clone(), "a".to_string(), "b".to_string()),
6180 ),
6181 (
6182 "TEXT_REPLACE_REGEX",
6183 text_replace_regex_string(pipe.clone(), "a".to_string(), "b".to_string()),
6184 ),
6185 ];
6186 for (name, result) in pipe_cases {
6187 let err = result.expect_err(&format!("{name} twin must refuse PIPE"));
6188 assert!(
6189 format!("{err:#}").contains("step IO"),
6190 "{name} refusal names the missing context: {err:#}"
6191 );
6192 }
6193 }
6194
6195 #[test]
6196 fn shell_words_join_split_round_trip() {
6197 let words = vec![
6201 "gh".to_string(),
6202 "issue".to_string(),
6203 "comment".to_string(),
6204 "with spaces".to_string(),
6205 "it's".to_string(),
6206 "say \"hi\"".to_string(),
6207 "$HOME".to_string(),
6208 "$(whoami)".to_string(),
6209 "C:\\path\\to".to_string(),
6210 "naïve café".to_string(),
6211 "".to_string(),
6212 ];
6213 let joined = shell_words::join(&words);
6214 let back = shell_words::split(&joined).expect("join output must parse");
6215 assert_eq!(back, words);
6216 assert!(shell_words::split("unbalanced \"quote").is_err());
6217 }
6218
6219 struct FakeView {
6223 exports: HashMap<String, Vec<String>>,
6224 targets: HashMap<String, AliasTargets>,
6225 bindings: HashMap<String, HashMap<String, bool>>,
6226 }
6227
6228 impl ModuleGraphView for FakeView {
6229 fn const_exports(&self, file: &str) -> Option<&[String]> {
6230 self.exports.get(file).map(Vec::as_slice)
6231 }
6232
6233 fn alias_targets(&self, file: &str) -> AliasTargets {
6234 self.targets.get(file).cloned().unwrap_or_default()
6235 }
6236
6237 fn binding(&self, file: &str, name: &str) -> BindingPresence {
6238 match self.bindings.get(file).and_then(|names| names.get(name)) {
6239 Some(true) => BindingPresence::Const,
6240 Some(false) => BindingPresence::Let,
6241 None => BindingPresence::Absent,
6242 }
6243 }
6244 }
6245
6246 fn fake_targets(pairs: &[(&str, &str)]) -> AliasTargets {
6247 let mut targets = AliasTargets::new();
6248 for (alias, file) in pairs {
6249 targets
6250 .entry((*alias).to_string())
6251 .or_default()
6252 .push((Some((*file).to_string()), None));
6253 }
6254 targets
6255 }
6256
6257 fn os_guard(os: &str) -> GuardExpr {
6258 GuardExpr::Predicate(oxdock_parser::Guard::Attr {
6259 ns: oxdock_parser::Ns::Os,
6260 key: None,
6261 val: Some(os.to_string()),
6262 })
6263 }
6264
6265 #[test]
6266 fn chase_resolves_bare_and_single_forward() {
6267 let mut view = FakeView {
6270 exports: HashMap::from([
6271 ("a".to_string(), vec!["N".to_string()]),
6272 ("b".to_string(), vec!["A::N".to_string()]),
6273 ("c".to_string(), vec!["B::N".to_string()]),
6274 ]),
6275 targets: HashMap::from([
6276 ("u".to_string(), fake_targets(&[("B", "b")])),
6277 ("b".to_string(), fake_targets(&[("A", "a")])),
6278 ("c".to_string(), fake_targets(&[("B", "b")])),
6279 ]),
6280 bindings: HashMap::new(),
6281 };
6282 assert_eq!(
6283 chase_const_forward(&view, "a", "N", "U::N").expect("bare"),
6284 vec!["a".to_string()]
6285 );
6286 assert_eq!(
6287 chase_const_forward(&view, "b", "N", "U::N").expect("forward"),
6288 vec!["a".to_string()]
6289 );
6290 view.targets
6291 .insert("u".to_string(), fake_targets(&[("C", "c")]));
6292 assert_eq!(
6293 chase_const_forward(&view, "c", "N", "U::N").expect("chain"),
6294 vec!["a".to_string()]
6295 );
6296 }
6297
6298 #[test]
6299 fn chase_prefers_bare_over_forwards() {
6300 let view = FakeView {
6303 exports: HashMap::from([("b".to_string(), vec!["N".to_string(), "A::N".to_string()])]),
6304 targets: HashMap::from([("b".to_string(), fake_targets(&[("A", "a")]))]),
6305 bindings: HashMap::new(),
6306 };
6307 assert_eq!(
6308 chase_const_forward(&view, "b", "N", "U::N").expect("bare wins"),
6309 vec!["b".to_string()]
6310 );
6311 }
6312
6313 #[test]
6314 fn chase_rejects_split_forwards() {
6315 let view = FakeView {
6318 exports: HashMap::from([(
6319 "b".to_string(),
6320 vec!["A::N".to_string(), "C::N".to_string()],
6321 )]),
6322 targets: HashMap::new(),
6323 bindings: HashMap::new(),
6324 };
6325 let err = format!(
6326 "{}",
6327 chase_const_forward(&view, "b", "N", "U::N").expect_err("split must fail")
6328 );
6329 assert!(err.contains("ambiguous CONST `U::N`"), "{err}");
6330 assert!(err.contains("A::N") && err.contains("C::N"), "{err}");
6331 }
6332
6333 #[test]
6334 fn chase_names_broken_link_detail() {
6335 let view = FakeView {
6338 exports: HashMap::from([
6339 ("b".to_string(), vec!["A::M".to_string()]),
6340 ("c".to_string(), vec!["A::P".to_string()]),
6341 ("d".to_string(), vec!["A::Q".to_string()]),
6342 ("a".to_string(), Vec::new()),
6343 ]),
6344 targets: HashMap::from([
6345 ("b".to_string(), fake_targets(&[("A", "a")])),
6346 ("c".to_string(), fake_targets(&[("A", "a")])),
6347 ("d".to_string(), fake_targets(&[("A", "a")])),
6348 ]),
6349 bindings: HashMap::from([(
6350 "a".to_string(),
6351 HashMap::from([("P".to_string(), true), ("Q".to_string(), false)]),
6352 )]),
6353 };
6354 let err = format!(
6355 "{}",
6356 chase_const_forward(&view, "b", "M", "U::M").expect_err("missing must fail")
6357 );
6358 assert!(err.contains("does not resolve"), "{err}");
6359 assert!(err.contains("no import alias `A` exports `M`"), "{err}");
6360 let err = format!(
6361 "{}",
6362 chase_const_forward(&view, "c", "P", "U::P").expect_err("unexported must fail")
6363 );
6364 assert!(
6365 err.contains("holds `P` as CONST but does not export it"),
6366 "{err}"
6367 );
6368 let err = format!(
6369 "{}",
6370 chase_const_forward(&view, "d", "Q", "U::Q").expect_err("LET must fail")
6371 );
6372 assert!(
6373 err.contains("is a LET binding and cannot be exported"),
6374 "{err}"
6375 );
6376 }
6377
6378 #[test]
6379 fn chase_rejects_cycles() {
6380 let view = FakeView {
6383 exports: HashMap::from([
6384 ("a".to_string(), vec!["B::N".to_string()]),
6385 ("b".to_string(), vec!["A::N".to_string()]),
6386 ]),
6387 targets: HashMap::from([
6388 ("a".to_string(), fake_targets(&[("B", "b")])),
6389 ("b".to_string(), fake_targets(&[("A", "a")])),
6390 ]),
6391 bindings: HashMap::new(),
6392 };
6393 let err = format!(
6394 "{}",
6395 chase_const_forward(&view, "a", "N", "U::N").expect_err("cycle must fail")
6396 );
6397 assert!(err.contains("re-export cycle"), "{err}");
6398 }
6399
6400 #[test]
6401 fn chase_unions_disjoint_guard_branches() {
6402 let mut guarded = AliasTargets::new();
6405 guarded.insert(
6406 "A".to_string(),
6407 vec![
6408 (Some("lin".to_string()), Some(os_guard("linux"))),
6409 (Some("mac".to_string()), Some(os_guard("macos"))),
6410 ],
6411 );
6412 let view = FakeView {
6413 exports: HashMap::from([
6414 ("b".to_string(), vec!["A::N".to_string()]),
6415 ("lin".to_string(), vec!["N".to_string()]),
6416 ("mac".to_string(), vec!["N".to_string()]),
6417 ]),
6418 targets: HashMap::from([("b".to_string(), guarded)]),
6419 bindings: HashMap::new(),
6420 };
6421 assert_eq!(
6422 chase_const_forward(&view, "b", "N", "U::N").expect("disjoint branches"),
6423 vec!["lin".to_string(), "mac".to_string()]
6424 );
6425 }
6426
6427 #[test]
6428 fn holder_classification_sorts_and_rejects() {
6429 let view = FakeView {
6432 exports: HashMap::from([
6433 ("b".to_string(), vec!["N".to_string()]),
6434 ("c".to_string(), vec!["N".to_string()]),
6435 ]),
6436 targets: HashMap::new(),
6437 bindings: HashMap::new(),
6438 };
6439 let unit = fake_targets(&[("B", "b"), ("B", "c")]);
6440 match const_holder_files(&view, &unit, "B", "N") {
6441 ConstHolders::Ambiguous { .. } => {}
6442 other => panic!("overlapping holders must be ambiguous, got {other:?}"),
6443 }
6444 match const_holder_files(&view, &unit, "Z", "N") {
6445 ConstHolders::NoAlias => {}
6446 other => panic!("unknown alias must report NoAlias, got {other:?}"),
6447 }
6448 let unit = fake_targets(&[("B", "b")]);
6449 match const_holder_files(&view, &unit, "B", "N") {
6450 ConstHolders::Found(files) => assert_eq!(files, vec!["b".to_string()]),
6451 other => panic!("single holder must be found, got {other:?}"),
6452 }
6453 }
6454}