1use std::collections::{BTreeMap, HashMap, HashSet};
2use std::sync::Arc;
3
4use oxdock_diagnostics::{Diagnostic, DiagnosticResult};
5use oxdock_fs::to_forward_slashes;
6use oxdock_fs::{GuardedPath, WorkspaceSelection};
7use oxdock_func_macro::oxdock_func;
8use oxdock_parser::value::HandleValue;
9use oxdock_parser::{
10 Field, GuardExpr, KEYWORD_CONST, KEYWORD_EXPORT, KEYWORD_FROM, KEYWORD_FUNC, KEYWORD_IMPORT,
11 KEYWORD_INSPECT, KEYWORD_LET, KEYWORD_TYPE, MODULE_SEPARATOR, SCRIPT_MODULE_NAME,
12 STD_MODULE_NAME, SemaphoreState, Step, TypeTag, Value, base_name, guards_overlap, qualify,
13 render_structural, split_qualified,
14};
15use oxdock_pipe::PipeHandle;
16use oxdock_process::{CommandStdin, DefaultProcessManager, ProcessManager};
17
18use super::diagnostics as std_diag;
19use super::function_names::{
20 FUNC_BOOL, FUNC_BOOL_OR, FUNC_PARSE_ARGS, FUNC_PARSE_FLAGS, FUNC_PARSE_POSITIONALS,
21 FUNC_TEXT_COUNT, FUNC_TEXT_COUNT_MATCHES, FUNC_TEXT_EXTRACT, FUNC_TEXT_GREP,
22 FUNC_TEXT_LINES_RANGE, FUNC_TEXT_MATCH, FUNC_TEXT_REPLACE, FUNC_TEXT_REPLACE_REGEX,
23};
24use super::io::StreamHandle;
25use super::state::ExecState;
26use super::steps::StepCtx;
27use super::typing::TypeDescriptor;
28
29#[derive(Debug, Clone, Copy, PartialEq, Eq)]
35pub enum FuncKind {
36 Script,
37 HostCtx,
38 HostPure,
39}
40
41pub(super) fn file_func_key(defining_file: &str, name: &str) -> String {
45 qualify(defining_file, name)
46}
47
48pub(super) fn ambiguous_alias_message(alias: &str, name: &str, files: &HashSet<String>) -> String {
51 let mut files: Vec<&str> = files.iter().map(|file| file.as_str()).collect();
52 files.sort();
53 format!(
54 "function `{alias}::{name}` is ambiguous: alias `{alias}` is imported from multiple files ({})",
55 files.join(", ")
56 )
57}
58
59pub(super) enum AliasResolution {
65 Global,
67 Canonical(String),
69 Unknown,
71 Ambiguous {
74 alias: String,
75 base: String,
76 files: HashSet<String>,
77 },
78 Any {
85 base: String,
86 files: HashSet<String>,
87 has_host: bool,
88 },
89}
90
91pub(super) type AliasTargets = HashMap<String, Vec<(Option<String>, Option<GuardExpr>)>>;
98
99pub(super) trait FuncFrameView {
105 type Hit;
107 fn find_nested(&self, base: &str) -> Option<Self::Hit>;
109 fn find_home(&self, unit: &str, base: &str) -> Option<Self::Hit>;
111 fn find_harvest(&self, unit: &str, base: &str) -> Option<Self::Hit>;
113 fn walk(&self, unit: &str, base: &str) -> Option<Self::Hit> {
115 self.find_nested(base)
116 .or_else(|| self.find_home(unit, base))
117 .or_else(|| self.find_harvest(unit, base))
118 }
119}
120
121pub(super) fn classify_alias_call(
127 unit_targets: &AliasTargets,
128 name: &str,
129 exists: &dyn Fn(&str) -> bool,
130) -> AliasResolution {
131 let Some((alias, base)) = split_qualified(name) else {
132 return AliasResolution::Global;
133 };
134 if alias == SCRIPT_MODULE_NAME {
135 return AliasResolution::Global;
136 }
137 let Some(entries) = unit_targets.get(alias) else {
138 return AliasResolution::Global;
139 };
140 if entries.is_empty() {
141 return AliasResolution::Unknown;
142 }
143 let mut files: Vec<(&str, Vec<Option<&GuardExpr>>)> = Vec::new();
146 let mut host_guards: Vec<Option<&GuardExpr>> = Vec::new();
147 for (file, guard) in entries {
148 match file {
149 Some(path) => match files.iter_mut().find(|(known, _)| *known == path) {
150 Some((_, guards)) => guards.push(guard.as_ref()),
151 None => files.push((path, vec![guard.as_ref()])),
152 },
153 None => host_guards.push(guard.as_ref()),
154 }
155 }
156 if files.is_empty() {
157 return AliasResolution::Unknown;
158 }
159 let overlaps = |left: &[Option<&GuardExpr>], right: &[Option<&GuardExpr>]| {
160 left.iter()
161 .any(|a| right.iter().any(|b| guards_overlap(*a, *b)))
162 };
163 if files.len() == 1 {
164 let disjoint_host = host_guards
168 .iter()
169 .any(|host| !overlaps(&files[0].1, &[*host]));
170 if !disjoint_host {
171 return AliasResolution::Canonical(file_func_key(files[0].0, base));
172 }
173 let mut all = HashSet::new();
174 all.insert(files[0].0.to_string());
175 return AliasResolution::Any {
176 base: base.to_string(),
177 files: all,
178 has_host: true,
179 };
180 }
181 let mut ambiguous = HashSet::new();
182 for (i, (file, guards)) in files.iter().enumerate() {
183 for (other, other_guards) in files.iter().skip(i + 1) {
184 if overlaps(guards, other_guards)
185 && (exists(&file_func_key(file, base)) || exists(&file_func_key(other, base)))
186 {
187 ambiguous.insert((*file).to_string());
188 ambiguous.insert((*other).to_string());
189 }
190 }
191 }
192 if !ambiguous.is_empty() {
193 return AliasResolution::Ambiguous {
194 alias: alias.to_string(),
195 base: base.to_string(),
196 files: ambiguous,
197 };
198 }
199 let all: HashSet<String> = files.iter().map(|(file, _)| (*file).to_string()).collect();
200 if all.iter().any(|file| exists(&file_func_key(file, base))) {
201 return AliasResolution::Any {
202 base: base.to_string(),
203 files: all,
204 has_host: !host_guards.is_empty(),
205 };
206 }
207 AliasResolution::Unknown
208}
209
210pub(super) fn missing_import_hint<'a>(
220 files: impl IntoIterator<Item = (&'a str, &'a [String])>,
221 unit_targets: &AliasTargets,
222 name: &str,
223) -> Option<String> {
224 let base = match split_qualified(name) {
225 Some((_, base)) => base,
226 None => name,
227 };
228 if base.is_empty() {
229 return None;
230 }
231 let mut exporters: Vec<&str> = files
232 .into_iter()
233 .filter(|(_, exports)| exports.iter().any(|exported| exported == base))
234 .map(|(file, _)| file)
235 .collect();
236 exporters.sort();
237 exporters.dedup();
238 if exporters.is_empty() {
239 return None;
240 }
241 let imported_as = |file: &str| {
243 let mut aliases: Vec<&str> = unit_targets
244 .iter()
245 .filter(|(_, targets)| {
246 targets
247 .iter()
248 .any(|(target, _)| target.as_deref() == Some(file))
249 })
250 .map(|(alias, _)| alias.as_str())
251 .collect();
252 aliases.sort();
253 aliases
254 };
255 if exporters.len() == 1 {
256 let file = exporters[0];
257 let aliases = imported_as(file);
258 let import_alias = aliases
263 .iter()
264 .find(|alias| qualify(alias, base) != name)
265 .or(aliases.first())
266 .copied();
267 let suggestion = match import_alias {
268 Some(import_alias) => {
269 let spelling = qualify(import_alias, base);
270 if spelling == name {
271 format!(
274 "file \"{file}\" exports `{base}` but the `{import_alias}` view does not resolve it here"
275 )
276 } else {
277 format!("did you mean `{spelling}`? (file \"{file}\" exports `{base}`)")
278 }
279 }
280 None => {
281 let path = to_forward_slashes(file);
284 format!(
285 "file \"{file}\" exports `{base}`: add `[{KEYWORD_FUNC} {base} {KEYWORD_FROM} \"{path}\"]` to an {KEYWORD_IMPORT}"
286 )
287 }
288 };
289 return Some(format!("; {suggestion}"));
290 }
291 let mut files = exporters.join("\", \"");
292 files.insert(0, '"');
293 files.push('"');
294 Some(format!(
295 "; files {files} export `{base}`: qualify the call with the importing alias"
296 ))
297}
298
299pub(super) fn const_export_covers(entry: &str, name: &str) -> bool {
304 base_name(entry) == name
305}
306
307pub(super) enum BindingPresence {
310 Const,
311 Let,
312 Absent,
313}
314
315pub(super) fn missing_const_hint<S: ModuleGraphView>(
322 view: &S,
323 targets: &AliasTargets,
324 alias: &str,
325 name: &str,
326) -> Option<String> {
327 targets
328 .get(alias)
329 .map(|entries| {
330 entries
331 .iter()
332 .filter_map(|(file, _)| file.as_ref())
333 .collect::<Vec<_>>()
334 })
335 .unwrap_or_default()
336 .iter()
337 .find_map(|file| match view.binding(file, name) {
338 BindingPresence::Const => Some(format!(
339 "module holds `{name}` as {KEYWORD_CONST} but does not export it: add `{KEYWORD_EXPORT} {KEYWORD_CONST} ${name}`"
340 )),
341 BindingPresence::Let => Some(format!(
342 "`{name}` is a {KEYWORD_LET} binding and cannot be exported: only {KEYWORD_CONST} bindings cross the module boundary"
343 )),
344 BindingPresence::Absent => None,
345 })
346}
347
348pub(super) trait ModuleGraphView {
355 fn const_exports(&self, file: &str) -> Option<&[String]>;
357 fn alias_targets(&self, file: &str) -> AliasTargets;
360 fn binding(&self, file: &str, name: &str) -> BindingPresence;
362}
363
364#[derive(Debug)]
370pub(super) enum ConstHolders {
371 Found(Vec<String>),
374 NoAlias,
376 Ambiguous {
378 alias: String,
379 base: String,
380 files: HashSet<String>,
381 },
382}
383
384fn const_canonical_suffix(name: &str) -> String {
389 format!("{MODULE_SEPARATOR}{name}")
390}
391
392pub(super) fn const_holder_files<S: ModuleGraphView>(
394 view: &S,
395 unit_targets: &AliasTargets,
396 alias: &str,
397 name: &str,
398) -> ConstHolders {
399 let qualified = qualify(alias, name);
400 let suffix = const_canonical_suffix(name);
401 let exports = |canonical: &str| {
405 canonical
406 .strip_suffix(suffix.as_str())
407 .and_then(|file| view.const_exports(file))
408 .is_some_and(|names| names.iter().any(|entry| const_export_covers(entry, name)))
409 };
410 let mut holders = match classify_alias_call(unit_targets, &qualified, &exports) {
411 AliasResolution::Global | AliasResolution::Unknown => return ConstHolders::NoAlias,
412 AliasResolution::Ambiguous { alias, base, files } => {
413 return ConstHolders::Ambiguous { alias, base, files };
414 }
415 AliasResolution::Canonical(canonical) => {
416 let Some(file) = canonical.strip_suffix(suffix.as_str()) else {
417 return ConstHolders::NoAlias;
418 };
419 vec![file.to_string()]
420 }
421 AliasResolution::Any { mut files, .. } => {
422 let mut files: Vec<String> = files.drain().collect();
423 files.sort();
424 files
425 }
426 };
427 holders.retain(|file| {
428 view.const_exports(file)
429 .is_some_and(|names| names.iter().any(|entry| const_export_covers(entry, name)))
430 });
431 ConstHolders::Found(holders)
432}
433
434#[derive(Debug)]
443pub(super) enum ForwardError {
444 Unknown { original: String },
446 Broken {
448 original: String,
449 hop: String,
450 detail: BrokenDetail,
451 },
452 Split { original: String, hops: Vec<String> },
454 Cycle { chain: Vec<String> },
457 HopAmbiguous {
459 alias: String,
460 base: String,
461 files: HashSet<String>,
462 },
463}
464
465#[derive(Debug)]
467pub(super) enum BrokenDetail {
468 UnexportedConst,
470 Let,
472 Absent,
474}
475
476impl std::fmt::Display for ForwardError {
477 fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
478 match self {
479 ForwardError::Unknown { original } => write!(f, "unknown {KEYWORD_CONST} `{original}`"),
480 ForwardError::Broken {
481 original,
482 hop,
483 detail,
484 } => {
485 let base = base_name(hop);
486 let detail = match detail {
487 BrokenDetail::UnexportedConst => format!(
488 "module holds `{base}` as {KEYWORD_CONST} but does not export it: add `{KEYWORD_EXPORT} {KEYWORD_CONST} ${base}`"
489 ),
490 BrokenDetail::Let => format!(
491 "`{base}` is a {KEYWORD_LET} binding and cannot be exported: only {KEYWORD_CONST} bindings cross the module boundary"
492 ),
493 BrokenDetail::Absent => {
494 let (forward, _) = split_qualified(hop).unwrap_or(("", base));
495 format!("no import alias `{forward}` exports `{base}`")
496 }
497 };
498 write!(
499 f,
500 "unknown {KEYWORD_CONST} `{original}`: re-export `{hop}` does not resolve: {detail}"
501 )
502 }
503 ForwardError::Split { original, hops } => write!(
504 f,
505 "ambiguous {KEYWORD_CONST} `{original}`: re-exported from {}; export exactly one source",
506 hops.join(" and ")
507 ),
508 ForwardError::Cycle { chain } => {
509 write!(
510 f,
511 "{KEYWORD_CONST} re-export cycle detected: {}",
512 chain.join(" -> ")
513 )
514 }
515 ForwardError::HopAmbiguous { alias, base, files } => write!(
516 f,
517 "{}",
518 ambiguous_alias_message(alias, base, files).replacen("function", KEYWORD_CONST, 1)
519 ),
520 }
521 }
522}
523
524fn forward_failed(err: ForwardError) -> Diagnostic {
529 std_diag::import_const_forward_failed(&err.to_string())
530}
531
532pub(super) fn chase_const_forward<S: ModuleGraphView>(
539 view: &S,
540 file: &str,
541 name: &str,
542 original: &str,
543) -> DiagnosticResult<Vec<String>> {
544 let mut terminals: Vec<String> = Vec::new();
545 chase_from(view, file, name, original, &mut Vec::new(), &mut terminals)?;
546 terminals.sort();
547 terminals.dedup();
548 Ok(terminals)
549}
550
551fn chase_from<S: ModuleGraphView>(
552 view: &S,
553 current: &str,
554 name: &str,
555 original: &str,
556 chain: &mut Vec<String>,
557 terminals: &mut Vec<String>,
558) -> DiagnosticResult<()> {
559 let suffix = const_canonical_suffix(name);
560 let covering = |canonical: &str| {
561 canonical
562 .strip_suffix(suffix.as_str())
563 .and_then(|file| view.const_exports(file))
564 .is_some_and(|names| names.iter().any(|entry| const_export_covers(entry, name)))
565 };
566 let mut current = current.to_string();
567 loop {
568 let Some(names) = view.const_exports(current.as_str()) else {
569 return Err(forward_failed(ForwardError::Unknown {
570 original: original.to_string(),
571 }));
572 };
573 if names.iter().any(|entry| entry == name) {
574 terminals.push(current);
575 return Ok(());
576 }
577 let mut aliases: Vec<&str> = Vec::new();
578 for entry in names {
579 if let Some((alias, base)) = split_qualified(entry)
580 && base == name
581 && !aliases.contains(&alias)
582 {
583 aliases.push(alias);
584 }
585 }
586 if aliases.is_empty() {
587 if chain.is_empty() {
588 return Err(forward_failed(ForwardError::Unknown {
589 original: original.to_string(),
590 }));
591 }
592 let hop = chain.last().expect("chain never empty").clone();
593 let detail = match view.binding(current.as_str(), name) {
594 BindingPresence::Const => BrokenDetail::UnexportedConst,
595 BindingPresence::Let => BrokenDetail::Let,
596 BindingPresence::Absent => BrokenDetail::Absent,
597 };
598 return Err(forward_failed(ForwardError::Broken {
599 original: original.to_string(),
600 hop,
601 detail,
602 }));
603 }
604 if aliases.len() > 1 {
605 let mut hops: Vec<String> = aliases.iter().map(|alias| qualify(alias, name)).collect();
606 hops.sort();
607 return Err(forward_failed(ForwardError::Split {
608 original: original.to_string(),
609 hops,
610 }));
611 }
612 let forward = aliases[0];
613 let hop = qualify(forward, name);
614 if chain.contains(&hop) {
615 chain.push(hop);
616 return Err(forward_failed(ForwardError::Cycle {
617 chain: chain.clone(),
618 }));
619 }
620 chain.push(hop.clone());
621 let targets = view.alias_targets(current.as_str());
622 match classify_alias_call(&targets, &hop, &covering) {
623 AliasResolution::Global | AliasResolution::Unknown => {
624 return Err(forward_failed(ForwardError::Broken {
625 original: original.to_string(),
626 hop,
627 detail: BrokenDetail::Absent,
628 }));
629 }
630 AliasResolution::Ambiguous { alias, base, files } => {
631 return Err(forward_failed(ForwardError::HopAmbiguous {
632 alias,
633 base,
634 files,
635 }));
636 }
637 AliasResolution::Canonical(canonical) => {
638 let Some(next) = canonical.strip_suffix(suffix.as_str()) else {
639 return Err(forward_failed(ForwardError::Unknown {
640 original: original.to_string(),
641 }));
642 };
643 current = next.to_string();
644 }
645 AliasResolution::Any { mut files, .. } => {
646 let mut covering: Vec<String> = files
647 .drain()
648 .filter(|file| {
649 view.const_exports(file).is_some_and(|names| {
650 names.iter().any(|entry| const_export_covers(entry, name))
651 })
652 })
653 .collect();
654 covering.sort();
655 match covering.len() {
656 0 => {
657 return Err(forward_failed(ForwardError::Broken {
658 original: original.to_string(),
659 hop,
660 detail: BrokenDetail::Absent,
661 }));
662 }
663 1 => {
664 current = covering.into_iter().next().expect("len checked");
665 }
666 _ => {
667 for branch in covering {
668 let mut branch_chain = chain.clone();
669 chase_from(
670 view,
671 branch.as_str(),
672 name,
673 original,
674 &mut branch_chain,
675 terminals,
676 )?;
677 }
678 return Ok(());
679 }
680 }
681 }
682 }
683 }
684}
685pub(super) fn disjoint_template_script_visible(
693 base: &str,
694 files: &HashSet<String>,
695 has_host: bool,
696 exists: &dyn Fn(&str) -> bool,
697) -> bool {
698 !has_host && !files.is_empty() && files.iter().all(|file| exists(&file_func_key(file, base)))
699}
700
701pub(super) fn disjoint_alias_placeholder_miss(
708 module: &str,
709 name: &str,
710 base: &str,
711 files: &HashSet<String>,
712 has_host: bool,
713 is_script: &dyn Fn(&str) -> bool,
714) -> String {
715 let script = disjoint_template_script_visible(base, files, has_host, is_script);
716 describe_placeholder_miss(module, name, script, false, !script)
717 .expect("disjoint miss always renders")
718}
719
720pub(super) fn spellings_for_defining_file(
727 unit_targets: &AliasTargets,
728 defining: &str,
729 base: &str,
730 is_script: &dyn Fn(&str) -> bool,
731) -> (Vec<String>, Vec<(String, HashSet<String>)>) {
732 let mut direct = Vec::new();
733 let mut ambiguous = Vec::new();
734 for (alias, files) in unit_targets {
735 if !files
736 .iter()
737 .any(|(file, _)| file.as_deref() == Some(defining))
738 {
739 continue;
740 }
741 let spelling = qualify(alias, base);
742 match classify_alias_call(unit_targets, &spelling, &|key| {
743 key == file_func_key(defining, base)
744 }) {
745 AliasResolution::Canonical(_) => direct.push(spelling),
746 AliasResolution::Ambiguous { files, .. } => {
747 ambiguous.push((spelling, files));
748 }
749 AliasResolution::Any {
750 base,
751 files,
752 has_host,
753 } => {
754 if disjoint_template_script_visible(&base, &files, has_host, is_script) {
755 direct.push(spelling);
756 }
757 }
758 AliasResolution::Global | AliasResolution::Unknown => {}
759 }
760 }
761 (direct, ambiguous)
762}
763
764impl FuncKind {
765 pub fn label(&self) -> &'static str {
766 match self {
767 FuncKind::Script => "script",
768 FuncKind::HostCtx | FuncKind::HostPure => "host",
769 }
770 }
771}
772
773#[derive(Debug, Clone)]
791pub struct FuncParam {
792 pub name: String,
793 pub param_type: Option<TypeTag>,
794 pub allowed: Option<&'static [&'static str]>,
795 pub docs: &'static str,
796 pub options: Option<&'static [ParamOption]>,
797 pub optional: bool,
798}
799
800pub fn required_arity(params: &[FuncParam]) -> usize {
805 params
806 .iter()
807 .rev()
808 .take_while(|param| param.optional)
809 .fold(params.len(), |count, _| count - 1)
810}
811
812pub fn fill_optional_args(params: &[FuncParam], mut values: Vec<Value>) -> Vec<Value> {
817 assert!(
818 values.len() <= params.len(),
819 "arity gate must run before fill_optional_args"
820 );
821 assert!(
822 values.len() >= required_arity(params),
823 "arity gate must run before fill_optional_args"
824 );
825 while values.len() < params.len() {
826 values.push(Value::map(BTreeMap::new()));
827 }
828 values
829}
830
831#[derive(Debug, Clone)]
838pub struct ParamOption {
839 pub name: &'static str,
840 pub value: TypeTag,
841 pub required: bool,
842 pub default: Option<&'static str>,
843}
844
845#[derive(Debug, Clone)]
851pub struct FuncMeta {
852 pub name: String,
853 pub module: String,
857 pub kind: FuncKind,
858 pub params: Option<Vec<FuncParam>>,
859 pub returns: Option<TypeTag>,
860 pub rpn: bool,
861 pub summary: &'static str,
862 pub docs: &'static str,
863 pub examples: &'static [crate::Example],
869}
870
871pub type PureFn = Arc<dyn Fn(Vec<Value>) -> DiagnosticResult<Value> + Send + Sync>;
874
875pub type NativeFn<P> =
877 Arc<dyn Fn(&mut StepCtx<P>, Vec<Value>) -> DiagnosticResult<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 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) -> DiagnosticResult<Value> {
2048 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) -> DiagnosticResult<Value> {
2071 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) -> DiagnosticResult<Value> {
2096 if bytes < 0 {
2097 return Err(std_diag::std_format_byte_count_negative(bytes));
2098 }
2099 Ok(Value::string(oxdock_parser::command::format_byte_count(
2100 bytes as u64,
2101 )))
2102}
2103
2104#[oxdock_func(pure, returns = TypeTag::Int)]
2139#[example(
2140 name = "parse",
2141 code = r###"
2142 IMPORT [STD]
2143 LET $n: INT = PARSE_BYTE_COUNT("10KB")
2144 ASSERT_EQ $n 10_000
2145 LET $identity: INT = PARSE_BYTE_COUNT(512)
2146 ASSERT_EQ $identity 512
2147 "###
2148)]
2149fn parse_byte_count(
2150 #[union(Int, Float, String)]
2152 text: Value,
2153) -> DiagnosticResult<Value> {
2154 if let Some(n) = text.as_i64() {
2155 if n < 0 {
2156 return Err(std_diag::std_parse_byte_count_negative(n));
2157 }
2158 return Ok(Value::int(n));
2159 }
2160 if let Some(f) = text.as_f64() {
2161 if f.is_finite() && f.fract() == 0.0 && f >= 0.0 && f <= i64::MAX as f64 {
2162 return Ok(Value::int(f as i64));
2163 }
2164 return Err(std_diag::std_parse_byte_count_integral(f));
2165 }
2166 let Some(s) = text.as_str() else {
2167 return Err(std_diag::std_parse_byte_count_shape(&text));
2168 };
2169 let n = oxdock_parser::command::parse_byte_count(s)?;
2170 let n = i64::try_from(n).map_err(|_| std_diag::std_parse_byte_count_range(s))?;
2171 Ok(Value::int(n))
2172}
2173
2174#[oxdock_func(pure, returns = TypeTag::String)]
2179#[example(
2180 name = "format and round-trip",
2181 code = r###"
2182 # Durations render in the largest exact unit.
2183 IMPORT [STD]
2184 LET $pretty: STRING = FORMAT_DURATION(90_000)
2185 ASSERT_EQ $pretty "90s"
2186
2187 # The pair round-trips through the parser.
2188 LET $back: INT = PARSE_DURATION($pretty)
2189 ASSERT_EQ $back 90_000
2190 "###
2191)]
2192fn format_duration(
2193 millis: i64,
2195) -> DiagnosticResult<Value> {
2196 if millis < 0 {
2197 return Err(std_diag::std_format_duration_negative(millis));
2198 }
2199 Ok(Value::string(oxdock_parser::command::format_duration(
2200 &std::time::Duration::from_millis(millis as u64),
2201 )))
2202}
2203
2204#[oxdock_func(pure, returns = TypeTag::Int)]
2210#[example(
2211 name = "parse",
2212 code = r###"
2213 # A bare number means seconds, like TIMEOUT.
2214 IMPORT [STD]
2215 LET $ms: INT = PARSE_DURATION("2m")
2216 ASSERT_EQ $ms 120_000
2217
2218 # Milliseconds stay exact.
2219 LET $exact: INT = PARSE_DURATION("1500ms")
2220 ASSERT_EQ $exact 1_500
2221
2222 # One optional space separates number from unit.
2223 LET $spaced: INT = PARSE_DURATION("1 h")
2224 ASSERT_EQ $spaced 3_600_000
2225 "###
2226)]
2227fn parse_duration(
2228 text: String,
2230) -> DiagnosticResult<Value> {
2231 let duration = oxdock_parser::command::parse_duration(&text)?;
2232 let millis = i64::try_from(duration.as_millis())
2233 .map_err(|_| std_diag::std_parse_duration_range(&text))?;
2234 Ok(Value::int(millis))
2235}
2236
2237#[oxdock_func(rpn, returns = TypeTag::ListOf(std::sync::Arc::new(TypeTag::String)))]
2242#[example(
2243 name = "match",
2244 code = r###"
2245 IMPORT [STD]
2246 WRITE "notes-a.md" "a"
2247 WRITE "notes-b.md" "b"
2248 WRITE "other.txt" "c"
2249 LET $found: LIST<STRING> = GLOB("notes-*.md")
2250 ASSERT_EQ $found.0 "notes-a.md"
2251 ASSERT_EQ $found.1 "notes-b.md"
2252 "###
2253)]
2254fn glob<P: ProcessManager>(
2255 cx: &mut StepCtx<P>,
2256 #[union(String, Path)]
2258 pattern: Value,
2259) -> DiagnosticResult<Value> {
2260 let text = super::args::string_or_path_text(&pattern)?;
2261 super::args::glob_from_value(&[Value::string(text)], cx)
2262}
2263
2264#[oxdock_func(rpn, returns = TypeTag::MapOf(std::sync::Arc::new(TypeTag::Any)))]
2269#[example(
2270 name = "load",
2271 code = r###"
2272 IMPORT [STD]
2273 WRITE "cfg.toml" "title = \"demo\""
2274 LET $cfg: MAP<ANY> = LOAD_TOML("cfg.toml")
2275 ASSERT_EQ $cfg.title "demo"
2276 "###
2277)]
2278fn load_toml<P: ProcessManager>(
2279 cx: &mut StepCtx<P>,
2280 #[union(String, Path)]
2282 path: Value,
2283) -> DiagnosticResult<Value> {
2284 let text = super::args::string_or_path_text(&path)?;
2285 super::args::load_toml_from_value(&[Value::string(text)], cx)
2286}
2287
2288#[oxdock_func(rpn, returns = TypeTag::Any)]
2296#[example(
2297 name = "load",
2298 code = r###"
2299 IMPORT [STD]
2300 WRITE "data.json" "{\"a\": 1}"
2301 LET $doc: MAP<ANY> = LOAD_JSON("data.json")
2302 ASSERT_EQ $doc.a 1
2303 "###
2304)]
2305fn load_json<P: ProcessManager>(
2306 cx: &mut StepCtx<P>,
2307 #[union(String, Path)]
2309 path: Value,
2310) -> DiagnosticResult<Value> {
2311 let text = super::args::string_or_path_text(&path)?;
2312 super::args::load_json_from_value(&[Value::string(text)], cx)
2313}
2314
2315#[oxdock_func(rpn, returns = TypeTag::String)]
2325#[example(
2326 name = "hash",
2327 code = r###"
2328 IMPORT [STD]
2329 WRITE payload.txt hello
2330 LET $digest: STRING = HASH_SHA256("payload.txt")
2331 ASSERT_EQ $digest "2cf24dba5fb0a30e26e83b2ac5b9e29e1b161e5c1fa7425e73043362938b9824"
2332 "###
2333)]
2334fn hash_sha256<P: ProcessManager>(
2335 cx: &mut StepCtx<P>,
2336 #[union(String, Path)]
2338 path: Value,
2339) -> DiagnosticResult<Value> {
2340 use sha2::Digest;
2341
2342 let text = super::args::string_or_path_text(&path)?;
2343 let target = cx.state.fs.resolve_read(&cx.state.cwd, &text)?;
2344 let mut hasher = sha2::Sha256::new();
2345 super::fs_ops::hash_path(cx.state.fs.as_ref(), &target, "", &mut hasher)?;
2346 let digest = hasher.finalize();
2347 let bytes: &[u8] = digest.as_ref();
2348 Ok(Value::string(oxdock_utils::hex_encode(bytes)))
2349}
2350
2351#[oxdock_func(rpn, returns = TypeTag::String)]
2362#[example(
2363 name = "cwd",
2364 code = r###"
2365 IMPORT [STD]
2366 WORKDIR sub
2367 LET $c: STRING = CWD()
2368 ASSERT_CONTAINS $c "sub"
2369 "###
2370)]
2371fn cwd<P: ProcessManager>(cx: &mut StepCtx<P>) -> DiagnosticResult<Value> {
2372 if cx.state.fs.is_snapshot_pending() {
2373 return Ok(Value::string(super::SNAPSHOT_PENDING_DISPLAY.to_string()));
2374 }
2375 let concrete = cx.state.fs.concretize_cwd(&cx.state.cwd);
2376 let real = super::fs_ops::canonical_cwd(cx.state.fs.as_ref(), &concrete)?;
2377 Ok(Value::string(real))
2378}
2379
2380#[oxdock_func(pure, returns = TypeTag::MapOf(std::sync::Arc::new(TypeTag::Any)))]
2386#[example(
2387 name = "parse",
2388 code = r###"
2389 IMPORT [STD]
2390 LET $doc: MAP<ANY> = PARSE_TOML("title = \"demo\"")
2391 ASSERT_EQ $doc.title "demo"
2392 "###
2393)]
2394fn parse_toml(
2395 text: String,
2397) -> DiagnosticResult<Value> {
2398 super::args::parse_toml_from_value(Value::string(text))
2399}
2400
2401#[oxdock_func(pure, returns = TypeTag::Any)]
2410#[example(
2411 name = "parse",
2412 code = r###"
2413 # Parse in-memory JSON text with the same conversion as file loading.
2414 IMPORT [STD]
2415 LET $body: STRING = "{\"a\": 1}"
2416 LET $doc: ANY = PARSE_JSON($body)
2417 ASSERT_EQ $doc.a 1
2418
2419 # Top-level arrays parse to LIST, which is why the return is ANY.
2420 LET $items: LIST<ANY> = PARSE_JSON("[1, 2]")
2421 ASSERT_EQ $items.0 1
2422 ASSERT_EQ $items.1 2
2423 "###
2424)]
2425fn parse_json(
2426 text: String,
2428) -> DiagnosticResult<Value> {
2429 super::args::parse_json_from_value(Value::string(text))
2430}
2431
2432#[oxdock_func(returns = TypeTag::String)]
2438#[example(
2439 name = "describe",
2440 code = r###"
2441 IMPORT [STD]
2442 WRITE "entry.txt" "words"
2443 LET $kind: STRING = PATH_TYPE("entry.txt")
2444 ASSERT_EQ $kind "file"
2445 LET $missing: STRING = PATH_TYPE("no-such-entry.txt")
2446 ASSERT_EQ $missing "absent"
2447 "###
2448)]
2449fn path_type<P: ProcessManager>(
2450 cx: &mut StepCtx<P>,
2451 #[union(String, Path)]
2453 path: Value,
2454) -> DiagnosticResult<Value> {
2455 let text = super::args::string_or_path_text(&path)?;
2456 super::args::path_type_from_value(&[Value::string(text)], cx)
2457}
2458
2459#[oxdock_func(returns = TypeTag::Bool)]
2468#[example(
2469 name = "probe",
2470 code = r###"
2471 # An absent nested path is writable when its ancestor is.
2472 IMPORT [STD]
2473 LET $fresh: BOOL = PATH_WRITABLE("probe-check/nested/file.txt")
2474 ASSERT_EQ $fresh true
2475
2476 # The empty string never aliases the working directory.
2477 LET $empty: BOOL = PATH_WRITABLE("")
2478 ASSERT_EQ $empty false
2479 "###
2480)]
2481fn path_writable<P: ProcessManager>(
2482 cx: &mut StepCtx<P>,
2483 #[union(String, Path)]
2485 path: Value,
2486) -> DiagnosticResult<Value> {
2487 let text = super::args::string_or_path_text(&path)?;
2488 super::args::path_writable_from_value(&[Value::string(text)], cx)
2489}
2490
2491#[oxdock_func(returns = TypeTag::Bool)]
2504#[example(
2505 name = "probe",
2506 code = r###"
2507 # Missing tools read false instead of failing the run.
2508 IMPORT [STD]
2509 LET $missing: BOOL = IS_EXEC("no-such-tool-xyz")
2510 ASSERT_EQ $missing false
2511
2512 # Plain files are not executable on any platform.
2513 WRITE tool.txt payload
2514 LET $plain: BOOL = IS_EXEC("tool.txt")
2515 ASSERT_EQ $plain false
2516 "###
2517)]
2518fn is_exec<P: ProcessManager>(
2519 cx: &mut StepCtx<P>,
2520 #[union(String, Path)]
2522 name: Value,
2523) -> DiagnosticResult<Value> {
2524 let text = super::args::string_or_path_text(&name)?;
2525 super::args::is_exec_from_value(&[Value::string(text)], cx)
2526}
2527
2528#[oxdock_func(returns = TypeTag::Bool)]
2536#[example(
2537 name = "probe",
2538 code = r###"
2539 # Ordinary files read true; missing paths read false.
2540 IMPORT [STD]
2541 WRITE "entry.txt" "words"
2542 LET $hit: BOOL = IS_FILE("entry.txt")
2543 ASSERT_EQ $hit true
2544 LET $miss: BOOL = IS_FILE("no-such-entry.txt")
2545 ASSERT_EQ $miss false
2546 "###
2547)]
2548fn is_file<P: ProcessManager>(
2549 cx: &mut StepCtx<P>,
2550 #[union(String, Path)]
2552 path: Value,
2553) -> DiagnosticResult<Value> {
2554 let text = super::args::string_or_path_text(&path)?;
2555 Ok(Value::bool(super::args::path_is_file(cx, &text)))
2556}
2557
2558#[oxdock_func(returns = TypeTag::Bool)]
2566#[example(
2567 name = "probe",
2568 code = r###"
2569 # Directories read true; files read false.
2570 IMPORT [STD]
2571 LET $hit: BOOL = IS_DIR(".")
2572 ASSERT_EQ $hit true
2573 WRITE "entry.txt" "words"
2574 LET $miss: BOOL = IS_DIR("entry.txt")
2575 ASSERT_EQ $miss false
2576 "###
2577)]
2578fn is_dir<P: ProcessManager>(
2579 cx: &mut StepCtx<P>,
2580 #[union(String, Path)]
2582 path: Value,
2583) -> DiagnosticResult<Value> {
2584 let text = super::args::string_or_path_text(&path)?;
2585 Ok(Value::bool(super::args::path_is_dir(cx, &text)))
2586}
2587
2588#[oxdock_func(returns = TypeTag::Bool)]
2595#[example(
2596 name = "probe",
2597 code = r###"
2598 # Present entries read true; absent paths read false.
2599 IMPORT [STD]
2600 WRITE "entry.txt" "words"
2601 LET $hit: BOOL = EXISTS("entry.txt")
2602 ASSERT_EQ $hit true
2603 LET $miss: BOOL = EXISTS("no-such-entry.txt")
2604 ASSERT_EQ $miss false
2605 "###
2606)]
2607fn exists<P: ProcessManager>(
2608 cx: &mut StepCtx<P>,
2609 #[union(String, Path)]
2611 path: Value,
2612) -> DiagnosticResult<Value> {
2613 let text = super::args::string_or_path_text(&path)?;
2614 Ok(Value::bool(super::args::path_exists(cx, &text)))
2615}
2616
2617#[oxdock_func(pure, returns = TypeTag::Bool)]
2623#[example(
2624 name = "probe",
2625 code = r###"
2626 IMPORT [STD]
2627 LET $m: MAP<ANY> = PARSE_JSON("{\"a\": 1}")
2628 LET $hit: BOOL = HAS_KEY($m, "a")
2629 ASSERT_EQ $hit true
2630 LET $miss: BOOL = HAS_KEY($m, "b")
2631 ASSERT_EQ $miss false
2632 "###
2633)]
2634fn has_key(
2635 map: BTreeMap<String, Value>,
2637 key: String,
2639) -> DiagnosticResult<Value> {
2640 super::args::has_key_from_value(Value::map(map), &key)
2641}
2642
2643#[oxdock_func(pure, returns = TypeTag::Any)]
2649#[example(
2650 name = "present and absent",
2651 code = r###"
2652 IMPORT [STD]
2653 LET $m: MAP<ANY> = PARSE_JSON("{\"a\": 1}")
2654 LET $hit: INT = GET($m, "a", 0)
2655 ASSERT_EQ $hit 1
2656 LET $miss: INT = GET($m, "b", 0)
2657 ASSERT_EQ $miss 0
2658 "###
2659)]
2660fn get(
2661 map: BTreeMap<String, Value>,
2663 key: String,
2665 default: Value,
2667) -> DiagnosticResult<Value> {
2668 Ok(map.get(&key).cloned().unwrap_or(default))
2669}
2670
2671#[oxdock_func(pure, returns = TypeTag::MapOf(std::sync::Arc::new(TypeTag::Any)))]
2681#[example(
2682 name = "insert",
2683 code = r###"
2684 IMPORT [STD]
2685 LET $m: MAP<ANY> = MAP_SET({seed: 0}, "a", 1)
2686 ASSERT_EQ $m.a 1
2687 "###
2688)]
2689fn map_set(
2690 #[reject_frozen]
2692 map: BTreeMap<String, Value>,
2693 key: String,
2695 value: Value,
2697) -> DiagnosticResult<Value> {
2698 super::args::map_set_from_value(Value::map(map), key, value)
2699}
2700
2701#[oxdock_func(returns = TypeTag::Float, summary = "Draw a random FLOAT uniformly from [0, 1), optionally seeded.")]
2709#[example(
2710 name = "seeded draw",
2711 code = r###"
2712 # A seed draws the same value on every run.
2713 IMPORT [STD]
2714 LET $one: FLOAT = RAND({seed: 7})
2715 LET $two: FLOAT = RAND({seed: 7})
2716 ASSERT_EQ $one $two
2717 "###
2718)]
2719#[example(
2720 name = "unseeded draw",
2721 code = r###"
2722 # Scale a unit draw into a backoff delay between 1 and 11 seconds.
2723 IMPORT [STD]
2724 LET $draw: FLOAT = RAND()
2725 LET $delay: FLOAT = 1.0 + $draw * 10.0
2726 IF $delay < 1.0 {
2727 FAIL "trap: RAND draw below range"
2728 }
2729 IF $delay >= 11.0 {
2730 FAIL "trap: RAND draw above range"
2731 }
2732 ECHO "retrying in {{ $delay }}s"
2733 "###
2734)]
2735fn rand<P: ProcessManager>(
2736 cx: &mut StepCtx<P>,
2737 #[options("seed?: INT")]
2739 #[optional]
2740 options: BTreeMap<String, Value>,
2741) -> DiagnosticResult<Value> {
2742 let _ = cx;
2743 let seed = options
2746 .get("seed")
2747 .map(|value| value.as_i64().expect("check_options verified INT"));
2748 super::args::rand_float_from_value(seed)
2749}
2750
2751#[oxdock_func(pure, returns = TypeTag::String)]
2757#[example(
2758 name = "encode",
2759 code = r###"
2760 # Encode text to standard base64.
2761 IMPORT [STD]
2762 LET $encoded: STRING = BASE64_ENCODE("hello")
2763 ASSERT_EQ $encoded "aGVsbG8="
2764 "###
2765)]
2766fn base64_encode(
2767 text: String,
2769) -> DiagnosticResult<Value> {
2770 super::args::base64_encode_from_value(Value::string(text))
2771}
2772
2773#[oxdock_func(pure, returns = TypeTag::String)]
2780#[example(
2781 name = "decode",
2782 code = r###"
2783 # Decode standard base64 back to text.
2784 IMPORT [STD]
2785 LET $decoded: STRING = BASE64_DECODE("aGVsbG8=")
2786 ASSERT_EQ $decoded "hello"
2787 "###
2788)]
2789fn base64_decode(
2790 text: String,
2792) -> DiagnosticResult<Value> {
2793 super::args::base64_decode_from_value(Value::string(text))
2794}
2795
2796#[oxdock_func(pure, returns = TypeTag::String)]
2803#[example(
2804 name = "encode",
2805 code = r###"
2806 IMPORT [STD]
2807 LET $json: STRING = TO_JSON({a: 1})
2808 ASSERT_EQ $json "{\"a\":1}\n"
2809 "###
2810)]
2811fn to_json(
2812 #[union(String, Int, Float, Bool, List, Map)]
2814 value: Value,
2815) -> DiagnosticResult<Value> {
2816 super::args::to_json_from_value(value)
2817}
2818
2819#[oxdock_func(pure, returns = TypeTag::String)]
2827#[example(
2828 name = "name the word",
2829 code = r###"
2830 IMPORT [STD]
2831 LET $word: STRING = TYPE_OF(42)
2832 ASSERT_EQ $word "INT"
2833 "###
2834)]
2835fn type_of(
2836 value: Value,
2838) -> DiagnosticResult<Value> {
2839 super::args::type_of_from_value(value)
2840}
2841
2842#[oxdock_func(pure, returns = TypeTag::MapOf(std::sync::Arc::new(TypeTag::Any)))]
2854#[example(
2855 name = "merge",
2856 code = r###"
2857 IMPORT [STD]
2858 LET $m: MAP<ANY> = MERGE_MAPS([{a: 1}, {b: 2}], "overwrite")
2859 ASSERT_EQ $m.a 1
2860 ASSERT_EQ $m.b 2
2861 "###
2862)]
2863fn merge_maps(
2864 #[reject_frozen]
2866 maps: Vec<BTreeMap<String, Value>>,
2867 #[values("fail_on_duplicate", "overwrite")]
2869 policy: String,
2870) -> DiagnosticResult<Value> {
2871 super::args::merge_maps_from_value(
2872 Value::list(maps.into_iter().map(Value::map).collect()),
2873 policy,
2874 )
2875}
2876
2877#[oxdock_func(pure, returns = TypeTag::String)]
2882#[example(
2883 name = "report",
2884 code = r###"
2885 # The engine reports its own build version as a dotted string.
2886 IMPORT [STD]
2887 LET $v: STRING = VERSION()
2888 ASSERT_CONTAINS $v "."
2889 "###
2890)]
2891fn version() -> DiagnosticResult<Value> {
2892 Ok(Value::string(env!("CARGO_PKG_VERSION").to_string()))
2893}
2894
2895#[oxdock_func(returns = TypeTag::ListOf(std::sync::Arc::new(TypeTag::String)))]
2900#[example(
2901 name = "list",
2902 code = r###"
2903 IMPORT [STD]
2904 LET $names: LIST<STRING> = FUNCTIONS()
2905 ASSERT_CONTAINS $names "STD::INT"
2906 "###
2907)]
2908fn functions<P: ProcessManager>(cx: &mut StepCtx<P>) -> DiagnosticResult<Value> {
2909 let mut names: Vec<String> = cx
2910 .state
2911 .list_functions()
2912 .into_iter()
2913 .map(|meta| meta.name)
2914 .collect();
2915 names.sort();
2916 names.dedup();
2917 Ok(Value::list(names.into_iter().map(Value::string).collect()))
2918}
2919
2920#[oxdock_func(returns = TypeTag::ListOf(std::sync::Arc::new(TypeTag::String)))]
2927#[example(
2928 name = "empty",
2929 code = r###"
2930 # With no staged args the list is empty.
2931 IMPORT [STD]
2932 LET $args: LIST<STRING> = ARGV()
2933 LET $n: INT = LEN($args)
2934 ASSERT_EQ $n 0
2935 "###
2936)]
2937fn argv<P: ProcessManager>(cx: &mut StepCtx<P>) -> DiagnosticResult<Value> {
2938 Ok(Value::list(
2939 cx.state
2940 .io
2941 .script_args()
2942 .iter()
2943 .cloned()
2944 .map(Value::string)
2945 .collect(),
2946 ))
2947}
2948
2949pub struct ParseArgs;
2969
2970impl<P: ProcessManager> OxDockFn<P> for ParseArgs {
2971 fn registration() -> HostRegistration<P> {
2972 let func: NativeFn<P> = Arc::new(|cx: &mut StepCtx<P>, values: Vec<Value>| {
2973 if values.len() != 1 {
2974 return Err(std_diag::std_parse_args_arity(values.len()));
2975 }
2976 let mut iter = values.into_iter();
2977 let args_val = iter.next().expect("arity checked above");
2978 let args =
2979 string_list_arg(&args_val, &format!("{FUNC_PARSE_ARGS}() argument `$args`"))?;
2980 let specs = resolve_flags_specs(cx)?;
2981 let (raw, positionals) = tokenize_raw_args(args)?;
2982 let coerced = coerce_flags(&specs, &raw)?;
2983 let mut out = BTreeMap::new();
2984 out.insert("flags".to_string(), Value::map(coerced));
2985 if !positionals.is_empty() {
2986 out.insert("positionals".to_string(), Value::list(positionals));
2987 }
2988 Ok(Value::map(out))
2989 });
2990 HostRegistration::Stateful {
2991 name: FUNC_PARSE_ARGS.to_string(),
2992 meta: FuncMeta {
2993 name: FUNC_PARSE_ARGS.to_string(),
2994 module: String::new(),
2995 kind: FuncKind::HostPure,
2996 params: Some(vec![FuncParam {
2997 name: "args".to_string(),
2998 param_type: Some(TypeTag::ListOf(Arc::new(TypeTag::String))),
2999 allowed: None,
3000 docs: "Argv tail to parse, usually from `STD::ARGV()`.",
3001 options: None,
3002 optional: false,
3003 }]),
3004 returns: Some(TypeTag::Record(Arc::from([
3005 Field {
3006 name: "flags".to_string(),
3007 ty: TypeTag::Map,
3008 docs: "Flags coerced to `TYPE FLAGS`.",
3009 optional: false,
3010 default: None,
3011
3012 alias: None,
3013 },
3014 Field {
3015 name: "positionals".to_string(),
3016 ty: TypeTag::ListOf(Arc::new(TypeTag::String)),
3017 docs: "Trailing values and entries after the first double dash. Omitted when empty.",
3018 optional: true,
3019 default: None,
3020
3021 alias: None,
3022 },
3023 ]))),
3024 rpn: true,
3025 summary: "Parse an argv tail against TYPE FLAGS.",
3026 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.",
3027 examples: &[
3028 crate::Example {
3029 name: "flags and positionals",
3030 fence_meta: None,
3031 code: indoc::indoc! {r#"
3032 IMPORT [STD]
3033 # One schema TYPE drives coercion; the pair binds both slots.
3034 TYPE FLAGS = MAP<model: STRING, verbose?: BOOL>
3035 TYPE POSITIONS = LIST<STRING>
3036 TYPE PARSED = MAP<flags: FLAGS, positionals?: POSITIONS>
3037 LET $parsed: PARSED = PARSE_ARGS(["--model=gpt-4", "--verbose", "serve"])
3038 LET $flags: FLAGS = $parsed.flags
3039 ASSERT_EQ $flags.model "gpt-4"
3040 ASSERT_EQ $flags.verbose true
3041 ASSERT_EQ $parsed.positionals.0 "serve"
3042 "#},
3043 },
3044 crate::Example {
3045 name: "optional stays absent",
3046 fence_meta: None,
3047 code: indoc::indoc! {r#"
3048 IMPORT [STD]
3049 # Absent optionals stay absent; read them with a typed GET default.
3050 TYPE FLAGS = MAP<model: STRING, propose?: BOOL>
3051 TYPE POSITIONS = LIST<STRING>
3052 TYPE PARSED = MAP<flags: FLAGS, positionals?: POSITIONS>
3053 LET $parsed: PARSED = PARSE_ARGS(["--model=x"])
3054 LET $flags: FLAGS = $parsed.flags
3055 LET $propose: BOOL = GET($flags, "propose", false)
3056 ASSERT_EQ $propose false
3057 "#},
3058 },
3059 crate::Example {
3060 name: "flags only omits positionals",
3061 fence_meta: None,
3062 code: indoc::indoc! {r#"
3063 IMPORT [STD]
3064 # Empty positionals are omitted, so a flags only shape binds clean.
3065 TYPE FLAGS = MAP<model: STRING>
3066 TYPE PARSED = MAP<flags: FLAGS>
3067 LET $parsed: PARSED = PARSE_ARGS(["--model=x"])
3068 LET $flags: FLAGS = $parsed.flags
3069 ASSERT_EQ $flags.model "x"
3070 "#},
3071 },
3072 crate::Example {
3073 name: "literal defaults",
3074 fence_meta: None,
3075 code: indoc::indoc! {r#"
3076 IMPORT [STD]
3077 # Defaults are literals only: INT, FLOAT, BOOL,
3078 # and double-quoted STRING fill absent flags.
3079 TYPE FLAGS = MAP<retries: INT = 2, ratio: FLOAT = 2.5, verbose: BOOL = true, model: STRING = "gpt-4">
3080 TYPE PARSED = MAP<flags: FLAGS>
3081 LET $parsed: PARSED = PARSE_ARGS([])
3082 LET $flags: FLAGS = $parsed.flags
3083 ASSERT_EQ $flags.retries 2
3084 ASSERT_EQ $flags.verbose true
3085 ASSERT_EQ $flags.model "gpt-4"
3086 LET $ratio_ok: BOOL = $flags.ratio == 2.5
3087 ASSERT_EQ $ratio_ok true
3088 "#},
3089 },
3090 crate::Example {
3091 name: "variable default fails",
3092 fence_meta: Some("expect_error:\"expected default literal\""),
3093 code: indoc::indoc! {r#"
3094 IMPORT [STD]
3095 # Defaults are literals: a variable in place
3096 # of a literal fails instead of evaluating.
3097 TYPE FLAGS = MAP<n: INT = $x>
3098 TYPE PARSED = MAP<flags: FLAGS>
3099 LET $p: PARSED = PARSE_ARGS([])
3100 "#},
3101 },
3102 crate::Example {
3103 name: "missing required",
3104 fence_meta: Some("expect_error:\"missing required flag\""),
3105 code: indoc::indoc! {r#"
3106 IMPORT [STD]
3107 # Absent required flags fail naming the flag.
3108 TYPE FLAGS = MAP<model: STRING>
3109 TYPE PARSED = MAP<flags: FLAGS>
3110 LET $parsed: PARSED = PARSE_ARGS([])
3111 "#},
3112 },
3113 crate::Example {
3114 name: "unknown flag",
3115 fence_meta: Some("expect_error:\"unknown flag\""),
3116 code: indoc::indoc! {r#"
3117 IMPORT [STD]
3118 # Undeclared flags fail instead of passing through.
3119 TYPE FLAGS = MAP<model: STRING>
3120 TYPE PARSED = MAP<flags: FLAGS>
3121 LET $parsed: PARSED = PARSE_ARGS(["--model=x", "--nope=1"])
3122 "#},
3123 },
3124 crate::Example {
3125 name: "alias accepted",
3126 fence_meta: None,
3127 code: indoc::indoc! {r#"
3128 IMPORT [STD]
3129 # One canonical key binds both spellings; the
3130 # alias never appears as a separate key.
3131 TYPE FLAGS = MAP<h: BOOL ALIAS help>
3132 TYPE PARSED = MAP<flags: FLAGS>
3133 LET $a: PARSED = PARSE_ARGS(["--help"])
3134 ASSERT_EQ $a.flags.h true
3135 LET $b: PARSED = PARSE_ARGS(["--h"])
3136 ASSERT_EQ $b.flags.h true
3137 "#},
3138 },
3139 crate::Example {
3140 name: "alias duplicate fails",
3141 fence_meta: Some("expect_error:\"duplicate flag\""),
3142 code: indoc::indoc! {r#"
3143 IMPORT [STD]
3144 # Canonical and alias together fail naming both.
3145 TYPE FLAGS = MAP<h: BOOL ALIAS help>
3146 TYPE PARSED = MAP<flags: FLAGS>
3147 LET $p: PARSED = PARSE_ARGS(["--h", "--help"])
3148 "#},
3149 },
3150 crate::Example {
3151 name: "alias missing names both",
3152 fence_meta: Some("expect_error:\"--h/--help\""),
3153 code: indoc::indoc! {r#"
3154 IMPORT [STD]
3155 # Missing required flags name both spellings.
3156 TYPE FLAGS = MAP<h: BOOL ALIAS help>
3157 TYPE PARSED = MAP<flags: FLAGS>
3158 LET $p: PARSED = PARSE_ARGS([])
3159 "#},
3160 },
3161 ],
3162 },
3163 func,
3164 }
3165 }
3166}
3167
3168#[derive(Debug, Clone, Copy, PartialEq, Eq)]
3172enum CliType {
3173 String,
3174 Bool,
3175 Int,
3176 Float,
3177}
3178
3179fn coerce_cli_flag(target: CliType, flag: &str, raw: Value) -> DiagnosticResult<Value> {
3184 match target {
3185 CliType::Bool => {
3186 if let Some(b) = raw.as_bool() {
3187 return Ok(Value::bool(b));
3188 }
3189 if let Some(s) = raw.as_str() {
3190 match super::args::parse_bool_str(s) {
3191 Some(b) => return Ok(Value::bool(b)),
3192 None => {
3193 return Err(std_diag::std_parse_args_bool_flag(flag, s));
3194 }
3195 }
3196 }
3197 Err(std_diag::std_parse_args_bool_type(flag, raw.type_name()))
3198 }
3199 CliType::String => {
3200 if let Some(s) = raw.as_str() {
3201 return Ok(Value::string(s.to_string()));
3202 }
3203 Err(std_diag::std_parse_args_needs_value(flag))
3204 }
3205 CliType::Int => {
3206 if raw.as_bool().is_some() {
3207 return Err(std_diag::std_parse_args_needs_value(flag));
3208 }
3209 super::args::int_from_value(raw).map_err(|_| std_diag::std_parse_args_expects_int(flag))
3210 }
3211 CliType::Float => {
3212 if raw.as_bool().is_some() {
3213 return Err(std_diag::std_parse_args_needs_value(flag));
3214 }
3215 super::args::float_from_value(raw)
3216 .map_err(|_| std_diag::std_parse_args_expects_float(flag))
3217 }
3218 }
3219}
3220
3221#[derive(Debug, Clone)]
3225struct CliSpec {
3226 target: CliType,
3227 required: bool,
3228 default: Option<Value>,
3229 alias: Option<String>,
3230}
3231
3232type CliSpecs = BTreeMap<String, CliSpec>;
3234
3235fn string_list_arg(val: &Value, what: &str) -> DiagnosticResult<Vec<String>> {
3238 crate::check_value_at(&TypeTag::ListOf(Arc::new(TypeTag::String)), val, what)
3239 .map_err(|err| std_diag::std_parse_args_arg_shape(&err))?;
3240 Ok(val
3241 .as_list()
3242 .expect("check_value_at enforces LIST")
3243 .iter()
3244 .map(|v| {
3245 v.as_str()
3246 .expect("check_value_at enforces STRING")
3247 .to_string()
3248 })
3249 .collect())
3250}
3251
3252fn tokenize_raw_args(args: Vec<String>) -> DiagnosticResult<(BTreeMap<String, Value>, Vec<Value>)> {
3256 use lexopt::Arg::{Long, Short, Value as ArgValue};
3257 let mut parser = lexopt::Parser::from_args(args);
3258 let mut flags: BTreeMap<String, Value> = BTreeMap::new();
3259 let mut positionals: Vec<Value> = Vec::new();
3260 let utf8 = |value: std::ffi::OsString| -> DiagnosticResult<String> {
3261 value
3262 .into_string()
3263 .map_err(|_| std_diag::std_parse_args_not_utf8())
3264 };
3265 loop {
3266 match parser.next() {
3267 Ok(None) => break,
3268 Ok(Some(Long(name))) => {
3269 let key = name.to_owned();
3270 if let Some(raw) = parser.optional_value() {
3271 flags.insert(key, Value::string(utf8(raw)?));
3272 } else {
3273 flags.insert(key, Value::bool(true));
3274 }
3275 }
3276 Ok(Some(Short(ch))) => {
3277 flags.insert(ch.to_string(), Value::bool(true));
3278 }
3279 Ok(Some(ArgValue(raw))) => {
3280 positionals.push(Value::string(utf8(raw)?));
3281 }
3282 Err(lexopt::Error::UnexpectedValue { option, value }) => {
3283 let key = option
3284 .strip_prefix("--")
3285 .or_else(|| option.strip_prefix('-'))
3286 .unwrap_or(option.as_str());
3287 flags.insert(key.to_string(), Value::string(utf8(value)?));
3288 }
3289 Err(err) => return Err(std_diag::std_parse_args_lex_error(&err)),
3290 }
3291 }
3292 Ok((flags, positionals))
3293}
3294
3295fn coerce_flags(
3303 specs: &CliSpecs,
3304 raw: &BTreeMap<String, Value>,
3305) -> DiagnosticResult<BTreeMap<String, Value>> {
3306 let mut alias_to_canonical: BTreeMap<&str, &str> = BTreeMap::new();
3309 for (canonical, spec) in specs.iter() {
3310 if let Some(alias) = spec.alias.as_ref() {
3311 alias_to_canonical.insert(alias.as_str(), canonical.as_str());
3312 }
3313 }
3314 let mut coerced: BTreeMap<String, Value> = BTreeMap::new();
3315 for (flag, spec) in specs.iter() {
3316 if flag.is_empty() {
3317 return Err(std_diag::std_parse_args_schema_flag_empty());
3318 }
3319 let canonical_raw = raw.get(flag);
3320 let alias_raw = spec.alias.as_ref().and_then(|alias| raw.get(alias));
3321 if canonical_raw.is_some() && alias_raw.is_some() {
3322 return Err(std_diag::std_parse_args_duplicate_flag(
3323 flag,
3324 spec.alias.as_deref(),
3325 ));
3326 }
3327 if let Some(raw_val) = canonical_raw.or(alias_raw) {
3328 coerced.insert(
3329 flag.clone(),
3330 coerce_cli_flag(spec.target, flag, raw_val.clone())?,
3331 );
3332 } else if let Some(d) = spec.default.as_ref() {
3333 coerced.insert(flag.clone(), d.clone());
3334 } else if spec.required {
3335 return Err(std_diag::std_parse_args_missing_flag(
3336 flag,
3337 spec.alias.as_deref(),
3338 ));
3339 }
3340 }
3341 for flag in raw.keys() {
3342 if !specs.contains_key(flag) && !alias_to_canonical.contains_key(flag.as_str()) {
3343 return Err(std_diag::std_parse_args_unknown_flag(flag));
3344 }
3345 }
3346 Ok(coerced)
3347}
3348
3349fn resolve_flags_specs<P: ProcessManager>(cx: &mut StepCtx<P>) -> DiagnosticResult<CliSpecs> {
3356 let name = "FLAGS";
3357 let tag = cx
3358 .state
3359 .resolve_tag(name)
3360 .map_err(|err| std_diag::std_parse_args_schema_type(name, &err))?;
3361 let TypeTag::Record(fields) = tag else {
3362 return Err(std_diag::std_parse_args_schema_shape(name));
3363 };
3364 let mut specs = BTreeMap::new();
3365 for field in fields.iter() {
3366 let target = match field.ty {
3367 TypeTag::String => CliType::String,
3368 TypeTag::Bool => CliType::Bool,
3369 TypeTag::Int => CliType::Int,
3370 TypeTag::Float => CliType::Float,
3371 _ => {
3372 return Err(std_diag::std_parse_args_schema_field_type(
3373 &field.name,
3374 field.ty.name(),
3375 ));
3376 }
3377 };
3378 specs.insert(
3379 field.name.clone(),
3380 CliSpec {
3381 target,
3382 required: !field.optional && field.default.is_none(),
3383 default: field.default.clone(),
3384 alias: field.alias.clone(),
3385 },
3386 );
3387 }
3388 Ok(specs)
3389}
3390
3391pub struct ParseFlags;
3399
3400impl<P: ProcessManager> OxDockFn<P> for ParseFlags {
3401 fn registration() -> HostRegistration<P> {
3402 let func: NativeFn<P> = Arc::new(|cx: &mut StepCtx<P>, values: Vec<Value>| {
3403 if values.len() != 1 {
3404 return Err(std_diag::std_parse_flags_arity(values.len()));
3405 }
3406 let mut iter = values.into_iter();
3407 let args_val = iter.next().expect("arity checked above");
3408 let args = string_list_arg(&args_val, "{FUNC_PARSE_FLAGS}() argument `$args`")?;
3409 let specs = resolve_flags_specs(cx)?;
3410 let (raw, positionals) = tokenize_raw_args(args)?;
3411 if !positionals.is_empty() {
3412 return Err(std_diag::std_parse_flags_positional(
3413 &positionals
3414 .iter()
3415 .map(|pos| pos.to_string())
3416 .collect::<Vec<_>>(),
3417 ));
3418 }
3419 Ok(Value::map(coerce_flags(&specs, &raw)?))
3420 });
3421 HostRegistration::Stateful {
3422 name: FUNC_PARSE_FLAGS.to_string(),
3423 meta: FuncMeta {
3424 name: FUNC_PARSE_FLAGS.to_string(),
3425 module: String::new(),
3426 kind: FuncKind::HostPure,
3427 params: Some(vec![FuncParam {
3428 name: "args".to_string(),
3429 param_type: Some(TypeTag::ListOf(Arc::new(TypeTag::String))),
3430 allowed: None,
3431 docs: "Argv tail to parse, usually from `STD::ARGV()`.",
3432 options: None,
3433 optional: false,
3434 }]),
3435 returns: Some(TypeTag::Map),
3436 rpn: true,
3437 summary: "Parse flags against TYPE FLAGS.",
3438 docs: "Consumes a `LIST<STRING>` and coerces flags through `TYPE FLAGS`. Returns the flags `MAP` directly; positional arguments fail.",
3439 examples: &[crate::Example {
3440 name: "flags only",
3441 fence_meta: None,
3442 code: indoc::indoc! {r#"
3443 IMPORT [STD]
3444 # Flags only returns the flags MAP directly.
3445 TYPE FLAGS = MAP<model: STRING, retries: INT = 2>
3446 LET $flags: FLAGS = PARSE_FLAGS(["--model=x"])
3447 ASSERT_EQ $flags.model "x"
3448 ASSERT_EQ $flags.retries 2
3449 "#},
3450 }],
3451 },
3452 func,
3453 }
3454 }
3455}
3456
3457pub struct ParsePositionals;
3462
3463impl<P: ProcessManager> OxDockFn<P> for ParsePositionals {
3464 fn registration() -> HostRegistration<P> {
3465 let func: NativeFn<P> = Arc::new(|_: &mut StepCtx<P>, values: Vec<Value>| {
3466 if values.len() != 1 {
3467 return Err(std_diag::std_parse_positionals_arity(values.len()));
3468 }
3469 let mut iter = values.into_iter();
3470 let args_val = iter.next().expect("arity checked above");
3471 let args = string_list_arg(
3472 &args_val,
3473 &format!("{FUNC_PARSE_POSITIONALS}() argument `$args`"),
3474 )?;
3475 let (_raw, positionals) = tokenize_raw_args(args)?;
3476 Ok(Value::list(positionals))
3477 });
3478 HostRegistration::Stateful {
3479 name: FUNC_PARSE_POSITIONALS.to_string(),
3480 meta: FuncMeta {
3481 name: FUNC_PARSE_POSITIONALS.to_string(),
3482 module: String::new(),
3483 kind: FuncKind::HostPure,
3484 params: Some(vec![FuncParam {
3485 name: "args".to_string(),
3486 param_type: Some(TypeTag::ListOf(Arc::new(TypeTag::String))),
3487 allowed: None,
3488 docs: "Argv tail to parse, usually from `STD::ARGV()`.",
3489 options: None,
3490 optional: false,
3491 }]),
3492 returns: Some(TypeTag::ListOf(Arc::new(TypeTag::String))),
3493 rpn: true,
3494 summary: "Parse positionals in argv order.",
3495 docs: "Consumes a `LIST<STRING>` and returns positionals in argv order with no schema.",
3496 examples: &[crate::Example {
3497 name: "positionals only",
3498 fence_meta: None,
3499 code: indoc::indoc! {r#"
3500 IMPORT [STD]
3501 # No schema needed: positionals are always strings in order.
3502 TYPE POSITIONS = LIST<STRING>
3503 LET $pos: POSITIONS = PARSE_POSITIONALS(["serve", "--", "--not-a-flag"])
3504 ASSERT_EQ $pos.0 "serve"
3505 ASSERT_EQ $pos.1 "--not-a-flag"
3506 "#},
3507 }],
3508 },
3509 func,
3510 }
3511 }
3512}
3513
3514#[oxdock_func(
3529 returns = TypeTag::Record(std::sync::Arc::from([Field {
3530 name: "name".to_string(),
3531 ty: TypeTag::String,
3532 docs: "Qualified function name.",
3533 optional: false,
3534 default: None,
3535
3536 alias: None,}, Field {
3537 name: "module".to_string(),
3538 ty: TypeTag::String,
3539 docs: "Owning module.",
3540 optional: false,
3541 default: None,
3542
3543 alias: None,}, Field {
3544 name: "kind".to_string(),
3545 ty: TypeTag::String,
3546 docs: "Origin label (`host` or `script`).",
3547 optional: false,
3548 default: None,
3549
3550 alias: None,}, Field {
3551 name: "params".to_string(),
3552 ty: TypeTag::ListOf(std::sync::Arc::new(TypeTag::MapOf(std::sync::Arc::new(
3553 TypeTag::Any,
3554 )))),
3555 docs: "Parameter entries (empty for parameterless functions).",
3556 optional: false,
3557 default: None,
3558
3559 alias: None,}, Field {
3560 name: "returns".to_string(),
3561 ty: TypeTag::String,
3562 docs: "Structural return shape (empty when untagged).",
3563 optional: false,
3564 default: None,
3565
3566 alias: None,}, Field {
3567 name: "rpn".to_string(),
3568 ty: TypeTag::Bool,
3569 docs: "True when callable in RPN position.",
3570 optional: false,
3571 default: None,
3572
3573 alias: None,}, Field {
3574 name: "summary".to_string(),
3575 ty: TypeTag::String,
3576 docs: "One-line description.",
3577 optional: false,
3578 default: None,
3579
3580 alias: None,}]))
3581 summary = "Describe one function by qualified name."
3582)]
3583#[example(
3584 name = "describe",
3585 code = r###"
3586 IMPORT [STD]
3587 LET $info: MAP<ANY> = DESCRIBE("STD::INT")
3588 ASSERT_EQ $info.name "STD::INT"
3589 ASSERT_EQ $info.returns "INT"
3590 "###
3591)]
3592fn describe<P: ProcessManager>(
3593 cx: &mut StepCtx<P>,
3594 name: String,
3596) -> DiagnosticResult<Value> {
3597 if split_qualified(&name).is_none() && name != KEYWORD_INSPECT {
3598 return Err(std_diag::func_describe_unqualified(&name));
3599 }
3600 cx.state
3601 .describe_function(&name)
3602 .ok_or_else(|| std_diag::func_unknown(&name))
3603}
3604
3605#[oxdock_func(returns = TypeTag::ListOf(std::sync::Arc::new(TypeTag::String)))]
3611#[example(
3612 name = "list",
3613 code = r###"
3614 IMPORT [STD]
3615 LET $names: LIST<STRING> = TYPES()
3616 ASSERT_CONTAINS $names "STRING"
3617 "###
3618)]
3619fn types<P: ProcessManager>(cx: &mut StepCtx<P>) -> DiagnosticResult<Value> {
3620 Ok(Value::list(
3621 cx.state
3622 .type_names()
3623 .into_iter()
3624 .map(Value::string)
3625 .collect(),
3626 ))
3627}
3628
3629#[oxdock_func(returns = TypeTag::Record(std::sync::Arc::from([Field {
3635 name: "name".to_string(),
3636 ty: TypeTag::String,
3637 docs: "Queried type name.",
3638 optional: false,
3639 default: None,
3640
3641 alias: None,}, Field {
3642 name: "summary".to_string(),
3643 ty: TypeTag::String,
3644 docs: "One-line description.",
3645 optional: false,
3646 default: None,
3647
3648 alias: None,}, Field {
3649 name: "docs".to_string(),
3650 ty: TypeTag::String,
3651 docs: "Full documentation text.",
3652 optional: false,
3653 default: None,
3654
3655 alias: None,}])))]
3656#[example(
3657 name = "describe",
3658 code = r###"
3659 IMPORT [STD]
3660 LET $info: MAP<ANY> = TYPE_DESCRIBE("STRING")
3661 ASSERT_EQ $info.name "STRING"
3662 "###
3663)]
3664fn type_describe<P: ProcessManager>(
3665 cx: &mut StepCtx<P>,
3666 name: String,
3668) -> DiagnosticResult<Value> {
3669 if let Some(descriptor) = cx.state.describe_type(&name) {
3670 let mut map = BTreeMap::new();
3671 map.insert(
3672 "name".to_string(),
3673 Value::string(descriptor.name.to_string()),
3674 );
3675 map.insert(
3676 "summary".to_string(),
3677 Value::string(descriptor.summary.to_string()),
3678 );
3679 map.insert(
3680 "docs".to_string(),
3681 Value::string(descriptor.docs.to_string()),
3682 );
3683 return Ok(Value::map(map));
3684 }
3685 if let Some(target) = cx.state.alias_target(&name) {
3688 let mut map = BTreeMap::new();
3689 map.insert("name".to_string(), Value::string(name.clone()));
3690 map.insert(
3691 "summary".to_string(),
3692 Value::string(format!("Script type alias for {target}.")),
3693 );
3694 map.insert(
3695 "docs".to_string(),
3696 Value::string(format!(
3697 "Declared with {KEYWORD_TYPE} {name} = {target}. The alias expands structurally at every declaration."
3698 )),
3699 );
3700 return Ok(Value::map(map));
3701 }
3702 Err(std_diag::std_unknown_type(&name))
3703}
3704
3705#[oxdock_func(returns = TypeTag::String)]
3719#[example(
3720 name = "self",
3721 code = r###"
3722 # The running interpreter resolves to a non-empty path.
3723 IMPORT [STD]
3724 LET $exe: STRING = INTERPRETER()
3725 LET $nonempty: BOOL = $exe != ""
3726 ASSERT_EQ $nonempty true
3727 "###
3728)]
3729#[example(
3730 name = "dynamic assembly",
3731 code = r###"
3732 # Assemble the child script dynamically: the parent interpolates
3733 # its own bindings into the pipe, then runs the interpreter on it.
3734 # Unescaped {{ }} bakes in at render time; \{{ }} stays literal
3735 # so the child expands it with its own bindings.
3736 # The pipe delivers EOF when the producer step ends, so the child
3737 # reads exactly one script.
3738 IMPORT [STD]
3739 LET $exe: STRING = INTERPRETER()
3740 LET $who: STRING = "Ada"
3741 LET $child: PIPE
3742 WITH_IO [stdout=$child] ECHO """
3743 ECHO "hello {{ $who }}!"
3744 LET $who: STRING = "Grace"
3745 ECHO "child sees \{{ $who }}!"
3746 """
3747 LET $out: STRING = WITH_IO [stdin=$child] RUN [$exe]
3748 ASSERT_CONTAINS $out "hello Ada!"
3749 ASSERT_CONTAINS $out "child sees Grace!"
3750 "###
3751)]
3752fn interpreter<P: ProcessManager>(cx: &mut StepCtx<P>) -> DiagnosticResult<Value> {
3753 if let Some(staged) = cx.state.io.interpreter_override() {
3754 return Ok(Value::string(staged));
3755 }
3756 Ok(Value::string(oxdock_process::interpreter_exe()?))
3757}
3758
3759#[oxdock_func(returns = TypeTag::Bool)]
3767#[example(
3768 name = "main",
3769 code = r###"
3770 # Entry top level runs as main.
3771 IMPORT [STD]
3772 LET $m: BOOL = IS_MAIN()
3773 ASSERT_EQ $m true
3774 "###
3775)]
3776#[example(
3777 name = "library doubles as demo",
3778 fence_meta = "roots:unified",
3779 code = r###"
3780 # A library doubles as a runnable demo: guard the demo with
3781 # IF IS_MAIN() so importing it stays side effect free. The
3782 # parent writes both files, then runs each in a fresh
3783 # interpreter: direct execution prints the demo, importing
3784 # it does not. Unified roots: the child inherits one
3785 # workspace, so parent and child see the same files. The
3786 # exact stdout match proves the demo line stays out of the
3787 # importing run.
3788 IMPORT [STD]
3789
3790 # The library under test: demo guarded by IS_MAIN.
3791 WRITE lib.oxfile """
3792 IMPORT [STD]
3793 FUNC GREET($x: STRING): STRING { RETURN "hi \{{ $x }}" }
3794 EXPORT GREET
3795 IF IS_MAIN() {
3796 ECHO "demo: hi Ada"
3797 }
3798 """
3799
3800 # The importer: calls the library, prints only its own line.
3801 WRITE main.oxfile """
3802 IMPORT ["lib.oxfile" AS LIB]
3803 LET $g: STRING = LIB::GREET("Bo")
3804 ECHO "imported: \{{ $g }}"
3805 """
3806
3807 # Direct run executes the demo.
3808 LET $exe: STRING = INTERPRETER()
3809 LET $direct: STRING = RUN [$exe, "lib.oxfile"]
3810 ASSERT_CONTAINS $direct "demo: hi Ada"
3811
3812 # Importing run stays silent apart from its own line.
3813 LET $via: STRING = RUN [$exe, "main.oxfile"]
3814 ASSERT_EQ $via "imported: hi Bo\n"
3815 "###
3816)]
3817fn is_main<P: ProcessManager>(cx: &mut StepCtx<P>) -> DiagnosticResult<Value> {
3818 let main = match cx.state.module_stack.last() {
3819 None | Some(None) => true,
3820 Some(Some(_)) => false,
3821 };
3822 Ok(Value::bool(main))
3823}
3824
3825#[oxdock_func(returns = TypeTag::Bool)]
3839#[example(
3840 name = "null stdin",
3841 code = r###"
3842 # A null stdin is never a terminal, in every harness.
3843 IMPORT [STD]
3844 LET $term: BOOL = IS_TERMINAL("stdin")
3845 ASSERT_EQ $term false
3846 "###
3847)]
3848fn is_terminal<P: ProcessManager>(
3849 cx: &mut StepCtx<P>,
3850 #[values("stdin", "stdout", "stderr")]
3852 stream_name: String,
3853) -> DiagnosticResult<Value> {
3854 use std::io::IsTerminal;
3855 let terminal = match stream_name.as_str() {
3856 "stdin" => {
3857 if cx.stdin_pipe.is_some() {
3862 false
3863 } else {
3864 match &cx.stdin {
3865 CommandStdin::Null => false,
3866 #[cfg(not(miri))]
3867 CommandStdin::OsPipe(_) => false,
3868 CommandStdin::Stream(_) => false,
3869 CommandStdin::Inherit => std::io::stdin().is_terminal(),
3870 }
3871 }
3872 }
3873 "stdout" => {
3874 if cx.out_pipe.is_some() {
3875 false
3877 } else if cx.state.io.stdout().is_some() {
3878 false
3881 } else {
3882 match &cx.out {
3883 None => std::io::stdout().is_terminal(),
3885 #[cfg(not(miri))]
3887 Some(StreamHandle::Os(_)) => false,
3888 Some(StreamHandle::Stream(_)) => std::io::stdout().is_terminal(),
3898 }
3899 }
3900 }
3901 "stderr" => {
3902 if cx.state.io.stderr().is_some() {
3903 false
3905 } else {
3906 match &cx.err {
3907 None => std::io::stderr().is_terminal(),
3909 #[cfg(not(miri))]
3911 Some(StreamHandle::Os(_)) => false,
3912 Some(StreamHandle::Stream(_)) => false,
3915 }
3916 }
3917 }
3918 _ => {
3919 return Err(std_diag::std_is_terminal_expected(&stream_name));
3920 }
3921 };
3922 Ok(Value::bool(terminal))
3923}
3924
3925#[oxdock_func(returns = TypeTag::Semaphore)]
3933#[example(
3934 name = "mint",
3935 code = r###"
3936 # Mint a semaphore admitting at most two holders.
3937 IMPORT [STD]
3938 LET $sem: SEMAPHORE = SEMAPHORE_NEW(2)
3939
3940 # A fresh semaphore reports its full cap as available.
3941 LET $free: INT = SEMAPHORE_AVAILABLE($sem)
3942 ASSERT_EQ $free 2
3943 "###
3944)]
3945fn semaphore_new<P: ProcessManager>(
3946 cx: &mut StepCtx<P>,
3947 max: i64,
3949) -> DiagnosticResult<Value> {
3950 let _ = cx;
3951 if max <= 0 {
3952 return Err(std_diag::std_semaphore_needs_positive(max));
3953 }
3954 Ok(Value::semaphore(max as usize))
3955}
3956
3957#[oxdock_func(returns = TypeTag::Record(std::sync::Arc::from([Field {
3966 name: "held".to_string(),
3967 ty: TypeTag::Bool,
3968 docs: "`true` with the permit under `permit`, `false` with no `permit` key.",
3969 optional: false,
3970 default: None,
3971
3972 alias: None,}, Field {
3973 name: "permit".to_string(),
3974 ty: TypeTag::Permit,
3975 docs: "Permit handle; read only when `held`.",
3976 optional: true,
3977 default: None,
3978
3979 alias: None,}])))]
3980#[example(
3981 name = "acquire",
3982 code = r###"
3983 # First acquire holds with a permit to bind.
3984 IMPORT [STD]
3985 LET $sem: SEMAPHORE = SEMAPHORE_NEW(1)
3986 LET $first: MAP<held: BOOL, permit?: PERMIT> = SEMAPHORE_TRY_ACQUIRE($sem)
3987 ASSERT_EQ $first.held true
3988 LET $permit: PERMIT = $first.permit
3989
3990 # A capped semaphore answers held false with no permit key.
3991 LET $second: MAP<held: BOOL, permit?: PERMIT> = SEMAPHORE_TRY_ACQUIRE($sem)
3992 ASSERT_EQ $second.held false
3993 LET $has_permit: BOOL = HAS_KEY($second, "permit")
3994 ASSERT_EQ $has_permit false
3995 "###
3996)]
3997fn semaphore_try_acquire<P: ProcessManager>(
3998 cx: &mut StepCtx<P>,
3999 sem: Arc<SemaphoreState>,
4001) -> DiagnosticResult<Value> {
4002 let _ = cx;
4003 let mut map = BTreeMap::new();
4004 if sem.try_acquire() {
4005 map.insert("held".to_string(), Value::bool(true));
4006 map.insert("permit".to_string(), Value::permit(&sem));
4007 } else {
4008 map.insert("held".to_string(), Value::bool(false));
4009 }
4010 Ok(Value::map(map))
4011}
4012
4013#[oxdock_func(pure, returns = TypeTag::Int)]
4020#[example(
4021 name = "readout",
4022 code = r###"
4023 # Hold one permit on a cap of two.
4024 IMPORT [STD]
4025 LET $sem: SEMAPHORE = SEMAPHORE_NEW(2)
4026 LET $acq: MAP<held: BOOL, permit?: PERMIT> = SEMAPHORE_TRY_ACQUIRE($sem)
4027 ASSERT_EQ $acq.held true
4028
4029 # One held permit leaves exactly one free.
4030 LET $free: INT = SEMAPHORE_AVAILABLE($sem)
4031 ASSERT_EQ $free 1
4032 "###
4033)]
4034fn semaphore_available(
4035 sem: Arc<SemaphoreState>,
4037) -> DiagnosticResult<Value> {
4038 Ok(Value::int(sem.available() as i64))
4039}
4040
4041#[oxdock_func(
4050 rpn,
4051 returns = TypeTag::union(vec![TypeTag::String, TypeTag::Pipe]),
4052 template = text_trim_string
4053)]
4054#[example(
4055 name = "trim",
4056 code = r###"
4057 # Leading and trailing whitespace falls away.
4058 IMPORT [STD]
4059 LET $clean: STRING = TEXT_TRIM(" hello ")
4060 ASSERT_EQ $clean "hello"
4061 "###
4062)]
4063#[example(
4064 name = "trim pipe mirrors",
4065 code = r###"
4066 # Pipe input mints pipe output with the same transform.
4067 IMPORT [STD]
4068 LET $cap: PIPE
4069 WITH_IO [stdout=$cap] {
4070 ECHO " hello "
4071 }
4072 LET $out: PIPE = TEXT_TRIM($cap)
4073 WITH_IO [stdin=$out] READ_LINE $line
4074 ASSERT_EQ $line "hello"
4075 "###
4076)]
4077#[example(
4078 name = "trim template",
4079 code = r###"
4080 # String inputs run inside placeholders too.
4081 IMPORT [STD]
4082 LET $msg: STRING = 'clean:{{ STD::TEXT_TRIM(" hello ") }}'
4083 ASSERT_EQ $msg "clean:hello"
4084 "###
4085)]
4086#[example(
4087 name = "trim file template",
4088 code = r###"
4089 # EXPAND templates resolve the same registry.
4090 IMPORT [STD]
4091 WRITE "tpl.txt" "clean:\{{ STD::TEXT_TRIM(\" hello \") }}"
4092 LET $out: STRING = EXPAND "tpl.txt"
4093 ASSERT_EQ $out "clean:hello"
4094 "###
4095)]
4096fn text_trim<P: ProcessManager>(
4097 cx: &mut StepCtx<P>,
4098 #[union(String, Pipe)]
4100 text: Value,
4101) -> DiagnosticResult<Value> {
4102 super::args::mirror_stream(cx, "TEXT_TRIM", &text, super::args::TextPump::Trim)
4103}
4104
4105fn text_trim_string(text: Value) -> DiagnosticResult<Value> {
4108 super::args::mirror_string("TEXT_TRIM", &text, super::args::TextPump::Trim)
4109}
4110
4111#[oxdock_func(
4120 rpn,
4121 returns = TypeTag::union(vec![TypeTag::String, TypeTag::Pipe]),
4122 template = text_trim_prefix_string
4123)]
4124#[example(
4125 name = "strip prefix",
4126 code = r###"
4127 # A present prefix falls away; absence returns the input unchanged.
4128 IMPORT [STD]
4129 LET $bare: STRING = TEXT_TRIM_PREFIX("v1.2.3", "v")
4130 ASSERT_EQ $bare "1.2.3"
4131
4132 # Missing prefixes pass through untouched.
4133 LET $same: STRING = TEXT_TRIM_PREFIX("1.2.3", "v")
4134 ASSERT_EQ $same "1.2.3"
4135 "###
4136)]
4137#[example(
4138 name = "strip prefix pipe mirrors",
4139 code = r###"
4140 # Pipe input mints pipe output with the same strip.
4141 IMPORT [STD]
4142 LET $cap: PIPE
4143 WITH_IO [stdout=$cap] {
4144 ECHO "v1.2.3"
4145 }
4146 LET $trimmed: PIPE = TEXT_TRIM($cap)
4147 LET $out: PIPE = TEXT_TRIM_PREFIX($trimmed, "v")
4148 WITH_IO [stdin=$out] READ_LINE $line
4149 ASSERT_EQ $line "1.2.3"
4150 "###
4151)]
4152#[example(
4153 name = "strip prefix template",
4154 code = r###"
4155 # String inputs run inside placeholders too.
4156 IMPORT [STD]
4157 LET $msg: STRING = 'bare:{{ STD::TEXT_TRIM_PREFIX("v1.2.3", "v") }}'
4158 ASSERT_EQ $msg "bare:1.2.3"
4159 "###
4160)]
4161fn text_trim_prefix<P: ProcessManager>(
4162 cx: &mut StepCtx<P>,
4163 #[union(String, Pipe)]
4165 text: Value,
4166 prefix: String,
4168) -> DiagnosticResult<Value> {
4169 super::args::mirror_stream(
4170 cx,
4171 "TEXT_TRIM_PREFIX",
4172 &text,
4173 super::args::TextPump::TrimPrefix(prefix),
4174 )
4175}
4176
4177fn text_trim_prefix_string(text: Value, prefix: String) -> DiagnosticResult<Value> {
4180 super::args::mirror_string(
4181 "TEXT_TRIM_PREFIX",
4182 &text,
4183 super::args::TextPump::TrimPrefix(prefix),
4184 )
4185}
4186
4187#[oxdock_func(
4194 rpn,
4195 returns = TypeTag::union(vec![TypeTag::String, TypeTag::Pipe]),
4196 template = text_trim_suffix_string
4197)]
4198#[example(
4199 name = "strip suffix",
4200 code = r###"
4201 # A present suffix falls away; absence returns the input unchanged.
4202 IMPORT [STD]
4203 LET $bare: STRING = TEXT_TRIM_SUFFIX("archive.tar.gz", ".gz")
4204 ASSERT_EQ $bare "archive.tar"
4205
4206 # Missing suffixes pass through untouched.
4207 LET $same: STRING = TEXT_TRIM_SUFFIX("archive.tar", ".gz")
4208 ASSERT_EQ $same "archive.tar"
4209 "###
4210)]
4211#[example(
4212 name = "strip suffix pipe mirrors",
4213 code = r###"
4214 # Pipe input mints pipe output with the same strip.
4215 IMPORT [STD]
4216 LET $cap: PIPE
4217 WITH_IO [stdout=$cap] {
4218 ECHO "archive.tar.gz"
4219 }
4220 LET $trimmed: PIPE = TEXT_TRIM($cap)
4221 LET $out: PIPE = TEXT_TRIM_SUFFIX($trimmed, ".gz")
4222 WITH_IO [stdin=$out] READ_LINE $line
4223 ASSERT_EQ $line "archive.tar"
4224 "###
4225)]
4226#[example(
4227 name = "strip suffix template",
4228 code = r###"
4229 # String inputs run inside placeholders too.
4230 IMPORT [STD]
4231 LET $msg: STRING = 'bare:{{ STD::TEXT_TRIM_SUFFIX("archive.tar.gz", ".gz") }}'
4232 ASSERT_EQ $msg "bare:archive.tar"
4233 "###
4234)]
4235fn text_trim_suffix<P: ProcessManager>(
4236 cx: &mut StepCtx<P>,
4237 #[union(String, Pipe)]
4239 text: Value,
4240 suffix: String,
4242) -> DiagnosticResult<Value> {
4243 super::args::mirror_stream(
4244 cx,
4245 "TEXT_TRIM_SUFFIX",
4246 &text,
4247 super::args::TextPump::TrimSuffix(suffix),
4248 )
4249}
4250
4251fn text_trim_suffix_string(text: Value, suffix: String) -> DiagnosticResult<Value> {
4254 super::args::mirror_string(
4255 "TEXT_TRIM_SUFFIX",
4256 &text,
4257 super::args::TextPump::TrimSuffix(suffix),
4258 )
4259}
4260
4261#[oxdock_func(returns = TypeTag::String)]
4272#[example(
4273 name = "join path",
4274 code = r###"
4275 # Directory and file stem join with the native separator.
4276 # Source `\\` is one backslash at runtime; `/` works on Windows
4277 # too, native just reads better there.
4278 IMPORT [STD]
4279 LET $p: STRING = PATH_JOIN("some-dir", "some-file")
4280 [family:unix] ASSERT_EQ $p "some-dir/some-file"
4281 [family:windows] ASSERT_EQ $p "some-dir\\some-file"
4282 "###
4283)]
4284fn path_join<P: ProcessManager>(
4285 _cx: &mut StepCtx<P>,
4286 #[union(String, Path)]
4288 dir: Value,
4289 #[union(String, Path)]
4291 name: Value,
4292) -> DiagnosticResult<Value> {
4293 let d = super::args::string_or_path_text(&dir)?;
4294 let n = super::args::string_or_path_text(&name)?;
4295 Ok(Value::string(oxdock_fs::join_native(&d, &n)))
4296}
4297
4298#[oxdock_func(pure, returns = TypeTag::String)]
4306#[example(
4307 name = "base",
4308 code = r###"
4309 # Final segments bind without filesystem access.
4310 IMPORT [STD]
4311 LET $b: STRING = PATH_BASE("some-dir/some-file")
4312 ASSERT_EQ $b "some-file"
4313
4314 # Trailing slashes trim before the split.
4315 LET $d: STRING = PATH_BASE("some-dir/")
4316 ASSERT_EQ $d "some-dir"
4317 "###
4318)]
4319fn path_base(
4320 #[union(String, Path)]
4322 path: Value,
4323) -> DiagnosticResult<Value> {
4324 let text = super::args::string_or_path_text(&path)?;
4325 let base = oxdock_fs::path_base(&text).map_err(|e| std_diag::std_path_base_failed(&e))?;
4326 Ok(Value::string(base))
4327}
4328
4329#[oxdock_func(pure, returns = TypeTag::String)]
4339#[example(
4340 name = "relativize",
4341 code = r###"
4342 # Prefix bases strip to their remainder.
4343 IMPORT [STD]
4344 LET $r: STRING = PATH_REL("some-dir", "some-dir/some-file")
4345 ASSERT_EQ $r "some-file"
4346
4347 # Equal paths bind dot.
4348 LET $dot: STRING = PATH_REL("some-dir", "some-dir")
4349 ASSERT_EQ $dot "."
4350 "###
4351)]
4352fn path_rel(
4353 #[union(String, Path)]
4355 base: Value,
4356 #[union(String, Path)]
4358 path: Value,
4359) -> DiagnosticResult<Value> {
4360 let b = super::args::string_or_path_text(&base)?;
4361 let p = super::args::string_or_path_text(&path)?;
4362 let rel = oxdock_fs::path_rel(&b, &p).map_err(|e| std_diag::std_path_rel_failed(&e))?;
4363 Ok(Value::string(rel))
4364}
4365
4366#[oxdock_func(
4373 rpn,
4374 returns = TypeTag::union(vec![TypeTag::String, TypeTag::Pipe]),
4375 template = text_to_upper_string
4376)]
4377#[example(
4378 name = "uppercase",
4379 code = r###"
4380 # Text folds to uppercase.
4381 IMPORT [STD]
4382 LET $loud: STRING = TEXT_TO_UPPER("hello")
4383 ASSERT_EQ $loud "HELLO"
4384 "###
4385)]
4386#[example(
4387 name = "uppercase pipe mirrors",
4388 code = r###"
4389 # Pipe input mints pipe output with the same fold.
4390 IMPORT [STD]
4391 LET $cap: PIPE
4392 WITH_IO [stdout=$cap] {
4393 ECHO "hello"
4394 }
4395 LET $out: PIPE = TEXT_TO_UPPER($cap)
4396 WITH_IO [stdin=$out] READ_LINE $line
4397 ASSERT_EQ $line "HELLO"
4398 "###
4399)]
4400#[example(
4401 name = "uppercase template",
4402 code = r###"
4403 # String inputs run inside placeholders too.
4404 IMPORT [STD]
4405 LET $msg: STRING = 'loud:{{ STD::TEXT_TO_UPPER("hello") }}'
4406 ASSERT_EQ $msg "loud:HELLO"
4407 "###
4408)]
4409fn text_to_upper<P: ProcessManager>(
4410 cx: &mut StepCtx<P>,
4411 #[union(String, Pipe)]
4413 text: Value,
4414) -> DiagnosticResult<Value> {
4415 super::args::mirror_stream(cx, "TEXT_TO_UPPER", &text, super::args::TextPump::ToUpper)
4416}
4417
4418fn text_to_upper_string(text: Value) -> DiagnosticResult<Value> {
4421 super::args::mirror_string("TEXT_TO_UPPER", &text, super::args::TextPump::ToUpper)
4422}
4423
4424#[oxdock_func(
4431 rpn,
4432 returns = TypeTag::union(vec![TypeTag::String, TypeTag::Pipe]),
4433 template = text_to_lower_string
4434)]
4435#[example(
4436 name = "lowercase",
4437 code = r###"
4438 # Text folds to lowercase.
4439 IMPORT [STD]
4440 LET $quiet: STRING = TEXT_TO_LOWER("HELLO")
4441 ASSERT_EQ $quiet "hello"
4442 "###
4443)]
4444#[example(
4445 name = "lowercase pipe mirrors",
4446 code = r###"
4447 # Pipe input mints pipe output with the same fold.
4448 IMPORT [STD]
4449 LET $cap: PIPE
4450 WITH_IO [stdout=$cap] {
4451 ECHO "HELLO"
4452 }
4453 LET $out: PIPE = TEXT_TO_LOWER($cap)
4454 WITH_IO [stdin=$out] READ_LINE $line
4455 ASSERT_EQ $line "hello"
4456 "###
4457)]
4458#[example(
4459 name = "lowercase template",
4460 code = r###"
4461 # String inputs run inside placeholders too.
4462 IMPORT [STD]
4463 LET $msg: STRING = 'quiet:{{ STD::TEXT_TO_LOWER("HELLO") }}'
4464 ASSERT_EQ $msg "quiet:hello"
4465 "###
4466)]
4467fn text_to_lower<P: ProcessManager>(
4468 cx: &mut StepCtx<P>,
4469 #[union(String, Pipe)]
4471 text: Value,
4472) -> DiagnosticResult<Value> {
4473 super::args::mirror_stream(cx, "TEXT_TO_LOWER", &text, super::args::TextPump::ToLower)
4474}
4475
4476fn text_to_lower_string(text: Value) -> DiagnosticResult<Value> {
4479 super::args::mirror_string("TEXT_TO_LOWER", &text, super::args::TextPump::ToLower)
4480}
4481
4482#[oxdock_func(
4493 rpn,
4494 returns = TypeTag::union(vec![TypeTag::String, TypeTag::Pipe]),
4495 template = text_replace_string
4496)]
4497#[example(
4498 name = "replace",
4499 code = r###"
4500 # Every literal occurrence rewrites in place.
4501 IMPORT [STD]
4502 LET $fixed: STRING = TEXT_REPLACE("hello world", "world", "there")
4503 ASSERT_EQ $fixed "hello there"
4504 "###
4505)]
4506#[example(
4507 name = "replace pipe mirrors",
4508 code = r###"
4509 # Pipe input mints pipe output with the same rewrite.
4510 IMPORT [STD]
4511 LET $cap: PIPE
4512 WITH_IO [stdout=$cap] {
4513 ECHO "hello world"
4514 }
4515 LET $trimmed: PIPE = TEXT_TRIM($cap)
4516 LET $out: PIPE = TEXT_REPLACE($trimmed, "world", "there")
4517 WITH_IO [stdin=$out] READ_LINE $line
4518 ASSERT_EQ $line "hello there"
4519 "###
4520)]
4521#[example(
4522 name = "replace template",
4523 code = r###"
4524 # String inputs run inside placeholders too.
4525 IMPORT [STD]
4526 LET $msg: STRING = 'fixed:{{ STD::TEXT_REPLACE("hello world", "world", "there") }}'
4527 ASSERT_EQ $msg "fixed:hello there"
4528 "###
4529)]
4530fn text_replace<P: ProcessManager>(
4531 cx: &mut StepCtx<P>,
4532 #[union(String, Pipe)]
4534 text: Value,
4535 from: String,
4537 to: String,
4539) -> DiagnosticResult<Value> {
4540 super::args::mirror_stream(
4541 cx,
4542 FUNC_TEXT_REPLACE,
4543 &text,
4544 super::args::TextPump::ReplaceLiteral { from, to },
4545 )
4546}
4547
4548fn text_replace_string(text: Value, from: String, to: String) -> DiagnosticResult<Value> {
4551 super::args::mirror_string(
4552 FUNC_TEXT_REPLACE,
4553 &text,
4554 super::args::TextPump::ReplaceLiteral { from, to },
4555 )
4556}
4557
4558#[oxdock_func(
4570 rpn,
4571 returns = TypeTag::union(vec![TypeTag::String, TypeTag::Pipe]),
4572 template = text_replace_regex_string
4573)]
4574#[example(
4575 name = "replace with captures",
4576 code = r###"
4577 # Capture groups expand in the replacement.
4578 IMPORT [STD]
4579 LET $swapped: STRING = TEXT_REPLACE_REGEX("2026-10-13", "(\\d+)-(\\d+)-(\\d+)", "$3/$2/$1")
4580 ASSERT_EQ $swapped "13/10/2026"
4581 "###
4582)]
4583#[example(
4584 name = "replace regex pipe mirrors",
4585 code = r###"
4586 # Pipe input mints pipe output with the same rewrite.
4587 IMPORT [STD]
4588 LET $cap: PIPE
4589 WITH_IO [stdout=$cap] {
4590 ECHO "2026-10-13"
4591 }
4592 LET $trimmed: PIPE = TEXT_TRIM($cap)
4593 LET $out: PIPE = TEXT_REPLACE_REGEX($trimmed, "(\\d+)-(\\d+)-(\\d+)", "$3/$2/$1")
4594 WITH_IO [stdin=$out] READ_LINE $line
4595 ASSERT_EQ $line "13/10/2026"
4596 "###
4597)]
4598#[example(
4599 name = "replace regex template",
4600 code = r###"
4601 # String inputs run inside placeholders too.
4602 IMPORT [STD]
4603 LET $msg: STRING = 'swapped:{{ STD::TEXT_REPLACE_REGEX("2026-10-13", "(\\d+)-(\\d+)-(\\d+)", "$3/$2/$1") }}'
4604 ASSERT_EQ $msg "swapped:13/10/2026"
4605 "###
4606)]
4607fn text_replace_regex<P: ProcessManager>(
4608 cx: &mut StepCtx<P>,
4609 #[union(String, Pipe)]
4611 text: Value,
4612 pattern: String,
4614 replacement: String,
4616) -> DiagnosticResult<Value> {
4617 if let Some(s) = text.as_str() {
4618 let out = super::args::text_replace_regex_str(
4619 s,
4620 &pattern,
4621 &replacement,
4622 FUNC_TEXT_REPLACE_REGEX,
4623 )?;
4624 return Ok(Value::string(out));
4625 }
4626 let content = super::args::read_pipe_eager(cx, FUNC_TEXT_REPLACE_REGEX, &text)?;
4627 let out = super::args::text_replace_regex_str(
4628 &content,
4629 &pattern,
4630 &replacement,
4631 FUNC_TEXT_REPLACE_REGEX,
4632 )?;
4633 super::args::write_completed_pipe(cx, FUNC_TEXT_REPLACE_REGEX, out)
4634}
4635
4636fn text_replace_regex_string(
4639 text: Value,
4640 pattern: String,
4641 replacement: String,
4642) -> DiagnosticResult<Value> {
4643 let Some(s) = text.as_str() else {
4644 return Err(std_diag::std_pipe_needs_step_io(FUNC_TEXT_REPLACE_REGEX));
4645 };
4646 let out =
4647 super::args::text_replace_regex_str(s, &pattern, &replacement, FUNC_TEXT_REPLACE_REGEX)?;
4648 Ok(Value::string(out))
4649}
4650
4651#[oxdock_func(pure, returns = TypeTag::ListOf(std::sync::Arc::new(TypeTag::String)))]
4659#[example(
4660 name = "split",
4661 code = r###"
4662 # Delimiters split into list items.
4663 IMPORT [STD]
4664 LET $parts: LIST<STRING> = TEXT_SPLIT("a,b,c", ",")
4665 ASSERT_EQ $parts.0 "a"
4666 ASSERT_EQ $parts.1 "b"
4667 ASSERT_EQ $parts.2 "c"
4668 "###
4669)]
4670fn text_split(
4671 text: String,
4673 delimiter: String,
4675) -> DiagnosticResult<Value> {
4676 Ok(super::args::text_list_value(super::args::text_split_str(
4677 &text, &delimiter,
4678 )))
4679}
4680
4681#[oxdock_func(pure, returns = TypeTag::String)]
4684#[example(
4685 name = "join",
4686 code = r###"
4687 # List items join with the separator between them.
4688 IMPORT [STD]
4689 LET $joined: STRING = TEXT_JOIN(["a", "b", "c"], ",")
4690 ASSERT_EQ $joined "a,b,c"
4691 "###
4692)]
4693fn text_join(
4694 elements: Vec<String>,
4696 delimiter: String,
4698) -> DiagnosticResult<Value> {
4699 Ok(Value::string(elements.join(delimiter.as_str())))
4700}
4701
4702#[oxdock_func(pure, returns = TypeTag::ListOf(std::sync::Arc::new(TypeTag::String)))]
4714#[example(
4715 name = "split args",
4716 code = r###"
4717 # Quoted segments stay one word.
4718 IMPORT [STD]
4719 LET $argv: LIST<STRING> = SHELL_SPLIT_ARGS("gh issue comment 153 --body-file notes.md")
4720 ASSERT_EQ $argv.0 "gh"
4721 ASSERT_EQ $argv.3 "153"
4722 ASSERT_EQ $argv.5 "notes.md"
4723
4724 # Quotes and escapes parse the shell way.
4725 LET $quoted: LIST<STRING> = SHELL_SPLIT_ARGS("say \"hi there\" 'a b'")
4726 ASSERT_EQ $quoted.0 "say"
4727 ASSERT_EQ $quoted.1 "hi there"
4728 ASSERT_EQ $quoted.2 "a b"
4729 "###
4730)]
4731fn shell_split_args(
4732 command: String,
4734) -> DiagnosticResult<Value> {
4735 match shell_words::split(&command) {
4736 Ok(words) => Ok(super::args::text_list_value(words)),
4737 Err(err) => Err(std_diag::std_shell_split_failed(&err)),
4738 }
4739}
4740
4741#[oxdock_func(pure, returns = TypeTag::String)]
4749#[example(
4750 name = "join args",
4751 code = r###"
4752 # Plain words join with spaces and no quoting.
4753 IMPORT [STD]
4754 LET $plain: STRING = SHELL_JOIN_ARGS(["gh", "issue", "list"])
4755 ASSERT_EQ $plain "gh issue list"
4756
4757 # Words with spaces quote, and the round trip is exact.
4758 LET $words: LIST<STRING> = ["say", "hi there", "a'b"]
4759 LET $joined: STRING = SHELL_JOIN_ARGS($words)
4760 LET $back: LIST<STRING> = SHELL_SPLIT_ARGS($joined)
4761 ASSERT_EQ $back.0 "say"
4762 ASSERT_EQ $back.1 "hi there"
4763 ASSERT_EQ $back.2 "a'b"
4764 "###
4765)]
4766fn shell_join_args(
4767 words: Vec<String>,
4769) -> DiagnosticResult<Value> {
4770 Ok(Value::string(shell_words::join(&words)))
4771}
4772
4773#[oxdock_func(pure, returns = TypeTag::ListOf(std::sync::Arc::new(TypeTag::String)))]
4781#[example(
4782 name = "lines",
4783 code = r###"
4784 # Newlines split into line items.
4785 IMPORT [STD]
4786 LET $lines: LIST<STRING> = TEXT_LINES("one\ntwo\nthree")
4787 ASSERT_EQ $lines.0 "one"
4788 ASSERT_EQ $lines.1 "two"
4789 ASSERT_EQ $lines.2 "three"
4790
4791 # Windows endings split the same way after normalization.
4792 LET $crlf: LIST<STRING> = TEXT_LINES("one\r\ntwo\r\nthree")
4793 ASSERT_EQ $crlf.0 "one"
4794 ASSERT_EQ $crlf.1 "two"
4795 ASSERT_EQ $crlf.2 "three"
4796
4797 # Old Mac endings split too, and mixed endings split together because the input normalizes to LF before splitting.
4798 LET $mixed: LIST<STRING> = TEXT_LINES("a\r\nb\nc\rd")
4799 ASSERT_EQ $mixed.0 "a"
4800 ASSERT_EQ $mixed.1 "b"
4801 ASSERT_EQ $mixed.2 "c"
4802 ASSERT_EQ $mixed.3 "d"
4803 "###
4804)]
4805fn text_lines(
4806 text: String,
4808) -> DiagnosticResult<Value> {
4809 Ok(super::args::text_list_value(super::args::text_lines_str(
4810 &text,
4811 )))
4812}
4813
4814#[oxdock_func(pure, returns = TypeTag::ListOf(std::sync::Arc::new(TypeTag::String)))]
4820#[example(
4821 name = "fields",
4822 code = r###"
4823 # Runs of whitespace separate fields; empties never appear.
4824 IMPORT [STD]
4825 LET $fields: LIST<STRING> = TEXT_FIELDS(" abc def ")
4826 ASSERT_EQ $fields.0 "abc"
4827 ASSERT_EQ $fields.1 "def"
4828 "###
4829)]
4830fn text_fields(
4831 text: String,
4833) -> DiagnosticResult<Value> {
4834 Ok(super::args::text_list_value(super::args::text_fields_str(
4835 &text,
4836 )))
4837}
4838
4839#[oxdock_func(pure, returns = TypeTag::ListOf(std::sync::Arc::new(TypeTag::String)))]
4848#[example(
4849 name = "line range",
4850 code = r###"
4851 # Lines 2 through 3 come back as a list, 1-based inclusive.
4852 IMPORT [STD]
4853 LET $window: LIST<STRING> = TEXT_LINES_RANGE("one\ntwo\nthree\nfour", 2, 3)
4854 ASSERT_EQ $window.0 "two"
4855 ASSERT_EQ $window.1 "three"
4856
4857 # Ranges past the end clamp instead of failing.
4858 LET $tail: LIST<STRING> = TEXT_LINES_RANGE("one\ntwo", 2, 9)
4859 ASSERT_EQ $tail.0 "two"
4860 "###
4861)]
4862fn text_lines_range(
4863 text: String,
4865 from: i64,
4867 to: i64,
4869) -> DiagnosticResult<Value> {
4870 Ok(super::args::text_list_value(
4871 super::args::text_lines_range_str(&text, from, to, FUNC_TEXT_LINES_RANGE)?,
4872 ))
4873}
4874
4875#[oxdock_func(pure, returns = TypeTag::Bool)]
4883#[example(
4884 name = "match",
4885 code = r###"
4886 # Regex matches report true; misses report false.
4887 IMPORT [STD]
4888 LET $hit: BOOL = TEXT_MATCH("abc123", "\\d+")
4889 ASSERT_EQ $hit true
4890
4891 # A miss is false, not a failure.
4892 LET $miss: BOOL = TEXT_MATCH("abc", "^\\d+$")
4893 ASSERT_EQ $miss false
4894 "###
4895)]
4896fn text_match(
4897 text: String,
4899 pattern: String,
4901) -> DiagnosticResult<Value> {
4902 let re = super::args::text_compile_pattern(FUNC_TEXT_MATCH, &pattern)?;
4903 Ok(Value::bool(re.is_match(&text)))
4904}
4905
4906#[oxdock_func(pure, name = "BOOL", returns = TypeTag::Bool)]
4915#[example(
4916 name = "convert",
4917 code = r###"
4918 IMPORT [STD]
4919 LET $n: BOOL = BOOL("yes")
4920 ASSERT_EQ $n true
4921 LET $f: BOOL = BOOL("0")
4922 ASSERT_EQ $f false
4923 "###
4924)]
4925fn bool_convert(
4926 #[union(Bool, String)]
4928 val: Value,
4929) -> DiagnosticResult<Value> {
4930 if let Some(b) = val.as_bool() {
4931 return Ok(Value::bool(b));
4932 }
4933 let Some(s) = val.as_str() else {
4934 return Err(std_diag::std_bool_needs_bool_or_string(&val));
4935 };
4936 match super::args::parse_bool_str(s) {
4937 Some(b) => Ok(Value::bool(b)),
4938 None => Err(std_diag::std_bool_cannot_coerce(FUNC_BOOL, s)),
4939 }
4940}
4941
4942#[oxdock_func(pure, returns = TypeTag::Bool)]
4952#[example(
4953 name = "absent-default",
4954 code = r###"
4955 # Absent names read empty; the default settles the polarity.
4956 IMPORT [STD]
4957 INHERIT_ENV [OXDOCK_TEST_ABSENT_FLAG]
4958 LET $dry: BOOL = BOOL_OR("{{ env:OXDOCK_TEST_ABSENT_FLAG }}", true)
4959 ASSERT_EQ $dry true
4960
4961 # Present values coerce strictly, ignoring the default.
4962 LET $off: BOOL = BOOL_OR("false", true)
4963 ASSERT_EQ $off false
4964 "###
4965)]
4966fn bool_or(
4967 text: String,
4969 default: bool,
4971) -> DiagnosticResult<Value> {
4972 if text.trim().is_empty() {
4973 return Ok(Value::bool(default));
4974 }
4975 match super::args::parse_bool_str(&text) {
4976 Some(b) => Ok(Value::bool(b)),
4977 None => Err(std_diag::std_bool_cannot_coerce(FUNC_BOOL_OR, &text)),
4978 }
4979}
4980
4981#[oxdock_func(pure, returns = TypeTag::ListOf(std::sync::Arc::new(TypeTag::String)))]
4990#[example(
4991 name = "extract",
4992 code = r###"
4993 # Index zero is the full match; groups follow in order.
4994 IMPORT [STD]
4995 LET $caps: LIST<STRING> = TEXT_EXTRACT("abc123", "([a-z]+)(\\d+)")
4996 ASSERT_EQ $caps.0 "abc123"
4997 ASSERT_EQ $caps.1 "abc"
4998 ASSERT_EQ $caps.2 "123"
4999 "###
5000)]
5001fn text_extract(
5002 text: String,
5004 pattern: String,
5006) -> DiagnosticResult<Value> {
5007 let groups = super::args::text_extract_str(&text, &pattern, FUNC_TEXT_EXTRACT)?;
5008 Ok(super::args::text_list_value(groups))
5009}
5010
5011#[oxdock_func(pure, returns = TypeTag::Bool)]
5018#[example(
5019 name = "starts with",
5020 code = r###"
5021 # Present prefixes report true; misses report false.
5022 IMPORT [STD]
5023 LET $hit: BOOL = TEXT_STARTS_WITH("linux-musl-x64", "linux")
5024 ASSERT_EQ $hit true
5025
5026 # A miss is false, not a failure.
5027 LET $miss: BOOL = TEXT_STARTS_WITH("macos-arm", "linux")
5028 ASSERT_EQ $miss false
5029 "###
5030)]
5031fn text_starts_with(
5032 text: String,
5034 prefix: String,
5036) -> DiagnosticResult<Value> {
5037 Ok(Value::bool(text.starts_with(prefix.as_str())))
5038}
5039
5040#[oxdock_func(pure, returns = TypeTag::Bool)]
5047#[example(
5048 name = "ends with",
5049 code = r###"
5050 # Present suffixes report true; misses report false.
5051 IMPORT [STD]
5052 LET $hit: BOOL = TEXT_ENDS_WITH("x86_64-linux-musl", "linux-musl")
5053 ASSERT_EQ $hit true
5054
5055 # A miss is false, not a failure.
5056 LET $miss: BOOL = TEXT_ENDS_WITH("x86_64-linux-gnu", "linux-musl")
5057 ASSERT_EQ $miss false
5058 "###
5059)]
5060fn text_ends_with(
5061 text: String,
5063 suffix: String,
5065) -> DiagnosticResult<Value> {
5066 Ok(Value::bool(text.ends_with(suffix.as_str())))
5067}
5068
5069#[oxdock_func(pure, returns = TypeTag::Bool)]
5079#[example(
5080 name = "contains",
5081 code = r###"
5082 # Present needles report true; misses report false.
5083 IMPORT [STD]
5084 LET $hit: BOOL = CONTAINS("x86_64-linux-musl", "musl")
5085 ASSERT_EQ $hit true
5086
5087 # A miss is false, not a failure.
5088 LET $miss: BOOL = CONTAINS("x86_64-linux-gnu", "musl")
5089 ASSERT_EQ $miss false
5090 "###
5091)]
5092#[example(
5093 name = "contains list",
5094 code = r###"
5095 # List membership uses strict equality across any element type.
5096 IMPORT [STD]
5097 LET $hit: BOOL = CONTAINS(["a", "b", "c"], "b")
5098 ASSERT_EQ $hit true
5099 LET $miss: BOOL = CONTAINS(["a", "b", "c"], "z")
5100 ASSERT_EQ $miss false
5101 LET $num: BOOL = CONTAINS([1, 2, 3], 2.0)
5102 ASSERT_EQ $num true
5103
5104 # Stringified numbers never coerce to integers.
5105 LET $strnum: BOOL = CONTAINS(["1", "2", "3"], 2)
5106 ASSERT_EQ $strnum false
5107
5108 # Boolean lists match true and miss false with no coercion.
5109 LET $bools: LIST<BOOL> = [true]
5110 LET $bhit: BOOL = CONTAINS($bools, true)
5111 ASSERT_EQ $bhit true
5112 LET $bmiss: BOOL = CONTAINS($bools, false)
5113 ASSERT_EQ $bmiss false
5114 LET $nocoerce: BOOL = CONTAINS($bools, 1)
5115 ASSERT_EQ $nocoerce false
5116 "###
5117)]
5118fn contains(
5119 #[union(String, List)]
5121 haystack: Value,
5122 needle: Value,
5124) -> DiagnosticResult<Value> {
5125 if let Some(text) = haystack.as_str() {
5126 let Some(n) = needle.as_str() else {
5127 return Err(std_diag::std_contains_needle_type(needle.type_name()));
5128 };
5129 return Ok(Value::bool(text.contains(n)));
5130 }
5131 if let Some(items) = haystack.as_list() {
5132 for item in items {
5133 if super::args::values_equal(item, &needle) {
5134 return Ok(Value::bool(true));
5135 }
5136 }
5137 return Ok(Value::bool(false));
5138 }
5139 Err(std_diag::std_contains_haystack_type(haystack.type_name()))
5140}
5141
5142#[oxdock_func(pure, returns = TypeTag::List)]
5150#[example(
5151 name = "deduplicate",
5152 code = r###"
5153 # First occurrences win, later repeats drop.
5154 IMPORT [STD]
5155 LET $seen: LIST<STRING> = UNIQUE(["a", "b", "a", "c", "b"])
5156 ASSERT_EQ $seen.0 "a"
5157 ASSERT_EQ $seen.1 "b"
5158 ASSERT_EQ $seen.2 "c"
5159 ASSERT_EQ LEN($seen) 3
5160
5161 # The empty list stays empty.
5162 LET $empty: LIST<STRING> = UNIQUE([])
5163 ASSERT_EQ LEN($empty) 0
5164 "###
5165)]
5166#[example(
5167 name = "strict membership",
5168 code = r###"
5169 # Numerics collapse across INT and FLOAT like CONTAINS.
5170 IMPORT [STD]
5171 LET $nums: LIST<ANY> = UNIQUE([1, 2.0, 1, 3])
5172 ASSERT_EQ $nums.0 1
5173 ASSERT_EQ $nums.1 2.0
5174 ASSERT_EQ $nums.2 3
5175 ASSERT_EQ LEN($nums) 3
5176
5177 # Stringified numbers never coerce to integers.
5178 LET $mixed: LIST<ANY> = UNIQUE(["1", 1])
5179 ASSERT_EQ $mixed.0 "1"
5180 ASSERT_EQ $mixed.1 1
5181 ASSERT_EQ LEN($mixed) 2
5182 "###
5183)]
5184fn unique(
5185 items: Vec<Value>,
5187) -> DiagnosticResult<Value> {
5188 let mut out: Vec<Value> = Vec::with_capacity(items.len());
5189 for item in items {
5190 if !out
5191 .iter()
5192 .any(|seen| super::args::values_equal(seen, &item))
5193 {
5194 out.push(item);
5195 }
5196 }
5197 Ok(Value::list(out))
5198}
5199
5200#[oxdock_func(pure, returns = TypeTag::Int)]
5209#[example(
5210 name = "length",
5211 code = r###"
5212 # Plain text counts one per character.
5213 IMPORT [STD]
5214 LET $n: INT = LEN("hello")
5215 ASSERT_EQ $n 5
5216
5217 # Multibyte characters count once each, not per byte.
5218 LET $wide: INT = LEN("héllo")
5219 ASSERT_EQ $wide 5
5220
5221 # Lists count elements, maps count entries.
5222 LET $items: LIST<STRING> = ["a", "b", "c"]
5223 LET $nitems: INT = LEN($items)
5224 ASSERT_EQ $nitems 3
5225 LET $row: MAP<name: STRING> = {name: "ada"}
5226 LET $nkeys: INT = LEN($row)
5227 ASSERT_EQ $nkeys 1
5228 LET $empty: INT = LEN([])
5229 ASSERT_EQ $empty 0
5230 "###
5231)]
5232fn len(
5233 #[union(String, List, Map)]
5235 value: Value,
5236) -> DiagnosticResult<Value> {
5237 if let Some(text) = value.as_str() {
5238 return Ok(Value::int(text.chars().count() as i64));
5239 }
5240 if let Some(items) = value.as_list() {
5241 return Ok(Value::int(items.len() as i64));
5242 }
5243 if let Some(entries) = value.as_map() {
5244 return Ok(Value::int(entries.len() as i64));
5245 }
5246 Err(std_diag::std_len_unexpected_type(value.type_name()))
5247}
5248
5249#[oxdock_func(pure, returns = TypeTag::Int)]
5257#[example(
5258 name = "count",
5259 code = r###"
5260 # Every non-overlapping occurrence counts once.
5261 IMPORT [STD]
5262 LET $n: INT = TEXT_COUNT("hello world", "o")
5263 ASSERT_EQ $n 2
5264
5265 # Overlapping candidates never double count.
5266 LET $once: INT = TEXT_COUNT("aaa", "aa")
5267 ASSERT_EQ $once 1
5268 "###
5269)]
5270fn text_count(
5271 text: String,
5273 needle: String,
5275) -> DiagnosticResult<Value> {
5276 let n = super::args::text_count_str(&text, &needle, FUNC_TEXT_COUNT)?;
5277 Ok(Value::int(n))
5278}
5279
5280#[oxdock_func(pure, returns = TypeTag::Int)]
5290#[example(
5291 name = "count matches",
5292 code = r###"
5293 # One line matches once no matter how many times it hits.
5294 IMPORT [STD]
5295 LET $n: INT = TEXT_COUNT_MATCHES("test a: test\ntest b: nope\ntest c: test", ": test")
5296 ASSERT_EQ $n 2
5297
5298 # A miss binds zero, never an error.
5299 LET $none: INT = TEXT_COUNT_MATCHES("test b: nope", ": test$")
5300 ASSERT_EQ $none 0
5301 "###
5302)]
5303fn text_count_matches(
5304 text: String,
5306 pattern: String,
5308) -> DiagnosticResult<Value> {
5309 let n = super::args::text_count_matches_str(&text, &pattern, FUNC_TEXT_COUNT_MATCHES)?;
5310 Ok(Value::int(n))
5311}
5312
5313#[oxdock_func(pure, returns = TypeTag::ListOf(std::sync::Arc::new(TypeTag::String)))]
5326#[example(
5327 name = "grep",
5328 code = r###"
5329 # Matching lines come back as a list, in order.
5330 IMPORT [STD]
5331 LET $hits: LIST<STRING> = TEXT_GREP("one\ntwo\none more", "^one")
5332 ASSERT_EQ $hits.0 "one"
5333 ASSERT_EQ $hits.1 "one more"
5334
5335 # A miss binds an empty list, never an error.
5336 LET $miss: LIST<STRING> = TEXT_GREP("one\ntwo", "^z")
5337 LET $joined: STRING = TEXT_JOIN($miss, ",")
5338 ASSERT_EQ $joined ""
5339
5340 # The (?i) flag ignores case, so uppercase lines match too.
5341 LET $folded: LIST<STRING> = TEXT_GREP("One\ntwo\nONE more", "(?i)^one")
5342 ASSERT_EQ $folded.0 "One"
5343 ASSERT_EQ $folded.1 "ONE more"
5344 "###
5345)]
5346#[example(
5347 name = "grep invert",
5348 code = r###"
5349 # The invert option keeps every non-matching line instead.
5350 IMPORT [STD]
5351 LET $kept: LIST<STRING> = TEXT_GREP("one\ntwo\none more", "^one", {invert: true})
5352 ASSERT_EQ $kept.0 "two"
5353
5354 # A pattern matching every line binds an empty list, never an error.
5355 LET $none: LIST<STRING> = TEXT_GREP("one\ntwo", "^", {invert: true})
5356 LET $joined: STRING = TEXT_JOIN($none, ",")
5357 ASSERT_EQ $joined ""
5358
5359 # Options ride into placeholders as MAP literals. Placeholder
5360 # strings unescape only backslash and quote, so multiline text
5361 # arrives through a variable.
5362 LET $two_lines: STRING = "one\ntwo"
5363 LET $msg: STRING = 'kept:{{ STD::TEXT_GREP($two_lines, "^one", {invert: true}) }}'
5364 ASSERT_EQ $msg "kept:two"
5365 "###
5366)]
5367fn text_grep(
5368 text: String,
5370 pattern: String,
5372 #[options("invert?: BOOL")]
5374 #[optional]
5375 options: BTreeMap<String, Value>,
5376) -> DiagnosticResult<Value> {
5377 let invert = super::args::text_invert_flag(&options);
5380 Ok(super::args::text_list_value(super::args::text_grep_str(
5381 &text,
5382 &pattern,
5383 invert,
5384 FUNC_TEXT_GREP,
5385 )?))
5386}
5387
5388#[oxdock_func(returns = TypeTag::Bool)]
5399#[example(
5400 name = "drain to end",
5401 code = r###"
5402 # Capture two lines, then drain to end of stream with no sentinel line.
5403 IMPORT [STD]
5404 LET $cap: PIPE
5405 WITH_IO [stdout=$cap] {
5406 ECHO "one"
5407 ECHO "two"
5408 }
5409
5410 # The loop exits on close, and the count proves both lines drained.
5411 LET $n: INT = 0
5412 WHILE !EOF($cap) {
5413 WITH_IO [stdin=$cap] READ_LINE $line
5414 $n = $n + 1
5415 }
5416 ASSERT_EQ $n 2
5417 "###
5418)]
5419fn eof<P: ProcessManager>(
5420 cx: &mut StepCtx<P>,
5421 pipe: PipeHandle,
5423) -> DiagnosticResult<Value> {
5424 let info = cx.state.io.inspect_pipe(&pipe);
5425 Ok(Value::bool(info.closed && info.buffered == 0))
5426}
5427
5428fn task_poll_result_fields() -> Arc<[Field]> {
5432 Arc::from(vec![
5433 Field {
5434 name: "state".to_string(),
5435 ty: TypeTag::String,
5436 docs: "Task phase: `running` or `finished`.",
5437 optional: false,
5438 default: None,
5439
5440 alias: None,
5441 },
5442 Field {
5443 name: "ok".to_string(),
5444 ty: TypeTag::Bool,
5445 docs: "True unless the task failed.",
5446 optional: false,
5447 default: None,
5448
5449 alias: None,
5450 },
5451 Field {
5452 name: "stdout_tail".to_string(),
5453 ty: TypeTag::String,
5454 docs: "Bounded stdout tail, live while running.",
5455 optional: false,
5456 default: None,
5457
5458 alias: None,
5459 },
5460 Field {
5461 name: "stderr_tail".to_string(),
5462 ty: TypeTag::String,
5463 docs: "Bounded stderr tail, live while running.",
5464 optional: false,
5465 default: None,
5466
5467 alias: None,
5468 },
5469 Field {
5470 name: "truncated_bytes".to_string(),
5471 ty: TypeTag::Int,
5472 docs: "Dropped head bytes past the per-stream cap.",
5473 optional: false,
5474 default: None,
5475
5476 alias: None,
5477 },
5478 Field {
5479 name: "exit_code".to_string(),
5480 ty: TypeTag::Int,
5481 docs: "Process exit code, present once finished.",
5482 optional: true,
5483 default: None,
5484
5485 alias: None,
5486 },
5487 Field {
5488 name: "result".to_string(),
5489 ty: TypeTag::Any,
5490 docs: "Task `RETURN` value, present on clean finish.",
5491 optional: true,
5492 default: None,
5493
5494 alias: None,
5495 },
5496 Field {
5497 name: "error".to_string(),
5498 ty: TypeTag::String,
5499 docs: "Failure text, present on failed finish.",
5500 optional: true,
5501 default: None,
5502
5503 alias: None,
5504 },
5505 ])
5506}
5507
5508#[oxdock_func(returns = TypeTag::Record(task_poll_result_fields()))]
5521#[example(
5522 name = "running poll",
5523 code = r###"
5524 # A sleeping task is still running on the first poll.
5525 IMPORT [STD]
5526 LET $t: HANDLE<STRING> = ASYNC { SLEEP 30s; RETURN "done" }
5527 LET $m: MAP<state: STRING, ok: BOOL, stdout_tail: STRING, stderr_tail: STRING, truncated_bytes: INT, exit_code?: INT, result?: ANY, error?: STRING> = TASK_POLL($t)
5528 ASSERT_EQ $m.state "running"
5529 ASSERT_EQ $m.ok true
5530 # Clean up the sleeper so the run ends promptly.
5531 CANCEL $t
5532 "###
5533)]
5534#[example(
5535 name = "finished poll",
5536 code = r###"
5537 # A finished task reports its value and final tails, then still awaits.
5538 IMPORT [STD]
5539 LET $t: HANDLE<STRING> = ASYNC { ECHO "hi"; SLEEP 1s; RETURN "done" }
5540 # Do other work while the task runs; poll once it should be done.
5541 SLEEP 2s
5542 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)
5543 ASSERT_EQ $m.state "finished"
5544 ASSERT_EQ $m.result "done"
5545 LET $o: STRING = AWAIT $t
5546 ASSERT_EQ $o "done"
5547 "###
5548)]
5549fn task_poll<P: ProcessManager>(
5550 cx: &mut StepCtx<P>,
5551 task: HandleValue,
5553) -> DiagnosticResult<Value> {
5554 let entry =
5555 super::handlers::resolve_task_entry_by_id(task.0, &format!("TASK_POLL({})", task.0), cx)?;
5556 let obs = entry.observe_completion();
5557 let (stdout_tail, stderr_tail, dropped) = entry.snapshot_tails();
5558 let mut out = BTreeMap::new();
5559 out.insert(
5560 "state".to_string(),
5561 Value::string(if obs.running { "running" } else { "finished" }.to_string()),
5562 );
5563 out.insert("ok".to_string(), Value::bool(obs.ok));
5564 if !obs.running {
5565 out.insert("exit_code".to_string(), Value::int(obs.exit_code));
5566 }
5567 if let Some(result) = obs.result {
5568 out.insert("result".to_string(), result);
5569 }
5570 if !obs.error.is_empty() {
5571 out.insert("error".to_string(), Value::string(obs.error));
5572 }
5573 out.insert("stdout_tail".to_string(), Value::string(stdout_tail));
5574 out.insert("stderr_tail".to_string(), Value::string(stderr_tail));
5575 out.insert(
5576 "truncated_bytes".to_string(),
5577 Value::int(dropped.min(i64::MAX as u64) as i64),
5578 );
5579 Ok(Value::map(out))
5580}
5581
5582fn meta_to_value(meta: &FuncMeta) -> Value {
5583 let mut map = BTreeMap::new();
5584 map.insert("name".to_string(), Value::string(meta.name.clone()));
5585 map.insert("module".to_string(), Value::string(meta.module.clone()));
5586 map.insert(
5587 "kind".to_string(),
5588 Value::string(meta.kind.label().to_string()),
5589 );
5590 let params = match &meta.params {
5591 Some(params) => Value::list(
5592 params
5593 .iter()
5594 .map(|p| {
5595 let mut entry = BTreeMap::new();
5596 entry.insert("name".to_string(), Value::string(p.name.clone()));
5597 entry.insert(
5598 "param_type".to_string(),
5599 Value::string(
5600 p.param_type
5601 .as_ref()
5602 .map(render_structural)
5603 .unwrap_or_default(),
5604 ),
5605 );
5606 entry.insert(
5607 "allowed".to_string(),
5608 Value::string(
5609 p.allowed
5610 .map(|values| values.join(", "))
5611 .unwrap_or_default(),
5612 ),
5613 );
5614 entry.insert("docs".to_string(), Value::string(String::new()));
5615 entry.insert("optional".to_string(), Value::bool(p.optional));
5616 entry.insert(
5617 "options".to_string(),
5618 match p.options {
5619 Some(keys) => Value::list(
5620 keys.iter()
5621 .map(|key| {
5622 let mut option = BTreeMap::new();
5623 option.insert(
5624 "name".to_string(),
5625 Value::string(key.name.to_string()),
5626 );
5627 option.insert(
5628 "value_type".to_string(),
5629 Value::string(render_structural(&key.value)),
5630 );
5631 option.insert(
5632 "required".to_string(),
5633 Value::bool(key.required),
5634 );
5635 option.insert(
5636 "default".to_string(),
5637 Value::string(
5638 key.default.unwrap_or_default().to_string(),
5639 ),
5640 );
5641 Value::map(option)
5642 })
5643 .collect(),
5644 ),
5645 None => Value::string(String::new()),
5646 },
5647 );
5648 Value::map(entry)
5649 })
5650 .collect(),
5651 ),
5652 None => Value::list(Vec::new()),
5656 };
5657 map.insert("params".to_string(), params);
5658 map.insert(
5659 "returns".to_string(),
5660 Value::string(
5661 meta.returns
5662 .as_ref()
5663 .map(render_structural)
5664 .unwrap_or_default(),
5665 ),
5666 );
5667 map.insert("rpn".to_string(), Value::bool(meta.rpn));
5668 map.insert(
5669 "summary".to_string(),
5670 Value::string(meta.summary.to_string()),
5671 );
5672 Value::map(map)
5673}
5674
5675#[derive(Debug, Clone)]
5679pub struct RecordSchema {
5680 pub name: &'static str,
5681 pub fields: std::sync::Arc<[Field]>,
5682}
5683
5684#[derive(Clone)]
5688pub struct HostModule<P: ProcessManager> {
5689 pub name: String,
5690 pub funcs: Vec<HostRegistration<P>>,
5691 pub types: Vec<&'static TypeDescriptor>,
5692 pub record_schemas: Vec<RecordSchema>,
5693 pub states: Vec<ModuleState>,
5700}
5701
5702#[derive(Clone)]
5706pub struct ModuleState {
5707 id: std::any::TypeId,
5708 state: std::sync::Arc<dyn std::any::Any + Send + Sync>,
5709}
5710
5711pub type PreRunInspector = dyn Fn(&[Step]) -> DiagnosticResult<()> + Send + Sync;
5715
5716#[derive(Clone)]
5722pub struct PreRunCheck {
5723 check: Arc<PreRunInspector>,
5724}
5725
5726impl PreRunCheck {
5727 pub fn new(check: impl Fn(&[Step]) -> DiagnosticResult<()> + Send + Sync + 'static) -> Self {
5729 Self {
5730 check: Arc::new(check),
5731 }
5732 }
5733
5734 pub fn run(&self, steps: &[Step]) -> DiagnosticResult<()> {
5736 (self.check)(steps)
5737 }
5738}
5739
5740impl<P: ProcessManager> HostModule<P> {
5741 pub fn with_state<T: Send + Sync + 'static>(mut self, state: std::sync::Arc<T>) -> Self {
5744 self.states.push(ModuleState {
5745 id: std::any::TypeId::of::<T>(),
5746 state,
5747 });
5748 self
5749 }
5750
5751 pub fn check_pre_run(&self, steps: &[Step]) -> DiagnosticResult<()> {
5755 for state in &self.states {
5756 if let Some(check) = state.state.downcast_ref::<PreRunCheck>() {
5757 check.run(steps)?;
5758 }
5759 }
5760 Ok(())
5761 }
5762}
5763
5764impl<P: ProcessManager> ExecState<P> {
5765 pub fn register_module(&mut self, module: HostModule<P>) {
5768 for registration in module.funcs {
5769 match registration {
5770 HostRegistration::Stateful { name, meta, func } => {
5771 self.functions.register_host(&module.name, name, meta, func);
5772 }
5773 HostRegistration::Pure { name, meta, func } => {
5774 self.functions
5775 .register_pure_host(&module.name, name, meta, func);
5776 }
5777 HostRegistration::Both {
5778 name,
5779 meta,
5780 func,
5781 template,
5782 } => {
5783 self.functions
5784 .register_both_host(&module.name, name, meta, func, template);
5785 }
5786 }
5787 }
5788 for descriptor in module.types {
5789 self.register_type(descriptor);
5790 }
5791 for schema in module.record_schemas {
5792 self.register_record_schema(schema.name, schema.fields);
5793 }
5794 for state in module.states {
5795 self.module_states
5796 .insert((module.name.clone(), state.id), state.state);
5797 }
5798 }
5799
5800 pub fn list_functions(&self) -> Vec<FuncMeta> {
5802 let mut out: Vec<FuncMeta> = self.functions.entries_metas().into_iter().collect();
5803 if !out.iter().any(|m| m.name == KEYWORD_INSPECT) {
5805 out.push(FuncMeta {
5806 name: KEYWORD_INSPECT.to_string(),
5807 module: STD_MODULE_NAME.to_string(),
5808 kind: FuncKind::HostCtx,
5809 params: None,
5810 returns: Some(TypeTag::Map),
5811 rpn: false,
5812 summary: "Inspect a variable binding.",
5813 docs: "INSPECT($var): dedicated AST node taking a variable, not a value.",
5814 examples: &[],
5815 });
5816 }
5817 out.sort_by(|a, b| a.name.cmp(&b.name));
5818 out
5819 }
5820
5821 pub fn describe_function(&self, name: &str) -> Option<Value> {
5823 if let Some(meta) = self.functions.meta(name) {
5824 return Some(meta_to_value(&meta));
5825 }
5826 if name == KEYWORD_INSPECT {
5828 return Some(meta_to_value(&FuncMeta {
5829 name: KEYWORD_INSPECT.to_string(),
5830 module: STD_MODULE_NAME.to_string(),
5831 kind: FuncKind::HostCtx,
5832 params: None,
5833 returns: Some(TypeTag::Map),
5834 rpn: false,
5835 summary: "Inspect a variable binding.",
5836 docs: "INSPECT($var): dedicated AST node taking a variable, not a value.",
5837 examples: &[],
5838 }));
5839 }
5840 None
5841 }
5842
5843 pub fn pure_function_table(&self) -> Arc<PureTable> {
5848 self.functions.pure_shared()
5849 }
5850}
5851
5852#[cfg(test)]
5853mod tests {
5854 use super::*;
5855
5856 #[test]
5857 fn placeholder_resolver_dispatches_table_entries() {
5858 let echo: PureFn = Arc::new(|args| {
5862 args.into_iter().next().ok_or_else(|| {
5863 Diagnostic::new(
5864 "test.echo.arity",
5865 "ECHO needs 1 arg".to_string(),
5866 Diagnostic::make_fields(&[]),
5867 )
5868 })
5869 });
5870 let mut entries = HashMap::new();
5871 entries.insert("ECHO".to_string(), echo);
5872 let mut table = PureTable::new();
5873 table.insert("T".to_string(), entries);
5874 let resolve = placeholder_resolver(Arc::new(table));
5875 let out = resolve("T", "ECHO", vec![Value::string("hi".to_string())]).expect("dispatch");
5876 assert_eq!(out.as_str().expect("string"), "hi");
5877 let err = format!(
5878 "{:#}",
5879 resolve("T", "NOPE", vec![]).expect_err("unknown must fail")
5880 );
5881 assert!(
5882 err.contains("unknown placeholder function `T::NOPE`"),
5883 "names the call: {err}"
5884 );
5885 assert!(
5886 err.contains("known functions: T::ECHO"),
5887 "lists known names: {err}"
5888 );
5889 }
5890
5891 #[test]
5892 fn describe_entry_renders_union_spellings() {
5893 let union = oxdock_parser::union_tag!(String, Pipe);
5899 let meta = FuncMeta {
5900 name: "T::F".to_string(),
5901 module: "T".to_string(),
5902 kind: FuncKind::HostPure,
5903 params: Some(vec![FuncParam {
5904 name: "text".to_string(),
5905 param_type: Some(union.clone()),
5906 allowed: None,
5907 docs: "",
5908 options: None,
5909 optional: false,
5910 }]),
5911 returns: Some(union),
5912 rpn: false,
5913 summary: "test-only",
5914 docs: "test-only",
5915 examples: &[],
5916 };
5917 let value = meta_to_value(&meta);
5918 let map = value.as_map().expect("describe value is a map");
5919 let params = map
5920 .get("params")
5921 .expect("params key")
5922 .as_list()
5923 .expect("params is a list");
5924 let first = params[0].as_map().expect("entry is a map");
5925 assert_eq!(
5926 first.get("param_type").and_then(Value::as_str),
5927 Some("STRING|PIPE"),
5928 "param renders the set"
5929 );
5930 assert_eq!(
5931 map.get("returns").and_then(Value::as_str),
5932 Some("STRING|PIPE"),
5933 "returns render the set"
5934 );
5935 }
5936
5937 #[test]
5938 fn describe_entry_renders_handle_payload() {
5939 let meta = FuncMeta {
5943 name: "SCRIPT::FETCH".to_string(),
5944 module: "SCRIPT".to_string(),
5945 kind: FuncKind::Script,
5946 params: Some(vec![]),
5947 returns: Some(TypeTag::HandleOf(std::sync::Arc::new(TypeTag::String))),
5948 rpn: false,
5949 summary: "test-only",
5950 docs: "test-only",
5951 examples: &[],
5952 };
5953 let value = meta_to_value(&meta);
5954 let map = value.as_map().expect("describe value is a map");
5955 assert_eq!(
5956 map.get("returns").and_then(Value::as_str),
5957 Some("HANDLE<STRING>"),
5958 "returns render the payload"
5959 );
5960 }
5961
5962 #[test]
5963 fn describe_entry_carries_optional_flag() {
5964 let meta = FuncMeta {
5968 name: "T::F".to_string(),
5969 module: "T".to_string(),
5970 kind: FuncKind::HostPure,
5971 params: Some(vec![
5972 FuncParam {
5973 name: "url".to_string(),
5974 param_type: Some(TypeTag::String),
5975 allowed: None,
5976 docs: "",
5977 options: None,
5978 optional: false,
5979 },
5980 FuncParam {
5981 name: "options".to_string(),
5982 param_type: Some(TypeTag::Map),
5983 allowed: None,
5984 docs: "",
5985 options: None,
5986 optional: true,
5987 },
5988 ]),
5989 returns: Some(TypeTag::String),
5990 rpn: false,
5991 summary: "test-only",
5992 docs: "test-only",
5993 examples: &[],
5994 };
5995 let value = meta_to_value(&meta);
5996 let map = value.as_map().expect("describe value is a map");
5997 let params = map
5998 .get("params")
5999 .expect("params key")
6000 .as_list()
6001 .expect("params is a list");
6002 assert_eq!(params.len(), 2);
6003 let first = params[0].as_map().expect("entry is a map");
6004 let second = params[1].as_map().expect("entry is a map");
6005 assert_eq!(
6006 first.get("optional").and_then(Value::as_bool),
6007 Some(false),
6008 "required param must read false"
6009 );
6010 assert_eq!(
6011 second.get("optional").and_then(Value::as_bool),
6012 Some(true),
6013 "omittable param must read true"
6014 );
6015 }
6016
6017 #[test]
6018 fn template_twins_mirror_string_paths_and_refuse_pipes() {
6019 let pipe = Value::pipe_fresh();
6025 type TwinCase = (&'static str, Box<dyn Fn() -> DiagnosticResult<Value>>);
6026 let cases: Vec<TwinCase> = vec![
6027 (
6028 "TEXT_TRIM",
6029 Box::new(|| text_trim_string(Value::string(" hello ".to_string()))),
6030 ),
6031 (
6032 "TEXT_TRIM_PREFIX",
6033 Box::new(|| {
6034 text_trim_prefix_string(Value::string("v1".to_string()), "v".to_string())
6035 }),
6036 ),
6037 (
6038 "TEXT_TRIM_SUFFIX",
6039 Box::new(|| {
6040 text_trim_suffix_string(Value::string("a.gz".to_string()), "x".to_string())
6041 }),
6042 ),
6043 (
6044 "TEXT_TO_UPPER",
6045 Box::new(|| text_to_upper_string(Value::string("hi".to_string()))),
6046 ),
6047 (
6048 "TEXT_TO_LOWER",
6049 Box::new(|| text_to_lower_string(Value::string("HI".to_string()))),
6050 ),
6051 (
6052 "TEXT_REPLACE",
6053 Box::new(|| {
6054 text_replace_string(
6055 Value::string("ab".to_string()),
6056 "b".to_string(),
6057 "c".to_string(),
6058 )
6059 }),
6060 ),
6061 (
6062 "TEXT_REPLACE_REGEX",
6063 Box::new(|| {
6064 text_replace_regex_string(
6065 Value::string("ab".to_string()),
6066 "b".to_string(),
6067 "c".to_string(),
6068 )
6069 }),
6070 ),
6071 ];
6072 assert_eq!(cases.len(), 7, "every mirror op needs a twin row");
6073 for (name, run) in &cases {
6074 let value = run().unwrap_or_else(|e| panic!("{name} twin must answer strings: {e:#}"));
6075 assert!(
6076 value.as_str().is_some(),
6077 "{name} twin must answer STRING, got {}",
6078 value.type_name()
6079 );
6080 }
6081 assert_eq!(
6082 text_trim_string(Value::string(" hello ".to_string()))
6083 .expect("trim twin")
6084 .as_str(),
6085 Some("hello")
6086 );
6087 let pipe_cases: Vec<(&str, DiagnosticResult<Value>)> = vec![
6089 ("TEXT_TRIM", text_trim_string(pipe.clone())),
6090 (
6091 "TEXT_TRIM_PREFIX",
6092 text_trim_prefix_string(pipe.clone(), "v".to_string()),
6093 ),
6094 (
6095 "TEXT_TRIM_SUFFIX",
6096 text_trim_suffix_string(pipe.clone(), ".gz".to_string()),
6097 ),
6098 ("TEXT_TO_UPPER", text_to_upper_string(pipe.clone())),
6099 ("TEXT_TO_LOWER", text_to_lower_string(pipe.clone())),
6100 (
6101 "TEXT_REPLACE",
6102 text_replace_string(pipe.clone(), "a".to_string(), "b".to_string()),
6103 ),
6104 (
6105 "TEXT_REPLACE_REGEX",
6106 text_replace_regex_string(pipe.clone(), "a".to_string(), "b".to_string()),
6107 ),
6108 ];
6109 for (name, result) in pipe_cases {
6110 let err = result.expect_err(&format!("{name} twin must refuse PIPE"));
6111 assert!(
6112 format!("{err:#}").contains("step IO"),
6113 "{name} refusal names the missing context: {err:#}"
6114 );
6115 }
6116 }
6117
6118 #[test]
6119 fn shell_words_join_split_round_trip() {
6120 let words = vec![
6124 "gh".to_string(),
6125 "issue".to_string(),
6126 "comment".to_string(),
6127 "with spaces".to_string(),
6128 "it's".to_string(),
6129 "say \"hi\"".to_string(),
6130 "$HOME".to_string(),
6131 "$(whoami)".to_string(),
6132 "C:\\path\\to".to_string(),
6133 "naïve café".to_string(),
6134 "".to_string(),
6135 ];
6136 let joined = shell_words::join(&words);
6137 let back = shell_words::split(&joined).expect("join output must parse");
6138 assert_eq!(back, words);
6139 assert!(shell_words::split("unbalanced \"quote").is_err());
6140 }
6141
6142 struct FakeView {
6146 exports: HashMap<String, Vec<String>>,
6147 targets: HashMap<String, AliasTargets>,
6148 bindings: HashMap<String, HashMap<String, bool>>,
6149 }
6150
6151 impl ModuleGraphView for FakeView {
6152 fn const_exports(&self, file: &str) -> Option<&[String]> {
6153 self.exports.get(file).map(Vec::as_slice)
6154 }
6155
6156 fn alias_targets(&self, file: &str) -> AliasTargets {
6157 self.targets.get(file).cloned().unwrap_or_default()
6158 }
6159
6160 fn binding(&self, file: &str, name: &str) -> BindingPresence {
6161 match self.bindings.get(file).and_then(|names| names.get(name)) {
6162 Some(true) => BindingPresence::Const,
6163 Some(false) => BindingPresence::Let,
6164 None => BindingPresence::Absent,
6165 }
6166 }
6167 }
6168
6169 fn fake_targets(pairs: &[(&str, &str)]) -> AliasTargets {
6170 let mut targets = AliasTargets::new();
6171 for (alias, file) in pairs {
6172 targets
6173 .entry((*alias).to_string())
6174 .or_default()
6175 .push((Some((*file).to_string()), None));
6176 }
6177 targets
6178 }
6179
6180 fn os_guard(os: &str) -> GuardExpr {
6181 GuardExpr::Predicate(oxdock_parser::Guard::Attr {
6182 ns: oxdock_parser::Ns::Os,
6183 key: None,
6184 val: Some(os.to_string()),
6185 })
6186 }
6187
6188 #[test]
6189 fn chase_resolves_bare_and_single_forward() {
6190 let mut view = FakeView {
6193 exports: HashMap::from([
6194 ("a".to_string(), vec!["N".to_string()]),
6195 ("b".to_string(), vec!["A::N".to_string()]),
6196 ("c".to_string(), vec!["B::N".to_string()]),
6197 ]),
6198 targets: HashMap::from([
6199 ("u".to_string(), fake_targets(&[("B", "b")])),
6200 ("b".to_string(), fake_targets(&[("A", "a")])),
6201 ("c".to_string(), fake_targets(&[("B", "b")])),
6202 ]),
6203 bindings: HashMap::new(),
6204 };
6205 assert_eq!(
6206 chase_const_forward(&view, "a", "N", "U::N").expect("bare"),
6207 vec!["a".to_string()]
6208 );
6209 assert_eq!(
6210 chase_const_forward(&view, "b", "N", "U::N").expect("forward"),
6211 vec!["a".to_string()]
6212 );
6213 view.targets
6214 .insert("u".to_string(), fake_targets(&[("C", "c")]));
6215 assert_eq!(
6216 chase_const_forward(&view, "c", "N", "U::N").expect("chain"),
6217 vec!["a".to_string()]
6218 );
6219 }
6220
6221 #[test]
6222 fn chase_prefers_bare_over_forwards() {
6223 let view = FakeView {
6226 exports: HashMap::from([("b".to_string(), vec!["N".to_string(), "A::N".to_string()])]),
6227 targets: HashMap::from([("b".to_string(), fake_targets(&[("A", "a")]))]),
6228 bindings: HashMap::new(),
6229 };
6230 assert_eq!(
6231 chase_const_forward(&view, "b", "N", "U::N").expect("bare wins"),
6232 vec!["b".to_string()]
6233 );
6234 }
6235
6236 #[test]
6237 fn chase_rejects_split_forwards() {
6238 let view = FakeView {
6241 exports: HashMap::from([(
6242 "b".to_string(),
6243 vec!["A::N".to_string(), "C::N".to_string()],
6244 )]),
6245 targets: HashMap::new(),
6246 bindings: HashMap::new(),
6247 };
6248 let err = format!(
6249 "{}",
6250 chase_const_forward(&view, "b", "N", "U::N").expect_err("split must fail")
6251 );
6252 assert!(err.contains("ambiguous CONST `U::N`"), "{err}");
6253 assert!(err.contains("A::N") && err.contains("C::N"), "{err}");
6254 }
6255
6256 #[test]
6257 fn chase_names_broken_link_detail() {
6258 let view = FakeView {
6261 exports: HashMap::from([
6262 ("b".to_string(), vec!["A::M".to_string()]),
6263 ("c".to_string(), vec!["A::P".to_string()]),
6264 ("d".to_string(), vec!["A::Q".to_string()]),
6265 ("a".to_string(), Vec::new()),
6266 ]),
6267 targets: HashMap::from([
6268 ("b".to_string(), fake_targets(&[("A", "a")])),
6269 ("c".to_string(), fake_targets(&[("A", "a")])),
6270 ("d".to_string(), fake_targets(&[("A", "a")])),
6271 ]),
6272 bindings: HashMap::from([(
6273 "a".to_string(),
6274 HashMap::from([("P".to_string(), true), ("Q".to_string(), false)]),
6275 )]),
6276 };
6277 let err = format!(
6278 "{}",
6279 chase_const_forward(&view, "b", "M", "U::M").expect_err("missing must fail")
6280 );
6281 assert!(err.contains("does not resolve"), "{err}");
6282 assert!(err.contains("no import alias `A` exports `M`"), "{err}");
6283 let err = format!(
6284 "{}",
6285 chase_const_forward(&view, "c", "P", "U::P").expect_err("unexported must fail")
6286 );
6287 assert!(
6288 err.contains("holds `P` as CONST but does not export it"),
6289 "{err}"
6290 );
6291 let err = format!(
6292 "{}",
6293 chase_const_forward(&view, "d", "Q", "U::Q").expect_err("LET must fail")
6294 );
6295 assert!(
6296 err.contains("is a LET binding and cannot be exported"),
6297 "{err}"
6298 );
6299 }
6300
6301 #[test]
6302 fn chase_rejects_cycles() {
6303 let view = FakeView {
6306 exports: HashMap::from([
6307 ("a".to_string(), vec!["B::N".to_string()]),
6308 ("b".to_string(), vec!["A::N".to_string()]),
6309 ]),
6310 targets: HashMap::from([
6311 ("a".to_string(), fake_targets(&[("B", "b")])),
6312 ("b".to_string(), fake_targets(&[("A", "a")])),
6313 ]),
6314 bindings: HashMap::new(),
6315 };
6316 let err = format!(
6317 "{}",
6318 chase_const_forward(&view, "a", "N", "U::N").expect_err("cycle must fail")
6319 );
6320 assert!(err.contains("re-export cycle"), "{err}");
6321 }
6322
6323 #[test]
6324 fn chase_unions_disjoint_guard_branches() {
6325 let mut guarded = AliasTargets::new();
6328 guarded.insert(
6329 "A".to_string(),
6330 vec![
6331 (Some("lin".to_string()), Some(os_guard("linux"))),
6332 (Some("mac".to_string()), Some(os_guard("macos"))),
6333 ],
6334 );
6335 let view = FakeView {
6336 exports: HashMap::from([
6337 ("b".to_string(), vec!["A::N".to_string()]),
6338 ("lin".to_string(), vec!["N".to_string()]),
6339 ("mac".to_string(), vec!["N".to_string()]),
6340 ]),
6341 targets: HashMap::from([("b".to_string(), guarded)]),
6342 bindings: HashMap::new(),
6343 };
6344 assert_eq!(
6345 chase_const_forward(&view, "b", "N", "U::N").expect("disjoint branches"),
6346 vec!["lin".to_string(), "mac".to_string()]
6347 );
6348 }
6349
6350 #[test]
6351 fn holder_classification_sorts_and_rejects() {
6352 let view = FakeView {
6355 exports: HashMap::from([
6356 ("b".to_string(), vec!["N".to_string()]),
6357 ("c".to_string(), vec!["N".to_string()]),
6358 ]),
6359 targets: HashMap::new(),
6360 bindings: HashMap::new(),
6361 };
6362 let unit = fake_targets(&[("B", "b"), ("B", "c")]);
6363 match const_holder_files(&view, &unit, "B", "N") {
6364 ConstHolders::Ambiguous { .. } => {}
6365 other => panic!("overlapping holders must be ambiguous, got {other:?}"),
6366 }
6367 match const_holder_files(&view, &unit, "Z", "N") {
6368 ConstHolders::NoAlias => {}
6369 other => panic!("unknown alias must report NoAlias, got {other:?}"),
6370 }
6371 let unit = fake_targets(&[("B", "b")]);
6372 match const_holder_files(&view, &unit, "B", "N") {
6373 ConstHolders::Found(files) => assert_eq!(files, vec!["b".to_string()]),
6374 other => panic!("single holder must be found, got {other:?}"),
6375 }
6376 }
6377}