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, strip_sigil,
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, TypeSnapshot};
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) fn const_ambiguous_message(alias: &str, name: &str, files: &HashSet<String>) -> String {
62 ambiguous_alias_message(alias, name, files).replacen("function", KEYWORD_CONST, 1)
63}
64
65pub(super) enum AliasResolution {
71 Global,
73 Canonical(String),
75 Unknown,
77 Ambiguous {
80 alias: String,
81 base: String,
82 files: HashSet<String>,
83 },
84 Any {
91 base: String,
92 files: HashSet<String>,
93 has_host: bool,
94 },
95}
96
97#[derive(Clone, Debug, PartialEq)]
110pub struct AliasTarget {
111 pub file: Option<String>,
112 pub host: Option<String>,
113 pub guard: Option<GuardExpr>,
114}
115
116pub type AliasTargets = HashMap<String, Vec<AliasTarget>>;
117
118pub(super) trait FuncFrameView {
124 type Hit;
126 fn find_nested(&self, base: &str) -> Option<Self::Hit>;
128 fn find_home(&self, unit: &str, base: &str) -> Option<Self::Hit>;
130 fn find_harvest(&self, unit: &str, base: &str) -> Option<Self::Hit>;
132 fn walk(&self, unit: &str, base: &str) -> Option<Self::Hit> {
134 self.find_nested(base)
135 .or_else(|| self.find_home(unit, base))
136 .or_else(|| self.find_harvest(unit, base))
137 }
138}
139
140pub(super) fn classify_alias_call(
146 unit_targets: &AliasTargets,
147 name: &str,
148 exists: &dyn Fn(&str) -> bool,
149) -> AliasResolution {
150 let Some((alias, base)) = split_qualified(name) else {
151 return AliasResolution::Global;
152 };
153 if alias == SCRIPT_MODULE_NAME {
154 return AliasResolution::Global;
155 }
156 let Some(entries) = unit_targets.get(alias) else {
157 return AliasResolution::Global;
158 };
159 if entries.is_empty() {
160 return AliasResolution::Unknown;
161 }
162 let mut files: Vec<(&str, Vec<Option<&GuardExpr>>)> = Vec::new();
165 let mut host_guards: Vec<Option<&GuardExpr>> = Vec::new();
166 for target in entries {
167 match &target.file {
168 Some(path) => match files.iter_mut().find(|(known, _)| *known == path) {
169 Some((_, guards)) => guards.push(target.guard.as_ref()),
170 None => files.push((path, vec![target.guard.as_ref()])),
171 },
172 None => host_guards.push(target.guard.as_ref()),
173 }
174 }
175 if files.is_empty() {
176 return AliasResolution::Unknown;
177 }
178 let overlaps = |left: &[Option<&GuardExpr>], right: &[Option<&GuardExpr>]| {
179 left.iter()
180 .any(|a| right.iter().any(|b| guards_overlap(*a, *b)))
181 };
182 if files.len() == 1 {
183 let disjoint_host = host_guards
187 .iter()
188 .any(|host| !overlaps(&files[0].1, &[*host]));
189 if !disjoint_host {
190 return AliasResolution::Canonical(file_func_key(files[0].0, base));
191 }
192 let mut all = HashSet::new();
193 all.insert(files[0].0.to_string());
194 return AliasResolution::Any {
195 base: base.to_string(),
196 files: all,
197 has_host: true,
198 };
199 }
200 let mut ambiguous = HashSet::new();
201 for (i, (file, guards)) in files.iter().enumerate() {
202 for (other, other_guards) in files.iter().skip(i + 1) {
203 if overlaps(guards, other_guards)
204 && (exists(&file_func_key(file, base)) || exists(&file_func_key(other, base)))
205 {
206 ambiguous.insert((*file).to_string());
207 ambiguous.insert((*other).to_string());
208 }
209 }
210 }
211 if !ambiguous.is_empty() {
212 return AliasResolution::Ambiguous {
213 alias: alias.to_string(),
214 base: base.to_string(),
215 files: ambiguous,
216 };
217 }
218 let all: HashSet<String> = files.iter().map(|(file, _)| (*file).to_string()).collect();
219 if all.iter().any(|file| exists(&file_func_key(file, base))) {
220 return AliasResolution::Any {
221 base: base.to_string(),
222 files: all,
223 has_host: !host_guards.is_empty(),
224 };
225 }
226 AliasResolution::Unknown
227}
228
229pub(super) fn missing_import_hint<'a>(
239 files: impl IntoIterator<Item = (&'a str, &'a [String])>,
240 unit_targets: &AliasTargets,
241 name: &str,
242) -> Option<String> {
243 let base = match split_qualified(name) {
244 Some((_, base)) => base,
245 None => name,
246 };
247 if base.is_empty() {
248 return None;
249 }
250 let mut exporters: Vec<&str> = files
251 .into_iter()
252 .filter(|(_, exports)| exports.iter().any(|exported| exported == base))
253 .map(|(file, _)| file)
254 .collect();
255 exporters.sort();
256 exporters.dedup();
257 if exporters.is_empty() {
258 return None;
259 }
260 let imported_as = |file: &str| {
262 let mut aliases: Vec<&str> = unit_targets
263 .iter()
264 .filter(|(_, targets)| targets.iter().any(|t| t.file.as_deref() == Some(file)))
265 .map(|(alias, _)| alias.as_str())
266 .collect();
267 aliases.sort();
268 aliases
269 };
270 if exporters.len() == 1 {
271 let file = exporters[0];
272 let aliases = imported_as(file);
273 let import_alias = aliases
278 .iter()
279 .find(|alias| qualify(alias, base) != name)
280 .or(aliases.first())
281 .copied();
282 let suggestion = match import_alias {
283 Some(import_alias) => {
284 let spelling = qualify(import_alias, base);
285 if spelling == name {
286 format!(
289 "file \"{file}\" exports `{base}` but the `{import_alias}` view does not resolve it here"
290 )
291 } else {
292 format!("did you mean `{spelling}`? (file \"{file}\" exports `{base}`)")
293 }
294 }
295 None => {
296 let path = to_forward_slashes(file);
299 format!(
300 "file \"{file}\" exports `{base}`: add `[{KEYWORD_FUNC} {base} {KEYWORD_FROM} \"{path}\"]` to an {KEYWORD_IMPORT}"
301 )
302 }
303 };
304 return Some(format!("; {suggestion}"));
305 }
306 let mut files = exporters.join("\", \"");
307 files.insert(0, '"');
308 files.push('"');
309 Some(format!(
310 "; files {files} export `{base}`: qualify the call with the importing alias"
311 ))
312}
313
314pub(super) fn const_export_covers(entry: &str, name: &str) -> bool {
319 base_name(entry) == name
320}
321
322pub(super) enum BindingPresence {
325 Const,
326 Let,
327 Absent,
328}
329
330pub(super) fn missing_const_hint<S: ModuleGraphView>(
337 view: &S,
338 targets: &AliasTargets,
339 alias: &str,
340 name: &str,
341) -> Option<String> {
342 targets
343 .get(alias)
344 .map(|entries| {
345 entries
346 .iter()
347 .filter_map(|t| t.file.as_ref())
348 .collect::<Vec<_>>()
349 })
350 .unwrap_or_default()
351 .iter()
352 .find_map(|file| match view.binding(file, name) {
353 BindingPresence::Const => Some(format!(
354 "module holds `{name}` as {KEYWORD_CONST} but does not export it: add `{KEYWORD_EXPORT} {KEYWORD_CONST} ${name}`"
355 )),
356 BindingPresence::Let => Some(format!(
357 "`{name}` is a {KEYWORD_LET} binding and cannot be exported: only {KEYWORD_CONST} bindings cross the module boundary"
358 )),
359 BindingPresence::Absent => None,
360 })
361}
362
363pub(super) trait ModuleGraphView {
370 fn const_exports(&self, file: &str) -> Option<&[String]>;
372 fn alias_targets(&self, file: &str) -> AliasTargets;
375 fn binding(&self, file: &str, name: &str) -> BindingPresence;
377}
378
379#[derive(Debug)]
385pub(super) enum ConstHolders {
386 Found(Vec<String>),
389 NoAlias,
391 Ambiguous {
393 alias: String,
394 base: String,
395 files: HashSet<String>,
396 },
397}
398
399fn const_canonical_suffix(name: &str) -> String {
404 format!("{MODULE_SEPARATOR}{name}")
405}
406
407pub(super) fn const_holder_files<S: ModuleGraphView>(
409 view: &S,
410 unit_targets: &AliasTargets,
411 alias: &str,
412 name: &str,
413) -> ConstHolders {
414 let qualified = qualify(alias, name);
415 let suffix = const_canonical_suffix(name);
416 let exports = |canonical: &str| {
420 canonical
421 .strip_suffix(suffix.as_str())
422 .and_then(|file| view.const_exports(file))
423 .is_some_and(|names| names.iter().any(|entry| const_export_covers(entry, name)))
424 };
425 let mut holders = match classify_alias_call(unit_targets, &qualified, &exports) {
426 AliasResolution::Global | AliasResolution::Unknown => return ConstHolders::NoAlias,
427 AliasResolution::Ambiguous { alias, base, files } => {
428 return ConstHolders::Ambiguous { alias, base, files };
429 }
430 AliasResolution::Canonical(canonical) => {
431 let Some(file) = canonical.strip_suffix(suffix.as_str()) else {
432 return ConstHolders::NoAlias;
433 };
434 vec![file.to_string()]
435 }
436 AliasResolution::Any { mut files, .. } => {
437 let mut files: Vec<String> = files.drain().collect();
438 files.sort();
439 files
440 }
441 };
442 holders.retain(|file| {
443 view.const_exports(file)
444 .is_some_and(|names| names.iter().any(|entry| const_export_covers(entry, name)))
445 });
446 ConstHolders::Found(holders)
447}
448
449#[derive(Debug)]
458pub(super) enum ForwardError {
459 Unknown { original: String },
461 Broken {
463 original: String,
464 hop: String,
465 detail: BrokenDetail,
466 },
467 Split { original: String, hops: Vec<String> },
469 Cycle { chain: Vec<String> },
472 HopAmbiguous {
474 alias: String,
475 base: String,
476 files: HashSet<String>,
477 },
478}
479
480#[derive(Debug)]
482pub(super) enum BrokenDetail {
483 UnexportedConst,
485 Let,
487 Absent,
489}
490
491impl std::fmt::Display for ForwardError {
492 fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
493 match self {
494 ForwardError::Unknown { original } => write!(f, "unknown {KEYWORD_CONST} `{original}`"),
495 ForwardError::Broken {
496 original,
497 hop,
498 detail,
499 } => {
500 let base = base_name(hop);
501 let detail = match detail {
502 BrokenDetail::UnexportedConst => format!(
503 "module holds `{base}` as {KEYWORD_CONST} but does not export it: add `{KEYWORD_EXPORT} {KEYWORD_CONST} ${base}`"
504 ),
505 BrokenDetail::Let => format!(
506 "`{base}` is a {KEYWORD_LET} binding and cannot be exported: only {KEYWORD_CONST} bindings cross the module boundary"
507 ),
508 BrokenDetail::Absent => {
509 let (forward, _) = split_qualified(hop).unwrap_or(("", base));
510 format!("no import alias `{forward}` exports `{base}`")
511 }
512 };
513 write!(
514 f,
515 "unknown {KEYWORD_CONST} `{original}`: re-export `{hop}` does not resolve: {detail}"
516 )
517 }
518 ForwardError::Split { original, hops } => write!(
519 f,
520 "ambiguous {KEYWORD_CONST} `{original}`: re-exported from {}; export exactly one source",
521 hops.join(" and ")
522 ),
523 ForwardError::Cycle { chain } => {
524 write!(
525 f,
526 "{KEYWORD_CONST} re-export cycle detected: {}",
527 chain.join(" -> ")
528 )
529 }
530 ForwardError::HopAmbiguous { alias, base, files } => {
531 write!(f, "{}", const_ambiguous_message(alias, base, files))
532 }
533 }
534 }
535}
536
537fn forward_failed(err: ForwardError) -> Diagnostic {
542 std_diag::import_const_forward_failed(&err.to_string())
543}
544
545pub(super) fn chase_const_forward<S: ModuleGraphView>(
552 view: &S,
553 file: &str,
554 name: &str,
555 original: &str,
556) -> DiagnosticResult<Vec<String>> {
557 let mut terminals: Vec<String> = Vec::new();
558 chase_from(view, file, name, original, &mut Vec::new(), &mut terminals)?;
559 terminals.sort();
560 terminals.dedup();
561 Ok(terminals)
562}
563
564pub(super) enum ConstWalkError {
571 NoAlias,
573 HolderAmbiguous {
575 alias: String,
576 base: String,
577 files: HashSet<String>,
578 },
579 Forward(Diagnostic),
581}
582
583pub(super) struct ConstTerminals {
587 pub holders: Vec<String>,
588 pub terminals: Vec<String>,
589}
590
591pub(super) fn const_terminal_files<S: ModuleGraphView>(
597 view: &S,
598 unit_targets: &AliasTargets,
599 alias: &str,
600 name: &str,
601 qualified: &str,
602) -> Result<ConstTerminals, ConstWalkError> {
603 let holders = match const_holder_files(view, unit_targets, alias, name) {
604 ConstHolders::Found(holders) => holders,
605 ConstHolders::NoAlias => return Err(ConstWalkError::NoAlias),
606 ConstHolders::Ambiguous { alias, base, files } => {
607 return Err(ConstWalkError::HolderAmbiguous { alias, base, files });
608 }
609 };
610 let mut terminals: Vec<String> = Vec::new();
611 for file in &holders {
612 match chase_const_forward(view, file, name, qualified) {
613 Ok(mut found) => terminals.append(&mut found),
614 Err(diag) => return Err(ConstWalkError::Forward(diag)),
615 }
616 }
617 terminals.sort();
618 terminals.dedup();
619 Ok(ConstTerminals { holders, terminals })
620}
621
622pub(super) fn unified_const_tag(
627 tags: Vec<TypeTag>,
628 holders: Vec<String>,
629) -> Result<TypeTag, HashSet<String>> {
630 let Some(first) = tags.first().cloned() else {
631 return Err(holders.into_iter().collect());
632 };
633 let first_render = render_structural(&first);
634 if tags
635 .iter()
636 .all(|tag| render_structural(tag) == first_render)
637 {
638 Ok(first)
639 } else {
640 Err(holders.into_iter().collect())
641 }
642}
643
644fn chase_from<S: ModuleGraphView>(
645 view: &S,
646 current: &str,
647 name: &str,
648 original: &str,
649 chain: &mut Vec<String>,
650 terminals: &mut Vec<String>,
651) -> DiagnosticResult<()> {
652 let suffix = const_canonical_suffix(name);
653 let covering = |canonical: &str| {
654 canonical
655 .strip_suffix(suffix.as_str())
656 .and_then(|file| view.const_exports(file))
657 .is_some_and(|names| names.iter().any(|entry| const_export_covers(entry, name)))
658 };
659 let mut current = current.to_string();
660 loop {
661 let Some(names) = view.const_exports(current.as_str()) else {
662 return Err(forward_failed(ForwardError::Unknown {
663 original: original.to_string(),
664 }));
665 };
666 if names.iter().any(|entry| entry == name) {
667 terminals.push(current);
668 return Ok(());
669 }
670 let mut aliases: Vec<&str> = Vec::new();
671 for entry in names {
672 if let Some((alias, base)) = split_qualified(entry)
673 && base == name
674 && !aliases.contains(&alias)
675 {
676 aliases.push(alias);
677 }
678 }
679 if aliases.is_empty() {
680 if chain.is_empty() {
681 return Err(forward_failed(ForwardError::Unknown {
682 original: original.to_string(),
683 }));
684 }
685 let hop = chain.last().expect("chain never empty").clone();
686 let detail = match view.binding(current.as_str(), name) {
687 BindingPresence::Const => BrokenDetail::UnexportedConst,
688 BindingPresence::Let => BrokenDetail::Let,
689 BindingPresence::Absent => BrokenDetail::Absent,
690 };
691 return Err(forward_failed(ForwardError::Broken {
692 original: original.to_string(),
693 hop,
694 detail,
695 }));
696 }
697 if aliases.len() > 1 {
698 let mut hops: Vec<String> = aliases.iter().map(|alias| qualify(alias, name)).collect();
699 hops.sort();
700 return Err(forward_failed(ForwardError::Split {
701 original: original.to_string(),
702 hops,
703 }));
704 }
705 let forward = aliases[0];
706 let hop = qualify(forward, name);
707 if chain.contains(&hop) {
708 chain.push(hop);
709 return Err(forward_failed(ForwardError::Cycle {
710 chain: chain.clone(),
711 }));
712 }
713 chain.push(hop.clone());
714 let targets = view.alias_targets(current.as_str());
715 match classify_alias_call(&targets, &hop, &covering) {
716 AliasResolution::Global | AliasResolution::Unknown => {
717 return Err(forward_failed(ForwardError::Broken {
718 original: original.to_string(),
719 hop,
720 detail: BrokenDetail::Absent,
721 }));
722 }
723 AliasResolution::Ambiguous { alias, base, files } => {
724 return Err(forward_failed(ForwardError::HopAmbiguous {
725 alias,
726 base,
727 files,
728 }));
729 }
730 AliasResolution::Canonical(canonical) => {
731 let Some(next) = canonical.strip_suffix(suffix.as_str()) else {
732 return Err(forward_failed(ForwardError::Unknown {
733 original: original.to_string(),
734 }));
735 };
736 current = next.to_string();
737 }
738 AliasResolution::Any { mut files, .. } => {
739 let mut covering: Vec<String> = files
740 .drain()
741 .filter(|file| {
742 view.const_exports(file).is_some_and(|names| {
743 names.iter().any(|entry| const_export_covers(entry, name))
744 })
745 })
746 .collect();
747 covering.sort();
748 match covering.len() {
749 0 => {
750 return Err(forward_failed(ForwardError::Broken {
751 original: original.to_string(),
752 hop,
753 detail: BrokenDetail::Absent,
754 }));
755 }
756 1 => {
757 current = covering.into_iter().next().expect("len checked");
758 }
759 _ => {
760 for branch in covering {
761 let mut branch_chain = chain.clone();
762 chase_from(
763 view,
764 branch.as_str(),
765 name,
766 original,
767 &mut branch_chain,
768 terminals,
769 )?;
770 }
771 return Ok(());
772 }
773 }
774 }
775 }
776 }
777}
778pub(super) fn disjoint_template_script_visible(
786 base: &str,
787 files: &HashSet<String>,
788 has_host: bool,
789 exists: &dyn Fn(&str) -> bool,
790) -> bool {
791 !has_host && !files.is_empty() && files.iter().all(|file| exists(&file_func_key(file, base)))
792}
793
794pub(super) fn disjoint_alias_placeholder_miss(
801 module: &str,
802 name: &str,
803 base: &str,
804 files: &HashSet<String>,
805 has_host: bool,
806 is_script: &dyn Fn(&str) -> bool,
807) -> String {
808 let script = disjoint_template_script_visible(base, files, has_host, is_script);
809 describe_placeholder_miss(module, name, script, false, !script)
810 .expect("disjoint miss always renders")
811}
812
813pub(super) fn spellings_for_defining_file(
820 unit_targets: &AliasTargets,
821 defining: &str,
822 base: &str,
823 is_script: &dyn Fn(&str) -> bool,
824) -> (Vec<String>, Vec<(String, HashSet<String>)>) {
825 let mut direct = Vec::new();
826 let mut ambiguous = Vec::new();
827 for (alias, files) in unit_targets {
828 if !files.iter().any(|t| t.file.as_deref() == Some(defining)) {
829 continue;
830 }
831 let spelling = qualify(alias, base);
832 match classify_alias_call(unit_targets, &spelling, &|key| {
833 key == file_func_key(defining, base)
834 }) {
835 AliasResolution::Canonical(_) => direct.push(spelling),
836 AliasResolution::Ambiguous { files, .. } => {
837 ambiguous.push((spelling, files));
838 }
839 AliasResolution::Any {
840 base,
841 files,
842 has_host,
843 } => {
844 if disjoint_template_script_visible(&base, &files, has_host, is_script) {
845 direct.push(spelling);
846 }
847 }
848 AliasResolution::Global | AliasResolution::Unknown => {}
849 }
850 }
851 (direct, ambiguous)
852}
853
854impl FuncKind {
855 pub fn label(&self) -> &'static str {
856 match self {
857 FuncKind::Script => "script",
858 FuncKind::HostCtx | FuncKind::HostPure => "host",
859 }
860 }
861}
862
863#[derive(Debug, Clone)]
881pub struct FuncParam {
882 pub name: String,
883 pub param_type: Option<TypeTag>,
884 pub allowed: Option<&'static [&'static str]>,
885 pub docs: &'static str,
886 pub options: Option<&'static [ParamOption]>,
887 pub optional: bool,
888}
889
890pub fn required_arity(params: &[FuncParam]) -> usize {
895 params
896 .iter()
897 .rev()
898 .take_while(|param| param.optional)
899 .fold(params.len(), |count, _| count - 1)
900}
901
902pub fn fill_optional_args(params: &[FuncParam], mut values: Vec<Value>) -> Vec<Value> {
907 assert!(
908 values.len() <= params.len(),
909 "arity gate must run before fill_optional_args"
910 );
911 assert!(
912 values.len() >= required_arity(params),
913 "arity gate must run before fill_optional_args"
914 );
915 while values.len() < params.len() {
916 values.push(Value::map(BTreeMap::new()));
917 }
918 values
919}
920
921#[derive(Debug, Clone)]
928pub struct ParamOption {
929 pub name: &'static str,
930 pub value: TypeTag,
931 pub required: bool,
932 pub default: Option<&'static str>,
933}
934
935#[derive(Debug, Clone)]
941pub struct FuncMeta {
942 pub name: String,
943 pub module: String,
947 pub kind: FuncKind,
948 pub params: Option<Vec<FuncParam>>,
949 pub returns: Option<TypeTag>,
950 pub rpn: bool,
951 pub summary: &'static str,
952 pub docs: &'static str,
953 pub examples: &'static [crate::Example],
959}
960
961pub type PureFn = Arc<dyn Fn(Vec<Value>) -> DiagnosticResult<Value> + Send + Sync>;
964
965pub type NativeFn<P> =
967 Arc<dyn Fn(&mut StepCtx<P>, Vec<Value>) -> DiagnosticResult<Value> + Send + Sync>;
968
969pub trait OxDockFn<P: ProcessManager> {
973 fn registration() -> HostRegistration<P>;
976}
977
978pub enum HostRegistration<P: ProcessManager> {
987 Stateful {
988 name: String,
989 meta: FuncMeta,
990 func: NativeFn<P>,
991 },
992 Pure {
993 name: String,
994 meta: FuncMeta,
995 func: PureFn,
996 },
997 Both {
998 name: String,
999 meta: FuncMeta,
1000 func: NativeFn<P>,
1001 template: PureFn,
1002 },
1003}
1004
1005impl<P: ProcessManager> Clone for HostRegistration<P> {
1008 fn clone(&self) -> Self {
1009 match self {
1010 HostRegistration::Stateful { name, meta, func } => HostRegistration::Stateful {
1011 name: name.clone(),
1012 meta: meta.clone(),
1013 func: Arc::clone(func),
1014 },
1015 HostRegistration::Pure { name, meta, func } => HostRegistration::Pure {
1016 name: name.clone(),
1017 meta: meta.clone(),
1018 func: Arc::clone(func),
1019 },
1020 HostRegistration::Both {
1021 name,
1022 meta,
1023 func,
1024 template,
1025 } => HostRegistration::Both {
1026 name: name.clone(),
1027 meta: meta.clone(),
1028 func: Arc::clone(func),
1029 template: Arc::clone(template),
1030 },
1031 }
1032 }
1033}
1034
1035impl<P: ProcessManager> HostRegistration<P> {
1036 pub fn name(&self) -> &str {
1042 match self {
1043 HostRegistration::Stateful { name, .. } => name,
1044 HostRegistration::Pure { name, .. } => name,
1045 HostRegistration::Both { name, .. } => name,
1046 }
1047 }
1048
1049 pub fn meta(&self) -> &FuncMeta {
1052 match self {
1053 HostRegistration::Stateful { meta, .. } => meta,
1054 HostRegistration::Pure { meta, .. } => meta,
1055 HostRegistration::Both { meta, .. } => meta,
1056 }
1057 }
1058}
1059
1060#[derive(Debug, Clone)]
1066pub(super) struct FuncDefData {
1067 pub(super) params: Vec<(String, TypeTag, bool)>,
1068 pub(super) return_type: TypeTag,
1069 pub(super) return_spelling: String,
1070 pub(super) is_async: bool,
1071 pub(super) body: Vec<Step>,
1072 pub(super) module: Option<String>,
1077 pub(super) def_jail: Option<(WorkspaceSelection, GuardedPath)>,
1083}
1084
1085pub fn optional_zero_value(tag: &TypeTag) -> DiagnosticResult<Value> {
1093 match tag {
1094 TypeTag::Bool => Ok(Value::bool(false)),
1095 TypeTag::String | TypeTag::Any => Ok(Value::string(String::new())),
1096 TypeTag::Int => Ok(Value::int(0)),
1097 TypeTag::Float => Ok(Value::float(0.0)),
1098 TypeTag::List | TypeTag::ListOf(_) => Ok(Value::list(Vec::new())),
1099 TypeTag::Map | TypeTag::MapOf(_) => Ok(Value::map(BTreeMap::new())),
1100 TypeTag::Record(fields)
1101 if fields
1102 .iter()
1103 .all(|field| field.optional || field.default.is_some()) =>
1104 {
1105 Ok(Value::map(BTreeMap::new()))
1106 }
1107 other => Err(std_diag::func_zero_value_missing(
1108 &oxdock_parser::render_structural(other),
1109 )),
1110 }
1111}
1112
1113pub fn resolve_script_params<P: ProcessManager>(
1119 state: &ExecState<P>,
1120 func_name: &str,
1121 params: &[(String, String, bool)],
1122) -> DiagnosticResult<Vec<(String, TypeTag, bool)>> {
1123 resolve_script_params_for_unit(
1124 state,
1125 &super::import::active_unit_key(state),
1126 func_name,
1127 params,
1128 )
1129}
1130
1131impl TypeSnapshot {
1139 pub fn resolve_script_params(
1140 &self,
1141 unit: &str,
1142 alias_targets: &AliasTargets,
1143 type_exports: &HashMap<String, Vec<String>>,
1144 func_name: &str,
1145 params: &[(String, String, bool)],
1146 ) -> DiagnosticResult<Vec<(String, TypeTag, bool)>> {
1147 let mut resolved = Vec::with_capacity(params.len());
1148 for (pname, ptype, optional) in params {
1149 let clean = strip_sigil(pname).to_string();
1150 let tag = self
1151 .resolve_tag_with_targets(unit, alias_targets, type_exports, ptype)
1152 .map_err(|err| std_diag::func_param_type(func_name, err))?;
1153 self.check_declaration_tag(&format!("function `{func_name}` param `${clean}`"), &tag)?;
1154 if *optional {
1155 optional_zero_value(&tag)
1156 .map(|_| ())
1157 .map_err(|err| std_diag::func_optional_param(func_name, &clean, err))?;
1158 }
1159 resolved.push((clean, tag, *optional));
1160 }
1161 Ok(resolved)
1162 }
1163}
1164
1165pub fn resolve_script_params_with_targets<P: ProcessManager>(
1166 state: &ExecState<P>,
1167 unit: &str,
1168 alias_targets: &AliasTargets,
1169 type_exports: &HashMap<String, Vec<String>>,
1170 func_name: &str,
1171 params: &[(String, String, bool)],
1172) -> DiagnosticResult<Vec<(String, TypeTag, bool)>> {
1173 state
1174 .type_env
1175 .resolve_script_params(unit, alias_targets, type_exports, func_name, params)
1176}
1177
1178pub fn resolve_script_params_for_unit<P: ProcessManager>(
1181 state: &ExecState<P>,
1182 unit: &str,
1183 func_name: &str,
1184 params: &[(String, String, bool)],
1185) -> DiagnosticResult<Vec<(String, TypeTag, bool)>> {
1186 let alias_targets = super::import::unit_alias_targets(state, unit);
1187 let type_exports = ExecState::<P>::module_type_exports(state);
1188 resolve_script_params_with_targets(
1189 state,
1190 unit,
1191 &alias_targets,
1192 &type_exports,
1193 func_name,
1194 params,
1195 )
1196}
1197
1198pub fn check_script_param_tags(
1201 func_name: &str,
1202 params: &[(String, TypeTag, bool)],
1203) -> DiagnosticResult<()> {
1204 for (pname, tag, optional) in params {
1205 if *optional {
1206 optional_zero_value(tag)
1207 .map(|_| ())
1208 .map_err(|err| std_diag::func_optional_param(func_name, pname, err))?;
1209 }
1210 }
1211 Ok(())
1212}
1213
1214pub(super) enum FuncBody<P: ProcessManager> {
1219 Script(FuncDefData),
1220 Pure(PureFn),
1221 Ctx(NativeFn<P>),
1222 Both { pure: PureFn, ctx: NativeFn<P> },
1223}
1224
1225impl<P: ProcessManager> Clone for FuncBody<P> {
1227 fn clone(&self) -> Self {
1228 match self {
1229 FuncBody::Script(def) => FuncBody::Script(def.clone()),
1230 FuncBody::Pure(func) => FuncBody::Pure(Arc::clone(func)),
1231 FuncBody::Ctx(func) => FuncBody::Ctx(Arc::clone(func)),
1232 FuncBody::Both { pure, ctx } => FuncBody::Both {
1233 pure: Arc::clone(pure),
1234 ctx: Arc::clone(ctx),
1235 },
1236 }
1237 }
1238}
1239
1240pub(super) struct FuncEntry<P: ProcessManager> {
1244 pub(super) meta: FuncMeta,
1245 pub(super) body: FuncBody<P>,
1246}
1247
1248impl<P: ProcessManager> Clone for FuncEntry<P> {
1250 fn clone(&self) -> Self {
1251 Self {
1252 meta: self.meta.clone(),
1253 body: self.body.clone(),
1254 }
1255 }
1256}
1257
1258struct ScopeFrame<P: ProcessManager> {
1261 defined: HashSet<String>,
1262 shadowed: Vec<(String, FuncEntry<P>)>,
1263}
1264
1265impl<P: ProcessManager> Clone for ScopeFrame<P> {
1267 fn clone(&self) -> Self {
1268 Self {
1269 defined: self.defined.clone(),
1270 shadowed: self.shadowed.clone(),
1271 }
1272 }
1273}
1274
1275pub type PureTable = HashMap<String, HashMap<String, PureFn>>;
1285
1286pub fn placeholder_resolver(table: Arc<PureTable>) -> oxdock_process::PlaceholderCall {
1295 Arc::new(move |module, func, args| {
1296 let callee = table
1297 .get(module)
1298 .and_then(|entries| entries.get(func))
1299 .ok_or_else(|| {
1300 let mut known: Vec<String> = table
1301 .iter()
1302 .flat_map(|(m, entries)| {
1303 entries
1304 .keys()
1305 .map(move |f| format!("{m}{MODULE_SEPARATOR}{f}"))
1306 })
1307 .collect();
1308 known.sort();
1309 std_diag::func_placeholder_unknown(module, func, &known)
1310 })?;
1311 callee(args)
1312 })
1313}
1314
1315pub(super) fn describe_placeholder_miss(
1322 module: &str,
1323 name: &str,
1324 is_script: bool,
1325 is_stateful: bool,
1326 alias_known: bool,
1327) -> Option<String> {
1328 let qualified = qualify(module, name);
1329 if is_script {
1330 let call = if module == SCRIPT_MODULE_NAME {
1331 format!("{name}(...)")
1332 } else {
1333 format!("{qualified}(...)")
1334 };
1335 return Some(format!(
1336 "placeholder function '{qualified}' is a script function and cannot run in {{{{ }}}}; bind the result first with {KEYWORD_LET} $v = {call} then interpolate {{{{ $v }}}}"
1337 ));
1338 }
1339 if is_stateful {
1340 return Some(format!(
1341 "placeholder function '{qualified}' is stateful and cannot run in {{{{ }}}}; capture it first with {KEYWORD_LET} then interpolate {{{{ $v }}}}"
1342 ));
1343 }
1344 if alias_known {
1345 return Some(format!(
1346 "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 }}}}"
1347 ));
1348 }
1349 None
1350}
1351
1352pub(super) struct PlaceholderClasses {
1355 pub script: HashSet<String>,
1356 pub stateful: HashSet<String>,
1357 pub aliases: HashSet<String>,
1358 pub ambiguous: HashMap<String, HashSet<String>>,
1360}
1361
1362impl PlaceholderClasses {
1363 pub(super) fn describe(&self, module: &str, name: &str) -> Option<String> {
1364 let qualified = qualify(module, name);
1365 if let Some(files) = self.ambiguous.get(&qualified) {
1366 return Some(ambiguous_alias_message(module, name, files));
1367 }
1368 describe_placeholder_miss(
1369 module,
1370 name,
1371 self.script.contains(&qualified),
1372 self.stateful.contains(&qualified),
1373 self.aliases.contains(module),
1374 )
1375 }
1376}
1377
1378pub struct FunctionRegistry<P: ProcessManager> {
1379 entries: HashMap<String, FuncEntry<P>>,
1380 scopes: Vec<ScopeFrame<P>>,
1381 pure_shared: Arc<PureTable>,
1382 script_docs: HashMap<String, (String, String)>,
1386}
1387
1388impl<P: ProcessManager> FunctionRegistry<P> {
1389 pub(super) fn with_builtins() -> Self {
1390 let mut reg = Self {
1391 entries: HashMap::new(),
1392 pure_shared: Arc::new(HashMap::new()),
1393 script_docs: HashMap::new(),
1394 scopes: vec![ScopeFrame {
1395 defined: HashSet::new(),
1396 shadowed: Vec::new(),
1397 }],
1398 };
1399 for host in Self::builtin_registrations() {
1403 match host {
1404 HostRegistration::Stateful { name, meta, func } => {
1405 reg.insert_qualified(STD_MODULE_NAME, name, meta, FuncBody::Ctx(func));
1406 }
1407 HostRegistration::Pure { name, meta, func } => {
1408 reg.insert_qualified(STD_MODULE_NAME, name, meta, FuncBody::Pure(func));
1409 }
1410 HostRegistration::Both {
1411 name,
1412 meta,
1413 func,
1414 template,
1415 } => {
1416 reg.insert_qualified(
1417 STD_MODULE_NAME,
1418 name,
1419 meta,
1420 FuncBody::Both {
1421 pure: template,
1422 ctx: func,
1423 },
1424 );
1425 }
1426 }
1427 }
1428 reg
1429 }
1430
1431 pub(super) fn builtin_registrations() -> Vec<HostRegistration<P>> {
1436 vec![
1437 Int::registration(),
1438 Float::registration(),
1439 BoolConvert::registration(),
1440 BoolOr::registration(),
1441 FormatByteCount::registration(),
1442 ParseByteCount::registration(),
1443 FormatDuration::registration(),
1444 ParseDuration::registration(),
1445 Types::registration(),
1446 TypeDescribe::registration(),
1447 Glob::registration(),
1448 LoadToml::registration(),
1449 LoadJson::registration(),
1450 HashSha256::registration(),
1451 Cwd::registration(),
1452 ParseToml::registration(),
1453 ParseJson::registration(),
1454 PathType::registration(),
1455 PathWritable::registration(),
1456 IsExec::registration(),
1457 IsFile::registration(),
1458 IsDir::registration(),
1459 Exists::registration(),
1460 HasKey::registration(),
1461 Get::registration(),
1462 MapSet::registration(),
1463 MergeMaps::registration(),
1464 Base64Encode::registration(),
1465 Base64Decode::registration(),
1466 Rand::registration(),
1467 ToJson::registration(),
1468 TypeOf::registration(),
1469 Functions::registration(),
1470 Describe::registration(),
1471 IsMain::registration(),
1472 IsTerminal::registration(),
1473 Eof::registration(),
1474 TaskPoll::registration(),
1475 Version::registration(),
1476 Interpreter::registration(),
1477 Argv::registration(),
1478 ParseArgs::registration(),
1479 ParseFlags::registration(),
1480 ParsePositionals::registration(),
1481 TextTrim::registration(),
1482 TextTrimPrefix::registration(),
1483 TextTrimSuffix::registration(),
1484 PathJoin::registration(),
1485 PathBase::registration(),
1486 PathRel::registration(),
1487 TextToUpper::registration(),
1488 TextToLower::registration(),
1489 TextReplace::registration(),
1490 TextReplaceRegex::registration(),
1491 TextSplit::registration(),
1492 TextJoin::registration(),
1493 TextLines::registration(),
1494 TextFields::registration(),
1495 TextMatch::registration(),
1496 TextExtract::registration(),
1497 TextStartsWith::registration(),
1498 TextEndsWith::registration(),
1499 Contains::registration(),
1500 Unique::registration(),
1501 Len::registration(),
1502 TextCount::registration(),
1503 TextCountMatches::registration(),
1504 TextGrep::registration(),
1505 TextLinesRange::registration(),
1506 SemaphoreNew::registration(),
1507 SemaphoreTryAcquire::registration(),
1508 SemaphoreAvailable::registration(),
1509 ShellSplitArgs::registration(),
1510 ShellJoinArgs::registration(),
1511 ]
1512 }
1513
1514 pub(super) fn keys(&self) -> HashSet<String> {
1517 self.entries.keys().cloned().collect()
1518 }
1519
1520 pub(super) fn get(&self, name: &str) -> Option<FuncEntry<P>> {
1522 self.entries.get(name).cloned()
1523 }
1524
1525 pub(super) fn scope_depth(&self) -> usize {
1529 self.scopes.len()
1530 }
1531
1532 pub(super) fn get_scoped(&self, base: &str, floor: usize) -> Option<FuncEntry<P>> {
1541 let qualified = qualify(SCRIPT_MODULE_NAME, base);
1542 let len = self.scopes.len();
1543 let start = floor.min(len);
1544 for frame in self.scopes[start..].iter().rev() {
1545 if frame.defined.contains(&qualified) {
1546 return self.entries.get(&qualified).cloned();
1547 }
1548 }
1549 None
1550 }
1551
1552 pub(super) fn describe_unit_placeholder_miss(
1558 &self,
1559 unit_targets: &AliasTargets,
1560 module: &str,
1561 name: &str,
1562 ) -> Option<String> {
1563 let qualified = qualify(module, name);
1564 match classify_alias_call(unit_targets, &qualified, &|key| {
1569 self.entries.contains_key(key)
1570 }) {
1571 AliasResolution::Canonical(canonical) => {
1572 if let Some(entry) = self.entries.get(&canonical) {
1573 if let Some(miss) = Self::placeholder_miss_for_body(module, name, &entry.body) {
1574 return Some(miss);
1575 }
1576 None
1577 } else {
1578 describe_placeholder_miss(module, name, false, false, true)
1579 }
1580 }
1581 AliasResolution::Global => {
1582 if let Some(entry) = self.entries.get(&qualified) {
1583 if let Some(miss) = Self::placeholder_miss_for_body(module, name, &entry.body) {
1587 return Some(miss);
1588 }
1589 }
1590 None
1591 }
1592 AliasResolution::Ambiguous { files, .. } => {
1593 Some(ambiguous_alias_message(module, name, &files))
1594 }
1595 AliasResolution::Unknown => describe_placeholder_miss(module, name, false, false, true),
1596 AliasResolution::Any {
1602 base,
1603 files,
1604 has_host,
1605 } => Some(disjoint_alias_placeholder_miss(
1606 module,
1607 name,
1608 &base,
1609 &files,
1610 has_host,
1611 &|key| matches!(self.entries.get(key), Some(entry) if matches!(entry.body, FuncBody::Script(_))),
1612 )),
1613 }
1614 }
1615
1616 fn placeholder_miss_for_body(module: &str, name: &str, body: &FuncBody<P>) -> Option<String> {
1620 match body {
1621 FuncBody::Script(_) => describe_placeholder_miss(module, name, true, false, false),
1622 FuncBody::Ctx(_) => describe_placeholder_miss(module, name, false, true, false),
1623 FuncBody::Pure(_) | FuncBody::Both { .. } => None,
1624 }
1625 }
1626
1627 pub(super) fn placeholder_snapshot(&self, unit_targets: &AliasTargets) -> PlaceholderClasses {
1631 let mut script = HashSet::new();
1632 let mut stateful = HashSet::new();
1633 let mut ambiguous: HashMap<String, HashSet<String>> = HashMap::new();
1634 for (key, entry) in self.entries.iter() {
1635 let Some((module, base)) = split_qualified(key) else {
1636 continue;
1637 };
1638 match &entry.body {
1639 FuncBody::Script(def) => {
1640 if module == SCRIPT_MODULE_NAME {
1641 script.insert(key.clone());
1643 continue;
1644 }
1645 let defining = def.module.as_deref().unwrap_or(module);
1653 let (direct, ambiguous_here) = spellings_for_defining_file(
1654 unit_targets,
1655 defining,
1656 base,
1657 &|key| matches!(self.entries.get(key), Some(entry) if matches!(entry.body, FuncBody::Script(_))),
1658 );
1659 script.extend(direct);
1660 for (spelling, files) in ambiguous_here {
1661 ambiguous.entry(spelling).or_default().extend(files);
1662 }
1663 }
1664 FuncBody::Ctx(_) => {
1665 stateful.insert(key.clone());
1666 }
1667 FuncBody::Pure(_) | FuncBody::Both { .. } => {}
1668 }
1669 }
1670 let aliases = unit_targets.keys().cloned().collect();
1671 PlaceholderClasses {
1672 script,
1673 stateful,
1674 aliases,
1675 ambiguous,
1676 }
1677 }
1678
1679 fn insert_native(&mut self, name: String, meta: FuncMeta, body: FuncBody<P>) {
1680 self.entries.insert(name, FuncEntry { meta, body });
1681 self.rebuild_pure_shared();
1682 }
1683
1684 fn rebuild_pure_shared(&mut self) {
1690 let mut table: PureTable = HashMap::new();
1691 for (name, entry) in &self.entries {
1692 let func = match &entry.body {
1693 FuncBody::Pure(func) => func,
1694 FuncBody::Both { pure, .. } => pure,
1695 FuncBody::Script(_) | FuncBody::Ctx(_) => continue,
1696 };
1697 if let Some((module, base)) = split_qualified(name) {
1698 table
1699 .entry(module.to_string())
1700 .or_default()
1701 .insert(base.to_string(), Arc::clone(func));
1702 }
1703 }
1704 self.pure_shared = Arc::new(table);
1705 }
1706
1707 fn insert_qualified(
1711 &mut self,
1712 module: &str,
1713 base: String,
1714 mut meta: FuncMeta,
1715 body: FuncBody<P>,
1716 ) {
1717 meta.name = qualify(module, &base);
1718 meta.module = module.to_string();
1719 if self.entries.contains_key(&meta.name) {
1724 panic!("duplicate function registration `{}`", meta.name);
1725 }
1726 self.insert_native(meta.name.clone(), meta, body);
1727 }
1728
1729 pub(super) fn register_host(
1730 &mut self,
1731 module: &str,
1732 name: String,
1733 mut meta: FuncMeta,
1734 func: NativeFn<P>,
1735 ) {
1736 meta.kind = FuncKind::HostCtx;
1737 self.insert_qualified(module, name, meta, FuncBody::Ctx(func));
1738 }
1739
1740 pub(super) fn register_pure_host(
1741 &mut self,
1742 module: &str,
1743 name: String,
1744 mut meta: FuncMeta,
1745 func: PureFn,
1746 ) {
1747 meta.kind = FuncKind::HostPure;
1748 self.insert_qualified(module, name, meta, FuncBody::Pure(func));
1749 }
1750
1751 pub(super) fn register_both_host(
1752 &mut self,
1753 module: &str,
1754 name: String,
1755 mut meta: FuncMeta,
1756 func: NativeFn<P>,
1757 template: PureFn,
1758 ) {
1759 meta.kind = FuncKind::HostCtx;
1760 self.insert_qualified(
1761 module,
1762 name,
1763 meta,
1764 FuncBody::Both {
1765 pure: template,
1766 ctx: func,
1767 },
1768 );
1769 }
1770
1771 #[allow(clippy::too_many_arguments)]
1776 pub(super) fn define_script(
1777 &mut self,
1778 name: &str,
1779 params: &[(String, TypeTag, bool)],
1780 return_type: TypeTag,
1781 return_spelling: &str,
1782 is_async: bool,
1783 body: &[Step],
1784 module: Option<&str>,
1785 def_jail: Option<(WorkspaceSelection, GuardedPath)>,
1786 ) -> DiagnosticResult<()> {
1787 let qualified = qualify(SCRIPT_MODULE_NAME, name);
1788 let shadowable = matches!(
1789 self.entries.get(&qualified).map(|entry| &entry.body),
1790 Some(FuncBody::Script(_))
1791 );
1792 let reserved = self.entries.iter().any(|(key, entry)| {
1797 split_qualified(key).is_some_and(|(_, base)| base == name)
1798 && !matches!(entry.body, FuncBody::Script(_))
1799 });
1800 if reserved && !shadowable {
1801 return Err(std_diag::func_shadow_reserved(name));
1802 }
1803 if self
1804 .scopes
1805 .last()
1806 .is_some_and(|frame| frame.defined.contains(&qualified))
1807 {
1808 return Err(std_diag::func_duplicate_in_scope(name));
1809 }
1810 check_script_param_tags(name, params)?;
1811 let old = self.entries.insert(
1812 qualified.clone(),
1813 FuncEntry {
1814 meta: FuncMeta {
1815 name: qualified.clone(),
1816 module: SCRIPT_MODULE_NAME.to_string(),
1817 kind: FuncKind::Script,
1818 params: Some(
1819 params
1820 .iter()
1821 .map(|(pname, param_type, optional)| {
1822 Ok(FuncParam {
1823 name: pname.clone(),
1824 param_type: Some(param_type.clone()),
1825 allowed: None,
1826 docs: "",
1829 options: None,
1830 optional: *optional,
1831 })
1832 })
1833 .collect::<DiagnosticResult<_>>()?,
1834 ),
1835 returns: Some(return_type.clone()),
1836 rpn: false,
1837 summary: "DSL-defined function.",
1838 docs: "Defined via FUNC in script.",
1839 examples: &[],
1840 },
1841 body: FuncBody::Script(FuncDefData {
1842 params: params.to_vec(),
1843 return_type,
1844 return_spelling: return_spelling.to_string(),
1845 is_async,
1846 body: body.to_vec(),
1847 module: module.map(|m| m.to_string()),
1848 def_jail,
1849 }),
1850 },
1851 );
1852 if let Some(frame) = self.scopes.last_mut() {
1853 frame.defined.insert(qualified.clone());
1854 if let Some(old) = old {
1855 frame.shadowed.push((qualified, old));
1856 }
1857 }
1858 Ok(())
1859 }
1860
1861 #[allow(clippy::too_many_arguments)]
1867 pub(super) fn define_file_func(
1868 &mut self,
1869 name: &str,
1870 params: &[(String, TypeTag, bool)],
1871 return_type: TypeTag,
1872 return_spelling: &str,
1873 is_async: bool,
1874 body: &[Step],
1875 defining: &str,
1876 ) -> DiagnosticResult<()> {
1877 let qualified = file_func_key(defining, name);
1881 let shadowable = matches!(
1882 self.entries.get(&qualified).map(|entry| &entry.body),
1883 Some(FuncBody::Script(_))
1884 );
1885 let reserved = self.entries.iter().any(|(key, entry)| {
1889 split_qualified(key).is_some_and(|(_, base)| base == name)
1890 && !matches!(entry.body, FuncBody::Script(_))
1891 });
1892 if reserved && !shadowable {
1893 return Err(std_diag::func_shadow_reserved(name));
1894 }
1895 let frame_idx = 0;
1899 if self
1900 .scopes
1901 .get(frame_idx)
1902 .is_some_and(|frame| frame.defined.contains(&qualified))
1903 {
1904 return Err(std_diag::func_duplicate_in_scope(name));
1905 }
1906 check_script_param_tags(name, params)?;
1907 let old = self.entries.insert(
1908 qualified.clone(),
1909 FuncEntry {
1910 meta: FuncMeta {
1911 name: qualified.clone(),
1912 module: defining.to_string(),
1913 kind: FuncKind::Script,
1914 params: Some(
1915 params
1916 .iter()
1917 .map(|(pname, param_type, optional)| {
1918 Ok(FuncParam {
1919 name: pname.clone(),
1920 param_type: Some(param_type.clone()),
1921 allowed: None,
1922 docs: "",
1923 options: None,
1924 optional: *optional,
1925 })
1926 })
1927 .collect::<DiagnosticResult<_>>()?,
1928 ),
1929 returns: Some(return_type.clone()),
1930 rpn: false,
1931 summary: "DSL-defined function.",
1932 docs: "Defined via FUNC in an imported script.",
1933 examples: &[],
1934 },
1935 body: FuncBody::Script(FuncDefData {
1936 params: params.to_vec(),
1937 return_type,
1938 return_spelling: return_spelling.to_string(),
1939 is_async,
1940 body: body.to_vec(),
1941 module: Some(defining.to_string()),
1942 def_jail: None,
1947 }),
1948 },
1949 );
1950 if let Some(frame) = self.scopes.get_mut(frame_idx) {
1951 frame.defined.insert(qualified.clone());
1952 if let Some(old) = old {
1953 frame.shadowed.push((qualified, old));
1954 }
1955 }
1956 Ok(())
1957 }
1958
1959 pub(super) fn seal_canonical_jail(
1967 &mut self,
1968 canonical: &str,
1969 jail: (WorkspaceSelection, GuardedPath),
1970 ) {
1971 if let Some(entry) = self.entries.get_mut(canonical)
1972 && let FuncBody::Script(def) = &mut entry.body
1973 && def.def_jail.is_none()
1974 {
1975 def.def_jail = Some(jail);
1976 }
1977 }
1978
1979 pub(super) fn push_scope(&mut self) {
1982 self.scopes.push(ScopeFrame {
1983 defined: HashSet::new(),
1984 shadowed: Vec::new(),
1985 });
1986 }
1987
1988 pub(super) fn pop_scope(&mut self) {
1991 let Some(frame) = self.scopes.pop() else {
1992 return;
1993 };
1994 for name in frame.defined {
1995 self.entries.remove(&name);
1996 }
1997 for (name, old) in frame.shadowed {
1998 self.entries.insert(name, old);
1999 }
2000 }
2001
2002 pub(super) fn resolve_file_call_key(
2005 &self,
2006 unit_targets: &AliasTargets,
2007 name: &str,
2008 ) -> DiagnosticResult<Option<String>> {
2009 match classify_alias_call(unit_targets, name, &|key| self.entries.contains_key(key)) {
2010 AliasResolution::Global | AliasResolution::Unknown | AliasResolution::Any { .. } => {
2011 Ok(None)
2012 }
2013 AliasResolution::Canonical(key) => Ok(Some(key)),
2014 AliasResolution::Ambiguous { alias, base, files } => {
2015 Err(std_diag::func_ambiguous_alias(&alias, &base, &files))
2016 }
2017 }
2018 }
2019
2020 pub(super) fn pure_shared(&self) -> Arc<PureTable> {
2024 Arc::clone(&self.pure_shared)
2025 }
2026
2027 pub(super) fn all_metas(&self) -> Vec<FuncMeta> {
2030 self.entries_metas()
2031 }
2032
2033 fn meta(&self, name: &str) -> Option<FuncMeta> {
2034 self.entries.get(name).map(|entry| entry.meta.clone())
2035 }
2036
2037 fn native_metas(&self) -> Vec<FuncMeta> {
2038 let mut out: Vec<FuncMeta> = Vec::new();
2039 for entry in self.entries.values() {
2040 if !matches!(entry.body, FuncBody::Script(_)) {
2041 out.push(entry.meta.clone());
2042 }
2043 }
2044 out.sort_by(|a, b| a.name.cmp(&b.name));
2045 out
2046 }
2047
2048 pub(super) fn pure_metas(&self) -> Vec<FuncMeta> {
2053 let mut out: Vec<FuncMeta> = Vec::new();
2054 for entry in self.entries.values() {
2055 if matches!(entry.body, FuncBody::Pure(_) | FuncBody::Both { .. }) {
2056 out.push(entry.meta.clone());
2057 }
2058 }
2059 out.sort_by(|a, b| a.name.cmp(&b.name));
2060 out
2061 }
2062
2063 fn entries_metas(&self) -> Vec<FuncMeta> {
2066 let mut out: Vec<FuncMeta> = self
2067 .entries
2068 .values()
2069 .map(|entry| entry.meta.clone())
2070 .collect();
2071 out.sort_by(|a, b| a.name.cmp(&b.name));
2072 out
2073 }
2074
2075 pub fn set_script_docs(&mut self, docs: &HashMap<String, (String, String)>) {
2078 for (base, pair) in docs {
2079 self.script_docs
2080 .insert(qualify(SCRIPT_MODULE_NAME, base), pair.clone());
2081 }
2082 }
2083
2084 pub fn script_doc_for(&self, qualified: &str) -> Option<(String, String)> {
2086 self.script_docs.get(qualified).cloned()
2087 }
2088
2089 pub fn exported_metas(
2094 &self,
2095 func_exports: &[String],
2096 unit_targets: &AliasTargets,
2097 ) -> DiagnosticResult<Vec<FuncMeta>> {
2098 let mut out = Vec::with_capacity(func_exports.len());
2099 for name in func_exports {
2100 let qualified = match split_qualified(name) {
2104 None => qualify(SCRIPT_MODULE_NAME, name),
2105 Some(_) => name.clone(),
2106 };
2107 let lookup = self
2108 .resolve_file_call_key(unit_targets, &qualified)?
2109 .unwrap_or_else(|| qualified.clone());
2110 if let Some(entry) = self.entries.get(&lookup) {
2111 let mut meta = entry.meta.clone();
2112 if lookup != qualified {
2113 meta.name = name.clone();
2114 }
2115 out.push(meta);
2116 continue;
2117 }
2118 return Err(std_diag::func_export_unknown(name));
2119 }
2120 Ok(out)
2121 }
2122}
2123
2124impl<P: ProcessManager> Clone for FunctionRegistry<P> {
2125 fn clone(&self) -> Self {
2126 Self {
2127 entries: self.entries.clone(),
2128 scopes: self.scopes.clone(),
2129 pure_shared: Arc::clone(&self.pure_shared),
2130 script_docs: self.script_docs.clone(),
2131 }
2132 }
2133}
2134
2135pub fn builtin_function_names() -> HashSet<String> {
2142 let mut names = FunctionRegistry::<DefaultProcessManager>::with_builtins().keys();
2143 names.insert(KEYWORD_INSPECT.to_string());
2144 names
2145}
2146
2147pub fn builtin_function_metas() -> Vec<FuncMeta> {
2151 FunctionRegistry::<DefaultProcessManager>::with_builtins().native_metas()
2152}
2153
2154pub fn std_module_table() -> oxdock_parser::ModuleTable {
2159 let func_names: HashSet<String> = builtin_function_metas()
2161 .into_iter()
2162 .map(|meta| base_name(&meta.name).to_string())
2163 .collect();
2164 oxdock_parser::ModuleTable {
2165 modules: HashMap::from([(
2166 STD_MODULE_NAME.to_string(),
2167 Some(oxdock_parser::ModuleFuncs { func_names }),
2168 )]),
2169 }
2170}
2171
2172#[oxdock_func(pure, returns = TypeTag::Int)]
2185#[example(
2186 name = "convert",
2187 code = r###"
2188 IMPORT [STD]
2189 LET $n: INT = INT("42")
2190 ASSERT_EQ $n 42
2191 LET $flag: INT = INT(true)
2192 ASSERT_EQ $flag 1
2193 "###
2194)]
2195fn int(
2196 #[union(Int, Float, String, Bool)]
2198 val: Value,
2199) -> DiagnosticResult<Value> {
2200 super::args::int_from_value(val)
2201}
2202
2203#[oxdock_func(pure, returns = TypeTag::Float)]
2208#[example(
2209 name = "convert",
2210 code = r###"
2211 IMPORT [STD]
2212 LET $f: FLOAT = FLOAT("1.5")
2213 ASSERT_EQ $f 1.5
2214 LET $whole: FLOAT = FLOAT(2)
2215 ASSERT_EQ $whole 2.0
2216 "###
2217)]
2218fn float(
2219 #[union(Float, Int, String)]
2221 val: Value,
2222) -> DiagnosticResult<Value> {
2223 super::args::float_from_value(val)
2224}
2225
2226#[oxdock_func(pure, returns = TypeTag::String)]
2231#[example(
2232 name = "format and round-trip",
2233 code = r###"
2234 # Byte counts render in the largest exact unit.
2235 IMPORT [STD]
2236 LET $pretty: STRING = FORMAT_BYTE_COUNT(1_048_576)
2237 ASSERT_EQ $pretty "1MiB"
2238
2239 # The pair round-trips through the parser.
2240 LET $back: INT = PARSE_BYTE_COUNT($pretty)
2241 ASSERT_EQ $back 1_048_576
2242 "###
2243)]
2244fn format_byte_count(
2245 bytes: i64,
2247) -> DiagnosticResult<Value> {
2248 if bytes < 0 {
2249 return Err(std_diag::std_format_byte_count_negative(bytes));
2250 }
2251 Ok(Value::string(oxdock_parser::command::format_byte_count(
2252 bytes as u64,
2253 )))
2254}
2255
2256#[oxdock_func(pure, returns = TypeTag::Int)]
2291#[example(
2292 name = "parse",
2293 code = r###"
2294 IMPORT [STD]
2295 LET $n: INT = PARSE_BYTE_COUNT("10KB")
2296 ASSERT_EQ $n 10_000
2297 LET $identity: INT = PARSE_BYTE_COUNT(512)
2298 ASSERT_EQ $identity 512
2299 "###
2300)]
2301fn parse_byte_count(
2302 #[union(Int, Float, String)]
2304 text: Value,
2305) -> DiagnosticResult<Value> {
2306 if let Some(n) = text.as_i64() {
2307 if n < 0 {
2308 return Err(std_diag::std_parse_byte_count_negative(n));
2309 }
2310 return Ok(Value::int(n));
2311 }
2312 if let Some(f) = text.as_f64() {
2313 if f.is_finite() && f.fract() == 0.0 && f >= 0.0 && f <= i64::MAX as f64 {
2314 return Ok(Value::int(f as i64));
2315 }
2316 return Err(std_diag::std_parse_byte_count_integral(f));
2317 }
2318 let Some(s) = text.as_str() else {
2319 return Err(std_diag::std_parse_byte_count_shape(&text));
2320 };
2321 let n = oxdock_parser::command::parse_byte_count(s)?;
2322 let n = i64::try_from(n).map_err(|_| std_diag::std_parse_byte_count_range(s))?;
2323 Ok(Value::int(n))
2324}
2325
2326#[oxdock_func(pure, returns = TypeTag::String)]
2331#[example(
2332 name = "format and round-trip",
2333 code = r###"
2334 # Durations render in the largest exact unit.
2335 IMPORT [STD]
2336 LET $pretty: STRING = FORMAT_DURATION(90_000)
2337 ASSERT_EQ $pretty "90s"
2338
2339 # The pair round-trips through the parser.
2340 LET $back: INT = PARSE_DURATION($pretty)
2341 ASSERT_EQ $back 90_000
2342 "###
2343)]
2344fn format_duration(
2345 millis: i64,
2347) -> DiagnosticResult<Value> {
2348 if millis < 0 {
2349 return Err(std_diag::std_format_duration_negative(millis));
2350 }
2351 Ok(Value::string(oxdock_parser::command::format_duration(
2352 &std::time::Duration::from_millis(millis as u64),
2353 )))
2354}
2355
2356#[oxdock_func(pure, returns = TypeTag::Int)]
2362#[example(
2363 name = "parse",
2364 code = r###"
2365 # A bare number means seconds, like TIMEOUT.
2366 IMPORT [STD]
2367 LET $ms: INT = PARSE_DURATION("2m")
2368 ASSERT_EQ $ms 120_000
2369
2370 # Milliseconds stay exact.
2371 LET $exact: INT = PARSE_DURATION("1500ms")
2372 ASSERT_EQ $exact 1_500
2373
2374 # One optional space separates number from unit.
2375 LET $spaced: INT = PARSE_DURATION("1 h")
2376 ASSERT_EQ $spaced 3_600_000
2377 "###
2378)]
2379fn parse_duration(
2380 text: String,
2382) -> DiagnosticResult<Value> {
2383 let duration = oxdock_parser::command::parse_duration(&text)?;
2384 let millis = i64::try_from(duration.as_millis())
2385 .map_err(|_| std_diag::std_parse_duration_range(&text))?;
2386 Ok(Value::int(millis))
2387}
2388
2389#[oxdock_func(rpn, returns = TypeTag::ListOf(std::sync::Arc::new(TypeTag::String)))]
2394#[example(
2395 name = "match",
2396 code = r###"
2397 IMPORT [STD]
2398 WRITE "notes-a.md" "a"
2399 WRITE "notes-b.md" "b"
2400 WRITE "other.txt" "c"
2401 LET $found: LIST<STRING> = GLOB("notes-*.md")
2402 ASSERT_EQ $found.0 "notes-a.md"
2403 ASSERT_EQ $found.1 "notes-b.md"
2404 "###
2405)]
2406fn glob<P: ProcessManager>(
2407 cx: &mut StepCtx<P>,
2408 #[union(String, Path)]
2410 pattern: Value,
2411) -> DiagnosticResult<Value> {
2412 let text = super::args::string_or_path_text(&pattern)?;
2413 super::args::glob_from_value(&[Value::string(text)], cx)
2414}
2415
2416#[oxdock_func(rpn, returns = TypeTag::MapOf(std::sync::Arc::new(TypeTag::Any)))]
2421#[example(
2422 name = "load",
2423 code = r###"
2424 IMPORT [STD]
2425 WRITE "cfg.toml" "title = \"demo\""
2426 LET $cfg: MAP<ANY> = LOAD_TOML("cfg.toml")
2427 ASSERT_EQ $cfg.title "demo"
2428 "###
2429)]
2430fn load_toml<P: ProcessManager>(
2431 cx: &mut StepCtx<P>,
2432 #[union(String, Path)]
2434 path: Value,
2435) -> DiagnosticResult<Value> {
2436 let text = super::args::string_or_path_text(&path)?;
2437 super::args::load_toml_from_value(&[Value::string(text)], cx)
2438}
2439
2440#[oxdock_func(rpn, returns = TypeTag::Any)]
2448#[example(
2449 name = "load",
2450 code = r###"
2451 IMPORT [STD]
2452 WRITE "data.json" "{\"a\": 1}"
2453 LET $doc: MAP<ANY> = LOAD_JSON("data.json")
2454 ASSERT_EQ $doc.a 1
2455 "###
2456)]
2457fn load_json<P: ProcessManager>(
2458 cx: &mut StepCtx<P>,
2459 #[union(String, Path)]
2461 path: Value,
2462) -> DiagnosticResult<Value> {
2463 let text = super::args::string_or_path_text(&path)?;
2464 super::args::load_json_from_value(&[Value::string(text)], cx)
2465}
2466
2467#[oxdock_func(rpn, returns = TypeTag::String)]
2477#[example(
2478 name = "hash",
2479 code = r###"
2480 IMPORT [STD]
2481 WRITE payload.txt hello
2482 LET $digest: STRING = HASH_SHA256("payload.txt")
2483 ASSERT_EQ $digest "2cf24dba5fb0a30e26e83b2ac5b9e29e1b161e5c1fa7425e73043362938b9824"
2484 "###
2485)]
2486fn hash_sha256<P: ProcessManager>(
2487 cx: &mut StepCtx<P>,
2488 #[union(String, Path)]
2490 path: Value,
2491) -> DiagnosticResult<Value> {
2492 use sha2::Digest;
2493
2494 let text = super::args::string_or_path_text(&path)?;
2495 let target = cx.state.fs.resolve_read(&cx.state.cwd, &text)?;
2496 let mut hasher = sha2::Sha256::new();
2497 super::fs_ops::hash_path(cx.state.fs.as_ref(), &target, "", &mut hasher)?;
2498 let digest = hasher.finalize();
2499 let bytes: &[u8] = digest.as_ref();
2500 Ok(Value::string(oxdock_utils::hex_encode(bytes)))
2501}
2502
2503#[oxdock_func(rpn, returns = TypeTag::String)]
2514#[example(
2515 name = "cwd",
2516 code = r###"
2517 IMPORT [STD]
2518 WORKDIR sub
2519 LET $c: STRING = CWD()
2520 ASSERT_CONTAINS $c "sub"
2521 "###
2522)]
2523fn cwd<P: ProcessManager>(cx: &mut StepCtx<P>) -> DiagnosticResult<Value> {
2524 if cx.state.fs.is_snapshot_pending() {
2525 return Ok(Value::string(super::SNAPSHOT_PENDING_DISPLAY.to_string()));
2526 }
2527 let concrete = cx.state.fs.concretize_cwd(&cx.state.cwd);
2528 let real = super::fs_ops::canonical_cwd(cx.state.fs.as_ref(), &concrete)?;
2529 Ok(Value::string(real))
2530}
2531
2532#[oxdock_func(pure, returns = TypeTag::MapOf(std::sync::Arc::new(TypeTag::Any)))]
2538#[example(
2539 name = "parse",
2540 code = r###"
2541 IMPORT [STD]
2542 LET $doc: MAP<ANY> = PARSE_TOML("title = \"demo\"")
2543 ASSERT_EQ $doc.title "demo"
2544 "###
2545)]
2546fn parse_toml(
2547 text: String,
2549) -> DiagnosticResult<Value> {
2550 super::args::parse_toml_from_value(Value::string(text))
2551}
2552
2553#[oxdock_func(pure, returns = TypeTag::Any)]
2562#[example(
2563 name = "parse",
2564 code = r###"
2565 # Parse in-memory JSON text with the same conversion as file loading.
2566 IMPORT [STD]
2567 LET $body: STRING = "{\"a\": 1}"
2568 LET $doc: ANY = PARSE_JSON($body)
2569 ASSERT_EQ $doc.a 1
2570
2571 # Top-level arrays parse to LIST, which is why the return is ANY.
2572 LET $items: LIST<ANY> = PARSE_JSON("[1, 2]")
2573 ASSERT_EQ $items.0 1
2574 ASSERT_EQ $items.1 2
2575 "###
2576)]
2577fn parse_json(
2578 text: String,
2580) -> DiagnosticResult<Value> {
2581 super::args::parse_json_from_value(Value::string(text))
2582}
2583
2584#[oxdock_func(returns = TypeTag::String)]
2590#[example(
2591 name = "describe",
2592 code = r###"
2593 IMPORT [STD]
2594 WRITE "entry.txt" "words"
2595 LET $kind: STRING = PATH_TYPE("entry.txt")
2596 ASSERT_EQ $kind "file"
2597 LET $missing: STRING = PATH_TYPE("no-such-entry.txt")
2598 ASSERT_EQ $missing "absent"
2599 "###
2600)]
2601fn path_type<P: ProcessManager>(
2602 cx: &mut StepCtx<P>,
2603 #[union(String, Path)]
2605 path: Value,
2606) -> DiagnosticResult<Value> {
2607 let text = super::args::string_or_path_text(&path)?;
2608 super::args::path_type_from_value(&[Value::string(text)], cx)
2609}
2610
2611#[oxdock_func(returns = TypeTag::Bool)]
2620#[example(
2621 name = "probe",
2622 code = r###"
2623 # An absent nested path is writable when its ancestor is.
2624 IMPORT [STD]
2625 LET $fresh: BOOL = PATH_WRITABLE("probe-check/nested/file.txt")
2626 ASSERT_EQ $fresh true
2627
2628 # The empty string never aliases the working directory.
2629 LET $empty: BOOL = PATH_WRITABLE("")
2630 ASSERT_EQ $empty false
2631 "###
2632)]
2633fn path_writable<P: ProcessManager>(
2634 cx: &mut StepCtx<P>,
2635 #[union(String, Path)]
2637 path: Value,
2638) -> DiagnosticResult<Value> {
2639 let text = super::args::string_or_path_text(&path)?;
2640 super::args::path_writable_from_value(&[Value::string(text)], cx)
2641}
2642
2643#[oxdock_func(returns = TypeTag::Bool)]
2656#[example(
2657 name = "probe",
2658 code = r###"
2659 # Missing tools read false instead of failing the run.
2660 IMPORT [STD]
2661 LET $missing: BOOL = IS_EXEC("no-such-tool-xyz")
2662 ASSERT_EQ $missing false
2663
2664 # Plain files are not executable on any platform.
2665 WRITE tool.txt payload
2666 LET $plain: BOOL = IS_EXEC("tool.txt")
2667 ASSERT_EQ $plain false
2668 "###
2669)]
2670fn is_exec<P: ProcessManager>(
2671 cx: &mut StepCtx<P>,
2672 #[union(String, Path)]
2674 name: Value,
2675) -> DiagnosticResult<Value> {
2676 let text = super::args::string_or_path_text(&name)?;
2677 super::args::is_exec_from_value(&[Value::string(text)], cx)
2678}
2679
2680#[oxdock_func(returns = TypeTag::Bool)]
2688#[example(
2689 name = "probe",
2690 code = r###"
2691 # Ordinary files read true; missing paths read false.
2692 IMPORT [STD]
2693 WRITE "entry.txt" "words"
2694 LET $hit: BOOL = IS_FILE("entry.txt")
2695 ASSERT_EQ $hit true
2696 LET $miss: BOOL = IS_FILE("no-such-entry.txt")
2697 ASSERT_EQ $miss false
2698 "###
2699)]
2700fn is_file<P: ProcessManager>(
2701 cx: &mut StepCtx<P>,
2702 #[union(String, Path)]
2704 path: Value,
2705) -> DiagnosticResult<Value> {
2706 let text = super::args::string_or_path_text(&path)?;
2707 Ok(Value::bool(super::args::path_is_file(cx, &text)))
2708}
2709
2710#[oxdock_func(returns = TypeTag::Bool)]
2718#[example(
2719 name = "probe",
2720 code = r###"
2721 # Directories read true; files read false.
2722 IMPORT [STD]
2723 LET $hit: BOOL = IS_DIR(".")
2724 ASSERT_EQ $hit true
2725 WRITE "entry.txt" "words"
2726 LET $miss: BOOL = IS_DIR("entry.txt")
2727 ASSERT_EQ $miss false
2728 "###
2729)]
2730fn is_dir<P: ProcessManager>(
2731 cx: &mut StepCtx<P>,
2732 #[union(String, Path)]
2734 path: Value,
2735) -> DiagnosticResult<Value> {
2736 let text = super::args::string_or_path_text(&path)?;
2737 Ok(Value::bool(super::args::path_is_dir(cx, &text)))
2738}
2739
2740#[oxdock_func(returns = TypeTag::Bool)]
2747#[example(
2748 name = "probe",
2749 code = r###"
2750 # Present entries read true; absent paths read false.
2751 IMPORT [STD]
2752 WRITE "entry.txt" "words"
2753 LET $hit: BOOL = EXISTS("entry.txt")
2754 ASSERT_EQ $hit true
2755 LET $miss: BOOL = EXISTS("no-such-entry.txt")
2756 ASSERT_EQ $miss false
2757 "###
2758)]
2759fn exists<P: ProcessManager>(
2760 cx: &mut StepCtx<P>,
2761 #[union(String, Path)]
2763 path: Value,
2764) -> DiagnosticResult<Value> {
2765 let text = super::args::string_or_path_text(&path)?;
2766 Ok(Value::bool(super::args::path_exists(cx, &text)))
2767}
2768
2769#[oxdock_func(pure, returns = TypeTag::Bool)]
2775#[example(
2776 name = "probe",
2777 code = r###"
2778 IMPORT [STD]
2779 LET $m: MAP<ANY> = PARSE_JSON("{\"a\": 1}")
2780 LET $hit: BOOL = HAS_KEY($m, "a")
2781 ASSERT_EQ $hit true
2782 LET $miss: BOOL = HAS_KEY($m, "b")
2783 ASSERT_EQ $miss false
2784 "###
2785)]
2786fn has_key(
2787 map: BTreeMap<String, Value>,
2789 key: String,
2791) -> DiagnosticResult<Value> {
2792 super::args::has_key_from_value(Value::map(map), &key)
2793}
2794
2795#[oxdock_func(pure, returns = TypeTag::Any)]
2801#[example(
2802 name = "present and absent",
2803 code = r###"
2804 IMPORT [STD]
2805 LET $m: MAP<ANY> = PARSE_JSON("{\"a\": 1}")
2806 LET $hit: INT = GET($m, "a", 0)
2807 ASSERT_EQ $hit 1
2808 LET $miss: INT = GET($m, "b", 0)
2809 ASSERT_EQ $miss 0
2810 "###
2811)]
2812fn get(
2813 map: BTreeMap<String, Value>,
2815 key: String,
2817 default: Value,
2819) -> DiagnosticResult<Value> {
2820 Ok(map.get(&key).cloned().unwrap_or(default))
2821}
2822
2823#[oxdock_func(pure, returns = TypeTag::MapOf(std::sync::Arc::new(TypeTag::Any)))]
2833#[example(
2834 name = "insert",
2835 code = r###"
2836 IMPORT [STD]
2837 LET $m: MAP<ANY> = MAP_SET({seed: 0}, "a", 1)
2838 ASSERT_EQ $m.a 1
2839 "###
2840)]
2841fn map_set(
2842 #[reject_frozen]
2844 map: BTreeMap<String, Value>,
2845 key: String,
2847 value: Value,
2849) -> DiagnosticResult<Value> {
2850 super::args::map_set_from_value(Value::map(map), key, value)
2851}
2852
2853#[oxdock_func(returns = TypeTag::Float, summary = "Draw a random FLOAT uniformly from [0, 1), optionally seeded.")]
2861#[example(
2862 name = "seeded draw",
2863 code = r###"
2864 # A seed draws the same value on every run.
2865 IMPORT [STD]
2866 LET $one: FLOAT = RAND({seed: 7})
2867 LET $two: FLOAT = RAND({seed: 7})
2868 ASSERT_EQ $one $two
2869 "###
2870)]
2871#[example(
2872 name = "unseeded draw",
2873 code = r###"
2874 # Scale a unit draw into a backoff delay between 1 and 11 seconds.
2875 IMPORT [STD]
2876 LET $draw: FLOAT = RAND()
2877 LET $delay: FLOAT = 1.0 + $draw * 10.0
2878 IF $delay < 1.0 {
2879 FAIL "trap: RAND draw below range"
2880 }
2881 IF $delay >= 11.0 {
2882 FAIL "trap: RAND draw above range"
2883 }
2884 ECHO "retrying in {{ $delay }}s"
2885 "###
2886)]
2887fn rand<P: ProcessManager>(
2888 cx: &mut StepCtx<P>,
2889 #[options("seed?: INT")]
2891 #[optional]
2892 options: BTreeMap<String, Value>,
2893) -> DiagnosticResult<Value> {
2894 let _ = cx;
2895 let seed = options
2898 .get("seed")
2899 .map(|value| value.as_i64().expect("check_options verified INT"));
2900 super::args::rand_float_from_value(seed)
2901}
2902
2903#[oxdock_func(pure, returns = TypeTag::String)]
2909#[example(
2910 name = "encode",
2911 code = r###"
2912 # Encode text to standard base64.
2913 IMPORT [STD]
2914 LET $encoded: STRING = BASE64_ENCODE("hello")
2915 ASSERT_EQ $encoded "aGVsbG8="
2916 "###
2917)]
2918fn base64_encode(
2919 text: String,
2921) -> DiagnosticResult<Value> {
2922 super::args::base64_encode_from_value(Value::string(text))
2923}
2924
2925#[oxdock_func(pure, returns = TypeTag::String)]
2932#[example(
2933 name = "decode",
2934 code = r###"
2935 # Decode standard base64 back to text.
2936 IMPORT [STD]
2937 LET $decoded: STRING = BASE64_DECODE("aGVsbG8=")
2938 ASSERT_EQ $decoded "hello"
2939 "###
2940)]
2941fn base64_decode(
2942 text: String,
2944) -> DiagnosticResult<Value> {
2945 super::args::base64_decode_from_value(Value::string(text))
2946}
2947
2948#[oxdock_func(pure, returns = TypeTag::String)]
2955#[example(
2956 name = "encode",
2957 code = r###"
2958 IMPORT [STD]
2959 LET $json: STRING = TO_JSON({a: 1})
2960 ASSERT_EQ $json "{\"a\":1}\n"
2961 "###
2962)]
2963fn to_json(
2964 #[union(String, Int, Float, Bool, List, Map)]
2966 value: Value,
2967) -> DiagnosticResult<Value> {
2968 super::args::to_json_from_value(value)
2969}
2970
2971#[oxdock_func(pure, returns = TypeTag::String)]
2979#[example(
2980 name = "name the word",
2981 code = r###"
2982 IMPORT [STD]
2983 LET $word: STRING = TYPE_OF(42)
2984 ASSERT_EQ $word "INT"
2985 "###
2986)]
2987fn type_of(
2988 value: Value,
2990) -> DiagnosticResult<Value> {
2991 super::args::type_of_from_value(value)
2992}
2993
2994#[oxdock_func(pure, returns = TypeTag::MapOf(std::sync::Arc::new(TypeTag::Any)))]
3006#[example(
3007 name = "merge",
3008 code = r###"
3009 IMPORT [STD]
3010 LET $m: MAP<ANY> = MERGE_MAPS([{a: 1}, {b: 2}], "overwrite")
3011 ASSERT_EQ $m.a 1
3012 ASSERT_EQ $m.b 2
3013 "###
3014)]
3015fn merge_maps(
3016 #[reject_frozen]
3018 maps: Vec<BTreeMap<String, Value>>,
3019 #[values("fail_on_duplicate", "overwrite")]
3021 policy: String,
3022) -> DiagnosticResult<Value> {
3023 super::args::merge_maps_from_value(
3024 Value::list(maps.into_iter().map(Value::map).collect()),
3025 policy,
3026 )
3027}
3028
3029#[oxdock_func(pure, returns = TypeTag::String)]
3034#[example(
3035 name = "report",
3036 code = r###"
3037 # The engine reports its own build version as a dotted string.
3038 IMPORT [STD]
3039 LET $v: STRING = VERSION()
3040 ASSERT_CONTAINS $v "."
3041 "###
3042)]
3043fn version() -> DiagnosticResult<Value> {
3044 Ok(Value::string(env!("CARGO_PKG_VERSION").to_string()))
3045}
3046
3047#[oxdock_func(returns = TypeTag::ListOf(std::sync::Arc::new(TypeTag::String)))]
3052#[example(
3053 name = "list",
3054 code = r###"
3055 IMPORT [STD]
3056 LET $names: LIST<STRING> = FUNCTIONS()
3057 ASSERT_CONTAINS $names "STD::INT"
3058 "###
3059)]
3060fn functions<P: ProcessManager>(cx: &mut StepCtx<P>) -> DiagnosticResult<Value> {
3061 let mut names: Vec<String> = cx
3062 .state
3063 .list_functions()
3064 .into_iter()
3065 .map(|meta| meta.name)
3066 .collect();
3067 names.sort();
3068 names.dedup();
3069 Ok(Value::list(names.into_iter().map(Value::string).collect()))
3070}
3071
3072#[oxdock_func(returns = TypeTag::ListOf(std::sync::Arc::new(TypeTag::String)))]
3079#[example(
3080 name = "empty",
3081 code = r###"
3082 # With no staged args the list is empty.
3083 IMPORT [STD]
3084 LET $args: LIST<STRING> = ARGV()
3085 LET $n: INT = LEN($args)
3086 ASSERT_EQ $n 0
3087 "###
3088)]
3089fn argv<P: ProcessManager>(cx: &mut StepCtx<P>) -> DiagnosticResult<Value> {
3090 Ok(Value::list(
3091 cx.state
3092 .io
3093 .script_args()
3094 .iter()
3095 .cloned()
3096 .map(Value::string)
3097 .collect(),
3098 ))
3099}
3100
3101pub struct ParseArgs;
3121
3122impl<P: ProcessManager> OxDockFn<P> for ParseArgs {
3123 fn registration() -> HostRegistration<P> {
3124 let func: NativeFn<P> = Arc::new(|cx: &mut StepCtx<P>, values: Vec<Value>| {
3125 if values.len() != 1 {
3126 return Err(std_diag::std_parse_args_arity(values.len()));
3127 }
3128 let mut iter = values.into_iter();
3129 let args_val = iter.next().expect("arity checked above");
3130 let args =
3131 string_list_arg(&args_val, &format!("{FUNC_PARSE_ARGS}() argument `$args`"))?;
3132 let specs = resolve_flags_specs(cx)?;
3133 let (raw, positionals) = tokenize_raw_args(args)?;
3134 let coerced = coerce_flags(&specs, &raw)?;
3135 let mut out = BTreeMap::new();
3136 out.insert("flags".to_string(), Value::map(coerced));
3137 if !positionals.is_empty() {
3138 out.insert("positionals".to_string(), Value::list(positionals));
3139 }
3140 Ok(Value::map(out))
3141 });
3142 HostRegistration::Stateful {
3143 name: FUNC_PARSE_ARGS.to_string(),
3144 meta: FuncMeta {
3145 name: FUNC_PARSE_ARGS.to_string(),
3146 module: String::new(),
3147 kind: FuncKind::HostPure,
3148 params: Some(vec![FuncParam {
3149 name: "args".to_string(),
3150 param_type: Some(TypeTag::ListOf(Arc::new(TypeTag::String))),
3151 allowed: None,
3152 docs: "Argv tail to parse, usually from `STD::ARGV()`.",
3153 options: None,
3154 optional: false,
3155 }]),
3156 returns: Some(TypeTag::Record(Arc::from([
3157 Field {
3158 name: "flags".to_string(),
3159 ty: TypeTag::Map,
3160 docs: "Flags coerced to `TYPE FLAGS`.",
3161 optional: false,
3162 default: None,
3163
3164 alias: None,
3165 },
3166 Field {
3167 name: "positionals".to_string(),
3168 ty: TypeTag::ListOf(Arc::new(TypeTag::String)),
3169 docs: "Trailing values and entries after the first double dash. Omitted when empty.",
3170 optional: true,
3171 default: None,
3172
3173 alias: None,
3174 },
3175 ]))),
3176 rpn: true,
3177 summary: "Parse an argv tail against TYPE FLAGS.",
3178 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.",
3179 examples: &[
3180 crate::Example {
3181 name: "flags and positionals",
3182 fence_meta: None,
3183 code: indoc::indoc! {r#"
3184 IMPORT [STD]
3185 # One schema TYPE drives coercion; the pair binds both slots.
3186 TYPE FLAGS = MAP<model: STRING, verbose?: BOOL>
3187 TYPE POSITIONS = LIST<STRING>
3188 TYPE PARSED = MAP<flags: FLAGS, positionals?: POSITIONS>
3189 LET $parsed: PARSED = PARSE_ARGS(["--model=gpt-4", "--verbose", "serve"])
3190 LET $flags: FLAGS = $parsed.flags
3191 ASSERT_EQ $flags.model "gpt-4"
3192 ASSERT_EQ $flags.verbose true
3193 ASSERT_EQ $parsed.positionals.0 "serve"
3194 "#},
3195 },
3196 crate::Example {
3197 name: "optional stays absent",
3198 fence_meta: None,
3199 code: indoc::indoc! {r#"
3200 IMPORT [STD]
3201 # Absent optionals stay absent; read them with a typed GET default.
3202 TYPE FLAGS = MAP<model: STRING, propose?: BOOL>
3203 TYPE POSITIONS = LIST<STRING>
3204 TYPE PARSED = MAP<flags: FLAGS, positionals?: POSITIONS>
3205 LET $parsed: PARSED = PARSE_ARGS(["--model=x"])
3206 LET $flags: FLAGS = $parsed.flags
3207 LET $propose: BOOL = GET($flags, "propose", false)
3208 ASSERT_EQ $propose false
3209 "#},
3210 },
3211 crate::Example {
3212 name: "flags only omits positionals",
3213 fence_meta: None,
3214 code: indoc::indoc! {r#"
3215 IMPORT [STD]
3216 # Empty positionals are omitted, so declare the slot
3217 # optional to bind a flags-only run clean.
3218 TYPE FLAGS = MAP<model: STRING>
3219 TYPE POSITIONS = LIST<STRING>
3220 TYPE PARSED = MAP<flags: FLAGS, positionals?: POSITIONS>
3221 LET $parsed: PARSED = PARSE_ARGS(["--model=x"])
3222 LET $flags: FLAGS = $parsed.flags
3223 ASSERT_EQ $flags.model "x"
3224 "#},
3225 },
3226 crate::Example {
3227 name: "literal defaults",
3228 fence_meta: None,
3229 code: indoc::indoc! {r#"
3230 IMPORT [STD]
3231 # Defaults are literals only: INT, FLOAT, BOOL,
3232 # and double-quoted STRING fill absent flags.
3233 TYPE FLAGS = MAP<retries: INT = 2, ratio: FLOAT = 2.5, verbose: BOOL = true, model: STRING = "gpt-4">
3234 TYPE POSITIONS = LIST<STRING>
3235 TYPE PARSED = MAP<flags: FLAGS, positionals?: POSITIONS>
3236 LET $parsed: PARSED = PARSE_ARGS([])
3237 LET $flags: FLAGS = $parsed.flags
3238 ASSERT_EQ $flags.retries 2
3239 ASSERT_EQ $flags.verbose true
3240 ASSERT_EQ $flags.model "gpt-4"
3241 LET $ratio_ok: BOOL = $flags.ratio == 2.5
3242 ASSERT_EQ $ratio_ok true
3243 "#},
3244 },
3245 crate::Example {
3246 name: "variable default fails",
3247 fence_meta: Some("expect_error:\"expected default literal\""),
3248 code: indoc::indoc! {r#"
3249 IMPORT [STD]
3250 # Defaults are literals: a variable in place
3251 # of a literal fails instead of evaluating.
3252 TYPE FLAGS = MAP<n: INT = $x>
3253 TYPE POSITIONS = LIST<STRING>
3254 TYPE PARSED = MAP<flags: FLAGS, positionals?: POSITIONS>
3255 LET $p: PARSED = PARSE_ARGS([])
3256 "#},
3257 },
3258 crate::Example {
3259 name: "missing required",
3260 fence_meta: Some("expect_error:\"missing required flag\""),
3261 code: indoc::indoc! {r#"
3262 IMPORT [STD]
3263 # Absent required flags fail naming the flag.
3264 TYPE FLAGS = MAP<model: STRING>
3265 TYPE POSITIONS = LIST<STRING>
3266 TYPE PARSED = MAP<flags: FLAGS, positionals?: POSITIONS>
3267 LET $parsed: PARSED = PARSE_ARGS([])
3268 "#},
3269 },
3270 crate::Example {
3271 name: "unknown flag",
3272 fence_meta: Some("expect_error:\"unknown flag\""),
3273 code: indoc::indoc! {r#"
3274 IMPORT [STD]
3275 # Undeclared flags fail instead of passing through.
3276 TYPE FLAGS = MAP<model: STRING>
3277 TYPE POSITIONS = LIST<STRING>
3278 TYPE PARSED = MAP<flags: FLAGS, positionals?: POSITIONS>
3279 LET $parsed: PARSED = PARSE_ARGS(["--model=x", "--nope=1"])
3280 "#},
3281 },
3282 crate::Example {
3283 name: "alias accepted",
3284 fence_meta: None,
3285 code: indoc::indoc! {r#"
3286 IMPORT [STD]
3287 # One canonical key binds both spellings; the
3288 # alias never appears as a separate key.
3289 TYPE FLAGS = MAP<h: BOOL ALIAS help>
3290 TYPE POSITIONS = LIST<STRING>
3291 TYPE PARSED = MAP<flags: FLAGS, positionals?: POSITIONS>
3292 LET $a: PARSED = PARSE_ARGS(["--help"])
3293 ASSERT_EQ $a.flags.h true
3294 LET $b: PARSED = PARSE_ARGS(["--h"])
3295 ASSERT_EQ $b.flags.h true
3296 "#},
3297 },
3298 crate::Example {
3299 name: "alias duplicate fails",
3300 fence_meta: Some("expect_error:\"duplicate flag\""),
3301 code: indoc::indoc! {r#"
3302 IMPORT [STD]
3303 # Canonical and alias together fail naming both.
3304 TYPE FLAGS = MAP<h: BOOL ALIAS help>
3305 TYPE POSITIONS = LIST<STRING>
3306 TYPE PARSED = MAP<flags: FLAGS, positionals?: POSITIONS>
3307 LET $p: PARSED = PARSE_ARGS(["--h", "--help"])
3308 "#},
3309 },
3310 crate::Example {
3311 name: "alias missing names both",
3312 fence_meta: Some("expect_error:\"--h/--help\""),
3313 code: indoc::indoc! {r#"
3314 IMPORT [STD]
3315 # Missing required flags name both spellings.
3316 TYPE FLAGS = MAP<h: BOOL ALIAS help>
3317 TYPE POSITIONS = LIST<STRING>
3318 TYPE PARSED = MAP<flags: FLAGS, positionals?: POSITIONS>
3319 LET $p: PARSED = PARSE_ARGS([])
3320 "#},
3321 },
3322 ],
3323 },
3324 func,
3325 }
3326 }
3327}
3328
3329#[derive(Debug, Clone, Copy, PartialEq, Eq)]
3333enum CliType {
3334 String,
3335 Bool,
3336 Int,
3337 Float,
3338}
3339
3340fn coerce_cli_flag(target: CliType, flag: &str, raw: Value) -> DiagnosticResult<Value> {
3345 match target {
3346 CliType::Bool => {
3347 if let Some(b) = raw.as_bool() {
3348 return Ok(Value::bool(b));
3349 }
3350 if let Some(s) = raw.as_str() {
3351 match super::args::parse_bool_str(s) {
3352 Some(b) => return Ok(Value::bool(b)),
3353 None => {
3354 return Err(std_diag::std_parse_args_bool_flag(flag, s));
3355 }
3356 }
3357 }
3358 Err(std_diag::std_parse_args_bool_type(flag, raw.type_name()))
3359 }
3360 CliType::String => {
3361 if let Some(s) = raw.as_str() {
3362 return Ok(Value::string(s.to_string()));
3363 }
3364 Err(std_diag::std_parse_args_needs_value(flag))
3365 }
3366 CliType::Int => {
3367 if raw.as_bool().is_some() {
3368 return Err(std_diag::std_parse_args_needs_value(flag));
3369 }
3370 super::args::int_from_value(raw).map_err(|_| std_diag::std_parse_args_expects_int(flag))
3371 }
3372 CliType::Float => {
3373 if raw.as_bool().is_some() {
3374 return Err(std_diag::std_parse_args_needs_value(flag));
3375 }
3376 super::args::float_from_value(raw)
3377 .map_err(|_| std_diag::std_parse_args_expects_float(flag))
3378 }
3379 }
3380}
3381
3382#[derive(Debug, Clone)]
3386struct CliSpec {
3387 target: CliType,
3388 required: bool,
3389 default: Option<Value>,
3390 alias: Option<String>,
3391}
3392
3393type CliSpecs = BTreeMap<String, CliSpec>;
3395
3396fn string_list_arg(val: &Value, what: &str) -> DiagnosticResult<Vec<String>> {
3399 crate::check_value_at(&TypeTag::ListOf(Arc::new(TypeTag::String)), val, what)
3400 .map_err(|err| std_diag::std_parse_args_arg_shape(&err))?;
3401 Ok(val
3402 .as_list()
3403 .expect("check_value_at enforces LIST")
3404 .iter()
3405 .map(|v| {
3406 v.as_str()
3407 .expect("check_value_at enforces STRING")
3408 .to_string()
3409 })
3410 .collect())
3411}
3412
3413fn tokenize_raw_args(args: Vec<String>) -> DiagnosticResult<(BTreeMap<String, Value>, Vec<Value>)> {
3417 use lexopt::Arg::{Long, Short, Value as ArgValue};
3418 let mut parser = lexopt::Parser::from_args(args);
3419 let mut flags: BTreeMap<String, Value> = BTreeMap::new();
3420 let mut positionals: Vec<Value> = Vec::new();
3421 let utf8 = |value: std::ffi::OsString| -> DiagnosticResult<String> {
3422 value
3423 .into_string()
3424 .map_err(|_| std_diag::std_parse_args_not_utf8())
3425 };
3426 loop {
3427 match parser.next() {
3428 Ok(None) => break,
3429 Ok(Some(Long(name))) => {
3430 let key = name.to_owned();
3431 if let Some(raw) = parser.optional_value() {
3432 flags.insert(key, Value::string(utf8(raw)?));
3433 } else {
3434 flags.insert(key, Value::bool(true));
3435 }
3436 }
3437 Ok(Some(Short(ch))) => {
3438 flags.insert(ch.to_string(), Value::bool(true));
3439 }
3440 Ok(Some(ArgValue(raw))) => {
3441 positionals.push(Value::string(utf8(raw)?));
3442 }
3443 Err(lexopt::Error::UnexpectedValue { option, value }) => {
3444 let key = option
3445 .strip_prefix("--")
3446 .or_else(|| option.strip_prefix('-'))
3447 .unwrap_or(option.as_str());
3448 flags.insert(key.to_string(), Value::string(utf8(value)?));
3449 }
3450 Err(err) => return Err(std_diag::std_parse_args_lex_error(&err)),
3451 }
3452 }
3453 Ok((flags, positionals))
3454}
3455
3456fn coerce_flags(
3464 specs: &CliSpecs,
3465 raw: &BTreeMap<String, Value>,
3466) -> DiagnosticResult<BTreeMap<String, Value>> {
3467 let mut alias_to_canonical: BTreeMap<&str, &str> = BTreeMap::new();
3470 for (canonical, spec) in specs.iter() {
3471 if let Some(alias) = spec.alias.as_ref() {
3472 alias_to_canonical.insert(alias.as_str(), canonical.as_str());
3473 }
3474 }
3475 let mut coerced: BTreeMap<String, Value> = BTreeMap::new();
3476 for (flag, spec) in specs.iter() {
3477 if flag.is_empty() {
3478 return Err(std_diag::std_parse_args_schema_flag_empty());
3479 }
3480 let canonical_raw = raw.get(flag);
3481 let alias_raw = spec.alias.as_ref().and_then(|alias| raw.get(alias));
3482 if canonical_raw.is_some() && alias_raw.is_some() {
3483 return Err(std_diag::std_parse_args_duplicate_flag(
3484 flag,
3485 spec.alias.as_deref(),
3486 ));
3487 }
3488 if let Some(raw_val) = canonical_raw.or(alias_raw) {
3489 coerced.insert(
3490 flag.clone(),
3491 coerce_cli_flag(spec.target, flag, raw_val.clone())?,
3492 );
3493 } else if let Some(d) = spec.default.as_ref() {
3494 coerced.insert(flag.clone(), d.clone());
3495 } else if spec.required {
3496 return Err(std_diag::std_parse_args_missing_flag(
3497 flag,
3498 spec.alias.as_deref(),
3499 ));
3500 }
3501 }
3502 for flag in raw.keys() {
3503 if !specs.contains_key(flag) && !alias_to_canonical.contains_key(flag.as_str()) {
3504 return Err(std_diag::std_parse_args_unknown_flag(flag));
3505 }
3506 }
3507 Ok(coerced)
3508}
3509
3510fn resolve_flags_specs<P: ProcessManager>(cx: &mut StepCtx<P>) -> DiagnosticResult<CliSpecs> {
3517 let name = "FLAGS";
3518 let tag = cx
3519 .state
3520 .resolve_tag(name)
3521 .map_err(|err| std_diag::std_parse_args_schema_type(name, &err))?;
3522 let TypeTag::Record(fields) = tag else {
3523 return Err(std_diag::std_parse_args_schema_shape(name));
3524 };
3525 let mut specs = BTreeMap::new();
3526 for field in fields.iter() {
3527 let target = match field.ty {
3528 TypeTag::String => CliType::String,
3529 TypeTag::Bool => CliType::Bool,
3530 TypeTag::Int => CliType::Int,
3531 TypeTag::Float => CliType::Float,
3532 _ => {
3533 return Err(std_diag::std_parse_args_schema_field_type(
3534 &field.name,
3535 field.ty.name(),
3536 ));
3537 }
3538 };
3539 specs.insert(
3540 field.name.clone(),
3541 CliSpec {
3542 target,
3543 required: !field.optional && field.default.is_none(),
3544 default: field.default.clone(),
3545 alias: field.alias.clone(),
3546 },
3547 );
3548 }
3549 Ok(specs)
3550}
3551
3552pub struct ParseFlags;
3560
3561impl<P: ProcessManager> OxDockFn<P> for ParseFlags {
3562 fn registration() -> HostRegistration<P> {
3563 let func: NativeFn<P> = Arc::new(|cx: &mut StepCtx<P>, values: Vec<Value>| {
3564 if values.len() != 1 {
3565 return Err(std_diag::std_parse_flags_arity(values.len()));
3566 }
3567 let mut iter = values.into_iter();
3568 let args_val = iter.next().expect("arity checked above");
3569 let args = string_list_arg(&args_val, "{FUNC_PARSE_FLAGS}() argument `$args`")?;
3570 let specs = resolve_flags_specs(cx)?;
3571 let (raw, positionals) = tokenize_raw_args(args)?;
3572 if !positionals.is_empty() {
3573 return Err(std_diag::std_parse_flags_positional(
3574 &positionals
3575 .iter()
3576 .map(|pos| pos.to_string())
3577 .collect::<Vec<_>>(),
3578 ));
3579 }
3580 Ok(Value::map(coerce_flags(&specs, &raw)?))
3581 });
3582 HostRegistration::Stateful {
3583 name: FUNC_PARSE_FLAGS.to_string(),
3584 meta: FuncMeta {
3585 name: FUNC_PARSE_FLAGS.to_string(),
3586 module: String::new(),
3587 kind: FuncKind::HostPure,
3588 params: Some(vec![FuncParam {
3589 name: "args".to_string(),
3590 param_type: Some(TypeTag::ListOf(Arc::new(TypeTag::String))),
3591 allowed: None,
3592 docs: "Argv tail to parse, usually from `STD::ARGV()`.",
3593 options: None,
3594 optional: false,
3595 }]),
3596 returns: Some(TypeTag::Map),
3597 rpn: true,
3598 summary: "Parse flags against TYPE FLAGS.",
3599 docs: "Consumes a `LIST<STRING>` and coerces flags through `TYPE FLAGS`. Returns the flags `MAP` directly; positional arguments fail.",
3600 examples: &[crate::Example {
3601 name: "flags only",
3602 fence_meta: None,
3603 code: indoc::indoc! {r#"
3604 IMPORT [STD]
3605 # Flags only returns the flags MAP directly.
3606 TYPE FLAGS = MAP<model: STRING, retries: INT = 2>
3607 LET $flags: FLAGS = PARSE_FLAGS(["--model=x"])
3608 ASSERT_EQ $flags.model "x"
3609 ASSERT_EQ $flags.retries 2
3610 "#},
3611 }],
3612 },
3613 func,
3614 }
3615 }
3616}
3617
3618pub struct ParsePositionals;
3623
3624impl<P: ProcessManager> OxDockFn<P> for ParsePositionals {
3625 fn registration() -> HostRegistration<P> {
3626 let func: NativeFn<P> = Arc::new(|_: &mut StepCtx<P>, values: Vec<Value>| {
3627 if values.len() != 1 {
3628 return Err(std_diag::std_parse_positionals_arity(values.len()));
3629 }
3630 let mut iter = values.into_iter();
3631 let args_val = iter.next().expect("arity checked above");
3632 let args = string_list_arg(
3633 &args_val,
3634 &format!("{FUNC_PARSE_POSITIONALS}() argument `$args`"),
3635 )?;
3636 let (_raw, positionals) = tokenize_raw_args(args)?;
3637 Ok(Value::list(positionals))
3638 });
3639 HostRegistration::Stateful {
3640 name: FUNC_PARSE_POSITIONALS.to_string(),
3641 meta: FuncMeta {
3642 name: FUNC_PARSE_POSITIONALS.to_string(),
3643 module: String::new(),
3644 kind: FuncKind::HostPure,
3645 params: Some(vec![FuncParam {
3646 name: "args".to_string(),
3647 param_type: Some(TypeTag::ListOf(Arc::new(TypeTag::String))),
3648 allowed: None,
3649 docs: "Argv tail to parse, usually from `STD::ARGV()`.",
3650 options: None,
3651 optional: false,
3652 }]),
3653 returns: Some(TypeTag::ListOf(Arc::new(TypeTag::String))),
3654 rpn: true,
3655 summary: "Parse positionals in argv order.",
3656 docs: "Consumes a `LIST<STRING>` and returns positionals in argv order with no schema.",
3657 examples: &[crate::Example {
3658 name: "positionals only",
3659 fence_meta: None,
3660 code: indoc::indoc! {r#"
3661 IMPORT [STD]
3662 # No schema needed: positionals are always strings in order.
3663 TYPE POSITIONS = LIST<STRING>
3664 LET $pos: POSITIONS = PARSE_POSITIONALS(["serve", "--", "--not-a-flag"])
3665 ASSERT_EQ $pos.0 "serve"
3666 ASSERT_EQ $pos.1 "--not-a-flag"
3667 "#},
3668 }],
3669 },
3670 func,
3671 }
3672 }
3673}
3674
3675#[oxdock_func(
3690 returns = TypeTag::Record(std::sync::Arc::from([Field {
3691 name: "name".to_string(),
3692 ty: TypeTag::String,
3693 docs: "Qualified function name.",
3694 optional: false,
3695 default: None,
3696
3697 alias: None,}, Field {
3698 name: "module".to_string(),
3699 ty: TypeTag::String,
3700 docs: "Owning module.",
3701 optional: false,
3702 default: None,
3703
3704 alias: None,}, Field {
3705 name: "kind".to_string(),
3706 ty: TypeTag::String,
3707 docs: "Origin label (`host` or `script`).",
3708 optional: false,
3709 default: None,
3710
3711 alias: None,}, Field {
3712 name: "params".to_string(),
3713 ty: TypeTag::ListOf(std::sync::Arc::new(TypeTag::MapOf(std::sync::Arc::new(
3714 TypeTag::Any,
3715 )))),
3716 docs: "Parameter entries (empty for parameterless functions).",
3717 optional: false,
3718 default: None,
3719
3720 alias: None,}, Field {
3721 name: "returns".to_string(),
3722 ty: TypeTag::String,
3723 docs: "Structural return shape (empty when untagged).",
3724 optional: false,
3725 default: None,
3726
3727 alias: None,}, Field {
3728 name: "rpn".to_string(),
3729 ty: TypeTag::Bool,
3730 docs: "True when callable in RPN position.",
3731 optional: false,
3732 default: None,
3733
3734 alias: None,}, Field {
3735 name: "summary".to_string(),
3736 ty: TypeTag::String,
3737 docs: "One-line description.",
3738 optional: false,
3739 default: None,
3740
3741 alias: None,}]))
3742 summary = "Describe one function by qualified name."
3743)]
3744#[example(
3745 name = "describe",
3746 code = r###"
3747 IMPORT [STD]
3748 LET $info: MAP<ANY> = DESCRIBE("STD::INT")
3749 ASSERT_EQ $info.name "STD::INT"
3750 ASSERT_EQ $info.returns "INT"
3751 "###
3752)]
3753fn describe<P: ProcessManager>(
3754 cx: &mut StepCtx<P>,
3755 name: String,
3757) -> DiagnosticResult<Value> {
3758 if split_qualified(&name).is_none() && name != KEYWORD_INSPECT {
3759 return Err(std_diag::func_describe_unqualified(&name));
3760 }
3761 cx.state
3762 .describe_function(&name)
3763 .ok_or_else(|| std_diag::func_unknown(&name))
3764}
3765
3766#[oxdock_func(returns = TypeTag::ListOf(std::sync::Arc::new(TypeTag::String)))]
3772#[example(
3773 name = "list",
3774 code = r###"
3775 IMPORT [STD]
3776 LET $names: LIST<STRING> = TYPES()
3777 ASSERT_CONTAINS $names "STRING"
3778 "###
3779)]
3780fn types<P: ProcessManager>(cx: &mut StepCtx<P>) -> DiagnosticResult<Value> {
3781 Ok(Value::list(
3782 cx.state
3783 .type_names()
3784 .into_iter()
3785 .map(Value::string)
3786 .collect(),
3787 ))
3788}
3789
3790#[oxdock_func(returns = TypeTag::Record(std::sync::Arc::from([Field {
3796 name: "name".to_string(),
3797 ty: TypeTag::String,
3798 docs: "Queried type name.",
3799 optional: false,
3800 default: None,
3801
3802 alias: None,}, Field {
3803 name: "summary".to_string(),
3804 ty: TypeTag::String,
3805 docs: "One-line description.",
3806 optional: false,
3807 default: None,
3808
3809 alias: None,}, Field {
3810 name: "docs".to_string(),
3811 ty: TypeTag::String,
3812 docs: "Full documentation text.",
3813 optional: false,
3814 default: None,
3815
3816 alias: None,}])))]
3817#[example(
3818 name = "describe",
3819 code = r###"
3820 IMPORT [STD]
3821 LET $info: MAP<ANY> = TYPE_DESCRIBE("STRING")
3822 ASSERT_EQ $info.name "STRING"
3823 "###
3824)]
3825fn type_describe<P: ProcessManager>(
3826 cx: &mut StepCtx<P>,
3827 name: String,
3829) -> DiagnosticResult<Value> {
3830 if let Some(descriptor) = cx.state.describe_type(&name) {
3831 let mut map = BTreeMap::new();
3832 map.insert(
3833 "name".to_string(),
3834 Value::string(descriptor.name.to_string()),
3835 );
3836 map.insert(
3837 "summary".to_string(),
3838 Value::string(descriptor.summary.to_string()),
3839 );
3840 map.insert(
3841 "docs".to_string(),
3842 Value::string(descriptor.docs.to_string()),
3843 );
3844 return Ok(Value::map(map));
3845 }
3846 if let Some(target) = cx.state.alias_target(&name) {
3849 let mut map = BTreeMap::new();
3850 map.insert("name".to_string(), Value::string(name.clone()));
3851 map.insert(
3852 "summary".to_string(),
3853 Value::string(format!("Script type alias for {target}.")),
3854 );
3855 map.insert(
3856 "docs".to_string(),
3857 Value::string(format!(
3858 "Declared with {KEYWORD_TYPE} {name} = {target}. The alias expands structurally at every declaration."
3859 )),
3860 );
3861 return Ok(Value::map(map));
3862 }
3863 Err(std_diag::std_unknown_type(&name))
3864}
3865
3866#[oxdock_func(returns = TypeTag::String)]
3880#[example(
3881 name = "self",
3882 code = r###"
3883 # The running interpreter resolves to a non-empty path.
3884 IMPORT [STD]
3885 LET $exe: STRING = INTERPRETER()
3886 LET $nonempty: BOOL = $exe != ""
3887 ASSERT_EQ $nonempty true
3888 "###
3889)]
3890#[example(
3891 name = "dynamic assembly",
3892 code = r###"
3893 # Assemble the child script dynamically: the parent interpolates
3894 # its own bindings into the pipe, then runs the interpreter on it.
3895 # Unescaped {{ }} bakes in at render time; \{{ }} stays literal
3896 # so the child expands it with its own bindings.
3897 # The pipe delivers EOF when the producer step ends, so the child
3898 # reads exactly one script.
3899 IMPORT [STD]
3900 LET $exe: STRING = INTERPRETER()
3901 LET $who: STRING = "Ada"
3902 LET $child: PIPE
3903 WITH_IO [stdout=$child] ECHO """
3904 ECHO "hello {{ $who }}!"
3905 LET $who: STRING = "Grace"
3906 ECHO "child sees \{{ $who }}!"
3907 """
3908 LET $out: STRING = WITH_IO [stdin=$child] RUN [$exe]
3909 ASSERT_CONTAINS $out "hello Ada!"
3910 ASSERT_CONTAINS $out "child sees Grace!"
3911 "###
3912)]
3913fn interpreter<P: ProcessManager>(cx: &mut StepCtx<P>) -> DiagnosticResult<Value> {
3914 if let Some(staged) = cx.state.io.interpreter_override() {
3915 return Ok(Value::string(staged));
3916 }
3917 Ok(Value::string(oxdock_process::interpreter_exe()?))
3918}
3919
3920#[oxdock_func(returns = TypeTag::Bool)]
3928#[example(
3929 name = "main",
3930 code = r###"
3931 # Entry top level runs as main.
3932 IMPORT [STD]
3933 LET $m: BOOL = IS_MAIN()
3934 ASSERT_EQ $m true
3935 "###
3936)]
3937#[example(
3938 name = "library doubles as demo",
3939 fence_meta = "roots:unified",
3940 code = r###"
3941 # A library doubles as a runnable demo: guard the demo with
3942 # IF IS_MAIN() so importing it stays side effect free. The
3943 # parent writes both files, then runs each in a fresh
3944 # interpreter: direct execution prints the demo, importing
3945 # it does not. Unified roots: the child inherits one
3946 # workspace, so parent and child see the same files. The
3947 # exact stdout match proves the demo line stays out of the
3948 # importing run.
3949 IMPORT [STD]
3950
3951 # The library under test: demo guarded by IS_MAIN.
3952 WRITE lib.oxfile """
3953 IMPORT [STD]
3954 FUNC GREET($x: STRING): STRING { RETURN "hi \{{ $x }}" }
3955 EXPORT GREET
3956 IF IS_MAIN() {
3957 ECHO "demo: hi Ada"
3958 }
3959 """
3960
3961 # The importer: calls the library, prints only its own line.
3962 WRITE main.oxfile """
3963 IMPORT ["lib.oxfile" AS LIB]
3964 LET $g: STRING = LIB::GREET("Bo")
3965 ECHO "imported: \{{ $g }}"
3966 """
3967
3968 # Direct run executes the demo.
3969 LET $exe: STRING = INTERPRETER()
3970 LET $direct: STRING = RUN [$exe, "lib.oxfile"]
3971 ASSERT_CONTAINS $direct "demo: hi Ada"
3972
3973 # Importing run stays silent apart from its own line.
3974 LET $via: STRING = RUN [$exe, "main.oxfile"]
3975 ASSERT_EQ $via "imported: hi Bo\n"
3976 "###
3977)]
3978fn is_main<P: ProcessManager>(cx: &mut StepCtx<P>) -> DiagnosticResult<Value> {
3979 let main = match cx.state.module_stack.last() {
3980 None | Some(None) => true,
3981 Some(Some(_)) => false,
3982 };
3983 Ok(Value::bool(main))
3984}
3985
3986#[oxdock_func(returns = TypeTag::Bool)]
4000#[example(
4001 name = "null stdin",
4002 code = r###"
4003 # A null stdin is never a terminal, in every harness.
4004 IMPORT [STD]
4005 LET $term: BOOL = IS_TERMINAL("stdin")
4006 ASSERT_EQ $term false
4007 "###
4008)]
4009fn is_terminal<P: ProcessManager>(
4010 cx: &mut StepCtx<P>,
4011 #[values("stdin", "stdout", "stderr")]
4013 stream_name: String,
4014) -> DiagnosticResult<Value> {
4015 use std::io::IsTerminal;
4016 let terminal = match stream_name.as_str() {
4017 "stdin" => {
4018 if cx.stdin_pipe.is_some() {
4023 false
4024 } else {
4025 match &cx.stdin {
4026 CommandStdin::Null => false,
4027 #[cfg(not(miri))]
4028 CommandStdin::OsPipe(_) => false,
4029 CommandStdin::Stream(_) => false,
4030 CommandStdin::Inherit => std::io::stdin().is_terminal(),
4031 }
4032 }
4033 }
4034 "stdout" => {
4035 if cx.out_pipe.is_some() {
4036 false
4038 } else if cx.state.io.stdout().is_some() {
4039 false
4042 } else {
4043 match &cx.out {
4044 None => std::io::stdout().is_terminal(),
4046 #[cfg(not(miri))]
4048 Some(StreamHandle::Os(_)) => false,
4049 Some(StreamHandle::Stream(_)) => std::io::stdout().is_terminal(),
4059 }
4060 }
4061 }
4062 "stderr" => {
4063 if cx.state.io.stderr().is_some() {
4064 false
4066 } else {
4067 match &cx.err {
4068 None => std::io::stderr().is_terminal(),
4070 #[cfg(not(miri))]
4072 Some(StreamHandle::Os(_)) => false,
4073 Some(StreamHandle::Stream(_)) => false,
4076 }
4077 }
4078 }
4079 _ => {
4080 return Err(std_diag::std_is_terminal_expected(&stream_name));
4081 }
4082 };
4083 Ok(Value::bool(terminal))
4084}
4085
4086#[oxdock_func(returns = TypeTag::Semaphore)]
4094#[example(
4095 name = "mint",
4096 code = r###"
4097 # Mint a semaphore admitting at most two holders.
4098 IMPORT [STD]
4099 LET $sem: SEMAPHORE = SEMAPHORE_NEW(2)
4100
4101 # A fresh semaphore reports its full cap as available.
4102 LET $free: INT = SEMAPHORE_AVAILABLE($sem)
4103 ASSERT_EQ $free 2
4104 "###
4105)]
4106fn semaphore_new<P: ProcessManager>(
4107 cx: &mut StepCtx<P>,
4108 max: i64,
4110) -> DiagnosticResult<Value> {
4111 let _ = cx;
4112 if max <= 0 {
4113 return Err(std_diag::std_semaphore_needs_positive(max));
4114 }
4115 Ok(Value::semaphore(max as usize))
4116}
4117
4118#[oxdock_func(returns = TypeTag::Record(std::sync::Arc::from([Field {
4127 name: "held".to_string(),
4128 ty: TypeTag::Bool,
4129 docs: "`true` with the permit under `permit`, `false` with no `permit` key.",
4130 optional: false,
4131 default: None,
4132
4133 alias: None,}, Field {
4134 name: "permit".to_string(),
4135 ty: TypeTag::Permit,
4136 docs: "Permit handle; read only when `held`.",
4137 optional: true,
4138 default: None,
4139
4140 alias: None,}])))]
4141#[example(
4142 name = "acquire",
4143 code = r###"
4144 # First acquire holds with a permit to bind.
4145 IMPORT [STD]
4146 LET $sem: SEMAPHORE = SEMAPHORE_NEW(1)
4147 LET $first: MAP<held: BOOL, permit?: PERMIT> = SEMAPHORE_TRY_ACQUIRE($sem)
4148 ASSERT_EQ $first.held true
4149 LET $permit: PERMIT = $first.permit
4150
4151 # A capped semaphore answers held false with no permit key.
4152 LET $second: MAP<held: BOOL, permit?: PERMIT> = SEMAPHORE_TRY_ACQUIRE($sem)
4153 ASSERT_EQ $second.held false
4154 LET $has_permit: BOOL = HAS_KEY($second, "permit")
4155 ASSERT_EQ $has_permit false
4156 "###
4157)]
4158fn semaphore_try_acquire<P: ProcessManager>(
4159 cx: &mut StepCtx<P>,
4160 sem: Arc<SemaphoreState>,
4162) -> DiagnosticResult<Value> {
4163 let _ = cx;
4164 let mut map = BTreeMap::new();
4165 if sem.try_acquire() {
4166 map.insert("held".to_string(), Value::bool(true));
4167 map.insert("permit".to_string(), Value::permit(&sem));
4168 } else {
4169 map.insert("held".to_string(), Value::bool(false));
4170 }
4171 Ok(Value::map(map))
4172}
4173
4174#[oxdock_func(pure, returns = TypeTag::Int)]
4181#[example(
4182 name = "readout",
4183 code = r###"
4184 # Hold one permit on a cap of two.
4185 IMPORT [STD]
4186 LET $sem: SEMAPHORE = SEMAPHORE_NEW(2)
4187 LET $acq: MAP<held: BOOL, permit?: PERMIT> = SEMAPHORE_TRY_ACQUIRE($sem)
4188 ASSERT_EQ $acq.held true
4189
4190 # One held permit leaves exactly one free.
4191 LET $free: INT = SEMAPHORE_AVAILABLE($sem)
4192 ASSERT_EQ $free 1
4193 "###
4194)]
4195fn semaphore_available(
4196 sem: Arc<SemaphoreState>,
4198) -> DiagnosticResult<Value> {
4199 Ok(Value::int(sem.available() as i64))
4200}
4201
4202#[oxdock_func(
4211 rpn,
4212 returns = TypeTag::union(vec![TypeTag::String, TypeTag::Pipe]),
4213 template = text_trim_string
4214)]
4215#[example(
4216 name = "trim",
4217 code = r###"
4218 # Leading and trailing whitespace falls away.
4219 IMPORT [STD]
4220 LET $clean: STRING = TEXT_TRIM(" hello ")
4221 ASSERT_EQ $clean "hello"
4222 "###
4223)]
4224#[example(
4225 name = "trim pipe mirrors",
4226 code = r###"
4227 # Pipe input mints pipe output with the same transform.
4228 IMPORT [STD]
4229 LET $cap: PIPE
4230 WITH_IO [stdout=$cap] {
4231 ECHO " hello "
4232 }
4233 LET $out: PIPE = TEXT_TRIM($cap)
4234 WITH_IO [stdin=$out] READ_LINE $line
4235 ASSERT_EQ $line "hello"
4236 "###
4237)]
4238#[example(
4239 name = "trim template",
4240 code = r###"
4241 # String inputs run inside placeholders too.
4242 IMPORT [STD]
4243 LET $msg: STRING = 'clean:{{ STD::TEXT_TRIM(" hello ") }}'
4244 ASSERT_EQ $msg "clean:hello"
4245 "###
4246)]
4247#[example(
4248 name = "trim file template",
4249 code = r###"
4250 # EXPAND templates resolve the same registry.
4251 IMPORT [STD]
4252 WRITE "tpl.txt" "clean:\{{ STD::TEXT_TRIM(\" hello \") }}"
4253 LET $out: STRING = EXPAND "tpl.txt"
4254 ASSERT_EQ $out "clean:hello"
4255 "###
4256)]
4257fn text_trim<P: ProcessManager>(
4258 cx: &mut StepCtx<P>,
4259 #[union(String, Pipe)]
4261 text: Value,
4262) -> DiagnosticResult<Value> {
4263 super::args::mirror_stream(cx, "TEXT_TRIM", &text, super::args::TextPump::Trim)
4264}
4265
4266fn text_trim_string(text: Value) -> DiagnosticResult<Value> {
4269 super::args::mirror_string("TEXT_TRIM", &text, super::args::TextPump::Trim)
4270}
4271
4272#[oxdock_func(
4281 rpn,
4282 returns = TypeTag::union(vec![TypeTag::String, TypeTag::Pipe]),
4283 template = text_trim_prefix_string
4284)]
4285#[example(
4286 name = "strip prefix",
4287 code = r###"
4288 # A present prefix falls away; absence returns the input unchanged.
4289 IMPORT [STD]
4290 LET $bare: STRING = TEXT_TRIM_PREFIX("v1.2.3", "v")
4291 ASSERT_EQ $bare "1.2.3"
4292
4293 # Missing prefixes pass through untouched.
4294 LET $same: STRING = TEXT_TRIM_PREFIX("1.2.3", "v")
4295 ASSERT_EQ $same "1.2.3"
4296 "###
4297)]
4298#[example(
4299 name = "strip prefix pipe mirrors",
4300 code = r###"
4301 # Pipe input mints pipe output with the same strip.
4302 IMPORT [STD]
4303 LET $cap: PIPE
4304 WITH_IO [stdout=$cap] {
4305 ECHO "v1.2.3"
4306 }
4307 LET $trimmed: PIPE = TEXT_TRIM($cap)
4308 LET $out: PIPE = TEXT_TRIM_PREFIX($trimmed, "v")
4309 WITH_IO [stdin=$out] READ_LINE $line
4310 ASSERT_EQ $line "1.2.3"
4311 "###
4312)]
4313#[example(
4314 name = "strip prefix template",
4315 code = r###"
4316 # String inputs run inside placeholders too.
4317 IMPORT [STD]
4318 LET $msg: STRING = 'bare:{{ STD::TEXT_TRIM_PREFIX("v1.2.3", "v") }}'
4319 ASSERT_EQ $msg "bare:1.2.3"
4320 "###
4321)]
4322fn text_trim_prefix<P: ProcessManager>(
4323 cx: &mut StepCtx<P>,
4324 #[union(String, Pipe)]
4326 text: Value,
4327 prefix: String,
4329) -> DiagnosticResult<Value> {
4330 super::args::mirror_stream(
4331 cx,
4332 "TEXT_TRIM_PREFIX",
4333 &text,
4334 super::args::TextPump::TrimPrefix(prefix),
4335 )
4336}
4337
4338fn text_trim_prefix_string(text: Value, prefix: String) -> DiagnosticResult<Value> {
4341 super::args::mirror_string(
4342 "TEXT_TRIM_PREFIX",
4343 &text,
4344 super::args::TextPump::TrimPrefix(prefix),
4345 )
4346}
4347
4348#[oxdock_func(
4355 rpn,
4356 returns = TypeTag::union(vec![TypeTag::String, TypeTag::Pipe]),
4357 template = text_trim_suffix_string
4358)]
4359#[example(
4360 name = "strip suffix",
4361 code = r###"
4362 # A present suffix falls away; absence returns the input unchanged.
4363 IMPORT [STD]
4364 LET $bare: STRING = TEXT_TRIM_SUFFIX("archive.tar.gz", ".gz")
4365 ASSERT_EQ $bare "archive.tar"
4366
4367 # Missing suffixes pass through untouched.
4368 LET $same: STRING = TEXT_TRIM_SUFFIX("archive.tar", ".gz")
4369 ASSERT_EQ $same "archive.tar"
4370 "###
4371)]
4372#[example(
4373 name = "strip suffix pipe mirrors",
4374 code = r###"
4375 # Pipe input mints pipe output with the same strip.
4376 IMPORT [STD]
4377 LET $cap: PIPE
4378 WITH_IO [stdout=$cap] {
4379 ECHO "archive.tar.gz"
4380 }
4381 LET $trimmed: PIPE = TEXT_TRIM($cap)
4382 LET $out: PIPE = TEXT_TRIM_SUFFIX($trimmed, ".gz")
4383 WITH_IO [stdin=$out] READ_LINE $line
4384 ASSERT_EQ $line "archive.tar"
4385 "###
4386)]
4387#[example(
4388 name = "strip suffix template",
4389 code = r###"
4390 # String inputs run inside placeholders too.
4391 IMPORT [STD]
4392 LET $msg: STRING = 'bare:{{ STD::TEXT_TRIM_SUFFIX("archive.tar.gz", ".gz") }}'
4393 ASSERT_EQ $msg "bare:archive.tar"
4394 "###
4395)]
4396fn text_trim_suffix<P: ProcessManager>(
4397 cx: &mut StepCtx<P>,
4398 #[union(String, Pipe)]
4400 text: Value,
4401 suffix: String,
4403) -> DiagnosticResult<Value> {
4404 super::args::mirror_stream(
4405 cx,
4406 "TEXT_TRIM_SUFFIX",
4407 &text,
4408 super::args::TextPump::TrimSuffix(suffix),
4409 )
4410}
4411
4412fn text_trim_suffix_string(text: Value, suffix: String) -> DiagnosticResult<Value> {
4415 super::args::mirror_string(
4416 "TEXT_TRIM_SUFFIX",
4417 &text,
4418 super::args::TextPump::TrimSuffix(suffix),
4419 )
4420}
4421
4422#[oxdock_func(returns = TypeTag::String)]
4433#[example(
4434 name = "join path",
4435 code = r###"
4436 # Directory and file stem join with the native separator.
4437 # Source `\\` is one backslash at runtime; `/` works on Windows
4438 # too, native just reads better there.
4439 IMPORT [STD]
4440 LET $p: STRING = PATH_JOIN("some-dir", "some-file")
4441 [family:unix] ASSERT_EQ $p "some-dir/some-file"
4442 [family:windows] ASSERT_EQ $p "some-dir\\some-file"
4443 "###
4444)]
4445fn path_join<P: ProcessManager>(
4446 _cx: &mut StepCtx<P>,
4447 #[union(String, Path)]
4449 dir: Value,
4450 #[union(String, Path)]
4452 name: Value,
4453) -> DiagnosticResult<Value> {
4454 let d = super::args::string_or_path_text(&dir)?;
4455 let n = super::args::string_or_path_text(&name)?;
4456 Ok(Value::string(oxdock_fs::join_native(&d, &n)))
4457}
4458
4459#[oxdock_func(pure, returns = TypeTag::String)]
4467#[example(
4468 name = "base",
4469 code = r###"
4470 # Final segments bind without filesystem access.
4471 IMPORT [STD]
4472 LET $b: STRING = PATH_BASE("some-dir/some-file")
4473 ASSERT_EQ $b "some-file"
4474
4475 # Trailing slashes trim before the split.
4476 LET $d: STRING = PATH_BASE("some-dir/")
4477 ASSERT_EQ $d "some-dir"
4478 "###
4479)]
4480fn path_base(
4481 #[union(String, Path)]
4483 path: Value,
4484) -> DiagnosticResult<Value> {
4485 let text = super::args::string_or_path_text(&path)?;
4486 let base = oxdock_fs::path_base(&text).map_err(|e| std_diag::std_path_base_failed(&e))?;
4487 Ok(Value::string(base))
4488}
4489
4490#[oxdock_func(pure, returns = TypeTag::String)]
4500#[example(
4501 name = "relativize",
4502 code = r###"
4503 # Prefix bases strip to their remainder.
4504 IMPORT [STD]
4505 LET $r: STRING = PATH_REL("some-dir", "some-dir/some-file")
4506 ASSERT_EQ $r "some-file"
4507
4508 # Equal paths bind dot.
4509 LET $dot: STRING = PATH_REL("some-dir", "some-dir")
4510 ASSERT_EQ $dot "."
4511 "###
4512)]
4513fn path_rel(
4514 #[union(String, Path)]
4516 base: Value,
4517 #[union(String, Path)]
4519 path: Value,
4520) -> DiagnosticResult<Value> {
4521 let b = super::args::string_or_path_text(&base)?;
4522 let p = super::args::string_or_path_text(&path)?;
4523 let rel = oxdock_fs::path_rel(&b, &p).map_err(|e| std_diag::std_path_rel_failed(&e))?;
4524 Ok(Value::string(rel))
4525}
4526
4527#[oxdock_func(
4534 rpn,
4535 returns = TypeTag::union(vec![TypeTag::String, TypeTag::Pipe]),
4536 template = text_to_upper_string
4537)]
4538#[example(
4539 name = "uppercase",
4540 code = r###"
4541 # Text folds to uppercase.
4542 IMPORT [STD]
4543 LET $loud: STRING = TEXT_TO_UPPER("hello")
4544 ASSERT_EQ $loud "HELLO"
4545 "###
4546)]
4547#[example(
4548 name = "uppercase pipe mirrors",
4549 code = r###"
4550 # Pipe input mints pipe output with the same fold.
4551 IMPORT [STD]
4552 LET $cap: PIPE
4553 WITH_IO [stdout=$cap] {
4554 ECHO "hello"
4555 }
4556 LET $out: PIPE = TEXT_TO_UPPER($cap)
4557 WITH_IO [stdin=$out] READ_LINE $line
4558 ASSERT_EQ $line "HELLO"
4559 "###
4560)]
4561#[example(
4562 name = "uppercase template",
4563 code = r###"
4564 # String inputs run inside placeholders too.
4565 IMPORT [STD]
4566 LET $msg: STRING = 'loud:{{ STD::TEXT_TO_UPPER("hello") }}'
4567 ASSERT_EQ $msg "loud:HELLO"
4568 "###
4569)]
4570fn text_to_upper<P: ProcessManager>(
4571 cx: &mut StepCtx<P>,
4572 #[union(String, Pipe)]
4574 text: Value,
4575) -> DiagnosticResult<Value> {
4576 super::args::mirror_stream(cx, "TEXT_TO_UPPER", &text, super::args::TextPump::ToUpper)
4577}
4578
4579fn text_to_upper_string(text: Value) -> DiagnosticResult<Value> {
4582 super::args::mirror_string("TEXT_TO_UPPER", &text, super::args::TextPump::ToUpper)
4583}
4584
4585#[oxdock_func(
4592 rpn,
4593 returns = TypeTag::union(vec![TypeTag::String, TypeTag::Pipe]),
4594 template = text_to_lower_string
4595)]
4596#[example(
4597 name = "lowercase",
4598 code = r###"
4599 # Text folds to lowercase.
4600 IMPORT [STD]
4601 LET $quiet: STRING = TEXT_TO_LOWER("HELLO")
4602 ASSERT_EQ $quiet "hello"
4603 "###
4604)]
4605#[example(
4606 name = "lowercase pipe mirrors",
4607 code = r###"
4608 # Pipe input mints pipe output with the same fold.
4609 IMPORT [STD]
4610 LET $cap: PIPE
4611 WITH_IO [stdout=$cap] {
4612 ECHO "HELLO"
4613 }
4614 LET $out: PIPE = TEXT_TO_LOWER($cap)
4615 WITH_IO [stdin=$out] READ_LINE $line
4616 ASSERT_EQ $line "hello"
4617 "###
4618)]
4619#[example(
4620 name = "lowercase template",
4621 code = r###"
4622 # String inputs run inside placeholders too.
4623 IMPORT [STD]
4624 LET $msg: STRING = 'quiet:{{ STD::TEXT_TO_LOWER("HELLO") }}'
4625 ASSERT_EQ $msg "quiet:hello"
4626 "###
4627)]
4628fn text_to_lower<P: ProcessManager>(
4629 cx: &mut StepCtx<P>,
4630 #[union(String, Pipe)]
4632 text: Value,
4633) -> DiagnosticResult<Value> {
4634 super::args::mirror_stream(cx, "TEXT_TO_LOWER", &text, super::args::TextPump::ToLower)
4635}
4636
4637fn text_to_lower_string(text: Value) -> DiagnosticResult<Value> {
4640 super::args::mirror_string("TEXT_TO_LOWER", &text, super::args::TextPump::ToLower)
4641}
4642
4643#[oxdock_func(
4654 rpn,
4655 returns = TypeTag::union(vec![TypeTag::String, TypeTag::Pipe]),
4656 template = text_replace_string
4657)]
4658#[example(
4659 name = "replace",
4660 code = r###"
4661 # Every literal occurrence rewrites in place.
4662 IMPORT [STD]
4663 LET $fixed: STRING = TEXT_REPLACE("hello world", "world", "there")
4664 ASSERT_EQ $fixed "hello there"
4665 "###
4666)]
4667#[example(
4668 name = "replace pipe mirrors",
4669 code = r###"
4670 # Pipe input mints pipe output with the same rewrite.
4671 IMPORT [STD]
4672 LET $cap: PIPE
4673 WITH_IO [stdout=$cap] {
4674 ECHO "hello world"
4675 }
4676 LET $trimmed: PIPE = TEXT_TRIM($cap)
4677 LET $out: PIPE = TEXT_REPLACE($trimmed, "world", "there")
4678 WITH_IO [stdin=$out] READ_LINE $line
4679 ASSERT_EQ $line "hello there"
4680 "###
4681)]
4682#[example(
4683 name = "replace template",
4684 code = r###"
4685 # String inputs run inside placeholders too.
4686 IMPORT [STD]
4687 LET $msg: STRING = 'fixed:{{ STD::TEXT_REPLACE("hello world", "world", "there") }}'
4688 ASSERT_EQ $msg "fixed:hello there"
4689 "###
4690)]
4691fn text_replace<P: ProcessManager>(
4692 cx: &mut StepCtx<P>,
4693 #[union(String, Pipe)]
4695 text: Value,
4696 from: String,
4698 to: String,
4700) -> DiagnosticResult<Value> {
4701 super::args::mirror_stream(
4702 cx,
4703 FUNC_TEXT_REPLACE,
4704 &text,
4705 super::args::TextPump::ReplaceLiteral { from, to },
4706 )
4707}
4708
4709fn text_replace_string(text: Value, from: String, to: String) -> DiagnosticResult<Value> {
4712 super::args::mirror_string(
4713 FUNC_TEXT_REPLACE,
4714 &text,
4715 super::args::TextPump::ReplaceLiteral { from, to },
4716 )
4717}
4718
4719#[oxdock_func(
4731 rpn,
4732 returns = TypeTag::union(vec![TypeTag::String, TypeTag::Pipe]),
4733 template = text_replace_regex_string
4734)]
4735#[example(
4736 name = "replace with captures",
4737 code = r###"
4738 # Capture groups expand in the replacement.
4739 IMPORT [STD]
4740 LET $swapped: STRING = TEXT_REPLACE_REGEX("2026-10-13", "(\\d+)-(\\d+)-(\\d+)", "$3/$2/$1")
4741 ASSERT_EQ $swapped "13/10/2026"
4742 "###
4743)]
4744#[example(
4745 name = "replace regex pipe mirrors",
4746 code = r###"
4747 # Pipe input mints pipe output with the same rewrite.
4748 IMPORT [STD]
4749 LET $cap: PIPE
4750 WITH_IO [stdout=$cap] {
4751 ECHO "2026-10-13"
4752 }
4753 LET $trimmed: PIPE = TEXT_TRIM($cap)
4754 LET $out: PIPE = TEXT_REPLACE_REGEX($trimmed, "(\\d+)-(\\d+)-(\\d+)", "$3/$2/$1")
4755 WITH_IO [stdin=$out] READ_LINE $line
4756 ASSERT_EQ $line "13/10/2026"
4757 "###
4758)]
4759#[example(
4760 name = "replace regex template",
4761 code = r###"
4762 # String inputs run inside placeholders too.
4763 IMPORT [STD]
4764 LET $msg: STRING = 'swapped:{{ STD::TEXT_REPLACE_REGEX("2026-10-13", "(\\d+)-(\\d+)-(\\d+)", "$3/$2/$1") }}'
4765 ASSERT_EQ $msg "swapped:13/10/2026"
4766 "###
4767)]
4768fn text_replace_regex<P: ProcessManager>(
4769 cx: &mut StepCtx<P>,
4770 #[union(String, Pipe)]
4772 text: Value,
4773 pattern: String,
4775 replacement: String,
4777) -> DiagnosticResult<Value> {
4778 if let Some(s) = text.as_str() {
4779 let out = super::args::text_replace_regex_str(
4780 s,
4781 &pattern,
4782 &replacement,
4783 FUNC_TEXT_REPLACE_REGEX,
4784 )?;
4785 return Ok(Value::string(out));
4786 }
4787 let content = super::args::read_pipe_eager(cx, FUNC_TEXT_REPLACE_REGEX, &text)?;
4788 let out = super::args::text_replace_regex_str(
4789 &content,
4790 &pattern,
4791 &replacement,
4792 FUNC_TEXT_REPLACE_REGEX,
4793 )?;
4794 super::args::write_completed_pipe(cx, FUNC_TEXT_REPLACE_REGEX, out)
4795}
4796
4797fn text_replace_regex_string(
4800 text: Value,
4801 pattern: String,
4802 replacement: String,
4803) -> DiagnosticResult<Value> {
4804 let Some(s) = text.as_str() else {
4805 return Err(std_diag::std_pipe_needs_step_io(FUNC_TEXT_REPLACE_REGEX));
4806 };
4807 let out =
4808 super::args::text_replace_regex_str(s, &pattern, &replacement, FUNC_TEXT_REPLACE_REGEX)?;
4809 Ok(Value::string(out))
4810}
4811
4812#[oxdock_func(pure, returns = TypeTag::ListOf(std::sync::Arc::new(TypeTag::String)))]
4820#[example(
4821 name = "split",
4822 code = r###"
4823 # Delimiters split into list items.
4824 IMPORT [STD]
4825 LET $parts: LIST<STRING> = TEXT_SPLIT("a,b,c", ",")
4826 ASSERT_EQ $parts.0 "a"
4827 ASSERT_EQ $parts.1 "b"
4828 ASSERT_EQ $parts.2 "c"
4829 "###
4830)]
4831fn text_split(
4832 text: String,
4834 delimiter: String,
4836) -> DiagnosticResult<Value> {
4837 Ok(super::args::text_list_value(super::args::text_split_str(
4838 &text, &delimiter,
4839 )))
4840}
4841
4842#[oxdock_func(pure, returns = TypeTag::String)]
4845#[example(
4846 name = "join",
4847 code = r###"
4848 # List items join with the separator between them.
4849 IMPORT [STD]
4850 LET $joined: STRING = TEXT_JOIN(["a", "b", "c"], ",")
4851 ASSERT_EQ $joined "a,b,c"
4852 "###
4853)]
4854fn text_join(
4855 elements: Vec<String>,
4857 delimiter: String,
4859) -> DiagnosticResult<Value> {
4860 Ok(Value::string(elements.join(delimiter.as_str())))
4861}
4862
4863#[oxdock_func(pure, returns = TypeTag::ListOf(std::sync::Arc::new(TypeTag::String)))]
4875#[example(
4876 name = "split args",
4877 code = r###"
4878 # Quoted segments stay one word.
4879 IMPORT [STD]
4880 LET $argv: LIST<STRING> = SHELL_SPLIT_ARGS("gh issue comment 153 --body-file notes.md")
4881 ASSERT_EQ $argv.0 "gh"
4882 ASSERT_EQ $argv.3 "153"
4883 ASSERT_EQ $argv.5 "notes.md"
4884
4885 # Quotes and escapes parse the shell way.
4886 LET $quoted: LIST<STRING> = SHELL_SPLIT_ARGS("say \"hi there\" 'a b'")
4887 ASSERT_EQ $quoted.0 "say"
4888 ASSERT_EQ $quoted.1 "hi there"
4889 ASSERT_EQ $quoted.2 "a b"
4890 "###
4891)]
4892fn shell_split_args(
4893 command: String,
4895) -> DiagnosticResult<Value> {
4896 match shell_words::split(&command) {
4897 Ok(words) => Ok(super::args::text_list_value(words)),
4898 Err(err) => Err(std_diag::std_shell_split_failed(&err)),
4899 }
4900}
4901
4902#[oxdock_func(pure, returns = TypeTag::String)]
4910#[example(
4911 name = "join args",
4912 code = r###"
4913 # Plain words join with spaces and no quoting.
4914 IMPORT [STD]
4915 LET $plain: STRING = SHELL_JOIN_ARGS(["gh", "issue", "list"])
4916 ASSERT_EQ $plain "gh issue list"
4917
4918 # Words with spaces quote, and the round trip is exact.
4919 LET $words: LIST<STRING> = ["say", "hi there", "a'b"]
4920 LET $joined: STRING = SHELL_JOIN_ARGS($words)
4921 LET $back: LIST<STRING> = SHELL_SPLIT_ARGS($joined)
4922 ASSERT_EQ $back.0 "say"
4923 ASSERT_EQ $back.1 "hi there"
4924 ASSERT_EQ $back.2 "a'b"
4925 "###
4926)]
4927fn shell_join_args(
4928 words: Vec<String>,
4930) -> DiagnosticResult<Value> {
4931 Ok(Value::string(shell_words::join(&words)))
4932}
4933
4934#[oxdock_func(pure, returns = TypeTag::ListOf(std::sync::Arc::new(TypeTag::String)))]
4942#[example(
4943 name = "lines",
4944 code = r###"
4945 # Newlines split into line items.
4946 IMPORT [STD]
4947 LET $lines: LIST<STRING> = TEXT_LINES("one\ntwo\nthree")
4948 ASSERT_EQ $lines.0 "one"
4949 ASSERT_EQ $lines.1 "two"
4950 ASSERT_EQ $lines.2 "three"
4951
4952 # Windows endings split the same way after normalization.
4953 LET $crlf: LIST<STRING> = TEXT_LINES("one\r\ntwo\r\nthree")
4954 ASSERT_EQ $crlf.0 "one"
4955 ASSERT_EQ $crlf.1 "two"
4956 ASSERT_EQ $crlf.2 "three"
4957
4958 # Old Mac endings split too, and mixed endings split together because the input normalizes to LF before splitting.
4959 LET $mixed: LIST<STRING> = TEXT_LINES("a\r\nb\nc\rd")
4960 ASSERT_EQ $mixed.0 "a"
4961 ASSERT_EQ $mixed.1 "b"
4962 ASSERT_EQ $mixed.2 "c"
4963 ASSERT_EQ $mixed.3 "d"
4964 "###
4965)]
4966fn text_lines(
4967 text: String,
4969) -> DiagnosticResult<Value> {
4970 Ok(super::args::text_list_value(super::args::text_lines_str(
4971 &text,
4972 )))
4973}
4974
4975#[oxdock_func(pure, returns = TypeTag::ListOf(std::sync::Arc::new(TypeTag::String)))]
4981#[example(
4982 name = "fields",
4983 code = r###"
4984 # Runs of whitespace separate fields; empties never appear.
4985 IMPORT [STD]
4986 LET $fields: LIST<STRING> = TEXT_FIELDS(" abc def ")
4987 ASSERT_EQ $fields.0 "abc"
4988 ASSERT_EQ $fields.1 "def"
4989 "###
4990)]
4991fn text_fields(
4992 text: String,
4994) -> DiagnosticResult<Value> {
4995 Ok(super::args::text_list_value(super::args::text_fields_str(
4996 &text,
4997 )))
4998}
4999
5000#[oxdock_func(pure, returns = TypeTag::ListOf(std::sync::Arc::new(TypeTag::String)))]
5009#[example(
5010 name = "line range",
5011 code = r###"
5012 # Lines 2 through 3 come back as a list, 1-based inclusive.
5013 IMPORT [STD]
5014 LET $window: LIST<STRING> = TEXT_LINES_RANGE("one\ntwo\nthree\nfour", 2, 3)
5015 ASSERT_EQ $window.0 "two"
5016 ASSERT_EQ $window.1 "three"
5017
5018 # Ranges past the end clamp instead of failing.
5019 LET $tail: LIST<STRING> = TEXT_LINES_RANGE("one\ntwo", 2, 9)
5020 ASSERT_EQ $tail.0 "two"
5021 "###
5022)]
5023fn text_lines_range(
5024 text: String,
5026 from: i64,
5028 to: i64,
5030) -> DiagnosticResult<Value> {
5031 Ok(super::args::text_list_value(
5032 super::args::text_lines_range_str(&text, from, to, FUNC_TEXT_LINES_RANGE)?,
5033 ))
5034}
5035
5036#[oxdock_func(pure, returns = TypeTag::Bool)]
5044#[example(
5045 name = "match",
5046 code = r###"
5047 # Regex matches report true; misses report false.
5048 IMPORT [STD]
5049 LET $hit: BOOL = TEXT_MATCH("abc123", "\\d+")
5050 ASSERT_EQ $hit true
5051
5052 # A miss is false, not a failure.
5053 LET $miss: BOOL = TEXT_MATCH("abc", "^\\d+$")
5054 ASSERT_EQ $miss false
5055 "###
5056)]
5057fn text_match(
5058 text: String,
5060 pattern: String,
5062) -> DiagnosticResult<Value> {
5063 let re = super::args::text_compile_pattern(FUNC_TEXT_MATCH, &pattern)?;
5064 Ok(Value::bool(re.is_match(&text)))
5065}
5066
5067#[oxdock_func(pure, name = "BOOL", returns = TypeTag::Bool)]
5076#[example(
5077 name = "convert",
5078 code = r###"
5079 IMPORT [STD]
5080 LET $n: BOOL = BOOL("yes")
5081 ASSERT_EQ $n true
5082 LET $f: BOOL = BOOL("0")
5083 ASSERT_EQ $f false
5084 "###
5085)]
5086fn bool_convert(
5087 #[union(Bool, String)]
5089 val: Value,
5090) -> DiagnosticResult<Value> {
5091 if let Some(b) = val.as_bool() {
5092 return Ok(Value::bool(b));
5093 }
5094 let Some(s) = val.as_str() else {
5095 return Err(std_diag::std_bool_needs_bool_or_string(&val));
5096 };
5097 match super::args::parse_bool_str(s) {
5098 Some(b) => Ok(Value::bool(b)),
5099 None => Err(std_diag::std_bool_cannot_coerce(FUNC_BOOL, s)),
5100 }
5101}
5102
5103#[oxdock_func(pure, returns = TypeTag::Bool)]
5113#[example(
5114 name = "absent-default",
5115 code = r###"
5116 # Absent names read empty; the default settles the polarity.
5117 IMPORT [STD]
5118 INHERIT_ENV [OXDOCK_TEST_ABSENT_FLAG]
5119 LET $dry: BOOL = BOOL_OR("{{ env:OXDOCK_TEST_ABSENT_FLAG }}", true)
5120 ASSERT_EQ $dry true
5121
5122 # Present values coerce strictly, ignoring the default.
5123 LET $off: BOOL = BOOL_OR("false", true)
5124 ASSERT_EQ $off false
5125 "###
5126)]
5127fn bool_or(
5128 text: String,
5130 default: bool,
5132) -> DiagnosticResult<Value> {
5133 if text.trim().is_empty() {
5134 return Ok(Value::bool(default));
5135 }
5136 match super::args::parse_bool_str(&text) {
5137 Some(b) => Ok(Value::bool(b)),
5138 None => Err(std_diag::std_bool_cannot_coerce(FUNC_BOOL_OR, &text)),
5139 }
5140}
5141
5142#[oxdock_func(pure, returns = TypeTag::ListOf(std::sync::Arc::new(TypeTag::String)))]
5151#[example(
5152 name = "extract",
5153 code = r###"
5154 # Index zero is the full match; groups follow in order.
5155 IMPORT [STD]
5156 LET $caps: LIST<STRING> = TEXT_EXTRACT("abc123", "([a-z]+)(\\d+)")
5157 ASSERT_EQ $caps.0 "abc123"
5158 ASSERT_EQ $caps.1 "abc"
5159 ASSERT_EQ $caps.2 "123"
5160 "###
5161)]
5162fn text_extract(
5163 text: String,
5165 pattern: String,
5167) -> DiagnosticResult<Value> {
5168 let groups = super::args::text_extract_str(&text, &pattern, FUNC_TEXT_EXTRACT)?;
5169 Ok(super::args::text_list_value(groups))
5170}
5171
5172#[oxdock_func(pure, returns = TypeTag::Bool)]
5179#[example(
5180 name = "starts with",
5181 code = r###"
5182 # Present prefixes report true; misses report false.
5183 IMPORT [STD]
5184 LET $hit: BOOL = TEXT_STARTS_WITH("linux-musl-x64", "linux")
5185 ASSERT_EQ $hit true
5186
5187 # A miss is false, not a failure.
5188 LET $miss: BOOL = TEXT_STARTS_WITH("macos-arm", "linux")
5189 ASSERT_EQ $miss false
5190 "###
5191)]
5192fn text_starts_with(
5193 text: String,
5195 prefix: String,
5197) -> DiagnosticResult<Value> {
5198 Ok(Value::bool(text.starts_with(prefix.as_str())))
5199}
5200
5201#[oxdock_func(pure, returns = TypeTag::Bool)]
5208#[example(
5209 name = "ends with",
5210 code = r###"
5211 # Present suffixes report true; misses report false.
5212 IMPORT [STD]
5213 LET $hit: BOOL = TEXT_ENDS_WITH("x86_64-linux-musl", "linux-musl")
5214 ASSERT_EQ $hit true
5215
5216 # A miss is false, not a failure.
5217 LET $miss: BOOL = TEXT_ENDS_WITH("x86_64-linux-gnu", "linux-musl")
5218 ASSERT_EQ $miss false
5219 "###
5220)]
5221fn text_ends_with(
5222 text: String,
5224 suffix: String,
5226) -> DiagnosticResult<Value> {
5227 Ok(Value::bool(text.ends_with(suffix.as_str())))
5228}
5229
5230#[oxdock_func(pure, returns = TypeTag::Bool)]
5240#[example(
5241 name = "contains",
5242 code = r###"
5243 # Present needles report true; misses report false.
5244 IMPORT [STD]
5245 LET $hit: BOOL = CONTAINS("x86_64-linux-musl", "musl")
5246 ASSERT_EQ $hit true
5247
5248 # A miss is false, not a failure.
5249 LET $miss: BOOL = CONTAINS("x86_64-linux-gnu", "musl")
5250 ASSERT_EQ $miss false
5251 "###
5252)]
5253#[example(
5254 name = "contains list",
5255 code = r###"
5256 # List membership uses strict equality across any element type.
5257 IMPORT [STD]
5258 LET $hit: BOOL = CONTAINS(["a", "b", "c"], "b")
5259 ASSERT_EQ $hit true
5260 LET $miss: BOOL = CONTAINS(["a", "b", "c"], "z")
5261 ASSERT_EQ $miss false
5262 LET $num: BOOL = CONTAINS([1, 2, 3], 2.0)
5263 ASSERT_EQ $num true
5264
5265 # Stringified numbers never coerce to integers.
5266 LET $strnum: BOOL = CONTAINS(["1", "2", "3"], 2)
5267 ASSERT_EQ $strnum false
5268
5269 # Boolean lists match true and miss false with no coercion.
5270 LET $bools: LIST<BOOL> = [true]
5271 LET $bhit: BOOL = CONTAINS($bools, true)
5272 ASSERT_EQ $bhit true
5273 LET $bmiss: BOOL = CONTAINS($bools, false)
5274 ASSERT_EQ $bmiss false
5275 LET $nocoerce: BOOL = CONTAINS($bools, 1)
5276 ASSERT_EQ $nocoerce false
5277 "###
5278)]
5279fn contains(
5280 #[union(String, List)]
5282 haystack: Value,
5283 needle: Value,
5285) -> DiagnosticResult<Value> {
5286 if let Some(text) = haystack.as_str() {
5287 let Some(n) = needle.as_str() else {
5288 return Err(std_diag::std_contains_needle_type(needle.type_name()));
5289 };
5290 return Ok(Value::bool(text.contains(n)));
5291 }
5292 if let Some(items) = haystack.as_list() {
5293 for item in items {
5294 if super::args::values_equal(item, &needle) {
5295 return Ok(Value::bool(true));
5296 }
5297 }
5298 return Ok(Value::bool(false));
5299 }
5300 Err(std_diag::std_contains_haystack_type(haystack.type_name()))
5301}
5302
5303#[oxdock_func(pure, returns = TypeTag::List)]
5311#[example(
5312 name = "deduplicate",
5313 code = r###"
5314 # First occurrences win, later repeats drop.
5315 IMPORT [STD]
5316 LET $seen: LIST<STRING> = UNIQUE(["a", "b", "a", "c", "b"])
5317 ASSERT_EQ $seen.0 "a"
5318 ASSERT_EQ $seen.1 "b"
5319 ASSERT_EQ $seen.2 "c"
5320 ASSERT_EQ LEN($seen) 3
5321
5322 # The empty list stays empty.
5323 LET $empty: LIST<STRING> = UNIQUE([])
5324 ASSERT_EQ LEN($empty) 0
5325 "###
5326)]
5327#[example(
5328 name = "strict membership",
5329 code = r###"
5330 # Numerics collapse across INT and FLOAT like CONTAINS.
5331 IMPORT [STD]
5332 LET $nums: LIST<ANY> = UNIQUE([1, 2.0, 1, 3])
5333 ASSERT_EQ $nums.0 1
5334 ASSERT_EQ $nums.1 2.0
5335 ASSERT_EQ $nums.2 3
5336 ASSERT_EQ LEN($nums) 3
5337
5338 # Stringified numbers never coerce to integers.
5339 LET $mixed: LIST<ANY> = UNIQUE(["1", 1])
5340 ASSERT_EQ $mixed.0 "1"
5341 ASSERT_EQ $mixed.1 1
5342 ASSERT_EQ LEN($mixed) 2
5343 "###
5344)]
5345fn unique(
5346 items: Vec<Value>,
5348) -> DiagnosticResult<Value> {
5349 let mut out: Vec<Value> = Vec::with_capacity(items.len());
5350 for item in items {
5351 if !out
5352 .iter()
5353 .any(|seen| super::args::values_equal(seen, &item))
5354 {
5355 out.push(item);
5356 }
5357 }
5358 Ok(Value::list(out))
5359}
5360
5361#[oxdock_func(pure, returns = TypeTag::Int)]
5370#[example(
5371 name = "length",
5372 code = r###"
5373 # Plain text counts one per character.
5374 IMPORT [STD]
5375 LET $n: INT = LEN("hello")
5376 ASSERT_EQ $n 5
5377
5378 # Multibyte characters count once each, not per byte.
5379 LET $wide: INT = LEN("héllo")
5380 ASSERT_EQ $wide 5
5381
5382 # Lists count elements, maps count entries.
5383 LET $items: LIST<STRING> = ["a", "b", "c"]
5384 LET $nitems: INT = LEN($items)
5385 ASSERT_EQ $nitems 3
5386 LET $row: MAP<name: STRING> = {name: "ada"}
5387 LET $nkeys: INT = LEN($row)
5388 ASSERT_EQ $nkeys 1
5389 LET $empty: INT = LEN([])
5390 ASSERT_EQ $empty 0
5391 "###
5392)]
5393fn len(
5394 #[union(String, List, Map)]
5396 value: Value,
5397) -> DiagnosticResult<Value> {
5398 if let Some(text) = value.as_str() {
5399 return Ok(Value::int(text.chars().count() as i64));
5400 }
5401 if let Some(items) = value.as_list() {
5402 return Ok(Value::int(items.len() as i64));
5403 }
5404 if let Some(entries) = value.as_map() {
5405 return Ok(Value::int(entries.len() as i64));
5406 }
5407 Err(std_diag::std_len_unexpected_type(value.type_name()))
5408}
5409
5410#[oxdock_func(pure, returns = TypeTag::Int)]
5418#[example(
5419 name = "count",
5420 code = r###"
5421 # Every non-overlapping occurrence counts once.
5422 IMPORT [STD]
5423 LET $n: INT = TEXT_COUNT("hello world", "o")
5424 ASSERT_EQ $n 2
5425
5426 # Overlapping candidates never double count.
5427 LET $once: INT = TEXT_COUNT("aaa", "aa")
5428 ASSERT_EQ $once 1
5429 "###
5430)]
5431fn text_count(
5432 text: String,
5434 needle: String,
5436) -> DiagnosticResult<Value> {
5437 let n = super::args::text_count_str(&text, &needle, FUNC_TEXT_COUNT)?;
5438 Ok(Value::int(n))
5439}
5440
5441#[oxdock_func(pure, returns = TypeTag::Int)]
5451#[example(
5452 name = "count matches",
5453 code = r###"
5454 # One line matches once no matter how many times it hits.
5455 IMPORT [STD]
5456 LET $n: INT = TEXT_COUNT_MATCHES("test a: test\ntest b: nope\ntest c: test", ": test")
5457 ASSERT_EQ $n 2
5458
5459 # A miss binds zero, never an error.
5460 LET $none: INT = TEXT_COUNT_MATCHES("test b: nope", ": test$")
5461 ASSERT_EQ $none 0
5462 "###
5463)]
5464fn text_count_matches(
5465 text: String,
5467 pattern: String,
5469) -> DiagnosticResult<Value> {
5470 let n = super::args::text_count_matches_str(&text, &pattern, FUNC_TEXT_COUNT_MATCHES)?;
5471 Ok(Value::int(n))
5472}
5473
5474#[oxdock_func(pure, returns = TypeTag::ListOf(std::sync::Arc::new(TypeTag::String)))]
5487#[example(
5488 name = "grep",
5489 code = r###"
5490 # Matching lines come back as a list, in order.
5491 IMPORT [STD]
5492 LET $hits: LIST<STRING> = TEXT_GREP("one\ntwo\none more", "^one")
5493 ASSERT_EQ $hits.0 "one"
5494 ASSERT_EQ $hits.1 "one more"
5495
5496 # A miss binds an empty list, never an error.
5497 LET $miss: LIST<STRING> = TEXT_GREP("one\ntwo", "^z")
5498 LET $joined: STRING = TEXT_JOIN($miss, ",")
5499 ASSERT_EQ $joined ""
5500
5501 # The (?i) flag ignores case, so uppercase lines match too.
5502 LET $folded: LIST<STRING> = TEXT_GREP("One\ntwo\nONE more", "(?i)^one")
5503 ASSERT_EQ $folded.0 "One"
5504 ASSERT_EQ $folded.1 "ONE more"
5505 "###
5506)]
5507#[example(
5508 name = "grep invert",
5509 code = r###"
5510 # The invert option keeps every non-matching line instead.
5511 IMPORT [STD]
5512 LET $kept: LIST<STRING> = TEXT_GREP("one\ntwo\none more", "^one", {invert: true})
5513 ASSERT_EQ $kept.0 "two"
5514
5515 # A pattern matching every line binds an empty list, never an error.
5516 LET $none: LIST<STRING> = TEXT_GREP("one\ntwo", "^", {invert: true})
5517 LET $joined: STRING = TEXT_JOIN($none, ",")
5518 ASSERT_EQ $joined ""
5519
5520 # Options ride into placeholders as MAP literals. Placeholder
5521 # strings unescape only backslash and quote, so multiline text
5522 # arrives through a variable.
5523 LET $two_lines: STRING = "one\ntwo"
5524 LET $msg: STRING = 'kept:{{ STD::TEXT_GREP($two_lines, "^one", {invert: true}) }}'
5525 ASSERT_EQ $msg "kept:two"
5526 "###
5527)]
5528fn text_grep(
5529 text: String,
5531 pattern: String,
5533 #[options("invert?: BOOL")]
5535 #[optional]
5536 options: BTreeMap<String, Value>,
5537) -> DiagnosticResult<Value> {
5538 let invert = super::args::text_invert_flag(&options);
5541 Ok(super::args::text_list_value(super::args::text_grep_str(
5542 &text,
5543 &pattern,
5544 invert,
5545 FUNC_TEXT_GREP,
5546 )?))
5547}
5548
5549#[oxdock_func(returns = TypeTag::Bool)]
5560#[example(
5561 name = "drain to end",
5562 code = r###"
5563 # Capture two lines, then drain to end of stream with no sentinel line.
5564 IMPORT [STD]
5565 LET $cap: PIPE
5566 WITH_IO [stdout=$cap] {
5567 ECHO "one"
5568 ECHO "two"
5569 }
5570
5571 # The loop exits on close, and the count proves both lines drained.
5572 LET $n: INT = 0
5573 WHILE !EOF($cap) {
5574 WITH_IO [stdin=$cap] READ_LINE $line
5575 $n = $n + 1
5576 }
5577 ASSERT_EQ $n 2
5578 "###
5579)]
5580fn eof<P: ProcessManager>(
5581 cx: &mut StepCtx<P>,
5582 pipe: PipeHandle,
5584) -> DiagnosticResult<Value> {
5585 let info = cx.state.io.inspect_pipe(&pipe);
5586 Ok(Value::bool(info.closed && info.buffered == 0))
5587}
5588
5589fn task_poll_result_fields() -> Arc<[Field]> {
5593 Arc::from(vec![
5594 Field {
5595 name: "state".to_string(),
5596 ty: TypeTag::String,
5597 docs: "Task phase: `running` or `finished`.",
5598 optional: false,
5599 default: None,
5600
5601 alias: None,
5602 },
5603 Field {
5604 name: "ok".to_string(),
5605 ty: TypeTag::Bool,
5606 docs: "True unless the task failed.",
5607 optional: false,
5608 default: None,
5609
5610 alias: None,
5611 },
5612 Field {
5613 name: "stdout_tail".to_string(),
5614 ty: TypeTag::String,
5615 docs: "Bounded stdout tail, live while running.",
5616 optional: false,
5617 default: None,
5618
5619 alias: None,
5620 },
5621 Field {
5622 name: "stderr_tail".to_string(),
5623 ty: TypeTag::String,
5624 docs: "Bounded stderr tail, live while running.",
5625 optional: false,
5626 default: None,
5627
5628 alias: None,
5629 },
5630 Field {
5631 name: "truncated_bytes".to_string(),
5632 ty: TypeTag::Int,
5633 docs: "Dropped head bytes past the per-stream cap.",
5634 optional: false,
5635 default: None,
5636
5637 alias: None,
5638 },
5639 Field {
5640 name: "exit_code".to_string(),
5641 ty: TypeTag::Int,
5642 docs: "Process exit code, present once finished.",
5643 optional: true,
5644 default: None,
5645
5646 alias: None,
5647 },
5648 Field {
5649 name: "result".to_string(),
5650 ty: TypeTag::Any,
5651 docs: "Task `RETURN` value, present on clean finish.",
5652 optional: true,
5653 default: None,
5654
5655 alias: None,
5656 },
5657 Field {
5658 name: "error".to_string(),
5659 ty: TypeTag::String,
5660 docs: "Failure text, present on failed finish.",
5661 optional: true,
5662 default: None,
5663
5664 alias: None,
5665 },
5666 ])
5667}
5668
5669#[oxdock_func(returns = TypeTag::Record(task_poll_result_fields()))]
5682#[example(
5683 name = "running poll",
5684 code = r###"
5685 # A sleeping task is still running on the first poll.
5686 IMPORT [STD]
5687 LET $t: HANDLE<STRING> = ASYNC { SLEEP 30s; RETURN "done" }
5688 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)
5689 ASSERT_EQ $m.state "running"
5690 ASSERT_EQ $m.ok true
5691 # Clean up the sleeper so the run ends promptly.
5692 CANCEL $t
5693 "###
5694)]
5695#[example(
5696 name = "finished poll",
5697 code = r###"
5698 # A finished task reports its value and final tails, then still awaits.
5699 IMPORT [STD]
5700 LET $t: HANDLE<STRING> = ASYNC { ECHO "hi"; SLEEP 1s; RETURN "done" }
5701 # Do other work while the task runs; poll once it should be done.
5702 SLEEP 2s
5703 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)
5704 ASSERT_EQ $m.state "finished"
5705 ASSERT_EQ $m.result "done"
5706 LET $o: STRING = AWAIT $t
5707 ASSERT_EQ $o "done"
5708 "###
5709)]
5710fn task_poll<P: ProcessManager>(
5711 cx: &mut StepCtx<P>,
5712 task: HandleValue,
5714) -> DiagnosticResult<Value> {
5715 let entry =
5716 super::handlers::resolve_task_entry_by_id(task.0, &format!("TASK_POLL({})", task.0), cx)?;
5717 let obs = entry.observe_completion();
5718 let (stdout_tail, stderr_tail, dropped) = entry.snapshot_tails();
5719 let mut out = BTreeMap::new();
5720 out.insert(
5721 "state".to_string(),
5722 Value::string(if obs.running { "running" } else { "finished" }.to_string()),
5723 );
5724 out.insert("ok".to_string(), Value::bool(obs.ok));
5725 if !obs.running {
5726 out.insert("exit_code".to_string(), Value::int(obs.exit_code));
5727 }
5728 if let Some(result) = obs.result {
5729 out.insert("result".to_string(), result);
5730 }
5731 if !obs.error.is_empty() {
5732 out.insert("error".to_string(), Value::string(obs.error));
5733 }
5734 out.insert("stdout_tail".to_string(), Value::string(stdout_tail));
5735 out.insert("stderr_tail".to_string(), Value::string(stderr_tail));
5736 out.insert(
5737 "truncated_bytes".to_string(),
5738 Value::int(dropped.min(i64::MAX as u64) as i64),
5739 );
5740 Ok(Value::map(out))
5741}
5742
5743fn meta_to_value(meta: &FuncMeta) -> Value {
5744 let mut map = BTreeMap::new();
5745 map.insert("name".to_string(), Value::string(meta.name.clone()));
5746 map.insert("module".to_string(), Value::string(meta.module.clone()));
5747 map.insert(
5748 "kind".to_string(),
5749 Value::string(meta.kind.label().to_string()),
5750 );
5751 let params = match &meta.params {
5752 Some(params) => Value::list(
5753 params
5754 .iter()
5755 .map(|p| {
5756 let mut entry = BTreeMap::new();
5757 entry.insert("name".to_string(), Value::string(p.name.clone()));
5758 entry.insert(
5759 "param_type".to_string(),
5760 Value::string(
5761 p.param_type
5762 .as_ref()
5763 .map(render_structural)
5764 .unwrap_or_default(),
5765 ),
5766 );
5767 entry.insert(
5768 "allowed".to_string(),
5769 Value::string(
5770 p.allowed
5771 .map(|values| values.join(", "))
5772 .unwrap_or_default(),
5773 ),
5774 );
5775 entry.insert("docs".to_string(), Value::string(String::new()));
5776 entry.insert("optional".to_string(), Value::bool(p.optional));
5777 entry.insert(
5778 "options".to_string(),
5779 match p.options {
5780 Some(keys) => Value::list(
5781 keys.iter()
5782 .map(|key| {
5783 let mut option = BTreeMap::new();
5784 option.insert(
5785 "name".to_string(),
5786 Value::string(key.name.to_string()),
5787 );
5788 option.insert(
5789 "value_type".to_string(),
5790 Value::string(render_structural(&key.value)),
5791 );
5792 option.insert(
5793 "required".to_string(),
5794 Value::bool(key.required),
5795 );
5796 option.insert(
5797 "default".to_string(),
5798 Value::string(
5799 key.default.unwrap_or_default().to_string(),
5800 ),
5801 );
5802 Value::map(option)
5803 })
5804 .collect(),
5805 ),
5806 None => Value::string(String::new()),
5807 },
5808 );
5809 Value::map(entry)
5810 })
5811 .collect(),
5812 ),
5813 None => Value::list(Vec::new()),
5817 };
5818 map.insert("params".to_string(), params);
5819 map.insert(
5820 "returns".to_string(),
5821 Value::string(
5822 meta.returns
5823 .as_ref()
5824 .map(render_structural)
5825 .unwrap_or_default(),
5826 ),
5827 );
5828 map.insert("rpn".to_string(), Value::bool(meta.rpn));
5829 map.insert(
5830 "summary".to_string(),
5831 Value::string(meta.summary.to_string()),
5832 );
5833 Value::map(map)
5834}
5835
5836#[derive(Debug, Clone)]
5840pub struct RecordSchema {
5841 pub name: &'static str,
5842 pub fields: std::sync::Arc<[Field]>,
5843}
5844
5845#[derive(Clone)]
5849pub struct HostModule<P: ProcessManager> {
5850 pub name: String,
5851 pub funcs: Vec<HostRegistration<P>>,
5852 pub types: Vec<&'static TypeDescriptor>,
5853 pub record_schemas: Vec<RecordSchema>,
5854 pub states: Vec<ModuleState>,
5861}
5862
5863#[derive(Clone)]
5867pub struct ModuleState {
5868 id: std::any::TypeId,
5869 state: std::sync::Arc<dyn std::any::Any + Send + Sync>,
5870}
5871
5872pub type PreRunInspector = dyn Fn(&[Step]) -> DiagnosticResult<()> + Send + Sync;
5876
5877#[derive(Clone)]
5883pub struct PreRunCheck {
5884 check: Arc<PreRunInspector>,
5885}
5886
5887impl PreRunCheck {
5888 pub fn new(check: impl Fn(&[Step]) -> DiagnosticResult<()> + Send + Sync + 'static) -> Self {
5890 Self {
5891 check: Arc::new(check),
5892 }
5893 }
5894
5895 pub fn run(&self, steps: &[Step]) -> DiagnosticResult<()> {
5897 (self.check)(steps)
5898 }
5899}
5900
5901impl<P: ProcessManager> HostModule<P> {
5902 pub fn with_state<T: Send + Sync + 'static>(mut self, state: std::sync::Arc<T>) -> Self {
5905 self.states.push(ModuleState {
5906 id: std::any::TypeId::of::<T>(),
5907 state,
5908 });
5909 self
5910 }
5911
5912 pub fn check_pre_run(&self, steps: &[Step]) -> DiagnosticResult<()> {
5916 for state in &self.states {
5917 if let Some(check) = state.state.downcast_ref::<PreRunCheck>() {
5918 check.run(steps)?;
5919 }
5920 }
5921 Ok(())
5922 }
5923}
5924
5925impl<P: ProcessManager> ExecState<P> {
5926 pub fn register_module(&mut self, module: HostModule<P>) {
5929 for registration in module.funcs {
5930 match registration {
5931 HostRegistration::Stateful { name, meta, func } => {
5932 self.functions.register_host(&module.name, name, meta, func);
5933 }
5934 HostRegistration::Pure { name, meta, func } => {
5935 self.functions
5936 .register_pure_host(&module.name, name, meta, func);
5937 }
5938 HostRegistration::Both {
5939 name,
5940 meta,
5941 func,
5942 template,
5943 } => {
5944 self.functions
5945 .register_both_host(&module.name, name, meta, func, template);
5946 }
5947 }
5948 }
5949 for descriptor in module.types {
5950 if let Some(live) = self.type_env.types.get(descriptor.name) {
5953 if !std::ptr::eq(live.descriptor, descriptor) {
5954 panic!(
5955 "type name `{}` already registered for a different descriptor",
5956 descriptor.name
5957 );
5958 }
5959 } else {
5960 self.type_env.types.insert(
5961 descriptor.name.to_string(),
5962 super::state::HostTypeEntry {
5963 descriptor,
5964 module: module.name.clone(),
5965 },
5966 );
5967 self.type_env.type_env_digest ^= {
5969 use std::hash::Hasher;
5970 let mut h = std::collections::hash_map::DefaultHasher::new();
5971 h.write_u8(b't');
5972 h.write(descriptor.name.as_bytes());
5973 h.write(descriptor.name.as_bytes());
5974 h.finish()
5975 };
5976 }
5977 }
5978 for schema in module.record_schemas {
5979 if let Some(live) = self.type_env.record_schemas.get(schema.name) {
5980 if live.fields.len() != schema.fields.len()
5981 || live
5982 .fields
5983 .iter()
5984 .zip(schema.fields.iter())
5985 .any(|(a, b)| a.name != b.name)
5986 {
5987 panic!(
5988 "record schema `{}` already registered with different fields",
5989 schema.name
5990 );
5991 }
5992 } else {
5993 let rendered = oxdock_parser::render_structural(&oxdock_parser::TypeTag::Record(
5994 schema.fields.clone(),
5995 ));
5996 self.type_env.record_schemas.insert(
5997 schema.name.to_string(),
5998 super::state::RecordSchemaEntry {
5999 fields: schema.fields,
6000 module: module.name.clone(),
6001 },
6002 );
6003 self.type_env.type_env_digest ^= {
6004 use std::hash::Hasher;
6005 let mut h = std::collections::hash_map::DefaultHasher::new();
6006 h.write_u8(b's');
6007 h.write(schema.name.as_bytes());
6008 h.write(rendered.as_bytes());
6009 h.finish()
6010 };
6011 }
6012 }
6013 for state in module.states {
6014 self.module_states
6015 .insert((module.name.clone(), state.id), state.state);
6016 }
6017 }
6018
6019 pub fn list_functions(&self) -> Vec<FuncMeta> {
6021 let mut out: Vec<FuncMeta> = self.functions.entries_metas().into_iter().collect();
6022 if !out.iter().any(|m| m.name == KEYWORD_INSPECT) {
6024 out.push(FuncMeta {
6025 name: KEYWORD_INSPECT.to_string(),
6026 module: STD_MODULE_NAME.to_string(),
6027 kind: FuncKind::HostCtx,
6028 params: None,
6029 returns: Some(TypeTag::Map),
6030 rpn: false,
6031 summary: "Inspect a variable binding.",
6032 docs: "INSPECT($var): dedicated AST node taking a variable, not a value.",
6033 examples: &[],
6034 });
6035 }
6036 out.sort_by(|a, b| a.name.cmp(&b.name));
6037 out
6038 }
6039
6040 pub fn describe_function(&self, name: &str) -> Option<Value> {
6042 if let Some(meta) = self.functions.meta(name) {
6043 return Some(meta_to_value(&meta));
6044 }
6045 if name == KEYWORD_INSPECT {
6047 return Some(meta_to_value(&FuncMeta {
6048 name: KEYWORD_INSPECT.to_string(),
6049 module: STD_MODULE_NAME.to_string(),
6050 kind: FuncKind::HostCtx,
6051 params: None,
6052 returns: Some(TypeTag::Map),
6053 rpn: false,
6054 summary: "Inspect a variable binding.",
6055 docs: "INSPECT($var): dedicated AST node taking a variable, not a value.",
6056 examples: &[],
6057 }));
6058 }
6059 None
6060 }
6061
6062 pub fn pure_function_table(&self) -> Arc<PureTable> {
6067 self.functions.pure_shared()
6068 }
6069}
6070
6071#[cfg(test)]
6072mod tests {
6073 use super::*;
6074
6075 #[test]
6076 fn placeholder_resolver_dispatches_table_entries() {
6077 let echo: PureFn = Arc::new(|args| {
6081 args.into_iter().next().ok_or_else(|| {
6082 Diagnostic::new(
6083 "test.echo.arity",
6084 "ECHO needs 1 arg".to_string(),
6085 Diagnostic::make_fields(&[]),
6086 )
6087 })
6088 });
6089 let mut entries = HashMap::new();
6090 entries.insert("ECHO".to_string(), echo);
6091 let mut table = PureTable::new();
6092 table.insert("T".to_string(), entries);
6093 let resolve = placeholder_resolver(Arc::new(table));
6094 let out = resolve("T", "ECHO", vec![Value::string("hi".to_string())]).expect("dispatch");
6095 assert_eq!(out.as_str().expect("string"), "hi");
6096 let err = format!(
6097 "{:#}",
6098 resolve("T", "NOPE", vec![]).expect_err("unknown must fail")
6099 );
6100 assert!(
6101 err.contains("unknown placeholder function `T::NOPE`"),
6102 "names the call: {err}"
6103 );
6104 assert!(
6105 err.contains("known functions: T::ECHO"),
6106 "lists known names: {err}"
6107 );
6108 }
6109
6110 #[test]
6111 fn describe_entry_renders_union_spellings() {
6112 let union = oxdock_parser::union_tag!(String, Pipe);
6118 let meta = FuncMeta {
6119 name: "T::F".to_string(),
6120 module: "T".to_string(),
6121 kind: FuncKind::HostPure,
6122 params: Some(vec![FuncParam {
6123 name: "text".to_string(),
6124 param_type: Some(union.clone()),
6125 allowed: None,
6126 docs: "",
6127 options: None,
6128 optional: false,
6129 }]),
6130 returns: Some(union),
6131 rpn: false,
6132 summary: "test-only",
6133 docs: "test-only",
6134 examples: &[],
6135 };
6136 let value = meta_to_value(&meta);
6137 let map = value.as_map().expect("describe value is a map");
6138 let params = map
6139 .get("params")
6140 .expect("params key")
6141 .as_list()
6142 .expect("params is a list");
6143 let first = params[0].as_map().expect("entry is a map");
6144 assert_eq!(
6145 first.get("param_type").and_then(Value::as_str),
6146 Some("STRING|PIPE"),
6147 "param renders the set"
6148 );
6149 assert_eq!(
6150 map.get("returns").and_then(Value::as_str),
6151 Some("STRING|PIPE"),
6152 "returns render the set"
6153 );
6154 }
6155
6156 #[test]
6157 fn describe_entry_renders_handle_payload() {
6158 let meta = FuncMeta {
6162 name: "SCRIPT::FETCH".to_string(),
6163 module: "SCRIPT".to_string(),
6164 kind: FuncKind::Script,
6165 params: Some(vec![]),
6166 returns: Some(TypeTag::HandleOf(std::sync::Arc::new(TypeTag::String))),
6167 rpn: false,
6168 summary: "test-only",
6169 docs: "test-only",
6170 examples: &[],
6171 };
6172 let value = meta_to_value(&meta);
6173 let map = value.as_map().expect("describe value is a map");
6174 assert_eq!(
6175 map.get("returns").and_then(Value::as_str),
6176 Some("HANDLE<STRING>"),
6177 "returns render the payload"
6178 );
6179 }
6180
6181 #[test]
6182 fn describe_entry_carries_optional_flag() {
6183 let meta = FuncMeta {
6187 name: "T::F".to_string(),
6188 module: "T".to_string(),
6189 kind: FuncKind::HostPure,
6190 params: Some(vec![
6191 FuncParam {
6192 name: "url".to_string(),
6193 param_type: Some(TypeTag::String),
6194 allowed: None,
6195 docs: "",
6196 options: None,
6197 optional: false,
6198 },
6199 FuncParam {
6200 name: "options".to_string(),
6201 param_type: Some(TypeTag::Map),
6202 allowed: None,
6203 docs: "",
6204 options: None,
6205 optional: true,
6206 },
6207 ]),
6208 returns: Some(TypeTag::String),
6209 rpn: false,
6210 summary: "test-only",
6211 docs: "test-only",
6212 examples: &[],
6213 };
6214 let value = meta_to_value(&meta);
6215 let map = value.as_map().expect("describe value is a map");
6216 let params = map
6217 .get("params")
6218 .expect("params key")
6219 .as_list()
6220 .expect("params is a list");
6221 assert_eq!(params.len(), 2);
6222 let first = params[0].as_map().expect("entry is a map");
6223 let second = params[1].as_map().expect("entry is a map");
6224 assert_eq!(
6225 first.get("optional").and_then(Value::as_bool),
6226 Some(false),
6227 "required param must read false"
6228 );
6229 assert_eq!(
6230 second.get("optional").and_then(Value::as_bool),
6231 Some(true),
6232 "omittable param must read true"
6233 );
6234 }
6235
6236 #[test]
6237 fn template_twins_mirror_string_paths_and_refuse_pipes() {
6238 let pipe = Value::pipe_fresh();
6244 type TwinCase = (&'static str, Box<dyn Fn() -> DiagnosticResult<Value>>);
6245 let cases: Vec<TwinCase> = vec![
6246 (
6247 "TEXT_TRIM",
6248 Box::new(|| text_trim_string(Value::string(" hello ".to_string()))),
6249 ),
6250 (
6251 "TEXT_TRIM_PREFIX",
6252 Box::new(|| {
6253 text_trim_prefix_string(Value::string("v1".to_string()), "v".to_string())
6254 }),
6255 ),
6256 (
6257 "TEXT_TRIM_SUFFIX",
6258 Box::new(|| {
6259 text_trim_suffix_string(Value::string("a.gz".to_string()), "x".to_string())
6260 }),
6261 ),
6262 (
6263 "TEXT_TO_UPPER",
6264 Box::new(|| text_to_upper_string(Value::string("hi".to_string()))),
6265 ),
6266 (
6267 "TEXT_TO_LOWER",
6268 Box::new(|| text_to_lower_string(Value::string("HI".to_string()))),
6269 ),
6270 (
6271 "TEXT_REPLACE",
6272 Box::new(|| {
6273 text_replace_string(
6274 Value::string("ab".to_string()),
6275 "b".to_string(),
6276 "c".to_string(),
6277 )
6278 }),
6279 ),
6280 (
6281 "TEXT_REPLACE_REGEX",
6282 Box::new(|| {
6283 text_replace_regex_string(
6284 Value::string("ab".to_string()),
6285 "b".to_string(),
6286 "c".to_string(),
6287 )
6288 }),
6289 ),
6290 ];
6291 assert_eq!(cases.len(), 7, "every mirror op needs a twin row");
6292 for (name, run) in &cases {
6293 let value = run().unwrap_or_else(|e| panic!("{name} twin must answer strings: {e:#}"));
6294 assert!(
6295 value.as_str().is_some(),
6296 "{name} twin must answer STRING, got {}",
6297 value.type_name()
6298 );
6299 }
6300 assert_eq!(
6301 text_trim_string(Value::string(" hello ".to_string()))
6302 .expect("trim twin")
6303 .as_str(),
6304 Some("hello")
6305 );
6306 let pipe_cases: Vec<(&str, DiagnosticResult<Value>)> = vec![
6308 ("TEXT_TRIM", text_trim_string(pipe.clone())),
6309 (
6310 "TEXT_TRIM_PREFIX",
6311 text_trim_prefix_string(pipe.clone(), "v".to_string()),
6312 ),
6313 (
6314 "TEXT_TRIM_SUFFIX",
6315 text_trim_suffix_string(pipe.clone(), ".gz".to_string()),
6316 ),
6317 ("TEXT_TO_UPPER", text_to_upper_string(pipe.clone())),
6318 ("TEXT_TO_LOWER", text_to_lower_string(pipe.clone())),
6319 (
6320 "TEXT_REPLACE",
6321 text_replace_string(pipe.clone(), "a".to_string(), "b".to_string()),
6322 ),
6323 (
6324 "TEXT_REPLACE_REGEX",
6325 text_replace_regex_string(pipe.clone(), "a".to_string(), "b".to_string()),
6326 ),
6327 ];
6328 for (name, result) in pipe_cases {
6329 let err = result.expect_err(&format!("{name} twin must refuse PIPE"));
6330 assert!(
6331 format!("{err:#}").contains("step IO"),
6332 "{name} refusal names the missing context: {err:#}"
6333 );
6334 }
6335 }
6336
6337 #[test]
6338 fn shell_words_join_split_round_trip() {
6339 let words = vec![
6343 "gh".to_string(),
6344 "issue".to_string(),
6345 "comment".to_string(),
6346 "with spaces".to_string(),
6347 "it's".to_string(),
6348 "say \"hi\"".to_string(),
6349 "$HOME".to_string(),
6350 "$(whoami)".to_string(),
6351 "C:\\path\\to".to_string(),
6352 "naïve café".to_string(),
6353 "".to_string(),
6354 ];
6355 let joined = shell_words::join(&words);
6356 let back = shell_words::split(&joined).expect("join output must parse");
6357 assert_eq!(back, words);
6358 assert!(shell_words::split("unbalanced \"quote").is_err());
6359 }
6360
6361 struct FakeView {
6365 exports: HashMap<String, Vec<String>>,
6366 targets: HashMap<String, AliasTargets>,
6367 bindings: HashMap<String, HashMap<String, bool>>,
6368 }
6369
6370 impl ModuleGraphView for FakeView {
6371 fn const_exports(&self, file: &str) -> Option<&[String]> {
6372 self.exports.get(file).map(Vec::as_slice)
6373 }
6374
6375 fn alias_targets(&self, file: &str) -> AliasTargets {
6376 self.targets.get(file).cloned().unwrap_or_default()
6377 }
6378
6379 fn binding(&self, file: &str, name: &str) -> BindingPresence {
6380 match self.bindings.get(file).and_then(|names| names.get(name)) {
6381 Some(true) => BindingPresence::Const,
6382 Some(false) => BindingPresence::Let,
6383 None => BindingPresence::Absent,
6384 }
6385 }
6386 }
6387
6388 fn fake_targets(pairs: &[(&str, &str)]) -> AliasTargets {
6389 let mut targets = AliasTargets::new();
6390 for (alias, file) in pairs {
6391 targets
6392 .entry((*alias).to_string())
6393 .or_default()
6394 .push(AliasTarget {
6395 file: Some((*file).to_string()),
6396 host: None,
6397 guard: None,
6398 });
6399 }
6400 targets
6401 }
6402
6403 fn os_guard(os: &str) -> GuardExpr {
6404 GuardExpr::Predicate(oxdock_parser::Guard::Attr {
6405 ns: oxdock_parser::Ns::Os,
6406 key: None,
6407 val: Some(os.to_string()),
6408 })
6409 }
6410
6411 #[test]
6412 fn chase_resolves_bare_and_single_forward() {
6413 let mut view = FakeView {
6416 exports: HashMap::from([
6417 ("a".to_string(), vec!["N".to_string()]),
6418 ("b".to_string(), vec!["A::N".to_string()]),
6419 ("c".to_string(), vec!["B::N".to_string()]),
6420 ]),
6421 targets: HashMap::from([
6422 ("u".to_string(), fake_targets(&[("B", "b")])),
6423 ("b".to_string(), fake_targets(&[("A", "a")])),
6424 ("c".to_string(), fake_targets(&[("B", "b")])),
6425 ]),
6426 bindings: HashMap::new(),
6427 };
6428 assert_eq!(
6429 chase_const_forward(&view, "a", "N", "U::N").expect("bare"),
6430 vec!["a".to_string()]
6431 );
6432 assert_eq!(
6433 chase_const_forward(&view, "b", "N", "U::N").expect("forward"),
6434 vec!["a".to_string()]
6435 );
6436 view.targets
6437 .insert("u".to_string(), fake_targets(&[("C", "c")]));
6438 assert_eq!(
6439 chase_const_forward(&view, "c", "N", "U::N").expect("chain"),
6440 vec!["a".to_string()]
6441 );
6442 }
6443
6444 #[test]
6445 fn chase_prefers_bare_over_forwards() {
6446 let view = FakeView {
6449 exports: HashMap::from([("b".to_string(), vec!["N".to_string(), "A::N".to_string()])]),
6450 targets: HashMap::from([("b".to_string(), fake_targets(&[("A", "a")]))]),
6451 bindings: HashMap::new(),
6452 };
6453 assert_eq!(
6454 chase_const_forward(&view, "b", "N", "U::N").expect("bare wins"),
6455 vec!["b".to_string()]
6456 );
6457 }
6458
6459 #[test]
6460 fn chase_rejects_split_forwards() {
6461 let view = FakeView {
6464 exports: HashMap::from([(
6465 "b".to_string(),
6466 vec!["A::N".to_string(), "C::N".to_string()],
6467 )]),
6468 targets: HashMap::new(),
6469 bindings: HashMap::new(),
6470 };
6471 let err = format!(
6472 "{}",
6473 chase_const_forward(&view, "b", "N", "U::N").expect_err("split must fail")
6474 );
6475 assert!(err.contains("ambiguous CONST `U::N`"), "{err}");
6476 assert!(err.contains("A::N") && err.contains("C::N"), "{err}");
6477 }
6478
6479 #[test]
6480 fn chase_names_broken_link_detail() {
6481 let view = FakeView {
6484 exports: HashMap::from([
6485 ("b".to_string(), vec!["A::M".to_string()]),
6486 ("c".to_string(), vec!["A::P".to_string()]),
6487 ("d".to_string(), vec!["A::Q".to_string()]),
6488 ("a".to_string(), Vec::new()),
6489 ]),
6490 targets: HashMap::from([
6491 ("b".to_string(), fake_targets(&[("A", "a")])),
6492 ("c".to_string(), fake_targets(&[("A", "a")])),
6493 ("d".to_string(), fake_targets(&[("A", "a")])),
6494 ]),
6495 bindings: HashMap::from([(
6496 "a".to_string(),
6497 HashMap::from([("P".to_string(), true), ("Q".to_string(), false)]),
6498 )]),
6499 };
6500 let err = format!(
6501 "{}",
6502 chase_const_forward(&view, "b", "M", "U::M").expect_err("missing must fail")
6503 );
6504 assert!(err.contains("does not resolve"), "{err}");
6505 assert!(err.contains("no import alias `A` exports `M`"), "{err}");
6506 let err = format!(
6507 "{}",
6508 chase_const_forward(&view, "c", "P", "U::P").expect_err("unexported must fail")
6509 );
6510 assert!(
6511 err.contains("holds `P` as CONST but does not export it"),
6512 "{err}"
6513 );
6514 let err = format!(
6515 "{}",
6516 chase_const_forward(&view, "d", "Q", "U::Q").expect_err("LET must fail")
6517 );
6518 assert!(
6519 err.contains("is a LET binding and cannot be exported"),
6520 "{err}"
6521 );
6522 }
6523
6524 #[test]
6525 fn chase_rejects_cycles() {
6526 let view = FakeView {
6529 exports: HashMap::from([
6530 ("a".to_string(), vec!["B::N".to_string()]),
6531 ("b".to_string(), vec!["A::N".to_string()]),
6532 ]),
6533 targets: HashMap::from([
6534 ("a".to_string(), fake_targets(&[("B", "b")])),
6535 ("b".to_string(), fake_targets(&[("A", "a")])),
6536 ]),
6537 bindings: HashMap::new(),
6538 };
6539 let err = format!(
6540 "{}",
6541 chase_const_forward(&view, "a", "N", "U::N").expect_err("cycle must fail")
6542 );
6543 assert!(err.contains("re-export cycle"), "{err}");
6544 }
6545
6546 #[test]
6547 fn chase_unions_disjoint_guard_branches() {
6548 let mut guarded = AliasTargets::new();
6551 guarded.insert(
6552 "A".to_string(),
6553 vec![
6554 AliasTarget {
6555 file: Some("lin".to_string()),
6556 host: None,
6557 guard: Some(os_guard("linux")),
6558 },
6559 AliasTarget {
6560 file: Some("mac".to_string()),
6561 host: None,
6562 guard: Some(os_guard("macos")),
6563 },
6564 ],
6565 );
6566 let view = FakeView {
6567 exports: HashMap::from([
6568 ("b".to_string(), vec!["A::N".to_string()]),
6569 ("lin".to_string(), vec!["N".to_string()]),
6570 ("mac".to_string(), vec!["N".to_string()]),
6571 ]),
6572 targets: HashMap::from([("b".to_string(), guarded)]),
6573 bindings: HashMap::new(),
6574 };
6575 assert_eq!(
6576 chase_const_forward(&view, "b", "N", "U::N").expect("disjoint branches"),
6577 vec!["lin".to_string(), "mac".to_string()]
6578 );
6579 }
6580
6581 #[test]
6582 fn holder_classification_sorts_and_rejects() {
6583 let view = FakeView {
6586 exports: HashMap::from([
6587 ("b".to_string(), vec!["N".to_string()]),
6588 ("c".to_string(), vec!["N".to_string()]),
6589 ]),
6590 targets: HashMap::new(),
6591 bindings: HashMap::new(),
6592 };
6593 let unit = fake_targets(&[("B", "b"), ("B", "c")]);
6594 match const_holder_files(&view, &unit, "B", "N") {
6595 ConstHolders::Ambiguous { .. } => {}
6596 other => panic!("overlapping holders must be ambiguous, got {other:?}"),
6597 }
6598 match const_holder_files(&view, &unit, "Z", "N") {
6599 ConstHolders::NoAlias => {}
6600 other => panic!("unknown alias must report NoAlias, got {other:?}"),
6601 }
6602 let unit = fake_targets(&[("B", "b")]);
6603 match const_holder_files(&view, &unit, "B", "N") {
6604 ConstHolders::Found(files) => assert_eq!(files, vec!["b".to_string()]),
6605 other => panic!("single holder must be found, got {other:?}"),
6606 }
6607 }
6608}