1use std::collections::{BTreeMap, HashMap, HashSet};
2use std::sync::Arc;
3
4use anyhow::Result;
5use oxdock_diagnostics::DiagnosticResult;
6use oxdock_fs::to_forward_slashes;
7use oxdock_fs::{GuardedPath, WorkspaceSelection};
8use oxdock_func_macro::oxdock_func;
9use oxdock_parser::value::HandleValue;
10use oxdock_parser::{
11 Field, GuardExpr, KEYWORD_CONST, KEYWORD_EXPORT, KEYWORD_FROM, KEYWORD_FUNC, KEYWORD_IMPORT,
12 KEYWORD_INSPECT, KEYWORD_LET, KEYWORD_TYPE, MODULE_SEPARATOR, SCRIPT_MODULE_NAME,
13 STD_MODULE_NAME, SemaphoreState, Step, TypeTag, Value, base_name, guards_overlap, qualify,
14 render_structural, split_qualified,
15};
16use oxdock_pipe::PipeHandle;
17use oxdock_process::{CommandStdin, DefaultProcessManager, ProcessManager};
18
19use super::diagnostics as std_diag;
20use super::function_names::{
21 FUNC_BOOL, FUNC_BOOL_OR, FUNC_PARSE_ARGS, FUNC_PARSE_FLAGS, FUNC_PARSE_POSITIONALS,
22 FUNC_TEXT_COUNT, FUNC_TEXT_COUNT_MATCHES, FUNC_TEXT_EXTRACT, FUNC_TEXT_GREP,
23 FUNC_TEXT_LINES_RANGE, FUNC_TEXT_MATCH, FUNC_TEXT_REPLACE, FUNC_TEXT_REPLACE_REGEX,
24};
25use super::io::StreamHandle;
26use super::state::ExecState;
27use super::steps::StepCtx;
28use super::typing::TypeDescriptor;
29
30#[derive(Debug, Clone, Copy, PartialEq, Eq)]
36pub enum FuncKind {
37 Script,
38 HostCtx,
39 HostPure,
40}
41
42pub(super) fn file_func_key(defining_file: &str, name: &str) -> String {
46 qualify(defining_file, name)
47}
48
49pub(super) fn ambiguous_alias_message(alias: &str, name: &str, files: &HashSet<String>) -> String {
52 let mut files: Vec<&str> = files.iter().map(|file| file.as_str()).collect();
53 files.sort();
54 format!(
55 "function `{alias}::{name}` is ambiguous: alias `{alias}` is imported from multiple files ({})",
56 files.join(", ")
57 )
58}
59
60pub(super) enum AliasResolution {
66 Global,
68 Canonical(String),
70 Unknown,
72 Ambiguous {
75 alias: String,
76 base: String,
77 files: HashSet<String>,
78 },
79 Any {
86 base: String,
87 files: HashSet<String>,
88 has_host: bool,
89 },
90}
91
92pub(super) type AliasTargets = HashMap<String, Vec<(Option<String>, Option<GuardExpr>)>>;
99
100pub(super) trait FuncFrameView {
106 type Hit;
108 fn find_nested(&self, base: &str) -> Option<Self::Hit>;
110 fn find_home(&self, unit: &str, base: &str) -> Option<Self::Hit>;
112 fn find_harvest(&self, unit: &str, base: &str) -> Option<Self::Hit>;
114 fn walk(&self, unit: &str, base: &str) -> Option<Self::Hit> {
116 self.find_nested(base)
117 .or_else(|| self.find_home(unit, base))
118 .or_else(|| self.find_harvest(unit, base))
119 }
120}
121
122pub(super) fn classify_alias_call(
128 unit_targets: &AliasTargets,
129 name: &str,
130 exists: &dyn Fn(&str) -> bool,
131) -> AliasResolution {
132 let Some((alias, base)) = split_qualified(name) else {
133 return AliasResolution::Global;
134 };
135 if alias == SCRIPT_MODULE_NAME {
136 return AliasResolution::Global;
137 }
138 let Some(entries) = unit_targets.get(alias) else {
139 return AliasResolution::Global;
140 };
141 if entries.is_empty() {
142 return AliasResolution::Unknown;
143 }
144 let mut files: Vec<(&str, Vec<Option<&GuardExpr>>)> = Vec::new();
147 let mut host_guards: Vec<Option<&GuardExpr>> = Vec::new();
148 for (file, guard) in entries {
149 match file {
150 Some(path) => match files.iter_mut().find(|(known, _)| *known == path) {
151 Some((_, guards)) => guards.push(guard.as_ref()),
152 None => files.push((path, vec![guard.as_ref()])),
153 },
154 None => host_guards.push(guard.as_ref()),
155 }
156 }
157 if files.is_empty() {
158 return AliasResolution::Unknown;
159 }
160 let overlaps = |left: &[Option<&GuardExpr>], right: &[Option<&GuardExpr>]| {
161 left.iter()
162 .any(|a| right.iter().any(|b| guards_overlap(*a, *b)))
163 };
164 if files.len() == 1 {
165 let disjoint_host = host_guards
169 .iter()
170 .any(|host| !overlaps(&files[0].1, &[*host]));
171 if !disjoint_host {
172 return AliasResolution::Canonical(file_func_key(files[0].0, base));
173 }
174 let mut all = HashSet::new();
175 all.insert(files[0].0.to_string());
176 return AliasResolution::Any {
177 base: base.to_string(),
178 files: all,
179 has_host: true,
180 };
181 }
182 let mut ambiguous = HashSet::new();
183 for (i, (file, guards)) in files.iter().enumerate() {
184 for (other, other_guards) in files.iter().skip(i + 1) {
185 if overlaps(guards, other_guards)
186 && (exists(&file_func_key(file, base)) || exists(&file_func_key(other, base)))
187 {
188 ambiguous.insert((*file).to_string());
189 ambiguous.insert((*other).to_string());
190 }
191 }
192 }
193 if !ambiguous.is_empty() {
194 return AliasResolution::Ambiguous {
195 alias: alias.to_string(),
196 base: base.to_string(),
197 files: ambiguous,
198 };
199 }
200 let all: HashSet<String> = files.iter().map(|(file, _)| (*file).to_string()).collect();
201 if all.iter().any(|file| exists(&file_func_key(file, base))) {
202 return AliasResolution::Any {
203 base: base.to_string(),
204 files: all,
205 has_host: !host_guards.is_empty(),
206 };
207 }
208 AliasResolution::Unknown
209}
210
211pub(super) fn missing_import_hint<'a>(
221 files: impl IntoIterator<Item = (&'a str, &'a [String])>,
222 unit_targets: &AliasTargets,
223 name: &str,
224) -> Option<String> {
225 let base = match split_qualified(name) {
226 Some((_, base)) => base,
227 None => name,
228 };
229 if base.is_empty() {
230 return None;
231 }
232 let mut exporters: Vec<&str> = files
233 .into_iter()
234 .filter(|(_, exports)| exports.iter().any(|exported| exported == base))
235 .map(|(file, _)| file)
236 .collect();
237 exporters.sort();
238 exporters.dedup();
239 if exporters.is_empty() {
240 return None;
241 }
242 let imported_as = |file: &str| {
244 let mut aliases: Vec<&str> = unit_targets
245 .iter()
246 .filter(|(_, targets)| {
247 targets
248 .iter()
249 .any(|(target, _)| target.as_deref() == Some(file))
250 })
251 .map(|(alias, _)| alias.as_str())
252 .collect();
253 aliases.sort();
254 aliases
255 };
256 if exporters.len() == 1 {
257 let file = exporters[0];
258 let aliases = imported_as(file);
259 let import_alias = aliases
264 .iter()
265 .find(|alias| qualify(alias, base) != name)
266 .or(aliases.first())
267 .copied();
268 let suggestion = match import_alias {
269 Some(import_alias) => {
270 let spelling = qualify(import_alias, base);
271 if spelling == name {
272 format!(
275 "file \"{file}\" exports `{base}` but the `{import_alias}` view does not resolve it here"
276 )
277 } else {
278 format!("did you mean `{spelling}`? (file \"{file}\" exports `{base}`)")
279 }
280 }
281 None => {
282 let path = to_forward_slashes(file);
285 format!(
286 "file \"{file}\" exports `{base}`: add `[{KEYWORD_FUNC} {base} {KEYWORD_FROM} \"{path}\"]` to an {KEYWORD_IMPORT}"
287 )
288 }
289 };
290 return Some(format!("; {suggestion}"));
291 }
292 let mut files = exporters.join("\", \"");
293 files.insert(0, '"');
294 files.push('"');
295 Some(format!(
296 "; files {files} export `{base}`: qualify the call with the importing alias"
297 ))
298}
299
300pub(super) fn const_export_covers(entry: &str, name: &str) -> bool {
305 base_name(entry) == name
306}
307
308pub(super) enum BindingPresence {
311 Const,
312 Let,
313 Absent,
314}
315
316pub(super) fn missing_const_hint<S: ModuleGraphView>(
323 view: &S,
324 targets: &AliasTargets,
325 alias: &str,
326 name: &str,
327) -> Option<String> {
328 targets
329 .get(alias)
330 .map(|entries| {
331 entries
332 .iter()
333 .filter_map(|(file, _)| file.as_ref())
334 .collect::<Vec<_>>()
335 })
336 .unwrap_or_default()
337 .iter()
338 .find_map(|file| match view.binding(file, name) {
339 BindingPresence::Const => Some(format!(
340 "module holds `{name}` as {KEYWORD_CONST} but does not export it: add `{KEYWORD_EXPORT} {KEYWORD_CONST} ${name}`"
341 )),
342 BindingPresence::Let => Some(format!(
343 "`{name}` is a {KEYWORD_LET} binding and cannot be exported: only {KEYWORD_CONST} bindings cross the module boundary"
344 )),
345 BindingPresence::Absent => None,
346 })
347}
348
349pub(super) trait ModuleGraphView {
356 fn const_exports(&self, file: &str) -> Option<&[String]>;
358 fn alias_targets(&self, file: &str) -> AliasTargets;
361 fn binding(&self, file: &str, name: &str) -> BindingPresence;
363}
364
365#[derive(Debug)]
371pub(super) enum ConstHolders {
372 Found(Vec<String>),
375 NoAlias,
377 Ambiguous {
379 alias: String,
380 base: String,
381 files: HashSet<String>,
382 },
383}
384
385fn const_canonical_suffix(name: &str) -> String {
390 format!("{MODULE_SEPARATOR}{name}")
391}
392
393pub(super) fn const_holder_files<S: ModuleGraphView>(
395 view: &S,
396 unit_targets: &AliasTargets,
397 alias: &str,
398 name: &str,
399) -> ConstHolders {
400 let qualified = qualify(alias, name);
401 let suffix = const_canonical_suffix(name);
402 let exports = |canonical: &str| {
406 canonical
407 .strip_suffix(suffix.as_str())
408 .and_then(|file| view.const_exports(file))
409 .is_some_and(|names| names.iter().any(|entry| const_export_covers(entry, name)))
410 };
411 let mut holders = match classify_alias_call(unit_targets, &qualified, &exports) {
412 AliasResolution::Global | AliasResolution::Unknown => return ConstHolders::NoAlias,
413 AliasResolution::Ambiguous { alias, base, files } => {
414 return ConstHolders::Ambiguous { alias, base, files };
415 }
416 AliasResolution::Canonical(canonical) => {
417 let Some(file) = canonical.strip_suffix(suffix.as_str()) else {
418 return ConstHolders::NoAlias;
419 };
420 vec![file.to_string()]
421 }
422 AliasResolution::Any { mut files, .. } => {
423 let mut files: Vec<String> = files.drain().collect();
424 files.sort();
425 files
426 }
427 };
428 holders.retain(|file| {
429 view.const_exports(file)
430 .is_some_and(|names| names.iter().any(|entry| const_export_covers(entry, name)))
431 });
432 ConstHolders::Found(holders)
433}
434
435#[derive(Debug)]
440pub(super) enum ForwardError {
441 Unknown { original: String },
443 Broken {
445 original: String,
446 hop: String,
447 detail: BrokenDetail,
448 },
449 Split { original: String, hops: Vec<String> },
451 Cycle { chain: Vec<String> },
454 HopAmbiguous {
456 alias: String,
457 base: String,
458 files: HashSet<String>,
459 },
460}
461
462#[derive(Debug)]
464pub(super) enum BrokenDetail {
465 UnexportedConst,
467 Let,
469 Absent,
471}
472
473impl std::fmt::Display for ForwardError {
474 fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
475 match self {
476 ForwardError::Unknown { original } => write!(f, "unknown {KEYWORD_CONST} `{original}`"),
477 ForwardError::Broken {
478 original,
479 hop,
480 detail,
481 } => {
482 let base = base_name(hop);
483 let detail = match detail {
484 BrokenDetail::UnexportedConst => format!(
485 "module holds `{base}` as {KEYWORD_CONST} but does not export it: add `{KEYWORD_EXPORT} {KEYWORD_CONST} ${base}`"
486 ),
487 BrokenDetail::Let => format!(
488 "`{base}` is a {KEYWORD_LET} binding and cannot be exported: only {KEYWORD_CONST} bindings cross the module boundary"
489 ),
490 BrokenDetail::Absent => {
491 let (forward, _) = split_qualified(hop).unwrap_or(("", base));
492 format!("no import alias `{forward}` exports `{base}`")
493 }
494 };
495 write!(
496 f,
497 "unknown {KEYWORD_CONST} `{original}`: re-export `{hop}` does not resolve: {detail}"
498 )
499 }
500 ForwardError::Split { original, hops } => write!(
501 f,
502 "ambiguous {KEYWORD_CONST} `{original}`: re-exported from {}; export exactly one source",
503 hops.join(" and ")
504 ),
505 ForwardError::Cycle { chain } => {
506 write!(
507 f,
508 "{KEYWORD_CONST} re-export cycle detected: {}",
509 chain.join(" -> ")
510 )
511 }
512 ForwardError::HopAmbiguous { alias, base, files } => write!(
513 f,
514 "{}",
515 ambiguous_alias_message(alias, base, files).replacen("function", KEYWORD_CONST, 1)
516 ),
517 }
518 }
519}
520
521impl std::error::Error for ForwardError {}
522
523pub(super) fn chase_const_forward<S: ModuleGraphView>(
530 view: &S,
531 file: &str,
532 name: &str,
533 original: &str,
534) -> Result<Vec<String>, ForwardError> {
535 let mut terminals: Vec<String> = Vec::new();
536 chase_from(view, file, name, original, &mut Vec::new(), &mut terminals)?;
537 terminals.sort();
538 terminals.dedup();
539 Ok(terminals)
540}
541
542fn chase_from<S: ModuleGraphView>(
543 view: &S,
544 current: &str,
545 name: &str,
546 original: &str,
547 chain: &mut Vec<String>,
548 terminals: &mut Vec<String>,
549) -> Result<(), ForwardError> {
550 let suffix = const_canonical_suffix(name);
551 let covering = |canonical: &str| {
552 canonical
553 .strip_suffix(suffix.as_str())
554 .and_then(|file| view.const_exports(file))
555 .is_some_and(|names| names.iter().any(|entry| const_export_covers(entry, name)))
556 };
557 let mut current = current.to_string();
558 loop {
559 let Some(names) = view.const_exports(current.as_str()) else {
560 return Err(ForwardError::Unknown {
561 original: original.to_string(),
562 });
563 };
564 if names.iter().any(|entry| entry == name) {
565 terminals.push(current);
566 return Ok(());
567 }
568 let mut aliases: Vec<&str> = Vec::new();
569 for entry in names {
570 if let Some((alias, base)) = split_qualified(entry)
571 && base == name
572 && !aliases.contains(&alias)
573 {
574 aliases.push(alias);
575 }
576 }
577 if aliases.is_empty() {
578 if chain.is_empty() {
579 return Err(ForwardError::Unknown {
580 original: original.to_string(),
581 });
582 }
583 let hop = chain.last().expect("chain never empty").clone();
584 let detail = match view.binding(current.as_str(), name) {
585 BindingPresence::Const => BrokenDetail::UnexportedConst,
586 BindingPresence::Let => BrokenDetail::Let,
587 BindingPresence::Absent => BrokenDetail::Absent,
588 };
589 return Err(ForwardError::Broken {
590 original: original.to_string(),
591 hop,
592 detail,
593 });
594 }
595 if aliases.len() > 1 {
596 let mut hops: Vec<String> = aliases.iter().map(|alias| qualify(alias, name)).collect();
597 hops.sort();
598 return Err(ForwardError::Split {
599 original: original.to_string(),
600 hops,
601 });
602 }
603 let forward = aliases[0];
604 let hop = qualify(forward, name);
605 if chain.contains(&hop) {
606 chain.push(hop);
607 return Err(ForwardError::Cycle {
608 chain: chain.clone(),
609 });
610 }
611 chain.push(hop.clone());
612 let targets = view.alias_targets(current.as_str());
613 match classify_alias_call(&targets, &hop, &covering) {
614 AliasResolution::Global | AliasResolution::Unknown => {
615 return Err(ForwardError::Broken {
616 original: original.to_string(),
617 hop,
618 detail: BrokenDetail::Absent,
619 });
620 }
621 AliasResolution::Ambiguous { alias, base, files } => {
622 return Err(ForwardError::HopAmbiguous { alias, base, files });
623 }
624 AliasResolution::Canonical(canonical) => {
625 let Some(next) = canonical.strip_suffix(suffix.as_str()) else {
626 return Err(ForwardError::Unknown {
627 original: original.to_string(),
628 });
629 };
630 current = next.to_string();
631 }
632 AliasResolution::Any { mut files, .. } => {
633 let mut covering: Vec<String> = files
634 .drain()
635 .filter(|file| {
636 view.const_exports(file).is_some_and(|names| {
637 names.iter().any(|entry| const_export_covers(entry, name))
638 })
639 })
640 .collect();
641 covering.sort();
642 match covering.len() {
643 0 => {
644 return Err(ForwardError::Broken {
645 original: original.to_string(),
646 hop,
647 detail: BrokenDetail::Absent,
648 });
649 }
650 1 => {
651 current = covering.into_iter().next().expect("len checked");
652 }
653 _ => {
654 for branch in covering {
655 let mut branch_chain = chain.clone();
656 chase_from(
657 view,
658 branch.as_str(),
659 name,
660 original,
661 &mut branch_chain,
662 terminals,
663 )?;
664 }
665 return Ok(());
666 }
667 }
668 }
669 }
670 }
671}
672pub(super) fn disjoint_template_script_visible(
680 base: &str,
681 files: &HashSet<String>,
682 has_host: bool,
683 exists: &dyn Fn(&str) -> bool,
684) -> bool {
685 !has_host && !files.is_empty() && files.iter().all(|file| exists(&file_func_key(file, base)))
686}
687
688pub(super) fn disjoint_alias_placeholder_miss(
695 module: &str,
696 name: &str,
697 base: &str,
698 files: &HashSet<String>,
699 has_host: bool,
700 is_script: &dyn Fn(&str) -> bool,
701) -> String {
702 let script = disjoint_template_script_visible(base, files, has_host, is_script);
703 describe_placeholder_miss(module, name, script, false, !script)
704 .expect("disjoint miss always renders")
705}
706
707pub(super) fn spellings_for_defining_file(
714 unit_targets: &AliasTargets,
715 defining: &str,
716 base: &str,
717 is_script: &dyn Fn(&str) -> bool,
718) -> (Vec<String>, Vec<(String, HashSet<String>)>) {
719 let mut direct = Vec::new();
720 let mut ambiguous = Vec::new();
721 for (alias, files) in unit_targets {
722 if !files
723 .iter()
724 .any(|(file, _)| file.as_deref() == Some(defining))
725 {
726 continue;
727 }
728 let spelling = qualify(alias, base);
729 match classify_alias_call(unit_targets, &spelling, &|key| {
730 key == file_func_key(defining, base)
731 }) {
732 AliasResolution::Canonical(_) => direct.push(spelling),
733 AliasResolution::Ambiguous { files, .. } => {
734 ambiguous.push((spelling, files));
735 }
736 AliasResolution::Any {
737 base,
738 files,
739 has_host,
740 } => {
741 if disjoint_template_script_visible(&base, &files, has_host, is_script) {
742 direct.push(spelling);
743 }
744 }
745 AliasResolution::Global | AliasResolution::Unknown => {}
746 }
747 }
748 (direct, ambiguous)
749}
750
751impl FuncKind {
752 pub fn label(&self) -> &'static str {
753 match self {
754 FuncKind::Script => "script",
755 FuncKind::HostCtx | FuncKind::HostPure => "host",
756 }
757 }
758}
759
760#[derive(Debug, Clone)]
778pub struct FuncParam {
779 pub name: String,
780 pub param_type: Option<TypeTag>,
781 pub allowed: Option<&'static [&'static str]>,
782 pub docs: &'static str,
783 pub options: Option<&'static [ParamOption]>,
784 pub optional: bool,
785}
786
787pub fn required_arity(params: &[FuncParam]) -> usize {
792 params
793 .iter()
794 .rev()
795 .take_while(|param| param.optional)
796 .fold(params.len(), |count, _| count - 1)
797}
798
799pub fn fill_optional_args(params: &[FuncParam], mut values: Vec<Value>) -> Vec<Value> {
804 assert!(
805 values.len() <= params.len(),
806 "arity gate must run before fill_optional_args"
807 );
808 assert!(
809 values.len() >= required_arity(params),
810 "arity gate must run before fill_optional_args"
811 );
812 while values.len() < params.len() {
813 values.push(Value::map(BTreeMap::new()));
814 }
815 values
816}
817
818#[derive(Debug, Clone)]
825pub struct ParamOption {
826 pub name: &'static str,
827 pub value: TypeTag,
828 pub required: bool,
829 pub default: Option<&'static str>,
830}
831
832#[derive(Debug, Clone)]
838pub struct FuncMeta {
839 pub name: String,
840 pub module: String,
844 pub kind: FuncKind,
845 pub params: Option<Vec<FuncParam>>,
846 pub returns: Option<TypeTag>,
847 pub rpn: bool,
848 pub summary: &'static str,
849 pub docs: &'static str,
850 pub examples: &'static [crate::Example],
856}
857
858pub type PureFn = Arc<dyn Fn(Vec<Value>) -> Result<Value> + Send + Sync>;
861
862pub type NativeFn<P> = Arc<dyn Fn(&mut StepCtx<P>, Vec<Value>) -> Result<Value> + Send + Sync>;
864
865pub trait OxDockFn<P: ProcessManager> {
869 fn registration() -> HostRegistration<P>;
872}
873
874pub enum HostRegistration<P: ProcessManager> {
883 Stateful {
884 name: String,
885 meta: FuncMeta,
886 func: NativeFn<P>,
887 },
888 Pure {
889 name: String,
890 meta: FuncMeta,
891 func: PureFn,
892 },
893 Both {
894 name: String,
895 meta: FuncMeta,
896 func: NativeFn<P>,
897 template: PureFn,
898 },
899}
900
901impl<P: ProcessManager> Clone for HostRegistration<P> {
904 fn clone(&self) -> Self {
905 match self {
906 HostRegistration::Stateful { name, meta, func } => HostRegistration::Stateful {
907 name: name.clone(),
908 meta: meta.clone(),
909 func: Arc::clone(func),
910 },
911 HostRegistration::Pure { name, meta, func } => HostRegistration::Pure {
912 name: name.clone(),
913 meta: meta.clone(),
914 func: Arc::clone(func),
915 },
916 HostRegistration::Both {
917 name,
918 meta,
919 func,
920 template,
921 } => HostRegistration::Both {
922 name: name.clone(),
923 meta: meta.clone(),
924 func: Arc::clone(func),
925 template: Arc::clone(template),
926 },
927 }
928 }
929}
930
931impl<P: ProcessManager> HostRegistration<P> {
932 pub fn name(&self) -> &str {
938 match self {
939 HostRegistration::Stateful { name, .. } => name,
940 HostRegistration::Pure { name, .. } => name,
941 HostRegistration::Both { name, .. } => name,
942 }
943 }
944
945 pub fn meta(&self) -> &FuncMeta {
948 match self {
949 HostRegistration::Stateful { meta, .. } => meta,
950 HostRegistration::Pure { meta, .. } => meta,
951 HostRegistration::Both { meta, .. } => meta,
952 }
953 }
954}
955
956#[derive(Debug, Clone)]
962pub(super) struct FuncDefData {
963 pub(super) params: Vec<(String, TypeTag, bool)>,
964 pub(super) return_type: TypeTag,
965 pub(super) return_spelling: String,
966 pub(super) is_async: bool,
967 pub(super) body: Vec<Step>,
968 pub(super) module: Option<String>,
973 pub(super) def_jail: Option<(WorkspaceSelection, GuardedPath)>,
979}
980
981pub fn optional_zero_value(tag: &TypeTag) -> DiagnosticResult<Value> {
989 match tag {
990 TypeTag::Bool => Ok(Value::bool(false)),
991 TypeTag::String | TypeTag::Any => Ok(Value::string(String::new())),
992 TypeTag::Int => Ok(Value::int(0)),
993 TypeTag::Float => Ok(Value::float(0.0)),
994 TypeTag::List | TypeTag::ListOf(_) => Ok(Value::list(Vec::new())),
995 TypeTag::Map | TypeTag::MapOf(_) => Ok(Value::map(BTreeMap::new())),
996 TypeTag::Record(fields)
997 if fields
998 .iter()
999 .all(|field| field.optional || field.default.is_some()) =>
1000 {
1001 Ok(Value::map(BTreeMap::new()))
1002 }
1003 other => Err(std_diag::func_zero_value_missing(
1004 &oxdock_parser::render_structural(other),
1005 )),
1006 }
1007}
1008
1009pub fn resolve_script_params<P: ProcessManager>(
1015 state: &ExecState<P>,
1016 func_name: &str,
1017 params: &[(String, String, bool)],
1018) -> DiagnosticResult<Vec<(String, TypeTag, bool)>> {
1019 let mut resolved = Vec::with_capacity(params.len());
1020 for (pname, ptype, optional) in params {
1021 let clean = pname.trim_start_matches('$').to_string();
1022 let tag = state
1023 .resolve_tag(ptype)
1024 .map_err(|err| std_diag::func_param_type(func_name, err))?;
1025 state.check_declaration_tag(&format!("function `{func_name}` param `${clean}`"), &tag)?;
1026 if *optional {
1027 optional_zero_value(&tag)
1028 .map(|_| ())
1029 .map_err(|err| std_diag::func_optional_param(func_name, &clean, err))?;
1030 }
1031 resolved.push((clean, tag, *optional));
1032 }
1033 Ok(resolved)
1034}
1035
1036pub fn check_script_param_tags(
1039 func_name: &str,
1040 params: &[(String, TypeTag, bool)],
1041) -> DiagnosticResult<()> {
1042 for (pname, tag, optional) in params {
1043 if *optional {
1044 optional_zero_value(tag)
1045 .map(|_| ())
1046 .map_err(|err| std_diag::func_optional_param(func_name, pname, err))?;
1047 }
1048 }
1049 Ok(())
1050}
1051
1052pub(super) enum FuncBody<P: ProcessManager> {
1057 Script(FuncDefData),
1058 Pure(PureFn),
1059 Ctx(NativeFn<P>),
1060 Both { pure: PureFn, ctx: NativeFn<P> },
1061}
1062
1063impl<P: ProcessManager> Clone for FuncBody<P> {
1065 fn clone(&self) -> Self {
1066 match self {
1067 FuncBody::Script(def) => FuncBody::Script(def.clone()),
1068 FuncBody::Pure(func) => FuncBody::Pure(Arc::clone(func)),
1069 FuncBody::Ctx(func) => FuncBody::Ctx(Arc::clone(func)),
1070 FuncBody::Both { pure, ctx } => FuncBody::Both {
1071 pure: Arc::clone(pure),
1072 ctx: Arc::clone(ctx),
1073 },
1074 }
1075 }
1076}
1077
1078pub(super) struct FuncEntry<P: ProcessManager> {
1082 pub(super) meta: FuncMeta,
1083 pub(super) body: FuncBody<P>,
1084}
1085
1086impl<P: ProcessManager> Clone for FuncEntry<P> {
1088 fn clone(&self) -> Self {
1089 Self {
1090 meta: self.meta.clone(),
1091 body: self.body.clone(),
1092 }
1093 }
1094}
1095
1096struct ScopeFrame<P: ProcessManager> {
1099 defined: HashSet<String>,
1100 shadowed: Vec<(String, FuncEntry<P>)>,
1101}
1102
1103impl<P: ProcessManager> Clone for ScopeFrame<P> {
1105 fn clone(&self) -> Self {
1106 Self {
1107 defined: self.defined.clone(),
1108 shadowed: self.shadowed.clone(),
1109 }
1110 }
1111}
1112
1113pub type PureTable = HashMap<String, HashMap<String, PureFn>>;
1123
1124pub fn placeholder_resolver(table: Arc<PureTable>) -> oxdock_process::PlaceholderCall {
1133 Arc::new(move |module, func, args| {
1134 let callee = table
1135 .get(module)
1136 .and_then(|entries| entries.get(func))
1137 .ok_or_else(|| {
1138 let mut known: Vec<String> = table
1139 .iter()
1140 .flat_map(|(m, entries)| entries.keys().map(move |f| format!("{m}::{f}")))
1141 .collect();
1142 known.sort();
1143 anyhow::Error::new(std_diag::func_placeholder_unknown(module, func, &known))
1144 })?;
1145 callee(args)
1146 })
1147}
1148
1149pub(super) fn describe_placeholder_miss(
1156 module: &str,
1157 name: &str,
1158 is_script: bool,
1159 is_stateful: bool,
1160 alias_known: bool,
1161) -> Option<String> {
1162 let qualified = qualify(module, name);
1163 if is_script {
1164 let call = if module == SCRIPT_MODULE_NAME {
1165 format!("{name}(...)")
1166 } else {
1167 format!("{qualified}(...)")
1168 };
1169 return Some(format!(
1170 "placeholder function '{qualified}' is a script function and cannot run in {{{{ }}}}; bind the result first with {KEYWORD_LET} $v = {call} then interpolate {{{{ $v }}}}"
1171 ));
1172 }
1173 if is_stateful {
1174 return Some(format!(
1175 "placeholder function '{qualified}' is stateful and cannot run in {{{{ }}}}; capture it first with {KEYWORD_LET} then interpolate {{{{ $v }}}}"
1176 ));
1177 }
1178 if alias_known {
1179 return Some(format!(
1180 "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 }}}}"
1181 ));
1182 }
1183 None
1184}
1185
1186pub(super) struct PlaceholderClasses {
1189 pub script: HashSet<String>,
1190 pub stateful: HashSet<String>,
1191 pub aliases: HashSet<String>,
1192 pub ambiguous: HashMap<String, HashSet<String>>,
1194}
1195
1196impl PlaceholderClasses {
1197 pub(super) fn describe(&self, module: &str, name: &str) -> Option<String> {
1198 let qualified = qualify(module, name);
1199 if let Some(files) = self.ambiguous.get(&qualified) {
1200 return Some(ambiguous_alias_message(module, name, files));
1201 }
1202 describe_placeholder_miss(
1203 module,
1204 name,
1205 self.script.contains(&qualified),
1206 self.stateful.contains(&qualified),
1207 self.aliases.contains(module),
1208 )
1209 }
1210}
1211
1212pub struct FunctionRegistry<P: ProcessManager> {
1213 entries: HashMap<String, FuncEntry<P>>,
1214 scopes: Vec<ScopeFrame<P>>,
1215 pure_shared: Arc<PureTable>,
1216 script_docs: HashMap<String, (String, String)>,
1220}
1221
1222impl<P: ProcessManager> FunctionRegistry<P> {
1223 pub(super) fn with_builtins() -> Self {
1224 let mut reg = Self {
1225 entries: HashMap::new(),
1226 pure_shared: Arc::new(HashMap::new()),
1227 script_docs: HashMap::new(),
1228 scopes: vec![ScopeFrame {
1229 defined: HashSet::new(),
1230 shadowed: Vec::new(),
1231 }],
1232 };
1233 for host in Self::builtin_registrations() {
1237 match host {
1238 HostRegistration::Stateful { name, meta, func } => {
1239 reg.insert_qualified(STD_MODULE_NAME, name, meta, FuncBody::Ctx(func));
1240 }
1241 HostRegistration::Pure { name, meta, func } => {
1242 reg.insert_qualified(STD_MODULE_NAME, name, meta, FuncBody::Pure(func));
1243 }
1244 HostRegistration::Both {
1245 name,
1246 meta,
1247 func,
1248 template,
1249 } => {
1250 reg.insert_qualified(
1251 STD_MODULE_NAME,
1252 name,
1253 meta,
1254 FuncBody::Both {
1255 pure: template,
1256 ctx: func,
1257 },
1258 );
1259 }
1260 }
1261 }
1262 reg
1263 }
1264
1265 pub(super) fn builtin_registrations() -> Vec<HostRegistration<P>> {
1270 vec![
1271 Int::registration(),
1272 Float::registration(),
1273 BoolConvert::registration(),
1274 BoolOr::registration(),
1275 FormatByteCount::registration(),
1276 ParseByteCount::registration(),
1277 FormatDuration::registration(),
1278 ParseDuration::registration(),
1279 Types::registration(),
1280 TypeDescribe::registration(),
1281 Glob::registration(),
1282 LoadToml::registration(),
1283 LoadJson::registration(),
1284 HashSha256::registration(),
1285 Cwd::registration(),
1286 ParseToml::registration(),
1287 ParseJson::registration(),
1288 PathType::registration(),
1289 PathWritable::registration(),
1290 IsExec::registration(),
1291 IsFile::registration(),
1292 IsDir::registration(),
1293 Exists::registration(),
1294 HasKey::registration(),
1295 Get::registration(),
1296 MapSet::registration(),
1297 MergeMaps::registration(),
1298 Base64Encode::registration(),
1299 Base64Decode::registration(),
1300 Rand::registration(),
1301 ToJson::registration(),
1302 TypeOf::registration(),
1303 Functions::registration(),
1304 Describe::registration(),
1305 IsMain::registration(),
1306 IsTerminal::registration(),
1307 Eof::registration(),
1308 TaskPoll::registration(),
1309 Version::registration(),
1310 Interpreter::registration(),
1311 Argv::registration(),
1312 ParseArgs::registration(),
1313 ParseFlags::registration(),
1314 ParsePositionals::registration(),
1315 TextTrim::registration(),
1316 TextTrimPrefix::registration(),
1317 TextTrimSuffix::registration(),
1318 PathJoin::registration(),
1319 PathBase::registration(),
1320 PathRel::registration(),
1321 TextToUpper::registration(),
1322 TextToLower::registration(),
1323 TextReplace::registration(),
1324 TextReplaceRegex::registration(),
1325 TextSplit::registration(),
1326 TextJoin::registration(),
1327 TextLines::registration(),
1328 TextFields::registration(),
1329 TextMatch::registration(),
1330 TextExtract::registration(),
1331 TextStartsWith::registration(),
1332 TextEndsWith::registration(),
1333 Contains::registration(),
1334 Unique::registration(),
1335 Len::registration(),
1336 TextCount::registration(),
1337 TextCountMatches::registration(),
1338 TextGrep::registration(),
1339 TextLinesRange::registration(),
1340 SemaphoreNew::registration(),
1341 SemaphoreTryAcquire::registration(),
1342 SemaphoreAvailable::registration(),
1343 ShellSplitArgs::registration(),
1344 ShellJoinArgs::registration(),
1345 ]
1346 }
1347
1348 pub(super) fn keys(&self) -> HashSet<String> {
1351 self.entries.keys().cloned().collect()
1352 }
1353
1354 pub(super) fn get(&self, name: &str) -> Option<FuncEntry<P>> {
1356 self.entries.get(name).cloned()
1357 }
1358
1359 pub(super) fn scope_depth(&self) -> usize {
1363 self.scopes.len()
1364 }
1365
1366 pub(super) fn get_scoped(&self, base: &str, floor: usize) -> Option<FuncEntry<P>> {
1375 let qualified = qualify(SCRIPT_MODULE_NAME, base);
1376 let len = self.scopes.len();
1377 let start = floor.min(len);
1378 for frame in self.scopes[start..].iter().rev() {
1379 if frame.defined.contains(&qualified) {
1380 return self.entries.get(&qualified).cloned();
1381 }
1382 }
1383 None
1384 }
1385
1386 pub(super) fn describe_unit_placeholder_miss(
1392 &self,
1393 unit_targets: &AliasTargets,
1394 module: &str,
1395 name: &str,
1396 ) -> Option<String> {
1397 let qualified = qualify(module, name);
1398 match classify_alias_call(unit_targets, &qualified, &|key| {
1403 self.entries.contains_key(key)
1404 }) {
1405 AliasResolution::Canonical(canonical) => {
1406 if let Some(entry) = self.entries.get(&canonical) {
1407 if let Some(miss) = Self::placeholder_miss_for_body(module, name, &entry.body) {
1408 return Some(miss);
1409 }
1410 None
1411 } else {
1412 describe_placeholder_miss(module, name, false, false, true)
1413 }
1414 }
1415 AliasResolution::Global => {
1416 if let Some(entry) = self.entries.get(&qualified) {
1417 if let Some(miss) = Self::placeholder_miss_for_body(module, name, &entry.body) {
1421 return Some(miss);
1422 }
1423 }
1424 None
1425 }
1426 AliasResolution::Ambiguous { files, .. } => {
1427 Some(ambiguous_alias_message(module, name, &files))
1428 }
1429 AliasResolution::Unknown => describe_placeholder_miss(module, name, false, false, true),
1430 AliasResolution::Any {
1436 base,
1437 files,
1438 has_host,
1439 } => Some(disjoint_alias_placeholder_miss(
1440 module,
1441 name,
1442 &base,
1443 &files,
1444 has_host,
1445 &|key| matches!(self.entries.get(key), Some(entry) if matches!(entry.body, FuncBody::Script(_))),
1446 )),
1447 }
1448 }
1449
1450 fn placeholder_miss_for_body(module: &str, name: &str, body: &FuncBody<P>) -> Option<String> {
1454 match body {
1455 FuncBody::Script(_) => describe_placeholder_miss(module, name, true, false, false),
1456 FuncBody::Ctx(_) => describe_placeholder_miss(module, name, false, true, false),
1457 FuncBody::Pure(_) | FuncBody::Both { .. } => None,
1458 }
1459 }
1460
1461 pub(super) fn placeholder_snapshot(&self, unit_targets: &AliasTargets) -> PlaceholderClasses {
1465 let mut script = HashSet::new();
1466 let mut stateful = HashSet::new();
1467 let mut ambiguous: HashMap<String, HashSet<String>> = HashMap::new();
1468 for (key, entry) in self.entries.iter() {
1469 let Some((module, base)) = split_qualified(key) else {
1470 continue;
1471 };
1472 match &entry.body {
1473 FuncBody::Script(def) => {
1474 if module == SCRIPT_MODULE_NAME {
1475 script.insert(key.clone());
1477 continue;
1478 }
1479 let defining = def.module.as_deref().unwrap_or(module);
1487 let (direct, ambiguous_here) = spellings_for_defining_file(
1488 unit_targets,
1489 defining,
1490 base,
1491 &|key| matches!(self.entries.get(key), Some(entry) if matches!(entry.body, FuncBody::Script(_))),
1492 );
1493 script.extend(direct);
1494 for (spelling, files) in ambiguous_here {
1495 ambiguous.entry(spelling).or_default().extend(files);
1496 }
1497 }
1498 FuncBody::Ctx(_) => {
1499 stateful.insert(key.clone());
1500 }
1501 FuncBody::Pure(_) | FuncBody::Both { .. } => {}
1502 }
1503 }
1504 let aliases = unit_targets.keys().cloned().collect();
1505 PlaceholderClasses {
1506 script,
1507 stateful,
1508 aliases,
1509 ambiguous,
1510 }
1511 }
1512
1513 fn insert_native(&mut self, name: String, meta: FuncMeta, body: FuncBody<P>) {
1514 self.entries.insert(name, FuncEntry { meta, body });
1515 self.rebuild_pure_shared();
1516 }
1517
1518 fn rebuild_pure_shared(&mut self) {
1524 let mut table: PureTable = HashMap::new();
1525 for (name, entry) in &self.entries {
1526 let func = match &entry.body {
1527 FuncBody::Pure(func) => func,
1528 FuncBody::Both { pure, .. } => pure,
1529 FuncBody::Script(_) | FuncBody::Ctx(_) => continue,
1530 };
1531 if let Some((module, base)) = split_qualified(name) {
1532 table
1533 .entry(module.to_string())
1534 .or_default()
1535 .insert(base.to_string(), Arc::clone(func));
1536 }
1537 }
1538 self.pure_shared = Arc::new(table);
1539 }
1540
1541 fn insert_qualified(
1545 &mut self,
1546 module: &str,
1547 base: String,
1548 mut meta: FuncMeta,
1549 body: FuncBody<P>,
1550 ) {
1551 meta.name = qualify(module, &base);
1552 meta.module = module.to_string();
1553 if self.entries.contains_key(&meta.name) {
1558 panic!("duplicate function registration `{}`", meta.name);
1559 }
1560 self.insert_native(meta.name.clone(), meta, body);
1561 }
1562
1563 pub(super) fn register_host(
1564 &mut self,
1565 module: &str,
1566 name: String,
1567 mut meta: FuncMeta,
1568 func: NativeFn<P>,
1569 ) {
1570 meta.kind = FuncKind::HostCtx;
1571 self.insert_qualified(module, name, meta, FuncBody::Ctx(func));
1572 }
1573
1574 pub(super) fn register_pure_host(
1575 &mut self,
1576 module: &str,
1577 name: String,
1578 mut meta: FuncMeta,
1579 func: PureFn,
1580 ) {
1581 meta.kind = FuncKind::HostPure;
1582 self.insert_qualified(module, name, meta, FuncBody::Pure(func));
1583 }
1584
1585 pub(super) fn register_both_host(
1586 &mut self,
1587 module: &str,
1588 name: String,
1589 mut meta: FuncMeta,
1590 func: NativeFn<P>,
1591 template: PureFn,
1592 ) {
1593 meta.kind = FuncKind::HostCtx;
1594 self.insert_qualified(
1595 module,
1596 name,
1597 meta,
1598 FuncBody::Both {
1599 pure: template,
1600 ctx: func,
1601 },
1602 );
1603 }
1604
1605 #[allow(clippy::too_many_arguments)]
1610 pub(super) fn define_script(
1611 &mut self,
1612 name: &str,
1613 params: &[(String, TypeTag, bool)],
1614 return_type: TypeTag,
1615 return_spelling: &str,
1616 is_async: bool,
1617 body: &[Step],
1618 module: Option<&str>,
1619 def_jail: Option<(WorkspaceSelection, GuardedPath)>,
1620 ) -> DiagnosticResult<()> {
1621 let qualified = qualify(SCRIPT_MODULE_NAME, name);
1622 let shadowable = matches!(
1623 self.entries.get(&qualified).map(|entry| &entry.body),
1624 Some(FuncBody::Script(_))
1625 );
1626 let reserved = self.entries.iter().any(|(key, entry)| {
1631 split_qualified(key).is_some_and(|(_, base)| base == name)
1632 && !matches!(entry.body, FuncBody::Script(_))
1633 });
1634 if reserved && !shadowable {
1635 return Err(std_diag::func_shadow_reserved(name));
1636 }
1637 if self
1638 .scopes
1639 .last()
1640 .is_some_and(|frame| frame.defined.contains(&qualified))
1641 {
1642 return Err(std_diag::func_duplicate_in_scope(name));
1643 }
1644 check_script_param_tags(name, params)?;
1645 let old = self.entries.insert(
1646 qualified.clone(),
1647 FuncEntry {
1648 meta: FuncMeta {
1649 name: qualified.clone(),
1650 module: SCRIPT_MODULE_NAME.to_string(),
1651 kind: FuncKind::Script,
1652 params: Some(
1653 params
1654 .iter()
1655 .map(|(pname, param_type, optional)| {
1656 Ok(FuncParam {
1657 name: pname.clone(),
1658 param_type: Some(param_type.clone()),
1659 allowed: None,
1660 docs: "",
1663 options: None,
1664 optional: *optional,
1665 })
1666 })
1667 .collect::<DiagnosticResult<_>>()?,
1668 ),
1669 returns: Some(return_type.clone()),
1670 rpn: false,
1671 summary: "DSL-defined function.",
1672 docs: "Defined via FUNC in script.",
1673 examples: &[],
1674 },
1675 body: FuncBody::Script(FuncDefData {
1676 params: params.to_vec(),
1677 return_type,
1678 return_spelling: return_spelling.to_string(),
1679 is_async,
1680 body: body.to_vec(),
1681 module: module.map(|m| m.to_string()),
1682 def_jail,
1683 }),
1684 },
1685 );
1686 if let Some(frame) = self.scopes.last_mut() {
1687 frame.defined.insert(qualified.clone());
1688 if let Some(old) = old {
1689 frame.shadowed.push((qualified, old));
1690 }
1691 }
1692 Ok(())
1693 }
1694
1695 #[allow(clippy::too_many_arguments)]
1701 pub(super) fn define_file_func(
1702 &mut self,
1703 name: &str,
1704 params: &[(String, TypeTag, bool)],
1705 return_type: TypeTag,
1706 return_spelling: &str,
1707 is_async: bool,
1708 body: &[Step],
1709 defining: &str,
1710 ) -> DiagnosticResult<()> {
1711 let qualified = file_func_key(defining, name);
1715 let shadowable = matches!(
1716 self.entries.get(&qualified).map(|entry| &entry.body),
1717 Some(FuncBody::Script(_))
1718 );
1719 let reserved = self.entries.iter().any(|(key, entry)| {
1723 split_qualified(key).is_some_and(|(_, base)| base == name)
1724 && !matches!(entry.body, FuncBody::Script(_))
1725 });
1726 if reserved && !shadowable {
1727 return Err(std_diag::func_shadow_reserved(name));
1728 }
1729 let frame_idx = 0;
1733 if self
1734 .scopes
1735 .get(frame_idx)
1736 .is_some_and(|frame| frame.defined.contains(&qualified))
1737 {
1738 return Err(std_diag::func_duplicate_in_scope(name));
1739 }
1740 check_script_param_tags(name, params)?;
1741 let old = self.entries.insert(
1742 qualified.clone(),
1743 FuncEntry {
1744 meta: FuncMeta {
1745 name: qualified.clone(),
1746 module: defining.to_string(),
1747 kind: FuncKind::Script,
1748 params: Some(
1749 params
1750 .iter()
1751 .map(|(pname, param_type, optional)| {
1752 Ok(FuncParam {
1753 name: pname.clone(),
1754 param_type: Some(param_type.clone()),
1755 allowed: None,
1756 docs: "",
1757 options: None,
1758 optional: *optional,
1759 })
1760 })
1761 .collect::<DiagnosticResult<_>>()?,
1762 ),
1763 returns: Some(return_type.clone()),
1764 rpn: false,
1765 summary: "DSL-defined function.",
1766 docs: "Defined via FUNC in an imported script.",
1767 examples: &[],
1768 },
1769 body: FuncBody::Script(FuncDefData {
1770 params: params.to_vec(),
1771 return_type,
1772 return_spelling: return_spelling.to_string(),
1773 is_async,
1774 body: body.to_vec(),
1775 module: Some(defining.to_string()),
1776 def_jail: None,
1781 }),
1782 },
1783 );
1784 if let Some(frame) = self.scopes.get_mut(frame_idx) {
1785 frame.defined.insert(qualified.clone());
1786 if let Some(old) = old {
1787 frame.shadowed.push((qualified, old));
1788 }
1789 }
1790 Ok(())
1791 }
1792
1793 pub(super) fn seal_canonical_jail(
1801 &mut self,
1802 canonical: &str,
1803 jail: (WorkspaceSelection, GuardedPath),
1804 ) {
1805 if let Some(entry) = self.entries.get_mut(canonical)
1806 && let FuncBody::Script(def) = &mut entry.body
1807 && def.def_jail.is_none()
1808 {
1809 def.def_jail = Some(jail);
1810 }
1811 }
1812
1813 pub(super) fn push_scope(&mut self) {
1816 self.scopes.push(ScopeFrame {
1817 defined: HashSet::new(),
1818 shadowed: Vec::new(),
1819 });
1820 }
1821
1822 pub(super) fn pop_scope(&mut self) {
1825 let Some(frame) = self.scopes.pop() else {
1826 return;
1827 };
1828 for name in frame.defined {
1829 self.entries.remove(&name);
1830 }
1831 for (name, old) in frame.shadowed {
1832 self.entries.insert(name, old);
1833 }
1834 }
1835
1836 pub(super) fn resolve_file_call_key(
1839 &self,
1840 unit_targets: &AliasTargets,
1841 name: &str,
1842 ) -> DiagnosticResult<Option<String>> {
1843 match classify_alias_call(unit_targets, name, &|key| self.entries.contains_key(key)) {
1844 AliasResolution::Global | AliasResolution::Unknown | AliasResolution::Any { .. } => {
1845 Ok(None)
1846 }
1847 AliasResolution::Canonical(key) => Ok(Some(key)),
1848 AliasResolution::Ambiguous { alias, base, files } => {
1849 Err(std_diag::func_ambiguous_alias(&alias, &base, &files))
1850 }
1851 }
1852 }
1853
1854 pub(super) fn pure_shared(&self) -> Arc<PureTable> {
1858 Arc::clone(&self.pure_shared)
1859 }
1860
1861 pub(super) fn all_metas(&self) -> Vec<FuncMeta> {
1864 self.entries_metas()
1865 }
1866
1867 fn meta(&self, name: &str) -> Option<FuncMeta> {
1868 self.entries.get(name).map(|entry| entry.meta.clone())
1869 }
1870
1871 fn native_metas(&self) -> Vec<FuncMeta> {
1872 let mut out: Vec<FuncMeta> = Vec::new();
1873 for entry in self.entries.values() {
1874 if !matches!(entry.body, FuncBody::Script(_)) {
1875 out.push(entry.meta.clone());
1876 }
1877 }
1878 out.sort_by(|a, b| a.name.cmp(&b.name));
1879 out
1880 }
1881
1882 pub(super) fn pure_metas(&self) -> Vec<FuncMeta> {
1887 let mut out: Vec<FuncMeta> = Vec::new();
1888 for entry in self.entries.values() {
1889 if matches!(entry.body, FuncBody::Pure(_) | FuncBody::Both { .. }) {
1890 out.push(entry.meta.clone());
1891 }
1892 }
1893 out.sort_by(|a, b| a.name.cmp(&b.name));
1894 out
1895 }
1896
1897 fn entries_metas(&self) -> Vec<FuncMeta> {
1900 let mut out: Vec<FuncMeta> = self
1901 .entries
1902 .values()
1903 .map(|entry| entry.meta.clone())
1904 .collect();
1905 out.sort_by(|a, b| a.name.cmp(&b.name));
1906 out
1907 }
1908
1909 pub fn set_script_docs(&mut self, docs: &HashMap<String, (String, String)>) {
1912 for (base, pair) in docs {
1913 self.script_docs
1914 .insert(qualify(SCRIPT_MODULE_NAME, base), pair.clone());
1915 }
1916 }
1917
1918 pub fn script_doc_for(&self, qualified: &str) -> Option<(String, String)> {
1920 self.script_docs.get(qualified).cloned()
1921 }
1922
1923 pub fn exported_metas(
1928 &self,
1929 func_exports: &[String],
1930 unit_targets: &AliasTargets,
1931 ) -> DiagnosticResult<Vec<FuncMeta>> {
1932 let mut out = Vec::with_capacity(func_exports.len());
1933 for name in func_exports {
1934 let qualified = match split_qualified(name) {
1938 None => qualify(SCRIPT_MODULE_NAME, name),
1939 Some(_) => name.clone(),
1940 };
1941 let lookup = self
1942 .resolve_file_call_key(unit_targets, &qualified)?
1943 .unwrap_or_else(|| qualified.clone());
1944 if let Some(entry) = self.entries.get(&lookup) {
1945 let mut meta = entry.meta.clone();
1946 if lookup != qualified {
1947 meta.name = name.clone();
1948 }
1949 out.push(meta);
1950 continue;
1951 }
1952 return Err(std_diag::func_export_unknown(name));
1953 }
1954 Ok(out)
1955 }
1956}
1957
1958impl<P: ProcessManager> Clone for FunctionRegistry<P> {
1959 fn clone(&self) -> Self {
1960 Self {
1961 entries: self.entries.clone(),
1962 scopes: self.scopes.clone(),
1963 pure_shared: Arc::clone(&self.pure_shared),
1964 script_docs: self.script_docs.clone(),
1965 }
1966 }
1967}
1968
1969pub fn builtin_function_names() -> HashSet<String> {
1976 let mut names = FunctionRegistry::<DefaultProcessManager>::with_builtins().keys();
1977 names.insert(KEYWORD_INSPECT.to_string());
1978 names
1979}
1980
1981pub fn builtin_function_metas() -> Vec<FuncMeta> {
1985 FunctionRegistry::<DefaultProcessManager>::with_builtins().native_metas()
1986}
1987
1988pub fn std_module_table() -> oxdock_parser::ModuleTable {
1993 let func_names: HashSet<String> = builtin_function_metas()
1995 .into_iter()
1996 .map(|meta| base_name(&meta.name).to_string())
1997 .collect();
1998 oxdock_parser::ModuleTable {
1999 modules: HashMap::from([(
2000 STD_MODULE_NAME.to_string(),
2001 Some(oxdock_parser::ModuleFuncs { func_names }),
2002 )]),
2003 }
2004}
2005
2006#[oxdock_func(pure, returns = TypeTag::Int)]
2019#[example(
2020 name = "convert",
2021 code = r###"
2022 IMPORT [STD]
2023 LET $n: INT = INT("42")
2024 ASSERT_EQ $n 42
2025 LET $flag: INT = INT(true)
2026 ASSERT_EQ $flag 1
2027 "###
2028)]
2029fn int(
2030 #[union(Int, Float, String, Bool)]
2032 val: Value,
2033) -> Result<Value> {
2034 Ok(super::args::int_from_value(val)?)
2035}
2036
2037#[oxdock_func(pure, returns = TypeTag::Float)]
2042#[example(
2043 name = "convert",
2044 code = r###"
2045 IMPORT [STD]
2046 LET $f: FLOAT = FLOAT("1.5")
2047 ASSERT_EQ $f 1.5
2048 LET $whole: FLOAT = FLOAT(2)
2049 ASSERT_EQ $whole 2.0
2050 "###
2051)]
2052fn float(
2053 #[union(Float, Int, String)]
2055 val: Value,
2056) -> Result<Value> {
2057 Ok(super::args::float_from_value(val)?)
2058}
2059
2060#[oxdock_func(pure, returns = TypeTag::String)]
2065#[example(
2066 name = "format and round-trip",
2067 code = r###"
2068 # Byte counts render in the largest exact unit.
2069 IMPORT [STD]
2070 LET $pretty: STRING = FORMAT_BYTE_COUNT(1_048_576)
2071 ASSERT_EQ $pretty "1MiB"
2072
2073 # The pair round-trips through the parser.
2074 LET $back: INT = PARSE_BYTE_COUNT($pretty)
2075 ASSERT_EQ $back 1_048_576
2076 "###
2077)]
2078fn format_byte_count(
2079 bytes: i64,
2081) -> Result<Value> {
2082 if bytes < 0 {
2083 return Err(anyhow::Error::new(
2084 std_diag::std_format_byte_count_negative(bytes),
2085 ));
2086 }
2087 Ok(Value::string(oxdock_parser::command::format_byte_count(
2088 bytes as u64,
2089 )))
2090}
2091
2092#[oxdock_func(pure, returns = TypeTag::Int)]
2127#[example(
2128 name = "parse",
2129 code = r###"
2130 IMPORT [STD]
2131 LET $n: INT = PARSE_BYTE_COUNT("10KB")
2132 ASSERT_EQ $n 10_000
2133 LET $identity: INT = PARSE_BYTE_COUNT(512)
2134 ASSERT_EQ $identity 512
2135 "###
2136)]
2137fn parse_byte_count(
2138 #[union(Int, Float, String)]
2140 text: Value,
2141) -> Result<Value> {
2142 if let Some(n) = text.as_i64() {
2143 if n < 0 {
2144 return Err(anyhow::Error::new(std_diag::std_parse_byte_count_negative(
2145 n,
2146 )));
2147 }
2148 return Ok(Value::int(n));
2149 }
2150 if let Some(f) = text.as_f64() {
2151 if f.is_finite() && f.fract() == 0.0 && f >= 0.0 && f <= i64::MAX as f64 {
2152 return Ok(Value::int(f as i64));
2153 }
2154 return Err(anyhow::Error::new(std_diag::std_parse_byte_count_integral(
2155 f,
2156 )));
2157 }
2158 let Some(s) = text.as_str() else {
2159 return Err(anyhow::Error::new(std_diag::std_parse_byte_count_shape(
2160 &text,
2161 )));
2162 };
2163 let n = oxdock_parser::command::parse_byte_count(s)?;
2164 let n = i64::try_from(n)
2165 .map_err(|_| anyhow::Error::new(std_diag::std_parse_byte_count_range(s)))?;
2166 Ok(Value::int(n))
2167}
2168
2169#[oxdock_func(pure, returns = TypeTag::String)]
2174#[example(
2175 name = "format and round-trip",
2176 code = r###"
2177 # Durations render in the largest exact unit.
2178 IMPORT [STD]
2179 LET $pretty: STRING = FORMAT_DURATION(90_000)
2180 ASSERT_EQ $pretty "90s"
2181
2182 # The pair round-trips through the parser.
2183 LET $back: INT = PARSE_DURATION($pretty)
2184 ASSERT_EQ $back 90_000
2185 "###
2186)]
2187fn format_duration(
2188 millis: i64,
2190) -> Result<Value> {
2191 if millis < 0 {
2192 return Err(anyhow::Error::new(std_diag::std_format_duration_negative(
2193 millis,
2194 )));
2195 }
2196 Ok(Value::string(oxdock_parser::command::format_duration(
2197 &std::time::Duration::from_millis(millis as u64),
2198 )))
2199}
2200
2201#[oxdock_func(pure, returns = TypeTag::Int)]
2207#[example(
2208 name = "parse",
2209 code = r###"
2210 # A bare number means seconds, like TIMEOUT.
2211 IMPORT [STD]
2212 LET $ms: INT = PARSE_DURATION("2m")
2213 ASSERT_EQ $ms 120_000
2214
2215 # Milliseconds stay exact.
2216 LET $exact: INT = PARSE_DURATION("1500ms")
2217 ASSERT_EQ $exact 1_500
2218
2219 # One optional space separates number from unit.
2220 LET $spaced: INT = PARSE_DURATION("1 h")
2221 ASSERT_EQ $spaced 3_600_000
2222 "###
2223)]
2224fn parse_duration(
2225 text: String,
2227) -> Result<Value> {
2228 let duration = oxdock_parser::command::parse_duration(&text)?;
2229 let millis = i64::try_from(duration.as_millis())
2230 .map_err(|_| anyhow::Error::new(std_diag::std_parse_duration_range(&text)))?;
2231 Ok(Value::int(millis))
2232}
2233
2234#[oxdock_func(rpn, returns = TypeTag::ListOf(std::sync::Arc::new(TypeTag::String)))]
2239#[example(
2240 name = "match",
2241 code = r###"
2242 IMPORT [STD]
2243 WRITE "notes-a.md" "a"
2244 WRITE "notes-b.md" "b"
2245 WRITE "other.txt" "c"
2246 LET $found: LIST<STRING> = GLOB("notes-*.md")
2247 ASSERT_EQ $found.0 "notes-a.md"
2248 ASSERT_EQ $found.1 "notes-b.md"
2249 "###
2250)]
2251fn glob<P: ProcessManager>(
2252 cx: &mut StepCtx<P>,
2253 #[union(String, Path)]
2255 pattern: Value,
2256) -> Result<Value> {
2257 let text = super::args::string_or_path_text(&pattern)?;
2258 Ok(super::args::glob_from_value(&[Value::string(text)], cx)?)
2259}
2260
2261#[oxdock_func(rpn, returns = TypeTag::MapOf(std::sync::Arc::new(TypeTag::Any)))]
2266#[example(
2267 name = "load",
2268 code = r###"
2269 IMPORT [STD]
2270 WRITE "cfg.toml" "title = \"demo\""
2271 LET $cfg: MAP<ANY> = LOAD_TOML("cfg.toml")
2272 ASSERT_EQ $cfg.title "demo"
2273 "###
2274)]
2275fn load_toml<P: ProcessManager>(
2276 cx: &mut StepCtx<P>,
2277 #[union(String, Path)]
2279 path: Value,
2280) -> Result<Value> {
2281 let text = super::args::string_or_path_text(&path)?;
2282 Ok(super::args::load_toml_from_value(
2283 &[Value::string(text)],
2284 cx,
2285 )?)
2286}
2287
2288#[oxdock_func(rpn, returns = TypeTag::Any)]
2296#[example(
2297 name = "load",
2298 code = r###"
2299 IMPORT [STD]
2300 WRITE "data.json" "{\"a\": 1}"
2301 LET $doc: MAP<ANY> = LOAD_JSON("data.json")
2302 ASSERT_EQ $doc.a 1
2303 "###
2304)]
2305fn load_json<P: ProcessManager>(
2306 cx: &mut StepCtx<P>,
2307 #[union(String, Path)]
2309 path: Value,
2310) -> Result<Value> {
2311 let text = super::args::string_or_path_text(&path)?;
2312 Ok(super::args::load_json_from_value(
2313 &[Value::string(text)],
2314 cx,
2315 )?)
2316}
2317
2318#[oxdock_func(rpn, returns = TypeTag::String)]
2328#[example(
2329 name = "hash",
2330 code = r###"
2331 IMPORT [STD]
2332 WRITE payload.txt hello
2333 LET $digest: STRING = HASH_SHA256("payload.txt")
2334 ASSERT_EQ $digest "2cf24dba5fb0a30e26e83b2ac5b9e29e1b161e5c1fa7425e73043362938b9824"
2335 "###
2336)]
2337fn hash_sha256<P: ProcessManager>(
2338 cx: &mut StepCtx<P>,
2339 #[union(String, Path)]
2341 path: Value,
2342) -> Result<Value> {
2343 use sha2::Digest;
2344
2345 let text = super::args::string_or_path_text(&path)?;
2346 let target = cx.state.fs.resolve_read(&cx.state.cwd, &text)?;
2347 let mut hasher = sha2::Sha256::new();
2348 super::fs_ops::hash_path(cx.state.fs.as_ref(), &target, "", &mut hasher)?;
2349 let digest = hasher.finalize();
2350 let bytes: &[u8] = digest.as_ref();
2351 Ok(Value::string(oxdock_utils::hex_encode(bytes)))
2352}
2353
2354#[oxdock_func(rpn, returns = TypeTag::String)]
2365#[example(
2366 name = "cwd",
2367 code = r###"
2368 IMPORT [STD]
2369 WORKDIR sub
2370 LET $c: STRING = CWD()
2371 ASSERT_CONTAINS $c "sub"
2372 "###
2373)]
2374fn cwd<P: ProcessManager>(cx: &mut StepCtx<P>) -> Result<Value> {
2375 if cx.state.fs.is_snapshot_pending() {
2376 return Ok(Value::string(super::SNAPSHOT_PENDING_DISPLAY.to_string()));
2377 }
2378 let concrete = cx.state.fs.concretize_cwd(&cx.state.cwd);
2379 let real = super::fs_ops::canonical_cwd(cx.state.fs.as_ref(), &concrete)?;
2380 Ok(Value::string(real))
2381}
2382
2383#[oxdock_func(pure, returns = TypeTag::MapOf(std::sync::Arc::new(TypeTag::Any)))]
2389#[example(
2390 name = "parse",
2391 code = r###"
2392 IMPORT [STD]
2393 LET $doc: MAP<ANY> = PARSE_TOML("title = \"demo\"")
2394 ASSERT_EQ $doc.title "demo"
2395 "###
2396)]
2397fn parse_toml(
2398 text: String,
2400) -> Result<Value> {
2401 Ok(super::args::parse_toml_from_value(Value::string(text))?)
2402}
2403
2404#[oxdock_func(pure, returns = TypeTag::Any)]
2413#[example(
2414 name = "parse",
2415 code = r###"
2416 # Parse in-memory JSON text with the same conversion as file loading.
2417 IMPORT [STD]
2418 LET $body: STRING = "{\"a\": 1}"
2419 LET $doc: ANY = PARSE_JSON($body)
2420 ASSERT_EQ $doc.a 1
2421
2422 # Top-level arrays parse to LIST, which is why the return is ANY.
2423 LET $items: LIST<ANY> = PARSE_JSON("[1, 2]")
2424 ASSERT_EQ $items.0 1
2425 ASSERT_EQ $items.1 2
2426 "###
2427)]
2428fn parse_json(
2429 text: String,
2431) -> Result<Value> {
2432 Ok(super::args::parse_json_from_value(Value::string(text))?)
2433}
2434
2435#[oxdock_func(returns = TypeTag::String)]
2441#[example(
2442 name = "describe",
2443 code = r###"
2444 IMPORT [STD]
2445 WRITE "entry.txt" "words"
2446 LET $kind: STRING = PATH_TYPE("entry.txt")
2447 ASSERT_EQ $kind "file"
2448 LET $missing: STRING = PATH_TYPE("no-such-entry.txt")
2449 ASSERT_EQ $missing "absent"
2450 "###
2451)]
2452fn path_type<P: ProcessManager>(
2453 cx: &mut StepCtx<P>,
2454 #[union(String, Path)]
2456 path: Value,
2457) -> Result<Value> {
2458 let text = super::args::string_or_path_text(&path)?;
2459 Ok(super::args::path_type_from_value(
2460 &[Value::string(text)],
2461 cx,
2462 )?)
2463}
2464
2465#[oxdock_func(returns = TypeTag::Bool)]
2474#[example(
2475 name = "probe",
2476 code = r###"
2477 # An absent nested path is writable when its ancestor is.
2478 IMPORT [STD]
2479 LET $fresh: BOOL = PATH_WRITABLE("probe-check/nested/file.txt")
2480 ASSERT_EQ $fresh true
2481
2482 # The empty string never aliases the working directory.
2483 LET $empty: BOOL = PATH_WRITABLE("")
2484 ASSERT_EQ $empty false
2485 "###
2486)]
2487fn path_writable<P: ProcessManager>(
2488 cx: &mut StepCtx<P>,
2489 #[union(String, Path)]
2491 path: Value,
2492) -> Result<Value> {
2493 let text = super::args::string_or_path_text(&path)?;
2494 Ok(super::args::path_writable_from_value(
2495 &[Value::string(text)],
2496 cx,
2497 )?)
2498}
2499
2500#[oxdock_func(returns = TypeTag::Bool)]
2513#[example(
2514 name = "probe",
2515 code = r###"
2516 # Missing tools read false instead of failing the run.
2517 IMPORT [STD]
2518 LET $missing: BOOL = IS_EXEC("no-such-tool-xyz")
2519 ASSERT_EQ $missing false
2520
2521 # Plain files are not executable on any platform.
2522 WRITE tool.txt payload
2523 LET $plain: BOOL = IS_EXEC("tool.txt")
2524 ASSERT_EQ $plain false
2525 "###
2526)]
2527fn is_exec<P: ProcessManager>(
2528 cx: &mut StepCtx<P>,
2529 #[union(String, Path)]
2531 name: Value,
2532) -> Result<Value> {
2533 let text = super::args::string_or_path_text(&name)?;
2534 Ok(super::args::is_exec_from_value(&[Value::string(text)], cx)?)
2535}
2536
2537#[oxdock_func(returns = TypeTag::Bool)]
2545#[example(
2546 name = "probe",
2547 code = r###"
2548 # Ordinary files read true; missing paths read false.
2549 IMPORT [STD]
2550 WRITE "entry.txt" "words"
2551 LET $hit: BOOL = IS_FILE("entry.txt")
2552 ASSERT_EQ $hit true
2553 LET $miss: BOOL = IS_FILE("no-such-entry.txt")
2554 ASSERT_EQ $miss false
2555 "###
2556)]
2557fn is_file<P: ProcessManager>(
2558 cx: &mut StepCtx<P>,
2559 #[union(String, Path)]
2561 path: Value,
2562) -> Result<Value> {
2563 let text = super::args::string_or_path_text(&path)?;
2564 Ok(Value::bool(super::args::path_is_file(cx, &text)))
2565}
2566
2567#[oxdock_func(returns = TypeTag::Bool)]
2575#[example(
2576 name = "probe",
2577 code = r###"
2578 # Directories read true; files read false.
2579 IMPORT [STD]
2580 LET $hit: BOOL = IS_DIR(".")
2581 ASSERT_EQ $hit true
2582 WRITE "entry.txt" "words"
2583 LET $miss: BOOL = IS_DIR("entry.txt")
2584 ASSERT_EQ $miss false
2585 "###
2586)]
2587fn is_dir<P: ProcessManager>(
2588 cx: &mut StepCtx<P>,
2589 #[union(String, Path)]
2591 path: Value,
2592) -> Result<Value> {
2593 let text = super::args::string_or_path_text(&path)?;
2594 Ok(Value::bool(super::args::path_is_dir(cx, &text)))
2595}
2596
2597#[oxdock_func(returns = TypeTag::Bool)]
2604#[example(
2605 name = "probe",
2606 code = r###"
2607 # Present entries read true; absent paths read false.
2608 IMPORT [STD]
2609 WRITE "entry.txt" "words"
2610 LET $hit: BOOL = EXISTS("entry.txt")
2611 ASSERT_EQ $hit true
2612 LET $miss: BOOL = EXISTS("no-such-entry.txt")
2613 ASSERT_EQ $miss false
2614 "###
2615)]
2616fn exists<P: ProcessManager>(
2617 cx: &mut StepCtx<P>,
2618 #[union(String, Path)]
2620 path: Value,
2621) -> Result<Value> {
2622 let text = super::args::string_or_path_text(&path)?;
2623 Ok(Value::bool(super::args::path_exists(cx, &text)))
2624}
2625
2626#[oxdock_func(pure, returns = TypeTag::Bool)]
2632#[example(
2633 name = "probe",
2634 code = r###"
2635 IMPORT [STD]
2636 LET $m: MAP<ANY> = PARSE_JSON("{\"a\": 1}")
2637 LET $hit: BOOL = HAS_KEY($m, "a")
2638 ASSERT_EQ $hit true
2639 LET $miss: BOOL = HAS_KEY($m, "b")
2640 ASSERT_EQ $miss false
2641 "###
2642)]
2643fn has_key(
2644 map: BTreeMap<String, Value>,
2646 key: String,
2648) -> Result<Value> {
2649 Ok(super::args::has_key_from_value(Value::map(map), &key)?)
2650}
2651
2652#[oxdock_func(pure, returns = TypeTag::Any)]
2658#[example(
2659 name = "present and absent",
2660 code = r###"
2661 IMPORT [STD]
2662 LET $m: MAP<ANY> = PARSE_JSON("{\"a\": 1}")
2663 LET $hit: INT = GET($m, "a", 0)
2664 ASSERT_EQ $hit 1
2665 LET $miss: INT = GET($m, "b", 0)
2666 ASSERT_EQ $miss 0
2667 "###
2668)]
2669fn get(
2670 map: BTreeMap<String, Value>,
2672 key: String,
2674 default: Value,
2676) -> Result<Value> {
2677 Ok(map.get(&key).cloned().unwrap_or(default))
2678}
2679
2680#[oxdock_func(pure, returns = TypeTag::MapOf(std::sync::Arc::new(TypeTag::Any)))]
2690#[example(
2691 name = "insert",
2692 code = r###"
2693 IMPORT [STD]
2694 LET $m: MAP<ANY> = MAP_SET({seed: 0}, "a", 1)
2695 ASSERT_EQ $m.a 1
2696 "###
2697)]
2698fn map_set(
2699 #[reject_frozen]
2701 map: BTreeMap<String, Value>,
2702 key: String,
2704 value: Value,
2706) -> Result<Value> {
2707 Ok(super::args::map_set_from_value(
2708 Value::map(map),
2709 key,
2710 value,
2711 )?)
2712}
2713
2714#[oxdock_func(returns = TypeTag::Float, summary = "Draw a random FLOAT uniformly from [0, 1), optionally seeded.")]
2722#[example(
2723 name = "seeded draw",
2724 code = r###"
2725 # A seed draws the same value on every run.
2726 IMPORT [STD]
2727 LET $one: FLOAT = RAND({seed: 7})
2728 LET $two: FLOAT = RAND({seed: 7})
2729 ASSERT_EQ $one $two
2730 "###
2731)]
2732#[example(
2733 name = "unseeded draw",
2734 code = r###"
2735 # Scale a unit draw into a backoff delay between 1 and 11 seconds.
2736 IMPORT [STD]
2737 LET $draw: FLOAT = RAND()
2738 LET $delay: FLOAT = 1.0 + $draw * 10.0
2739 IF $delay < 1.0 {
2740 FAIL "trap: RAND draw below range"
2741 }
2742 IF $delay >= 11.0 {
2743 FAIL "trap: RAND draw above range"
2744 }
2745 ECHO "retrying in {{ $delay }}s"
2746 "###
2747)]
2748fn rand<P: ProcessManager>(
2749 cx: &mut StepCtx<P>,
2750 #[options("seed?: INT")]
2752 #[optional]
2753 options: BTreeMap<String, Value>,
2754) -> Result<Value> {
2755 let _ = cx;
2756 let seed = options
2759 .get("seed")
2760 .map(|value| value.as_i64().expect("check_options verified INT"));
2761 Ok(super::args::rand_float_from_value(seed)?)
2762}
2763
2764#[oxdock_func(pure, returns = TypeTag::String)]
2770#[example(
2771 name = "encode",
2772 code = r###"
2773 # Encode text to standard base64.
2774 IMPORT [STD]
2775 LET $encoded: STRING = BASE64_ENCODE("hello")
2776 ASSERT_EQ $encoded "aGVsbG8="
2777 "###
2778)]
2779fn base64_encode(
2780 text: String,
2782) -> Result<Value> {
2783 Ok(super::args::base64_encode_from_value(Value::string(text))?)
2784}
2785
2786#[oxdock_func(pure, returns = TypeTag::String)]
2793#[example(
2794 name = "decode",
2795 code = r###"
2796 # Decode standard base64 back to text.
2797 IMPORT [STD]
2798 LET $decoded: STRING = BASE64_DECODE("aGVsbG8=")
2799 ASSERT_EQ $decoded "hello"
2800 "###
2801)]
2802fn base64_decode(
2803 text: String,
2805) -> Result<Value> {
2806 Ok(super::args::base64_decode_from_value(Value::string(text))?)
2807}
2808
2809#[oxdock_func(pure, returns = TypeTag::String)]
2816#[example(
2817 name = "encode",
2818 code = r###"
2819 IMPORT [STD]
2820 LET $json: STRING = TO_JSON({a: 1})
2821 ASSERT_EQ $json "{\"a\":1}\n"
2822 "###
2823)]
2824fn to_json(
2825 #[union(String, Int, Float, Bool, List, Map)]
2827 value: Value,
2828) -> Result<Value> {
2829 Ok(super::args::to_json_from_value(value)?)
2830}
2831
2832#[oxdock_func(pure, returns = TypeTag::String)]
2840#[example(
2841 name = "name the word",
2842 code = r###"
2843 IMPORT [STD]
2844 LET $word: STRING = TYPE_OF(42)
2845 ASSERT_EQ $word "INT"
2846 "###
2847)]
2848fn type_of(
2849 value: Value,
2851) -> Result<Value> {
2852 Ok(super::args::type_of_from_value(value)?)
2853}
2854
2855#[oxdock_func(pure, returns = TypeTag::MapOf(std::sync::Arc::new(TypeTag::Any)))]
2867#[example(
2868 name = "merge",
2869 code = r###"
2870 IMPORT [STD]
2871 LET $m: MAP<ANY> = MERGE_MAPS([{a: 1}, {b: 2}], "overwrite")
2872 ASSERT_EQ $m.a 1
2873 ASSERT_EQ $m.b 2
2874 "###
2875)]
2876fn merge_maps(
2877 #[reject_frozen]
2879 maps: Vec<BTreeMap<String, Value>>,
2880 #[values("fail_on_duplicate", "overwrite")]
2882 policy: String,
2883) -> Result<Value> {
2884 Ok(super::args::merge_maps_from_value(
2885 Value::list(maps.into_iter().map(Value::map).collect()),
2886 policy,
2887 )?)
2888}
2889
2890#[oxdock_func(pure, returns = TypeTag::String)]
2895#[example(
2896 name = "report",
2897 code = r###"
2898 # The engine reports its own build version as a dotted string.
2899 IMPORT [STD]
2900 LET $v: STRING = VERSION()
2901 ASSERT_CONTAINS $v "."
2902 "###
2903)]
2904fn version() -> Result<Value> {
2905 Ok(Value::string(env!("CARGO_PKG_VERSION").to_string()))
2906}
2907
2908#[oxdock_func(returns = TypeTag::ListOf(std::sync::Arc::new(TypeTag::String)))]
2913#[example(
2914 name = "list",
2915 code = r###"
2916 IMPORT [STD]
2917 LET $names: LIST<STRING> = FUNCTIONS()
2918 ASSERT_CONTAINS $names "STD::INT"
2919 "###
2920)]
2921fn functions<P: ProcessManager>(cx: &mut StepCtx<P>) -> Result<Value> {
2922 let mut names: Vec<String> = cx
2923 .state
2924 .list_functions()
2925 .into_iter()
2926 .map(|meta| meta.name)
2927 .collect();
2928 names.sort();
2929 names.dedup();
2930 Ok(Value::list(names.into_iter().map(Value::string).collect()))
2931}
2932
2933#[oxdock_func(returns = TypeTag::ListOf(std::sync::Arc::new(TypeTag::String)))]
2940#[example(
2941 name = "empty",
2942 code = r###"
2943 # With no staged args the list is empty.
2944 IMPORT [STD]
2945 LET $args: LIST<STRING> = ARGV()
2946 LET $n: INT = LEN($args)
2947 ASSERT_EQ $n 0
2948 "###
2949)]
2950fn argv<P: ProcessManager>(cx: &mut StepCtx<P>) -> Result<Value> {
2951 Ok(Value::list(
2952 cx.state
2953 .io
2954 .script_args()
2955 .iter()
2956 .cloned()
2957 .map(Value::string)
2958 .collect(),
2959 ))
2960}
2961
2962pub struct ParseArgs;
2982
2983impl<P: ProcessManager> OxDockFn<P> for ParseArgs {
2984 fn registration() -> HostRegistration<P> {
2985 let func: NativeFn<P> = Arc::new(|cx: &mut StepCtx<P>, values: Vec<Value>| {
2986 if values.len() != 1 {
2987 return Err(anyhow::Error::new(std_diag::std_parse_args_arity(
2988 values.len(),
2989 )));
2990 }
2991 let mut iter = values.into_iter();
2992 let args_val = iter.next().expect("arity checked above");
2993 let args =
2994 string_list_arg(&args_val, &format!("{FUNC_PARSE_ARGS}() argument `$args`"))?;
2995 let specs = resolve_flags_specs(cx)?;
2996 let (raw, positionals) = tokenize_raw_args(args)?;
2997 let coerced = coerce_flags(&specs, &raw)?;
2998 let mut out = BTreeMap::new();
2999 out.insert("flags".to_string(), Value::map(coerced));
3000 if !positionals.is_empty() {
3001 out.insert("positionals".to_string(), Value::list(positionals));
3002 }
3003 Ok(Value::map(out))
3004 });
3005 HostRegistration::Stateful {
3006 name: FUNC_PARSE_ARGS.to_string(),
3007 meta: FuncMeta {
3008 name: FUNC_PARSE_ARGS.to_string(),
3009 module: String::new(),
3010 kind: FuncKind::HostPure,
3011 params: Some(vec![FuncParam {
3012 name: "args".to_string(),
3013 param_type: Some(TypeTag::ListOf(Arc::new(TypeTag::String))),
3014 allowed: None,
3015 docs: "Argv tail to parse, usually from `STD::ARGV()`.",
3016 options: None,
3017 optional: false,
3018 }]),
3019 returns: Some(TypeTag::Record(Arc::from([
3020 Field {
3021 name: "flags".to_string(),
3022 ty: TypeTag::Map,
3023 docs: "Flags coerced to `TYPE FLAGS`.",
3024 optional: false,
3025 default: None,
3026
3027 alias: None,
3028 },
3029 Field {
3030 name: "positionals".to_string(),
3031 ty: TypeTag::ListOf(Arc::new(TypeTag::String)),
3032 docs: "Trailing values and entries after the first double dash. Omitted when empty.",
3033 optional: true,
3034 default: None,
3035
3036 alias: None,
3037 },
3038 ]))),
3039 rpn: true,
3040 summary: "Parse an argv tail against TYPE FLAGS.",
3041 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.",
3042 examples: &[
3043 crate::Example {
3044 name: "flags and positionals",
3045 fence_meta: None,
3046 code: indoc::indoc! {r#"
3047 IMPORT [STD]
3048 # One schema TYPE drives coercion; the pair binds both slots.
3049 TYPE FLAGS = MAP<model: STRING, verbose?: BOOL>
3050 TYPE POSITIONS = LIST<STRING>
3051 TYPE PARSED = MAP<flags: FLAGS, positionals?: POSITIONS>
3052 LET $parsed: PARSED = PARSE_ARGS(["--model=gpt-4", "--verbose", "serve"])
3053 LET $flags: FLAGS = $parsed.flags
3054 ASSERT_EQ $flags.model "gpt-4"
3055 ASSERT_EQ $flags.verbose true
3056 ASSERT_EQ $parsed.positionals.0 "serve"
3057 "#},
3058 },
3059 crate::Example {
3060 name: "optional stays absent",
3061 fence_meta: None,
3062 code: indoc::indoc! {r#"
3063 IMPORT [STD]
3064 # Absent optionals stay absent; read them with a typed GET default.
3065 TYPE FLAGS = MAP<model: STRING, propose?: BOOL>
3066 TYPE POSITIONS = LIST<STRING>
3067 TYPE PARSED = MAP<flags: FLAGS, positionals?: POSITIONS>
3068 LET $parsed: PARSED = PARSE_ARGS(["--model=x"])
3069 LET $flags: FLAGS = $parsed.flags
3070 LET $propose: BOOL = GET($flags, "propose", false)
3071 ASSERT_EQ $propose false
3072 "#},
3073 },
3074 crate::Example {
3075 name: "flags only omits positionals",
3076 fence_meta: None,
3077 code: indoc::indoc! {r#"
3078 IMPORT [STD]
3079 # Empty positionals are omitted, so a flags only shape binds clean.
3080 TYPE FLAGS = MAP<model: STRING>
3081 TYPE PARSED = MAP<flags: FLAGS>
3082 LET $parsed: PARSED = PARSE_ARGS(["--model=x"])
3083 LET $flags: FLAGS = $parsed.flags
3084 ASSERT_EQ $flags.model "x"
3085 "#},
3086 },
3087 crate::Example {
3088 name: "literal defaults",
3089 fence_meta: None,
3090 code: indoc::indoc! {r#"
3091 IMPORT [STD]
3092 # Defaults are literals only: INT, FLOAT, BOOL,
3093 # and double-quoted STRING fill absent flags.
3094 TYPE FLAGS = MAP<retries: INT = 2, ratio: FLOAT = 2.5, verbose: BOOL = true, model: STRING = "gpt-4">
3095 TYPE PARSED = MAP<flags: FLAGS>
3096 LET $parsed: PARSED = PARSE_ARGS([])
3097 LET $flags: FLAGS = $parsed.flags
3098 ASSERT_EQ $flags.retries 2
3099 ASSERT_EQ $flags.verbose true
3100 ASSERT_EQ $flags.model "gpt-4"
3101 LET $ratio_ok: BOOL = $flags.ratio == 2.5
3102 ASSERT_EQ $ratio_ok true
3103 "#},
3104 },
3105 crate::Example {
3106 name: "variable default fails",
3107 fence_meta: Some("expect_error:\"expected default literal\""),
3108 code: indoc::indoc! {r#"
3109 IMPORT [STD]
3110 # Defaults are literals: a variable in place
3111 # of a literal fails instead of evaluating.
3112 TYPE FLAGS = MAP<n: INT = $x>
3113 TYPE PARSED = MAP<flags: FLAGS>
3114 LET $p: PARSED = PARSE_ARGS([])
3115 "#},
3116 },
3117 crate::Example {
3118 name: "missing required",
3119 fence_meta: Some("expect_error:\"missing required flag\""),
3120 code: indoc::indoc! {r#"
3121 IMPORT [STD]
3122 # Absent required flags fail naming the flag.
3123 TYPE FLAGS = MAP<model: STRING>
3124 TYPE PARSED = MAP<flags: FLAGS>
3125 LET $parsed: PARSED = PARSE_ARGS([])
3126 "#},
3127 },
3128 crate::Example {
3129 name: "unknown flag",
3130 fence_meta: Some("expect_error:\"unknown flag\""),
3131 code: indoc::indoc! {r#"
3132 IMPORT [STD]
3133 # Undeclared flags fail instead of passing through.
3134 TYPE FLAGS = MAP<model: STRING>
3135 TYPE PARSED = MAP<flags: FLAGS>
3136 LET $parsed: PARSED = PARSE_ARGS(["--model=x", "--nope=1"])
3137 "#},
3138 },
3139 crate::Example {
3140 name: "alias accepted",
3141 fence_meta: None,
3142 code: indoc::indoc! {r#"
3143 IMPORT [STD]
3144 # One canonical key binds both spellings; the
3145 # alias never appears as a separate key.
3146 TYPE FLAGS = MAP<h: BOOL ALIAS help>
3147 TYPE PARSED = MAP<flags: FLAGS>
3148 LET $a: PARSED = PARSE_ARGS(["--help"])
3149 ASSERT_EQ $a.flags.h true
3150 LET $b: PARSED = PARSE_ARGS(["--h"])
3151 ASSERT_EQ $b.flags.h true
3152 "#},
3153 },
3154 crate::Example {
3155 name: "alias duplicate fails",
3156 fence_meta: Some("expect_error:\"duplicate flag\""),
3157 code: indoc::indoc! {r#"
3158 IMPORT [STD]
3159 # Canonical and alias together fail naming both.
3160 TYPE FLAGS = MAP<h: BOOL ALIAS help>
3161 TYPE PARSED = MAP<flags: FLAGS>
3162 LET $p: PARSED = PARSE_ARGS(["--h", "--help"])
3163 "#},
3164 },
3165 crate::Example {
3166 name: "alias missing names both",
3167 fence_meta: Some("expect_error:\"--h/--help\""),
3168 code: indoc::indoc! {r#"
3169 IMPORT [STD]
3170 # Missing required flags name both spellings.
3171 TYPE FLAGS = MAP<h: BOOL ALIAS help>
3172 TYPE PARSED = MAP<flags: FLAGS>
3173 LET $p: PARSED = PARSE_ARGS([])
3174 "#},
3175 },
3176 ],
3177 },
3178 func,
3179 }
3180 }
3181}
3182
3183#[derive(Debug, Clone, Copy, PartialEq, Eq)]
3187enum CliType {
3188 String,
3189 Bool,
3190 Int,
3191 Float,
3192}
3193
3194fn coerce_cli_flag(target: CliType, flag: &str, raw: Value) -> DiagnosticResult<Value> {
3199 match target {
3200 CliType::Bool => {
3201 if let Some(b) = raw.as_bool() {
3202 return Ok(Value::bool(b));
3203 }
3204 if let Some(s) = raw.as_str() {
3205 match super::args::parse_bool_str(s) {
3206 Some(b) => return Ok(Value::bool(b)),
3207 None => {
3208 return Err(std_diag::std_parse_args_bool_flag(flag, s));
3209 }
3210 }
3211 }
3212 Err(std_diag::std_parse_args_bool_type(flag, raw.type_name()))
3213 }
3214 CliType::String => {
3215 if let Some(s) = raw.as_str() {
3216 return Ok(Value::string(s.to_string()));
3217 }
3218 Err(std_diag::std_parse_args_needs_value(flag))
3219 }
3220 CliType::Int => {
3221 if raw.as_bool().is_some() {
3222 return Err(std_diag::std_parse_args_needs_value(flag));
3223 }
3224 super::args::int_from_value(raw).map_err(|_| std_diag::std_parse_args_expects_int(flag))
3225 }
3226 CliType::Float => {
3227 if raw.as_bool().is_some() {
3228 return Err(std_diag::std_parse_args_needs_value(flag));
3229 }
3230 super::args::float_from_value(raw)
3231 .map_err(|_| std_diag::std_parse_args_expects_float(flag))
3232 }
3233 }
3234}
3235
3236#[derive(Debug, Clone)]
3240struct CliSpec {
3241 target: CliType,
3242 required: bool,
3243 default: Option<Value>,
3244 alias: Option<String>,
3245}
3246
3247type CliSpecs = BTreeMap<String, CliSpec>;
3249
3250fn string_list_arg(val: &Value, what: &str) -> DiagnosticResult<Vec<String>> {
3253 crate::check_value_at(&TypeTag::ListOf(Arc::new(TypeTag::String)), val, what)
3254 .map_err(|err| std_diag::std_parse_args_arg_shape(&err))?;
3255 Ok(val
3256 .as_list()
3257 .expect("check_value_at enforces LIST")
3258 .iter()
3259 .map(|v| {
3260 v.as_str()
3261 .expect("check_value_at enforces STRING")
3262 .to_string()
3263 })
3264 .collect())
3265}
3266
3267fn tokenize_raw_args(args: Vec<String>) -> DiagnosticResult<(BTreeMap<String, Value>, Vec<Value>)> {
3271 use lexopt::Arg::{Long, Short, Value as ArgValue};
3272 let mut parser = lexopt::Parser::from_args(args);
3273 let mut flags: BTreeMap<String, Value> = BTreeMap::new();
3274 let mut positionals: Vec<Value> = Vec::new();
3275 let utf8 = |value: std::ffi::OsString| -> DiagnosticResult<String> {
3276 value
3277 .into_string()
3278 .map_err(|_| std_diag::std_parse_args_not_utf8())
3279 };
3280 loop {
3281 match parser.next() {
3282 Ok(None) => break,
3283 Ok(Some(Long(name))) => {
3284 let key = name.to_owned();
3285 if let Some(raw) = parser.optional_value() {
3286 flags.insert(key, Value::string(utf8(raw)?));
3287 } else {
3288 flags.insert(key, Value::bool(true));
3289 }
3290 }
3291 Ok(Some(Short(ch))) => {
3292 flags.insert(ch.to_string(), Value::bool(true));
3293 }
3294 Ok(Some(ArgValue(raw))) => {
3295 positionals.push(Value::string(utf8(raw)?));
3296 }
3297 Err(lexopt::Error::UnexpectedValue { option, value }) => {
3298 let key = option
3299 .strip_prefix("--")
3300 .or_else(|| option.strip_prefix('-'))
3301 .unwrap_or(option.as_str());
3302 flags.insert(key.to_string(), Value::string(utf8(value)?));
3303 }
3304 Err(err) => return Err(std_diag::std_parse_args_lex_error(&err)),
3305 }
3306 }
3307 Ok((flags, positionals))
3308}
3309
3310fn coerce_flags(
3318 specs: &CliSpecs,
3319 raw: &BTreeMap<String, Value>,
3320) -> DiagnosticResult<BTreeMap<String, Value>> {
3321 let mut alias_to_canonical: BTreeMap<&str, &str> = BTreeMap::new();
3324 for (canonical, spec) in specs.iter() {
3325 if let Some(alias) = spec.alias.as_ref() {
3326 alias_to_canonical.insert(alias.as_str(), canonical.as_str());
3327 }
3328 }
3329 let mut coerced: BTreeMap<String, Value> = BTreeMap::new();
3330 for (flag, spec) in specs.iter() {
3331 if flag.is_empty() {
3332 return Err(std_diag::std_parse_args_schema_flag_empty());
3333 }
3334 let canonical_raw = raw.get(flag);
3335 let alias_raw = spec.alias.as_ref().and_then(|alias| raw.get(alias));
3336 if canonical_raw.is_some() && alias_raw.is_some() {
3337 return Err(std_diag::std_parse_args_duplicate_flag(
3338 flag,
3339 spec.alias.as_deref(),
3340 ));
3341 }
3342 if let Some(raw_val) = canonical_raw.or(alias_raw) {
3343 coerced.insert(
3344 flag.clone(),
3345 coerce_cli_flag(spec.target, flag, raw_val.clone())?,
3346 );
3347 } else if let Some(d) = spec.default.as_ref() {
3348 coerced.insert(flag.clone(), d.clone());
3349 } else if spec.required {
3350 return Err(std_diag::std_parse_args_missing_flag(
3351 flag,
3352 spec.alias.as_deref(),
3353 ));
3354 }
3355 }
3356 for flag in raw.keys() {
3357 if !specs.contains_key(flag) && !alias_to_canonical.contains_key(flag.as_str()) {
3358 return Err(std_diag::std_parse_args_unknown_flag(flag));
3359 }
3360 }
3361 Ok(coerced)
3362}
3363
3364fn resolve_flags_specs<P: ProcessManager>(cx: &mut StepCtx<P>) -> DiagnosticResult<CliSpecs> {
3371 let name = "FLAGS";
3372 let tag = cx
3373 .state
3374 .resolve_tag(name)
3375 .map_err(|err| std_diag::std_parse_args_schema_type(name, &anyhow::Error::new(err)))?;
3376 let TypeTag::Record(fields) = tag else {
3377 return Err(std_diag::std_parse_args_schema_shape(name));
3378 };
3379 let mut specs = BTreeMap::new();
3380 for field in fields.iter() {
3381 let target = match field.ty {
3382 TypeTag::String => CliType::String,
3383 TypeTag::Bool => CliType::Bool,
3384 TypeTag::Int => CliType::Int,
3385 TypeTag::Float => CliType::Float,
3386 _ => {
3387 return Err(std_diag::std_parse_args_schema_field_type(
3388 &field.name,
3389 field.ty.name(),
3390 ));
3391 }
3392 };
3393 specs.insert(
3394 field.name.clone(),
3395 CliSpec {
3396 target,
3397 required: !field.optional && field.default.is_none(),
3398 default: field.default.clone(),
3399 alias: field.alias.clone(),
3400 },
3401 );
3402 }
3403 Ok(specs)
3404}
3405
3406pub struct ParseFlags;
3414
3415impl<P: ProcessManager> OxDockFn<P> for ParseFlags {
3416 fn registration() -> HostRegistration<P> {
3417 let func: NativeFn<P> = Arc::new(|cx: &mut StepCtx<P>, values: Vec<Value>| {
3418 if values.len() != 1 {
3419 return Err(anyhow::Error::new(std_diag::std_parse_flags_arity(
3420 values.len(),
3421 )));
3422 }
3423 let mut iter = values.into_iter();
3424 let args_val = iter.next().expect("arity checked above");
3425 let args = string_list_arg(&args_val, "{FUNC_PARSE_FLAGS}() argument `$args`")?;
3426 let specs = resolve_flags_specs(cx)?;
3427 let (raw, positionals) = tokenize_raw_args(args)?;
3428 if !positionals.is_empty() {
3429 return Err(anyhow::Error::new(std_diag::std_parse_flags_positional(
3430 &positionals
3431 .iter()
3432 .map(|pos| pos.to_string())
3433 .collect::<Vec<_>>(),
3434 )));
3435 }
3436 Ok(Value::map(coerce_flags(&specs, &raw)?))
3437 });
3438 HostRegistration::Stateful {
3439 name: FUNC_PARSE_FLAGS.to_string(),
3440 meta: FuncMeta {
3441 name: FUNC_PARSE_FLAGS.to_string(),
3442 module: String::new(),
3443 kind: FuncKind::HostPure,
3444 params: Some(vec![FuncParam {
3445 name: "args".to_string(),
3446 param_type: Some(TypeTag::ListOf(Arc::new(TypeTag::String))),
3447 allowed: None,
3448 docs: "Argv tail to parse, usually from `STD::ARGV()`.",
3449 options: None,
3450 optional: false,
3451 }]),
3452 returns: Some(TypeTag::Map),
3453 rpn: true,
3454 summary: "Parse flags against TYPE FLAGS.",
3455 docs: "Consumes a `LIST<STRING>` and coerces flags through `TYPE FLAGS`. Returns the flags `MAP` directly; positional arguments fail.",
3456 examples: &[crate::Example {
3457 name: "flags only",
3458 fence_meta: None,
3459 code: indoc::indoc! {r#"
3460 IMPORT [STD]
3461 # Flags only returns the flags MAP directly.
3462 TYPE FLAGS = MAP<model: STRING, retries: INT = 2>
3463 LET $flags: FLAGS = PARSE_FLAGS(["--model=x"])
3464 ASSERT_EQ $flags.model "x"
3465 ASSERT_EQ $flags.retries 2
3466 "#},
3467 }],
3468 },
3469 func,
3470 }
3471 }
3472}
3473
3474pub struct ParsePositionals;
3479
3480impl<P: ProcessManager> OxDockFn<P> for ParsePositionals {
3481 fn registration() -> HostRegistration<P> {
3482 let func: NativeFn<P> = Arc::new(|_: &mut StepCtx<P>, values: Vec<Value>| {
3483 if values.len() != 1 {
3484 return Err(anyhow::Error::new(std_diag::std_parse_positionals_arity(
3485 values.len(),
3486 )));
3487 }
3488 let mut iter = values.into_iter();
3489 let args_val = iter.next().expect("arity checked above");
3490 let args = string_list_arg(
3491 &args_val,
3492 &format!("{FUNC_PARSE_POSITIONALS}() argument `$args`"),
3493 )?;
3494 let (_raw, positionals) = tokenize_raw_args(args)?;
3495 Ok(Value::list(positionals))
3496 });
3497 HostRegistration::Stateful {
3498 name: FUNC_PARSE_POSITIONALS.to_string(),
3499 meta: FuncMeta {
3500 name: FUNC_PARSE_POSITIONALS.to_string(),
3501 module: String::new(),
3502 kind: FuncKind::HostPure,
3503 params: Some(vec![FuncParam {
3504 name: "args".to_string(),
3505 param_type: Some(TypeTag::ListOf(Arc::new(TypeTag::String))),
3506 allowed: None,
3507 docs: "Argv tail to parse, usually from `STD::ARGV()`.",
3508 options: None,
3509 optional: false,
3510 }]),
3511 returns: Some(TypeTag::ListOf(Arc::new(TypeTag::String))),
3512 rpn: true,
3513 summary: "Parse positionals in argv order.",
3514 docs: "Consumes a `LIST<STRING>` and returns positionals in argv order with no schema.",
3515 examples: &[crate::Example {
3516 name: "positionals only",
3517 fence_meta: None,
3518 code: indoc::indoc! {r#"
3519 IMPORT [STD]
3520 # No schema needed: positionals are always strings in order.
3521 TYPE POSITIONS = LIST<STRING>
3522 LET $pos: POSITIONS = PARSE_POSITIONALS(["serve", "--", "--not-a-flag"])
3523 ASSERT_EQ $pos.0 "serve"
3524 ASSERT_EQ $pos.1 "--not-a-flag"
3525 "#},
3526 }],
3527 },
3528 func,
3529 }
3530 }
3531}
3532
3533#[oxdock_func(
3548 returns = TypeTag::Record(std::sync::Arc::from([Field {
3549 name: "name".to_string(),
3550 ty: TypeTag::String,
3551 docs: "Qualified function name.",
3552 optional: false,
3553 default: None,
3554
3555 alias: None,}, Field {
3556 name: "module".to_string(),
3557 ty: TypeTag::String,
3558 docs: "Owning module.",
3559 optional: false,
3560 default: None,
3561
3562 alias: None,}, Field {
3563 name: "kind".to_string(),
3564 ty: TypeTag::String,
3565 docs: "Origin label (`host` or `script`).",
3566 optional: false,
3567 default: None,
3568
3569 alias: None,}, Field {
3570 name: "params".to_string(),
3571 ty: TypeTag::ListOf(std::sync::Arc::new(TypeTag::MapOf(std::sync::Arc::new(
3572 TypeTag::Any,
3573 )))),
3574 docs: "Parameter entries (empty for parameterless functions).",
3575 optional: false,
3576 default: None,
3577
3578 alias: None,}, Field {
3579 name: "returns".to_string(),
3580 ty: TypeTag::String,
3581 docs: "Structural return shape (empty when untagged).",
3582 optional: false,
3583 default: None,
3584
3585 alias: None,}, Field {
3586 name: "rpn".to_string(),
3587 ty: TypeTag::Bool,
3588 docs: "True when callable in RPN position.",
3589 optional: false,
3590 default: None,
3591
3592 alias: None,}, Field {
3593 name: "summary".to_string(),
3594 ty: TypeTag::String,
3595 docs: "One-line description.",
3596 optional: false,
3597 default: None,
3598
3599 alias: None,}]))
3600 summary = "Describe one function by qualified name."
3601)]
3602#[example(
3603 name = "describe",
3604 code = r###"
3605 IMPORT [STD]
3606 LET $info: MAP<ANY> = DESCRIBE("STD::INT")
3607 ASSERT_EQ $info.name "STD::INT"
3608 ASSERT_EQ $info.returns "INT"
3609 "###
3610)]
3611fn describe<P: ProcessManager>(
3612 cx: &mut StepCtx<P>,
3613 name: String,
3615) -> Result<Value> {
3616 if split_qualified(&name).is_none() && name != KEYWORD_INSPECT {
3617 return Err(anyhow::Error::new(std_diag::func_describe_unqualified(
3618 &name,
3619 )));
3620 }
3621 cx.state
3622 .describe_function(&name)
3623 .ok_or_else(|| anyhow::Error::new(std_diag::func_unknown(&name)))
3624}
3625
3626#[oxdock_func(returns = TypeTag::ListOf(std::sync::Arc::new(TypeTag::String)))]
3632#[example(
3633 name = "list",
3634 code = r###"
3635 IMPORT [STD]
3636 LET $names: LIST<STRING> = TYPES()
3637 ASSERT_CONTAINS $names "STRING"
3638 "###
3639)]
3640fn types<P: ProcessManager>(cx: &mut StepCtx<P>) -> Result<Value> {
3641 Ok(Value::list(
3642 cx.state
3643 .type_names()
3644 .into_iter()
3645 .map(Value::string)
3646 .collect(),
3647 ))
3648}
3649
3650#[oxdock_func(returns = TypeTag::Record(std::sync::Arc::from([Field {
3656 name: "name".to_string(),
3657 ty: TypeTag::String,
3658 docs: "Queried type name.",
3659 optional: false,
3660 default: None,
3661
3662 alias: None,}, Field {
3663 name: "summary".to_string(),
3664 ty: TypeTag::String,
3665 docs: "One-line description.",
3666 optional: false,
3667 default: None,
3668
3669 alias: None,}, Field {
3670 name: "docs".to_string(),
3671 ty: TypeTag::String,
3672 docs: "Full documentation text.",
3673 optional: false,
3674 default: None,
3675
3676 alias: None,}])))]
3677#[example(
3678 name = "describe",
3679 code = r###"
3680 IMPORT [STD]
3681 LET $info: MAP<ANY> = TYPE_DESCRIBE("STRING")
3682 ASSERT_EQ $info.name "STRING"
3683 "###
3684)]
3685fn type_describe<P: ProcessManager>(
3686 cx: &mut StepCtx<P>,
3687 name: String,
3689) -> Result<Value> {
3690 if let Some(descriptor) = cx.state.describe_type(&name) {
3691 let mut map = BTreeMap::new();
3692 map.insert(
3693 "name".to_string(),
3694 Value::string(descriptor.name.to_string()),
3695 );
3696 map.insert(
3697 "summary".to_string(),
3698 Value::string(descriptor.summary.to_string()),
3699 );
3700 map.insert(
3701 "docs".to_string(),
3702 Value::string(descriptor.docs.to_string()),
3703 );
3704 return Ok(Value::map(map));
3705 }
3706 if let Some(target) = cx.state.alias_target(&name) {
3709 let mut map = BTreeMap::new();
3710 map.insert("name".to_string(), Value::string(name.clone()));
3711 map.insert(
3712 "summary".to_string(),
3713 Value::string(format!("Script type alias for {target}.")),
3714 );
3715 map.insert(
3716 "docs".to_string(),
3717 Value::string(format!(
3718 "Declared with {KEYWORD_TYPE} {name} = {target}. The alias expands structurally at every declaration."
3719 )),
3720 );
3721 return Ok(Value::map(map));
3722 }
3723 Err(anyhow::Error::new(std_diag::std_unknown_type(&name)))
3724}
3725
3726#[oxdock_func(returns = TypeTag::String)]
3740#[example(
3741 name = "self",
3742 code = r###"
3743 # The running interpreter resolves to a non-empty path.
3744 IMPORT [STD]
3745 LET $exe: STRING = INTERPRETER()
3746 LET $nonempty: BOOL = $exe != ""
3747 ASSERT_EQ $nonempty true
3748 "###
3749)]
3750#[example(
3751 name = "dynamic assembly",
3752 code = r###"
3753 # Assemble the child script dynamically: the parent interpolates
3754 # its own bindings into the pipe, then runs the interpreter on it.
3755 # Unescaped {{ }} bakes in at render time; \{{ }} stays literal
3756 # so the child expands it with its own bindings.
3757 # The pipe delivers EOF when the producer step ends, so the child
3758 # reads exactly one script.
3759 IMPORT [STD]
3760 LET $exe: STRING = INTERPRETER()
3761 LET $who: STRING = "Ada"
3762 LET $child: PIPE
3763 WITH_IO [stdout=$child] ECHO """
3764 ECHO "hello {{ $who }}!"
3765 LET $who: STRING = "Grace"
3766 ECHO "child sees \{{ $who }}!"
3767 """
3768 LET $out: STRING = WITH_IO [stdin=$child] RUN [$exe]
3769 ASSERT_CONTAINS $out "hello Ada!"
3770 ASSERT_CONTAINS $out "child sees Grace!"
3771 "###
3772)]
3773fn interpreter<P: ProcessManager>(cx: &mut StepCtx<P>) -> Result<Value> {
3774 if let Some(staged) = cx.state.io.interpreter_override() {
3775 return Ok(Value::string(staged));
3776 }
3777 Ok(Value::string(oxdock_process::interpreter_exe()?))
3778}
3779
3780#[oxdock_func(returns = TypeTag::Bool)]
3788#[example(
3789 name = "main",
3790 code = r###"
3791 # Entry top level runs as main.
3792 IMPORT [STD]
3793 LET $m: BOOL = IS_MAIN()
3794 ASSERT_EQ $m true
3795 "###
3796)]
3797#[example(
3798 name = "library doubles as demo",
3799 fence_meta = "roots:unified",
3800 code = r###"
3801 # A library doubles as a runnable demo: guard the demo with
3802 # IF IS_MAIN() so importing it stays side effect free. The
3803 # parent writes both files, then runs each in a fresh
3804 # interpreter: direct execution prints the demo, importing
3805 # it does not. Unified roots: the child inherits one
3806 # workspace, so parent and child see the same files. The
3807 # exact stdout match proves the demo line stays out of the
3808 # importing run.
3809 IMPORT [STD]
3810
3811 # The library under test: demo guarded by IS_MAIN.
3812 WRITE lib.oxfile """
3813 IMPORT [STD]
3814 FUNC GREET($x: STRING): STRING { RETURN "hi \{{ $x }}" }
3815 EXPORT GREET
3816 IF IS_MAIN() {
3817 ECHO "demo: hi Ada"
3818 }
3819 """
3820
3821 # The importer: calls the library, prints only its own line.
3822 WRITE main.oxfile """
3823 IMPORT ["lib.oxfile" AS LIB]
3824 LET $g: STRING = LIB::GREET("Bo")
3825 ECHO "imported: \{{ $g }}"
3826 """
3827
3828 # Direct run executes the demo.
3829 LET $exe: STRING = INTERPRETER()
3830 LET $direct: STRING = RUN [$exe, "lib.oxfile"]
3831 ASSERT_CONTAINS $direct "demo: hi Ada"
3832
3833 # Importing run stays silent apart from its own line.
3834 LET $via: STRING = RUN [$exe, "main.oxfile"]
3835 ASSERT_EQ $via "imported: hi Bo\n"
3836 "###
3837)]
3838fn is_main<P: ProcessManager>(cx: &mut StepCtx<P>) -> Result<Value> {
3839 let main = match cx.state.module_stack.last() {
3840 None | Some(None) => true,
3841 Some(Some(_)) => false,
3842 };
3843 Ok(Value::bool(main))
3844}
3845
3846#[oxdock_func(returns = TypeTag::Bool)]
3860#[example(
3861 name = "null stdin",
3862 code = r###"
3863 # A null stdin is never a terminal, in every harness.
3864 IMPORT [STD]
3865 LET $term: BOOL = IS_TERMINAL("stdin")
3866 ASSERT_EQ $term false
3867 "###
3868)]
3869fn is_terminal<P: ProcessManager>(
3870 cx: &mut StepCtx<P>,
3871 #[values("stdin", "stdout", "stderr")]
3873 stream_name: String,
3874) -> Result<Value> {
3875 use std::io::IsTerminal;
3876 let terminal = match stream_name.as_str() {
3877 "stdin" => {
3878 if cx.stdin_pipe.is_some() {
3883 false
3884 } else {
3885 match &cx.stdin {
3886 CommandStdin::Null => false,
3887 #[cfg(not(miri))]
3888 CommandStdin::OsPipe(_) => false,
3889 CommandStdin::Stream(_) => false,
3890 CommandStdin::Inherit => std::io::stdin().is_terminal(),
3891 }
3892 }
3893 }
3894 "stdout" => {
3895 if cx.out_pipe.is_some() {
3896 false
3898 } else if cx.state.io.stdout().is_some() {
3899 false
3902 } else {
3903 match &cx.out {
3904 None => std::io::stdout().is_terminal(),
3906 #[cfg(not(miri))]
3908 Some(StreamHandle::Os(_)) => false,
3909 Some(StreamHandle::Stream(_)) => std::io::stdout().is_terminal(),
3919 }
3920 }
3921 }
3922 "stderr" => {
3923 if cx.state.io.stderr().is_some() {
3924 false
3926 } else {
3927 match &cx.err {
3928 None => std::io::stderr().is_terminal(),
3930 #[cfg(not(miri))]
3932 Some(StreamHandle::Os(_)) => false,
3933 Some(StreamHandle::Stream(_)) => false,
3936 }
3937 }
3938 }
3939 _ => {
3940 return Err(anyhow::Error::new(std_diag::std_is_terminal_expected(
3941 &stream_name,
3942 )));
3943 }
3944 };
3945 Ok(Value::bool(terminal))
3946}
3947
3948#[oxdock_func(returns = TypeTag::Semaphore)]
3956#[example(
3957 name = "mint",
3958 code = r###"
3959 # Mint a semaphore admitting at most two holders.
3960 IMPORT [STD]
3961 LET $sem: SEMAPHORE = SEMAPHORE_NEW(2)
3962
3963 # A fresh semaphore reports its full cap as available.
3964 LET $free: INT = SEMAPHORE_AVAILABLE($sem)
3965 ASSERT_EQ $free 2
3966 "###
3967)]
3968fn semaphore_new<P: ProcessManager>(
3969 cx: &mut StepCtx<P>,
3970 max: i64,
3972) -> Result<Value> {
3973 let _ = cx;
3974 if max <= 0 {
3975 return Err(anyhow::Error::new(std_diag::std_semaphore_needs_positive(
3976 max,
3977 )));
3978 }
3979 Ok(Value::semaphore(max as usize))
3980}
3981
3982#[oxdock_func(returns = TypeTag::Record(std::sync::Arc::from([Field {
3991 name: "held".to_string(),
3992 ty: TypeTag::Bool,
3993 docs: "`true` with the permit under `permit`, `false` with no `permit` key.",
3994 optional: false,
3995 default: None,
3996
3997 alias: None,}, Field {
3998 name: "permit".to_string(),
3999 ty: TypeTag::Permit,
4000 docs: "Permit handle; read only when `held`.",
4001 optional: true,
4002 default: None,
4003
4004 alias: None,}])))]
4005#[example(
4006 name = "acquire",
4007 code = r###"
4008 # First acquire holds with a permit to bind.
4009 IMPORT [STD]
4010 LET $sem: SEMAPHORE = SEMAPHORE_NEW(1)
4011 LET $first: MAP<held: BOOL, permit?: PERMIT> = SEMAPHORE_TRY_ACQUIRE($sem)
4012 ASSERT_EQ $first.held true
4013 LET $permit: PERMIT = $first.permit
4014
4015 # A capped semaphore answers held false with no permit key.
4016 LET $second: MAP<held: BOOL, permit?: PERMIT> = SEMAPHORE_TRY_ACQUIRE($sem)
4017 ASSERT_EQ $second.held false
4018 LET $has_permit: BOOL = HAS_KEY($second, "permit")
4019 ASSERT_EQ $has_permit false
4020 "###
4021)]
4022fn semaphore_try_acquire<P: ProcessManager>(
4023 cx: &mut StepCtx<P>,
4024 sem: Arc<SemaphoreState>,
4026) -> Result<Value> {
4027 let _ = cx;
4028 let mut map = BTreeMap::new();
4029 if sem.try_acquire() {
4030 map.insert("held".to_string(), Value::bool(true));
4031 map.insert("permit".to_string(), Value::permit(&sem));
4032 } else {
4033 map.insert("held".to_string(), Value::bool(false));
4034 }
4035 Ok(Value::map(map))
4036}
4037
4038#[oxdock_func(pure, returns = TypeTag::Int)]
4045#[example(
4046 name = "readout",
4047 code = r###"
4048 # Hold one permit on a cap of two.
4049 IMPORT [STD]
4050 LET $sem: SEMAPHORE = SEMAPHORE_NEW(2)
4051 LET $acq: MAP<held: BOOL, permit?: PERMIT> = SEMAPHORE_TRY_ACQUIRE($sem)
4052 ASSERT_EQ $acq.held true
4053
4054 # One held permit leaves exactly one free.
4055 LET $free: INT = SEMAPHORE_AVAILABLE($sem)
4056 ASSERT_EQ $free 1
4057 "###
4058)]
4059fn semaphore_available(
4060 sem: Arc<SemaphoreState>,
4062) -> Result<Value> {
4063 Ok(Value::int(sem.available() as i64))
4064}
4065
4066#[oxdock_func(
4075 rpn,
4076 returns = TypeTag::union(vec![TypeTag::String, TypeTag::Pipe]),
4077 template = text_trim_string
4078)]
4079#[example(
4080 name = "trim",
4081 code = r###"
4082 # Leading and trailing whitespace falls away.
4083 IMPORT [STD]
4084 LET $clean: STRING = TEXT_TRIM(" hello ")
4085 ASSERT_EQ $clean "hello"
4086 "###
4087)]
4088#[example(
4089 name = "trim pipe mirrors",
4090 code = r###"
4091 # Pipe input mints pipe output with the same transform.
4092 IMPORT [STD]
4093 LET $cap: PIPE
4094 WITH_IO [stdout=$cap] {
4095 ECHO " hello "
4096 }
4097 LET $out: PIPE = TEXT_TRIM($cap)
4098 WITH_IO [stdin=$out] READ_LINE $line
4099 ASSERT_EQ $line "hello"
4100 "###
4101)]
4102#[example(
4103 name = "trim template",
4104 code = r###"
4105 # String inputs run inside placeholders too.
4106 IMPORT [STD]
4107 LET $msg: STRING = 'clean:{{ STD::TEXT_TRIM(" hello ") }}'
4108 ASSERT_EQ $msg "clean:hello"
4109 "###
4110)]
4111#[example(
4112 name = "trim file template",
4113 code = r###"
4114 # EXPAND templates resolve the same registry.
4115 IMPORT [STD]
4116 WRITE "tpl.txt" "clean:\{{ STD::TEXT_TRIM(\" hello \") }}"
4117 LET $out: STRING = EXPAND "tpl.txt"
4118 ASSERT_EQ $out "clean:hello"
4119 "###
4120)]
4121fn text_trim<P: ProcessManager>(
4122 cx: &mut StepCtx<P>,
4123 #[union(String, Pipe)]
4125 text: Value,
4126) -> Result<Value> {
4127 Ok(super::args::mirror_stream(
4128 cx,
4129 "TEXT_TRIM",
4130 &text,
4131 super::args::TextPump::Trim,
4132 )?)
4133}
4134
4135fn text_trim_string(text: Value) -> Result<Value> {
4138 Ok(super::args::mirror_string(
4139 "TEXT_TRIM",
4140 &text,
4141 super::args::TextPump::Trim,
4142 )?)
4143}
4144
4145#[oxdock_func(
4154 rpn,
4155 returns = TypeTag::union(vec![TypeTag::String, TypeTag::Pipe]),
4156 template = text_trim_prefix_string
4157)]
4158#[example(
4159 name = "strip prefix",
4160 code = r###"
4161 # A present prefix falls away; absence returns the input unchanged.
4162 IMPORT [STD]
4163 LET $bare: STRING = TEXT_TRIM_PREFIX("v1.2.3", "v")
4164 ASSERT_EQ $bare "1.2.3"
4165
4166 # Missing prefixes pass through untouched.
4167 LET $same: STRING = TEXT_TRIM_PREFIX("1.2.3", "v")
4168 ASSERT_EQ $same "1.2.3"
4169 "###
4170)]
4171#[example(
4172 name = "strip prefix pipe mirrors",
4173 code = r###"
4174 # Pipe input mints pipe output with the same strip.
4175 IMPORT [STD]
4176 LET $cap: PIPE
4177 WITH_IO [stdout=$cap] {
4178 ECHO "v1.2.3"
4179 }
4180 LET $trimmed: PIPE = TEXT_TRIM($cap)
4181 LET $out: PIPE = TEXT_TRIM_PREFIX($trimmed, "v")
4182 WITH_IO [stdin=$out] READ_LINE $line
4183 ASSERT_EQ $line "1.2.3"
4184 "###
4185)]
4186#[example(
4187 name = "strip prefix template",
4188 code = r###"
4189 # String inputs run inside placeholders too.
4190 IMPORT [STD]
4191 LET $msg: STRING = 'bare:{{ STD::TEXT_TRIM_PREFIX("v1.2.3", "v") }}'
4192 ASSERT_EQ $msg "bare:1.2.3"
4193 "###
4194)]
4195fn text_trim_prefix<P: ProcessManager>(
4196 cx: &mut StepCtx<P>,
4197 #[union(String, Pipe)]
4199 text: Value,
4200 prefix: String,
4202) -> Result<Value> {
4203 Ok(super::args::mirror_stream(
4204 cx,
4205 "TEXT_TRIM_PREFIX",
4206 &text,
4207 super::args::TextPump::TrimPrefix(prefix),
4208 )?)
4209}
4210
4211fn text_trim_prefix_string(text: Value, prefix: String) -> Result<Value> {
4214 Ok(super::args::mirror_string(
4215 "TEXT_TRIM_PREFIX",
4216 &text,
4217 super::args::TextPump::TrimPrefix(prefix),
4218 )?)
4219}
4220
4221#[oxdock_func(
4228 rpn,
4229 returns = TypeTag::union(vec![TypeTag::String, TypeTag::Pipe]),
4230 template = text_trim_suffix_string
4231)]
4232#[example(
4233 name = "strip suffix",
4234 code = r###"
4235 # A present suffix falls away; absence returns the input unchanged.
4236 IMPORT [STD]
4237 LET $bare: STRING = TEXT_TRIM_SUFFIX("archive.tar.gz", ".gz")
4238 ASSERT_EQ $bare "archive.tar"
4239
4240 # Missing suffixes pass through untouched.
4241 LET $same: STRING = TEXT_TRIM_SUFFIX("archive.tar", ".gz")
4242 ASSERT_EQ $same "archive.tar"
4243 "###
4244)]
4245#[example(
4246 name = "strip suffix pipe mirrors",
4247 code = r###"
4248 # Pipe input mints pipe output with the same strip.
4249 IMPORT [STD]
4250 LET $cap: PIPE
4251 WITH_IO [stdout=$cap] {
4252 ECHO "archive.tar.gz"
4253 }
4254 LET $trimmed: PIPE = TEXT_TRIM($cap)
4255 LET $out: PIPE = TEXT_TRIM_SUFFIX($trimmed, ".gz")
4256 WITH_IO [stdin=$out] READ_LINE $line
4257 ASSERT_EQ $line "archive.tar"
4258 "###
4259)]
4260#[example(
4261 name = "strip suffix template",
4262 code = r###"
4263 # String inputs run inside placeholders too.
4264 IMPORT [STD]
4265 LET $msg: STRING = 'bare:{{ STD::TEXT_TRIM_SUFFIX("archive.tar.gz", ".gz") }}'
4266 ASSERT_EQ $msg "bare:archive.tar"
4267 "###
4268)]
4269fn text_trim_suffix<P: ProcessManager>(
4270 cx: &mut StepCtx<P>,
4271 #[union(String, Pipe)]
4273 text: Value,
4274 suffix: String,
4276) -> Result<Value> {
4277 Ok(super::args::mirror_stream(
4278 cx,
4279 "TEXT_TRIM_SUFFIX",
4280 &text,
4281 super::args::TextPump::TrimSuffix(suffix),
4282 )?)
4283}
4284
4285fn text_trim_suffix_string(text: Value, suffix: String) -> Result<Value> {
4288 Ok(super::args::mirror_string(
4289 "TEXT_TRIM_SUFFIX",
4290 &text,
4291 super::args::TextPump::TrimSuffix(suffix),
4292 )?)
4293}
4294
4295#[oxdock_func(returns = TypeTag::String)]
4306#[example(
4307 name = "join path",
4308 code = r###"
4309 # Directory and file stem join with the native separator.
4310 # Source `\\` is one backslash at runtime; `/` works on Windows
4311 # too, native just reads better there.
4312 IMPORT [STD]
4313 LET $p: STRING = PATH_JOIN("some-dir", "some-file")
4314 [family:unix] ASSERT_EQ $p "some-dir/some-file"
4315 [family:windows] ASSERT_EQ $p "some-dir\\some-file"
4316 "###
4317)]
4318fn path_join<P: ProcessManager>(
4319 _cx: &mut StepCtx<P>,
4320 #[union(String, Path)]
4322 dir: Value,
4323 #[union(String, Path)]
4325 name: Value,
4326) -> Result<Value> {
4327 let d = super::args::string_or_path_text(&dir)?;
4328 let n = super::args::string_or_path_text(&name)?;
4329 Ok(Value::string(oxdock_fs::join_native(&d, &n)))
4330}
4331
4332#[oxdock_func(pure, returns = TypeTag::String)]
4340#[example(
4341 name = "base",
4342 code = r###"
4343 # Final segments bind without filesystem access.
4344 IMPORT [STD]
4345 LET $b: STRING = PATH_BASE("some-dir/some-file")
4346 ASSERT_EQ $b "some-file"
4347
4348 # Trailing slashes trim before the split.
4349 LET $d: STRING = PATH_BASE("some-dir/")
4350 ASSERT_EQ $d "some-dir"
4351 "###
4352)]
4353fn path_base(
4354 #[union(String, Path)]
4356 path: Value,
4357) -> Result<Value> {
4358 let text = super::args::string_or_path_text(&path)?;
4359 let base = oxdock_fs::path_base(&text)
4360 .map_err(|e| anyhow::Error::new(std_diag::std_path_base_failed(&e)))?;
4361 Ok(Value::string(base))
4362}
4363
4364#[oxdock_func(pure, returns = TypeTag::String)]
4374#[example(
4375 name = "relativize",
4376 code = r###"
4377 # Prefix bases strip to their remainder.
4378 IMPORT [STD]
4379 LET $r: STRING = PATH_REL("some-dir", "some-dir/some-file")
4380 ASSERT_EQ $r "some-file"
4381
4382 # Equal paths bind dot.
4383 LET $dot: STRING = PATH_REL("some-dir", "some-dir")
4384 ASSERT_EQ $dot "."
4385 "###
4386)]
4387fn path_rel(
4388 #[union(String, Path)]
4390 base: Value,
4391 #[union(String, Path)]
4393 path: Value,
4394) -> Result<Value> {
4395 let b = super::args::string_or_path_text(&base)?;
4396 let p = super::args::string_or_path_text(&path)?;
4397 let rel = oxdock_fs::path_rel(&b, &p)
4398 .map_err(|e| anyhow::Error::new(std_diag::std_path_rel_failed(&e)))?;
4399 Ok(Value::string(rel))
4400}
4401
4402#[oxdock_func(
4409 rpn,
4410 returns = TypeTag::union(vec![TypeTag::String, TypeTag::Pipe]),
4411 template = text_to_upper_string
4412)]
4413#[example(
4414 name = "uppercase",
4415 code = r###"
4416 # Text folds to uppercase.
4417 IMPORT [STD]
4418 LET $loud: STRING = TEXT_TO_UPPER("hello")
4419 ASSERT_EQ $loud "HELLO"
4420 "###
4421)]
4422#[example(
4423 name = "uppercase pipe mirrors",
4424 code = r###"
4425 # Pipe input mints pipe output with the same fold.
4426 IMPORT [STD]
4427 LET $cap: PIPE
4428 WITH_IO [stdout=$cap] {
4429 ECHO "hello"
4430 }
4431 LET $out: PIPE = TEXT_TO_UPPER($cap)
4432 WITH_IO [stdin=$out] READ_LINE $line
4433 ASSERT_EQ $line "HELLO"
4434 "###
4435)]
4436#[example(
4437 name = "uppercase template",
4438 code = r###"
4439 # String inputs run inside placeholders too.
4440 IMPORT [STD]
4441 LET $msg: STRING = 'loud:{{ STD::TEXT_TO_UPPER("hello") }}'
4442 ASSERT_EQ $msg "loud:HELLO"
4443 "###
4444)]
4445fn text_to_upper<P: ProcessManager>(
4446 cx: &mut StepCtx<P>,
4447 #[union(String, Pipe)]
4449 text: Value,
4450) -> Result<Value> {
4451 Ok(super::args::mirror_stream(
4452 cx,
4453 "TEXT_TO_UPPER",
4454 &text,
4455 super::args::TextPump::ToUpper,
4456 )?)
4457}
4458
4459fn text_to_upper_string(text: Value) -> Result<Value> {
4462 Ok(super::args::mirror_string(
4463 "TEXT_TO_UPPER",
4464 &text,
4465 super::args::TextPump::ToUpper,
4466 )?)
4467}
4468
4469#[oxdock_func(
4476 rpn,
4477 returns = TypeTag::union(vec![TypeTag::String, TypeTag::Pipe]),
4478 template = text_to_lower_string
4479)]
4480#[example(
4481 name = "lowercase",
4482 code = r###"
4483 # Text folds to lowercase.
4484 IMPORT [STD]
4485 LET $quiet: STRING = TEXT_TO_LOWER("HELLO")
4486 ASSERT_EQ $quiet "hello"
4487 "###
4488)]
4489#[example(
4490 name = "lowercase pipe mirrors",
4491 code = r###"
4492 # Pipe input mints pipe output with the same fold.
4493 IMPORT [STD]
4494 LET $cap: PIPE
4495 WITH_IO [stdout=$cap] {
4496 ECHO "HELLO"
4497 }
4498 LET $out: PIPE = TEXT_TO_LOWER($cap)
4499 WITH_IO [stdin=$out] READ_LINE $line
4500 ASSERT_EQ $line "hello"
4501 "###
4502)]
4503#[example(
4504 name = "lowercase template",
4505 code = r###"
4506 # String inputs run inside placeholders too.
4507 IMPORT [STD]
4508 LET $msg: STRING = 'quiet:{{ STD::TEXT_TO_LOWER("HELLO") }}'
4509 ASSERT_EQ $msg "quiet:hello"
4510 "###
4511)]
4512fn text_to_lower<P: ProcessManager>(
4513 cx: &mut StepCtx<P>,
4514 #[union(String, Pipe)]
4516 text: Value,
4517) -> Result<Value> {
4518 Ok(super::args::mirror_stream(
4519 cx,
4520 "TEXT_TO_LOWER",
4521 &text,
4522 super::args::TextPump::ToLower,
4523 )?)
4524}
4525
4526fn text_to_lower_string(text: Value) -> Result<Value> {
4529 Ok(super::args::mirror_string(
4530 "TEXT_TO_LOWER",
4531 &text,
4532 super::args::TextPump::ToLower,
4533 )?)
4534}
4535
4536#[oxdock_func(
4547 rpn,
4548 returns = TypeTag::union(vec![TypeTag::String, TypeTag::Pipe]),
4549 template = text_replace_string
4550)]
4551#[example(
4552 name = "replace",
4553 code = r###"
4554 # Every literal occurrence rewrites in place.
4555 IMPORT [STD]
4556 LET $fixed: STRING = TEXT_REPLACE("hello world", "world", "there")
4557 ASSERT_EQ $fixed "hello there"
4558 "###
4559)]
4560#[example(
4561 name = "replace pipe mirrors",
4562 code = r###"
4563 # Pipe input mints pipe output with the same rewrite.
4564 IMPORT [STD]
4565 LET $cap: PIPE
4566 WITH_IO [stdout=$cap] {
4567 ECHO "hello world"
4568 }
4569 LET $trimmed: PIPE = TEXT_TRIM($cap)
4570 LET $out: PIPE = TEXT_REPLACE($trimmed, "world", "there")
4571 WITH_IO [stdin=$out] READ_LINE $line
4572 ASSERT_EQ $line "hello there"
4573 "###
4574)]
4575#[example(
4576 name = "replace template",
4577 code = r###"
4578 # String inputs run inside placeholders too.
4579 IMPORT [STD]
4580 LET $msg: STRING = 'fixed:{{ STD::TEXT_REPLACE("hello world", "world", "there") }}'
4581 ASSERT_EQ $msg "fixed:hello there"
4582 "###
4583)]
4584fn text_replace<P: ProcessManager>(
4585 cx: &mut StepCtx<P>,
4586 #[union(String, Pipe)]
4588 text: Value,
4589 from: String,
4591 to: String,
4593) -> Result<Value> {
4594 Ok(super::args::mirror_stream(
4595 cx,
4596 FUNC_TEXT_REPLACE,
4597 &text,
4598 super::args::TextPump::ReplaceLiteral { from, to },
4599 )?)
4600}
4601
4602fn text_replace_string(text: Value, from: String, to: String) -> Result<Value> {
4605 Ok(super::args::mirror_string(
4606 FUNC_TEXT_REPLACE,
4607 &text,
4608 super::args::TextPump::ReplaceLiteral { from, to },
4609 )?)
4610}
4611
4612#[oxdock_func(
4624 rpn,
4625 returns = TypeTag::union(vec![TypeTag::String, TypeTag::Pipe]),
4626 template = text_replace_regex_string
4627)]
4628#[example(
4629 name = "replace with captures",
4630 code = r###"
4631 # Capture groups expand in the replacement.
4632 IMPORT [STD]
4633 LET $swapped: STRING = TEXT_REPLACE_REGEX("2026-10-13", "(\\d+)-(\\d+)-(\\d+)", "$3/$2/$1")
4634 ASSERT_EQ $swapped "13/10/2026"
4635 "###
4636)]
4637#[example(
4638 name = "replace regex pipe mirrors",
4639 code = r###"
4640 # Pipe input mints pipe output with the same rewrite.
4641 IMPORT [STD]
4642 LET $cap: PIPE
4643 WITH_IO [stdout=$cap] {
4644 ECHO "2026-10-13"
4645 }
4646 LET $trimmed: PIPE = TEXT_TRIM($cap)
4647 LET $out: PIPE = TEXT_REPLACE_REGEX($trimmed, "(\\d+)-(\\d+)-(\\d+)", "$3/$2/$1")
4648 WITH_IO [stdin=$out] READ_LINE $line
4649 ASSERT_EQ $line "13/10/2026"
4650 "###
4651)]
4652#[example(
4653 name = "replace regex template",
4654 code = r###"
4655 # String inputs run inside placeholders too.
4656 IMPORT [STD]
4657 LET $msg: STRING = 'swapped:{{ STD::TEXT_REPLACE_REGEX("2026-10-13", "(\\d+)-(\\d+)-(\\d+)", "$3/$2/$1") }}'
4658 ASSERT_EQ $msg "swapped:13/10/2026"
4659 "###
4660)]
4661fn text_replace_regex<P: ProcessManager>(
4662 cx: &mut StepCtx<P>,
4663 #[union(String, Pipe)]
4665 text: Value,
4666 pattern: String,
4668 replacement: String,
4670) -> Result<Value> {
4671 if let Some(s) = text.as_str() {
4672 let out = super::args::text_replace_regex_str(
4673 s,
4674 &pattern,
4675 &replacement,
4676 FUNC_TEXT_REPLACE_REGEX,
4677 )?;
4678 return Ok(Value::string(out));
4679 }
4680 let content = super::args::read_pipe_eager(cx, FUNC_TEXT_REPLACE_REGEX, &text)?;
4681 let out = super::args::text_replace_regex_str(
4682 &content,
4683 &pattern,
4684 &replacement,
4685 FUNC_TEXT_REPLACE_REGEX,
4686 )?;
4687 Ok(super::args::write_completed_pipe(
4688 cx,
4689 FUNC_TEXT_REPLACE_REGEX,
4690 out,
4691 )?)
4692}
4693
4694fn text_replace_regex_string(text: Value, pattern: String, replacement: String) -> Result<Value> {
4697 let Some(s) = text.as_str() else {
4698 return Err(std_diag::std_pipe_needs_step_io(FUNC_TEXT_REPLACE_REGEX).into());
4699 };
4700 let out =
4701 super::args::text_replace_regex_str(s, &pattern, &replacement, FUNC_TEXT_REPLACE_REGEX)?;
4702 Ok(Value::string(out))
4703}
4704
4705#[oxdock_func(pure, returns = TypeTag::ListOf(std::sync::Arc::new(TypeTag::String)))]
4713#[example(
4714 name = "split",
4715 code = r###"
4716 # Delimiters split into list items.
4717 IMPORT [STD]
4718 LET $parts: LIST<STRING> = TEXT_SPLIT("a,b,c", ",")
4719 ASSERT_EQ $parts.0 "a"
4720 ASSERT_EQ $parts.1 "b"
4721 ASSERT_EQ $parts.2 "c"
4722 "###
4723)]
4724fn text_split(
4725 text: String,
4727 delimiter: String,
4729) -> Result<Value> {
4730 Ok(super::args::text_list_value(super::args::text_split_str(
4731 &text, &delimiter,
4732 )))
4733}
4734
4735#[oxdock_func(pure, returns = TypeTag::String)]
4738#[example(
4739 name = "join",
4740 code = r###"
4741 # List items join with the separator between them.
4742 IMPORT [STD]
4743 LET $joined: STRING = TEXT_JOIN(["a", "b", "c"], ",")
4744 ASSERT_EQ $joined "a,b,c"
4745 "###
4746)]
4747fn text_join(
4748 elements: Vec<String>,
4750 delimiter: String,
4752) -> Result<Value> {
4753 Ok(Value::string(elements.join(delimiter.as_str())))
4754}
4755
4756#[oxdock_func(pure, returns = TypeTag::ListOf(std::sync::Arc::new(TypeTag::String)))]
4768#[example(
4769 name = "split args",
4770 code = r###"
4771 # Quoted segments stay one word.
4772 IMPORT [STD]
4773 LET $argv: LIST<STRING> = SHELL_SPLIT_ARGS("gh issue comment 153 --body-file notes.md")
4774 ASSERT_EQ $argv.0 "gh"
4775 ASSERT_EQ $argv.3 "153"
4776 ASSERT_EQ $argv.5 "notes.md"
4777
4778 # Quotes and escapes parse the shell way.
4779 LET $quoted: LIST<STRING> = SHELL_SPLIT_ARGS("say \"hi there\" 'a b'")
4780 ASSERT_EQ $quoted.0 "say"
4781 ASSERT_EQ $quoted.1 "hi there"
4782 ASSERT_EQ $quoted.2 "a b"
4783 "###
4784)]
4785fn shell_split_args(
4786 command: String,
4788) -> Result<Value> {
4789 match shell_words::split(&command) {
4790 Ok(words) => Ok(super::args::text_list_value(words)),
4791 Err(err) => Err(anyhow::Error::new(std_diag::std_shell_split_failed(&err))),
4792 }
4793}
4794
4795#[oxdock_func(pure, returns = TypeTag::String)]
4803#[example(
4804 name = "join args",
4805 code = r###"
4806 # Plain words join with spaces and no quoting.
4807 IMPORT [STD]
4808 LET $plain: STRING = SHELL_JOIN_ARGS(["gh", "issue", "list"])
4809 ASSERT_EQ $plain "gh issue list"
4810
4811 # Words with spaces quote, and the round trip is exact.
4812 LET $words: LIST<STRING> = ["say", "hi there", "a'b"]
4813 LET $joined: STRING = SHELL_JOIN_ARGS($words)
4814 LET $back: LIST<STRING> = SHELL_SPLIT_ARGS($joined)
4815 ASSERT_EQ $back.0 "say"
4816 ASSERT_EQ $back.1 "hi there"
4817 ASSERT_EQ $back.2 "a'b"
4818 "###
4819)]
4820fn shell_join_args(
4821 words: Vec<String>,
4823) -> Result<Value> {
4824 Ok(Value::string(shell_words::join(&words)))
4825}
4826
4827#[oxdock_func(pure, returns = TypeTag::ListOf(std::sync::Arc::new(TypeTag::String)))]
4835#[example(
4836 name = "lines",
4837 code = r###"
4838 # Newlines split into line items.
4839 IMPORT [STD]
4840 LET $lines: LIST<STRING> = TEXT_LINES("one\ntwo\nthree")
4841 ASSERT_EQ $lines.0 "one"
4842 ASSERT_EQ $lines.1 "two"
4843 ASSERT_EQ $lines.2 "three"
4844
4845 # Windows endings split the same way after normalization.
4846 LET $crlf: LIST<STRING> = TEXT_LINES("one\r\ntwo\r\nthree")
4847 ASSERT_EQ $crlf.0 "one"
4848 ASSERT_EQ $crlf.1 "two"
4849 ASSERT_EQ $crlf.2 "three"
4850
4851 # Old Mac endings split too, and mixed endings split together because the input normalizes to LF before splitting.
4852 LET $mixed: LIST<STRING> = TEXT_LINES("a\r\nb\nc\rd")
4853 ASSERT_EQ $mixed.0 "a"
4854 ASSERT_EQ $mixed.1 "b"
4855 ASSERT_EQ $mixed.2 "c"
4856 ASSERT_EQ $mixed.3 "d"
4857 "###
4858)]
4859fn text_lines(
4860 text: String,
4862) -> Result<Value> {
4863 Ok(super::args::text_list_value(super::args::text_lines_str(
4864 &text,
4865 )))
4866}
4867
4868#[oxdock_func(pure, returns = TypeTag::ListOf(std::sync::Arc::new(TypeTag::String)))]
4874#[example(
4875 name = "fields",
4876 code = r###"
4877 # Runs of whitespace separate fields; empties never appear.
4878 IMPORT [STD]
4879 LET $fields: LIST<STRING> = TEXT_FIELDS(" abc def ")
4880 ASSERT_EQ $fields.0 "abc"
4881 ASSERT_EQ $fields.1 "def"
4882 "###
4883)]
4884fn text_fields(
4885 text: String,
4887) -> Result<Value> {
4888 Ok(super::args::text_list_value(super::args::text_fields_str(
4889 &text,
4890 )))
4891}
4892
4893#[oxdock_func(pure, returns = TypeTag::ListOf(std::sync::Arc::new(TypeTag::String)))]
4902#[example(
4903 name = "line range",
4904 code = r###"
4905 # Lines 2 through 3 come back as a list, 1-based inclusive.
4906 IMPORT [STD]
4907 LET $window: LIST<STRING> = TEXT_LINES_RANGE("one\ntwo\nthree\nfour", 2, 3)
4908 ASSERT_EQ $window.0 "two"
4909 ASSERT_EQ $window.1 "three"
4910
4911 # Ranges past the end clamp instead of failing.
4912 LET $tail: LIST<STRING> = TEXT_LINES_RANGE("one\ntwo", 2, 9)
4913 ASSERT_EQ $tail.0 "two"
4914 "###
4915)]
4916fn text_lines_range(
4917 text: String,
4919 from: i64,
4921 to: i64,
4923) -> Result<Value> {
4924 Ok(super::args::text_list_value(
4925 super::args::text_lines_range_str(&text, from, to, FUNC_TEXT_LINES_RANGE)?,
4926 ))
4927}
4928
4929#[oxdock_func(pure, returns = TypeTag::Bool)]
4937#[example(
4938 name = "match",
4939 code = r###"
4940 # Regex matches report true; misses report false.
4941 IMPORT [STD]
4942 LET $hit: BOOL = TEXT_MATCH("abc123", "\\d+")
4943 ASSERT_EQ $hit true
4944
4945 # A miss is false, not a failure.
4946 LET $miss: BOOL = TEXT_MATCH("abc", "^\\d+$")
4947 ASSERT_EQ $miss false
4948 "###
4949)]
4950fn text_match(
4951 text: String,
4953 pattern: String,
4955) -> Result<Value> {
4956 let re = super::args::text_compile_pattern(FUNC_TEXT_MATCH, &pattern)?;
4957 Ok(Value::bool(re.is_match(&text)))
4958}
4959
4960#[oxdock_func(pure, name = "BOOL", returns = TypeTag::Bool)]
4969#[example(
4970 name = "convert",
4971 code = r###"
4972 IMPORT [STD]
4973 LET $n: BOOL = BOOL("yes")
4974 ASSERT_EQ $n true
4975 LET $f: BOOL = BOOL("0")
4976 ASSERT_EQ $f false
4977 "###
4978)]
4979fn bool_convert(
4980 #[union(Bool, String)]
4982 val: Value,
4983) -> Result<Value> {
4984 if let Some(b) = val.as_bool() {
4985 return Ok(Value::bool(b));
4986 }
4987 let Some(s) = val.as_str() else {
4988 return Err(anyhow::Error::new(std_diag::std_bool_needs_bool_or_string(
4989 &val,
4990 )));
4991 };
4992 match super::args::parse_bool_str(s) {
4993 Some(b) => Ok(Value::bool(b)),
4994 None => Err(anyhow::Error::new(std_diag::std_bool_cannot_coerce(
4995 FUNC_BOOL, s,
4996 ))),
4997 }
4998}
4999
5000#[oxdock_func(pure, returns = TypeTag::Bool)]
5010#[example(
5011 name = "absent-default",
5012 code = r###"
5013 # Absent names read empty; the default settles the polarity.
5014 IMPORT [STD]
5015 INHERIT_ENV [OXDOCK_TEST_ABSENT_FLAG]
5016 LET $dry: BOOL = BOOL_OR("{{ env:OXDOCK_TEST_ABSENT_FLAG }}", true)
5017 ASSERT_EQ $dry true
5018
5019 # Present values coerce strictly, ignoring the default.
5020 LET $off: BOOL = BOOL_OR("false", true)
5021 ASSERT_EQ $off false
5022 "###
5023)]
5024fn bool_or(
5025 text: String,
5027 default: bool,
5029) -> Result<Value> {
5030 if text.trim().is_empty() {
5031 return Ok(Value::bool(default));
5032 }
5033 match super::args::parse_bool_str(&text) {
5034 Some(b) => Ok(Value::bool(b)),
5035 None => Err(anyhow::Error::new(std_diag::std_bool_cannot_coerce(
5036 FUNC_BOOL_OR,
5037 &text,
5038 ))),
5039 }
5040}
5041
5042#[oxdock_func(pure, returns = TypeTag::ListOf(std::sync::Arc::new(TypeTag::String)))]
5051#[example(
5052 name = "extract",
5053 code = r###"
5054 # Index zero is the full match; groups follow in order.
5055 IMPORT [STD]
5056 LET $caps: LIST<STRING> = TEXT_EXTRACT("abc123", "([a-z]+)(\\d+)")
5057 ASSERT_EQ $caps.0 "abc123"
5058 ASSERT_EQ $caps.1 "abc"
5059 ASSERT_EQ $caps.2 "123"
5060 "###
5061)]
5062fn text_extract(
5063 text: String,
5065 pattern: String,
5067) -> Result<Value> {
5068 let groups = super::args::text_extract_str(&text, &pattern, FUNC_TEXT_EXTRACT)?;
5069 Ok(super::args::text_list_value(groups))
5070}
5071
5072#[oxdock_func(pure, returns = TypeTag::Bool)]
5079#[example(
5080 name = "starts with",
5081 code = r###"
5082 # Present prefixes report true; misses report false.
5083 IMPORT [STD]
5084 LET $hit: BOOL = TEXT_STARTS_WITH("linux-musl-x64", "linux")
5085 ASSERT_EQ $hit true
5086
5087 # A miss is false, not a failure.
5088 LET $miss: BOOL = TEXT_STARTS_WITH("macos-arm", "linux")
5089 ASSERT_EQ $miss false
5090 "###
5091)]
5092fn text_starts_with(
5093 text: String,
5095 prefix: String,
5097) -> Result<Value> {
5098 Ok(Value::bool(text.starts_with(prefix.as_str())))
5099}
5100
5101#[oxdock_func(pure, returns = TypeTag::Bool)]
5108#[example(
5109 name = "ends with",
5110 code = r###"
5111 # Present suffixes report true; misses report false.
5112 IMPORT [STD]
5113 LET $hit: BOOL = TEXT_ENDS_WITH("x86_64-linux-musl", "linux-musl")
5114 ASSERT_EQ $hit true
5115
5116 # A miss is false, not a failure.
5117 LET $miss: BOOL = TEXT_ENDS_WITH("x86_64-linux-gnu", "linux-musl")
5118 ASSERT_EQ $miss false
5119 "###
5120)]
5121fn text_ends_with(
5122 text: String,
5124 suffix: String,
5126) -> Result<Value> {
5127 Ok(Value::bool(text.ends_with(suffix.as_str())))
5128}
5129
5130#[oxdock_func(pure, returns = TypeTag::Bool)]
5140#[example(
5141 name = "contains",
5142 code = r###"
5143 # Present needles report true; misses report false.
5144 IMPORT [STD]
5145 LET $hit: BOOL = CONTAINS("x86_64-linux-musl", "musl")
5146 ASSERT_EQ $hit true
5147
5148 # A miss is false, not a failure.
5149 LET $miss: BOOL = CONTAINS("x86_64-linux-gnu", "musl")
5150 ASSERT_EQ $miss false
5151 "###
5152)]
5153#[example(
5154 name = "contains list",
5155 code = r###"
5156 # List membership uses strict equality across any element type.
5157 IMPORT [STD]
5158 LET $hit: BOOL = CONTAINS(["a", "b", "c"], "b")
5159 ASSERT_EQ $hit true
5160 LET $miss: BOOL = CONTAINS(["a", "b", "c"], "z")
5161 ASSERT_EQ $miss false
5162 LET $num: BOOL = CONTAINS([1, 2, 3], 2.0)
5163 ASSERT_EQ $num true
5164
5165 # Stringified numbers never coerce to integers.
5166 LET $strnum: BOOL = CONTAINS(["1", "2", "3"], 2)
5167 ASSERT_EQ $strnum false
5168
5169 # Boolean lists match true and miss false with no coercion.
5170 LET $bools: LIST<BOOL> = [true]
5171 LET $bhit: BOOL = CONTAINS($bools, true)
5172 ASSERT_EQ $bhit true
5173 LET $bmiss: BOOL = CONTAINS($bools, false)
5174 ASSERT_EQ $bmiss false
5175 LET $nocoerce: BOOL = CONTAINS($bools, 1)
5176 ASSERT_EQ $nocoerce false
5177 "###
5178)]
5179fn contains(
5180 #[union(String, List)]
5182 haystack: Value,
5183 needle: Value,
5185) -> Result<Value> {
5186 if let Some(text) = haystack.as_str() {
5187 let Some(n) = needle.as_str() else {
5188 return Err(anyhow::Error::new(std_diag::std_contains_needle_type(
5189 needle.type_name(),
5190 )));
5191 };
5192 return Ok(Value::bool(text.contains(n)));
5193 }
5194 if let Some(items) = haystack.as_list() {
5195 for item in items {
5196 if super::args::values_equal(item, &needle) {
5197 return Ok(Value::bool(true));
5198 }
5199 }
5200 return Ok(Value::bool(false));
5201 }
5202 Err(anyhow::Error::new(std_diag::std_contains_haystack_type(
5203 haystack.type_name(),
5204 )))
5205}
5206
5207#[oxdock_func(pure, returns = TypeTag::List)]
5215#[example(
5216 name = "deduplicate",
5217 code = r###"
5218 # First occurrences win, later repeats drop.
5219 IMPORT [STD]
5220 LET $seen: LIST<STRING> = UNIQUE(["a", "b", "a", "c", "b"])
5221 ASSERT_EQ $seen.0 "a"
5222 ASSERT_EQ $seen.1 "b"
5223 ASSERT_EQ $seen.2 "c"
5224 ASSERT_EQ LEN($seen) 3
5225
5226 # The empty list stays empty.
5227 LET $empty: LIST<STRING> = UNIQUE([])
5228 ASSERT_EQ LEN($empty) 0
5229 "###
5230)]
5231#[example(
5232 name = "strict membership",
5233 code = r###"
5234 # Numerics collapse across INT and FLOAT like CONTAINS.
5235 IMPORT [STD]
5236 LET $nums: LIST<ANY> = UNIQUE([1, 2.0, 1, 3])
5237 ASSERT_EQ $nums.0 1
5238 ASSERT_EQ $nums.1 2.0
5239 ASSERT_EQ $nums.2 3
5240 ASSERT_EQ LEN($nums) 3
5241
5242 # Stringified numbers never coerce to integers.
5243 LET $mixed: LIST<ANY> = UNIQUE(["1", 1])
5244 ASSERT_EQ $mixed.0 "1"
5245 ASSERT_EQ $mixed.1 1
5246 ASSERT_EQ LEN($mixed) 2
5247 "###
5248)]
5249fn unique(
5250 items: Vec<Value>,
5252) -> Result<Value> {
5253 let mut out: Vec<Value> = Vec::with_capacity(items.len());
5254 for item in items {
5255 if !out
5256 .iter()
5257 .any(|seen| super::args::values_equal(seen, &item))
5258 {
5259 out.push(item);
5260 }
5261 }
5262 Ok(Value::list(out))
5263}
5264
5265#[oxdock_func(pure, returns = TypeTag::Int)]
5274#[example(
5275 name = "length",
5276 code = r###"
5277 # Plain text counts one per character.
5278 IMPORT [STD]
5279 LET $n: INT = LEN("hello")
5280 ASSERT_EQ $n 5
5281
5282 # Multibyte characters count once each, not per byte.
5283 LET $wide: INT = LEN("héllo")
5284 ASSERT_EQ $wide 5
5285
5286 # Lists count elements, maps count entries.
5287 LET $items: LIST<STRING> = ["a", "b", "c"]
5288 LET $nitems: INT = LEN($items)
5289 ASSERT_EQ $nitems 3
5290 LET $row: MAP<name: STRING> = {name: "ada"}
5291 LET $nkeys: INT = LEN($row)
5292 ASSERT_EQ $nkeys 1
5293 LET $empty: INT = LEN([])
5294 ASSERT_EQ $empty 0
5295 "###
5296)]
5297fn len(
5298 #[union(String, List, Map)]
5300 value: Value,
5301) -> Result<Value> {
5302 if let Some(text) = value.as_str() {
5303 return Ok(Value::int(text.chars().count() as i64));
5304 }
5305 if let Some(items) = value.as_list() {
5306 return Ok(Value::int(items.len() as i64));
5307 }
5308 if let Some(entries) = value.as_map() {
5309 return Ok(Value::int(entries.len() as i64));
5310 }
5311 Err(anyhow::Error::new(std_diag::std_len_unexpected_type(
5312 value.type_name(),
5313 )))
5314}
5315
5316#[oxdock_func(pure, returns = TypeTag::Int)]
5324#[example(
5325 name = "count",
5326 code = r###"
5327 # Every non-overlapping occurrence counts once.
5328 IMPORT [STD]
5329 LET $n: INT = TEXT_COUNT("hello world", "o")
5330 ASSERT_EQ $n 2
5331
5332 # Overlapping candidates never double count.
5333 LET $once: INT = TEXT_COUNT("aaa", "aa")
5334 ASSERT_EQ $once 1
5335 "###
5336)]
5337fn text_count(
5338 text: String,
5340 needle: String,
5342) -> Result<Value> {
5343 let n = super::args::text_count_str(&text, &needle, FUNC_TEXT_COUNT)?;
5344 Ok(Value::int(n))
5345}
5346
5347#[oxdock_func(pure, returns = TypeTag::Int)]
5357#[example(
5358 name = "count matches",
5359 code = r###"
5360 # One line matches once no matter how many times it hits.
5361 IMPORT [STD]
5362 LET $n: INT = TEXT_COUNT_MATCHES("test a: test\ntest b: nope\ntest c: test", ": test")
5363 ASSERT_EQ $n 2
5364
5365 # A miss binds zero, never an error.
5366 LET $none: INT = TEXT_COUNT_MATCHES("test b: nope", ": test$")
5367 ASSERT_EQ $none 0
5368 "###
5369)]
5370fn text_count_matches(
5371 text: String,
5373 pattern: String,
5375) -> Result<Value> {
5376 let n = super::args::text_count_matches_str(&text, &pattern, FUNC_TEXT_COUNT_MATCHES)?;
5377 Ok(Value::int(n))
5378}
5379
5380#[oxdock_func(pure, returns = TypeTag::ListOf(std::sync::Arc::new(TypeTag::String)))]
5393#[example(
5394 name = "grep",
5395 code = r###"
5396 # Matching lines come back as a list, in order.
5397 IMPORT [STD]
5398 LET $hits: LIST<STRING> = TEXT_GREP("one\ntwo\none more", "^one")
5399 ASSERT_EQ $hits.0 "one"
5400 ASSERT_EQ $hits.1 "one more"
5401
5402 # A miss binds an empty list, never an error.
5403 LET $miss: LIST<STRING> = TEXT_GREP("one\ntwo", "^z")
5404 LET $joined: STRING = TEXT_JOIN($miss, ",")
5405 ASSERT_EQ $joined ""
5406
5407 # The (?i) flag ignores case, so uppercase lines match too.
5408 LET $folded: LIST<STRING> = TEXT_GREP("One\ntwo\nONE more", "(?i)^one")
5409 ASSERT_EQ $folded.0 "One"
5410 ASSERT_EQ $folded.1 "ONE more"
5411 "###
5412)]
5413#[example(
5414 name = "grep invert",
5415 code = r###"
5416 # The invert option keeps every non-matching line instead.
5417 IMPORT [STD]
5418 LET $kept: LIST<STRING> = TEXT_GREP("one\ntwo\none more", "^one", {invert: true})
5419 ASSERT_EQ $kept.0 "two"
5420
5421 # A pattern matching every line binds an empty list, never an error.
5422 LET $none: LIST<STRING> = TEXT_GREP("one\ntwo", "^", {invert: true})
5423 LET $joined: STRING = TEXT_JOIN($none, ",")
5424 ASSERT_EQ $joined ""
5425
5426 # Options ride into placeholders as MAP literals. Placeholder
5427 # strings unescape only backslash and quote, so multiline text
5428 # arrives through a variable.
5429 LET $two_lines: STRING = "one\ntwo"
5430 LET $msg: STRING = 'kept:{{ STD::TEXT_GREP($two_lines, "^one", {invert: true}) }}'
5431 ASSERT_EQ $msg "kept:two"
5432 "###
5433)]
5434fn text_grep(
5435 text: String,
5437 pattern: String,
5439 #[options("invert?: BOOL")]
5441 #[optional]
5442 options: BTreeMap<String, Value>,
5443) -> Result<Value> {
5444 let invert = super::args::text_invert_flag(&options);
5447 Ok(super::args::text_list_value(super::args::text_grep_str(
5448 &text,
5449 &pattern,
5450 invert,
5451 FUNC_TEXT_GREP,
5452 )?))
5453}
5454
5455#[oxdock_func(returns = TypeTag::Bool)]
5466#[example(
5467 name = "drain to end",
5468 code = r###"
5469 # Capture two lines, then drain to end of stream with no sentinel line.
5470 IMPORT [STD]
5471 LET $cap: PIPE
5472 WITH_IO [stdout=$cap] {
5473 ECHO "one"
5474 ECHO "two"
5475 }
5476
5477 # The loop exits on close, and the count proves both lines drained.
5478 LET $n: INT = 0
5479 WHILE !EOF($cap) {
5480 WITH_IO [stdin=$cap] READ_LINE $line
5481 $n = $n + 1
5482 }
5483 ASSERT_EQ $n 2
5484 "###
5485)]
5486fn eof<P: ProcessManager>(
5487 cx: &mut StepCtx<P>,
5488 pipe: PipeHandle,
5490) -> Result<Value> {
5491 let info = cx.state.io.inspect_pipe(&pipe);
5492 Ok(Value::bool(info.closed && info.buffered == 0))
5493}
5494
5495fn task_poll_result_fields() -> Arc<[Field]> {
5499 Arc::from(vec![
5500 Field {
5501 name: "state".to_string(),
5502 ty: TypeTag::String,
5503 docs: "Task phase: `running` or `finished`.",
5504 optional: false,
5505 default: None,
5506
5507 alias: None,
5508 },
5509 Field {
5510 name: "ok".to_string(),
5511 ty: TypeTag::Bool,
5512 docs: "True unless the task failed.",
5513 optional: false,
5514 default: None,
5515
5516 alias: None,
5517 },
5518 Field {
5519 name: "stdout_tail".to_string(),
5520 ty: TypeTag::String,
5521 docs: "Bounded stdout tail, live while running.",
5522 optional: false,
5523 default: None,
5524
5525 alias: None,
5526 },
5527 Field {
5528 name: "stderr_tail".to_string(),
5529 ty: TypeTag::String,
5530 docs: "Bounded stderr tail, live while running.",
5531 optional: false,
5532 default: None,
5533
5534 alias: None,
5535 },
5536 Field {
5537 name: "truncated_bytes".to_string(),
5538 ty: TypeTag::Int,
5539 docs: "Dropped head bytes past the per-stream cap.",
5540 optional: false,
5541 default: None,
5542
5543 alias: None,
5544 },
5545 Field {
5546 name: "exit_code".to_string(),
5547 ty: TypeTag::Int,
5548 docs: "Process exit code, present once finished.",
5549 optional: true,
5550 default: None,
5551
5552 alias: None,
5553 },
5554 Field {
5555 name: "result".to_string(),
5556 ty: TypeTag::Any,
5557 docs: "Task `RETURN` value, present on clean finish.",
5558 optional: true,
5559 default: None,
5560
5561 alias: None,
5562 },
5563 Field {
5564 name: "error".to_string(),
5565 ty: TypeTag::String,
5566 docs: "Failure text, present on failed finish.",
5567 optional: true,
5568 default: None,
5569
5570 alias: None,
5571 },
5572 ])
5573}
5574
5575#[oxdock_func(returns = TypeTag::Record(task_poll_result_fields()))]
5588#[example(
5589 name = "running poll",
5590 code = r###"
5591 # A sleeping task is still running on the first poll.
5592 IMPORT [STD]
5593 LET $t: HANDLE<STRING> = ASYNC { SLEEP 30s; RETURN "done" }
5594 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)
5595 ASSERT_EQ $m.state "running"
5596 ASSERT_EQ $m.ok true
5597 # Clean up the sleeper so the run ends promptly.
5598 CANCEL $t
5599 "###
5600)]
5601#[example(
5602 name = "finished poll",
5603 code = r###"
5604 # A finished task reports its value and final tails, then still awaits.
5605 IMPORT [STD]
5606 LET $t: HANDLE<STRING> = ASYNC { ECHO "hi"; SLEEP 1s; RETURN "done" }
5607 # Do other work while the task runs; poll once it should be done.
5608 SLEEP 2s
5609 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)
5610 ASSERT_EQ $m.state "finished"
5611 ASSERT_EQ $m.result "done"
5612 LET $o: STRING = AWAIT $t
5613 ASSERT_EQ $o "done"
5614 "###
5615)]
5616fn task_poll<P: ProcessManager>(
5617 cx: &mut StepCtx<P>,
5618 task: HandleValue,
5620) -> Result<Value> {
5621 let entry =
5622 super::handlers::resolve_task_entry_by_id(task.0, &format!("TASK_POLL({})", task.0), cx)?;
5623 let obs = entry.observe_completion();
5624 let (stdout_tail, stderr_tail, dropped) = entry.snapshot_tails();
5625 let mut out = BTreeMap::new();
5626 out.insert(
5627 "state".to_string(),
5628 Value::string(if obs.running { "running" } else { "finished" }.to_string()),
5629 );
5630 out.insert("ok".to_string(), Value::bool(obs.ok));
5631 if !obs.running {
5632 out.insert("exit_code".to_string(), Value::int(obs.exit_code));
5633 }
5634 if let Some(result) = obs.result {
5635 out.insert("result".to_string(), result);
5636 }
5637 if !obs.error.is_empty() {
5638 out.insert("error".to_string(), Value::string(obs.error));
5639 }
5640 out.insert("stdout_tail".to_string(), Value::string(stdout_tail));
5641 out.insert("stderr_tail".to_string(), Value::string(stderr_tail));
5642 out.insert(
5643 "truncated_bytes".to_string(),
5644 Value::int(dropped.min(i64::MAX as u64) as i64),
5645 );
5646 Ok(Value::map(out))
5647}
5648
5649fn meta_to_value(meta: &FuncMeta) -> Value {
5650 let mut map = BTreeMap::new();
5651 map.insert("name".to_string(), Value::string(meta.name.clone()));
5652 map.insert("module".to_string(), Value::string(meta.module.clone()));
5653 map.insert(
5654 "kind".to_string(),
5655 Value::string(meta.kind.label().to_string()),
5656 );
5657 let params = match &meta.params {
5658 Some(params) => Value::list(
5659 params
5660 .iter()
5661 .map(|p| {
5662 let mut entry = BTreeMap::new();
5663 entry.insert("name".to_string(), Value::string(p.name.clone()));
5664 entry.insert(
5665 "param_type".to_string(),
5666 Value::string(
5667 p.param_type
5668 .as_ref()
5669 .map(render_structural)
5670 .unwrap_or_default(),
5671 ),
5672 );
5673 entry.insert(
5674 "allowed".to_string(),
5675 Value::string(
5676 p.allowed
5677 .map(|values| values.join(", "))
5678 .unwrap_or_default(),
5679 ),
5680 );
5681 entry.insert("docs".to_string(), Value::string(String::new()));
5682 entry.insert("optional".to_string(), Value::bool(p.optional));
5683 entry.insert(
5684 "options".to_string(),
5685 match p.options {
5686 Some(keys) => Value::list(
5687 keys.iter()
5688 .map(|key| {
5689 let mut option = BTreeMap::new();
5690 option.insert(
5691 "name".to_string(),
5692 Value::string(key.name.to_string()),
5693 );
5694 option.insert(
5695 "value_type".to_string(),
5696 Value::string(render_structural(&key.value)),
5697 );
5698 option.insert(
5699 "required".to_string(),
5700 Value::bool(key.required),
5701 );
5702 option.insert(
5703 "default".to_string(),
5704 Value::string(
5705 key.default.unwrap_or_default().to_string(),
5706 ),
5707 );
5708 Value::map(option)
5709 })
5710 .collect(),
5711 ),
5712 None => Value::string(String::new()),
5713 },
5714 );
5715 Value::map(entry)
5716 })
5717 .collect(),
5718 ),
5719 None => Value::list(Vec::new()),
5723 };
5724 map.insert("params".to_string(), params);
5725 map.insert(
5726 "returns".to_string(),
5727 Value::string(
5728 meta.returns
5729 .as_ref()
5730 .map(render_structural)
5731 .unwrap_or_default(),
5732 ),
5733 );
5734 map.insert("rpn".to_string(), Value::bool(meta.rpn));
5735 map.insert(
5736 "summary".to_string(),
5737 Value::string(meta.summary.to_string()),
5738 );
5739 Value::map(map)
5740}
5741
5742#[derive(Debug, Clone)]
5746pub struct RecordSchema {
5747 pub name: &'static str,
5748 pub fields: std::sync::Arc<[Field]>,
5749}
5750
5751#[derive(Clone)]
5755pub struct HostModule<P: ProcessManager> {
5756 pub name: String,
5757 pub funcs: Vec<HostRegistration<P>>,
5758 pub types: Vec<&'static TypeDescriptor>,
5759 pub record_schemas: Vec<RecordSchema>,
5760 pub states: Vec<ModuleState>,
5767}
5768
5769#[derive(Clone)]
5773pub struct ModuleState {
5774 id: std::any::TypeId,
5775 state: std::sync::Arc<dyn std::any::Any + Send + Sync>,
5776}
5777
5778pub type PreRunInspector = dyn Fn(&[Step]) -> DiagnosticResult<()> + Send + Sync;
5782
5783#[derive(Clone)]
5789pub struct PreRunCheck {
5790 check: Arc<PreRunInspector>,
5791}
5792
5793impl PreRunCheck {
5794 pub fn new(check: impl Fn(&[Step]) -> DiagnosticResult<()> + Send + Sync + 'static) -> Self {
5796 Self {
5797 check: Arc::new(check),
5798 }
5799 }
5800
5801 pub fn run(&self, steps: &[Step]) -> DiagnosticResult<()> {
5803 (self.check)(steps)
5804 }
5805}
5806
5807impl<P: ProcessManager> HostModule<P> {
5808 pub fn with_state<T: Send + Sync + 'static>(mut self, state: std::sync::Arc<T>) -> Self {
5811 self.states.push(ModuleState {
5812 id: std::any::TypeId::of::<T>(),
5813 state,
5814 });
5815 self
5816 }
5817
5818 pub fn check_pre_run(&self, steps: &[Step]) -> DiagnosticResult<()> {
5822 for state in &self.states {
5823 if let Some(check) = state.state.downcast_ref::<PreRunCheck>() {
5824 check.run(steps)?;
5825 }
5826 }
5827 Ok(())
5828 }
5829}
5830
5831impl<P: ProcessManager> ExecState<P> {
5832 pub fn register_module(&mut self, module: HostModule<P>) {
5835 for registration in module.funcs {
5836 match registration {
5837 HostRegistration::Stateful { name, meta, func } => {
5838 self.functions.register_host(&module.name, name, meta, func);
5839 }
5840 HostRegistration::Pure { name, meta, func } => {
5841 self.functions
5842 .register_pure_host(&module.name, name, meta, func);
5843 }
5844 HostRegistration::Both {
5845 name,
5846 meta,
5847 func,
5848 template,
5849 } => {
5850 self.functions
5851 .register_both_host(&module.name, name, meta, func, template);
5852 }
5853 }
5854 }
5855 for descriptor in module.types {
5856 self.register_type(descriptor);
5857 }
5858 for schema in module.record_schemas {
5859 self.register_record_schema(schema.name, schema.fields);
5860 }
5861 for state in module.states {
5862 self.module_states
5863 .insert((module.name.clone(), state.id), state.state);
5864 }
5865 }
5866
5867 pub fn list_functions(&self) -> Vec<FuncMeta> {
5869 let mut out: Vec<FuncMeta> = self.functions.entries_metas().into_iter().collect();
5870 if !out.iter().any(|m| m.name == KEYWORD_INSPECT) {
5872 out.push(FuncMeta {
5873 name: KEYWORD_INSPECT.to_string(),
5874 module: STD_MODULE_NAME.to_string(),
5875 kind: FuncKind::HostCtx,
5876 params: None,
5877 returns: Some(TypeTag::Map),
5878 rpn: false,
5879 summary: "Inspect a variable binding.",
5880 docs: "INSPECT($var): dedicated AST node taking a variable, not a value.",
5881 examples: &[],
5882 });
5883 }
5884 out.sort_by(|a, b| a.name.cmp(&b.name));
5885 out
5886 }
5887
5888 pub fn describe_function(&self, name: &str) -> Option<Value> {
5890 if let Some(meta) = self.functions.meta(name) {
5891 return Some(meta_to_value(&meta));
5892 }
5893 if name == KEYWORD_INSPECT {
5895 return Some(meta_to_value(&FuncMeta {
5896 name: KEYWORD_INSPECT.to_string(),
5897 module: STD_MODULE_NAME.to_string(),
5898 kind: FuncKind::HostCtx,
5899 params: None,
5900 returns: Some(TypeTag::Map),
5901 rpn: false,
5902 summary: "Inspect a variable binding.",
5903 docs: "INSPECT($var): dedicated AST node taking a variable, not a value.",
5904 examples: &[],
5905 }));
5906 }
5907 None
5908 }
5909
5910 pub fn pure_function_table(&self) -> Arc<PureTable> {
5915 self.functions.pure_shared()
5916 }
5917}
5918
5919#[cfg(test)]
5920mod tests {
5921 use super::*;
5922
5923 #[test]
5924 fn placeholder_resolver_dispatches_table_entries() {
5925 let echo: PureFn = Arc::new(|args| {
5929 args.into_iter()
5930 .next()
5931 .ok_or_else(|| anyhow::anyhow!("ECHO needs 1 arg"))
5932 });
5933 let mut entries = HashMap::new();
5934 entries.insert("ECHO".to_string(), echo);
5935 let mut table = PureTable::new();
5936 table.insert("T".to_string(), entries);
5937 let resolve = placeholder_resolver(Arc::new(table));
5938 let out = resolve("T", "ECHO", vec![Value::string("hi".to_string())]).expect("dispatch");
5939 assert_eq!(out.as_str().expect("string"), "hi");
5940 let err = format!(
5941 "{:#}",
5942 resolve("T", "NOPE", vec![]).expect_err("unknown must fail")
5943 );
5944 assert!(
5945 err.contains("unknown placeholder function `T::NOPE`"),
5946 "names the call: {err}"
5947 );
5948 assert!(
5949 err.contains("known functions: T::ECHO"),
5950 "lists known names: {err}"
5951 );
5952 }
5953
5954 #[test]
5955 fn describe_entry_renders_union_spellings() {
5956 let union = oxdock_parser::union_tag!(String, Pipe);
5962 let meta = FuncMeta {
5963 name: "T::F".to_string(),
5964 module: "T".to_string(),
5965 kind: FuncKind::HostPure,
5966 params: Some(vec![FuncParam {
5967 name: "text".to_string(),
5968 param_type: Some(union.clone()),
5969 allowed: None,
5970 docs: "",
5971 options: None,
5972 optional: false,
5973 }]),
5974 returns: Some(union),
5975 rpn: false,
5976 summary: "test-only",
5977 docs: "test-only",
5978 examples: &[],
5979 };
5980 let value = meta_to_value(&meta);
5981 let map = value.as_map().expect("describe value is a map");
5982 let params = map
5983 .get("params")
5984 .expect("params key")
5985 .as_list()
5986 .expect("params is a list");
5987 let first = params[0].as_map().expect("entry is a map");
5988 assert_eq!(
5989 first.get("param_type").and_then(Value::as_str),
5990 Some("STRING|PIPE"),
5991 "param renders the set"
5992 );
5993 assert_eq!(
5994 map.get("returns").and_then(Value::as_str),
5995 Some("STRING|PIPE"),
5996 "returns render the set"
5997 );
5998 }
5999
6000 #[test]
6001 fn describe_entry_renders_handle_payload() {
6002 let meta = FuncMeta {
6006 name: "SCRIPT::FETCH".to_string(),
6007 module: "SCRIPT".to_string(),
6008 kind: FuncKind::Script,
6009 params: Some(vec![]),
6010 returns: Some(TypeTag::HandleOf(std::sync::Arc::new(TypeTag::String))),
6011 rpn: false,
6012 summary: "test-only",
6013 docs: "test-only",
6014 examples: &[],
6015 };
6016 let value = meta_to_value(&meta);
6017 let map = value.as_map().expect("describe value is a map");
6018 assert_eq!(
6019 map.get("returns").and_then(Value::as_str),
6020 Some("HANDLE<STRING>"),
6021 "returns render the payload"
6022 );
6023 }
6024
6025 #[test]
6026 fn describe_entry_carries_optional_flag() {
6027 let meta = FuncMeta {
6031 name: "T::F".to_string(),
6032 module: "T".to_string(),
6033 kind: FuncKind::HostPure,
6034 params: Some(vec![
6035 FuncParam {
6036 name: "url".to_string(),
6037 param_type: Some(TypeTag::String),
6038 allowed: None,
6039 docs: "",
6040 options: None,
6041 optional: false,
6042 },
6043 FuncParam {
6044 name: "options".to_string(),
6045 param_type: Some(TypeTag::Map),
6046 allowed: None,
6047 docs: "",
6048 options: None,
6049 optional: true,
6050 },
6051 ]),
6052 returns: Some(TypeTag::String),
6053 rpn: false,
6054 summary: "test-only",
6055 docs: "test-only",
6056 examples: &[],
6057 };
6058 let value = meta_to_value(&meta);
6059 let map = value.as_map().expect("describe value is a map");
6060 let params = map
6061 .get("params")
6062 .expect("params key")
6063 .as_list()
6064 .expect("params is a list");
6065 assert_eq!(params.len(), 2);
6066 let first = params[0].as_map().expect("entry is a map");
6067 let second = params[1].as_map().expect("entry is a map");
6068 assert_eq!(
6069 first.get("optional").and_then(Value::as_bool),
6070 Some(false),
6071 "required param must read false"
6072 );
6073 assert_eq!(
6074 second.get("optional").and_then(Value::as_bool),
6075 Some(true),
6076 "omittable param must read true"
6077 );
6078 }
6079
6080 #[test]
6081 fn template_twins_mirror_string_paths_and_refuse_pipes() {
6082 let pipe = Value::pipe_fresh();
6088 type TwinCase = (&'static str, Box<dyn Fn() -> Result<Value>>);
6089 let cases: Vec<TwinCase> = vec![
6090 (
6091 "TEXT_TRIM",
6092 Box::new(|| text_trim_string(Value::string(" hello ".to_string()))),
6093 ),
6094 (
6095 "TEXT_TRIM_PREFIX",
6096 Box::new(|| {
6097 text_trim_prefix_string(Value::string("v1".to_string()), "v".to_string())
6098 }),
6099 ),
6100 (
6101 "TEXT_TRIM_SUFFIX",
6102 Box::new(|| {
6103 text_trim_suffix_string(Value::string("a.gz".to_string()), "x".to_string())
6104 }),
6105 ),
6106 (
6107 "TEXT_TO_UPPER",
6108 Box::new(|| text_to_upper_string(Value::string("hi".to_string()))),
6109 ),
6110 (
6111 "TEXT_TO_LOWER",
6112 Box::new(|| text_to_lower_string(Value::string("HI".to_string()))),
6113 ),
6114 (
6115 "TEXT_REPLACE",
6116 Box::new(|| {
6117 text_replace_string(
6118 Value::string("ab".to_string()),
6119 "b".to_string(),
6120 "c".to_string(),
6121 )
6122 }),
6123 ),
6124 (
6125 "TEXT_REPLACE_REGEX",
6126 Box::new(|| {
6127 text_replace_regex_string(
6128 Value::string("ab".to_string()),
6129 "b".to_string(),
6130 "c".to_string(),
6131 )
6132 }),
6133 ),
6134 ];
6135 assert_eq!(cases.len(), 7, "every mirror op needs a twin row");
6136 for (name, run) in &cases {
6137 let value = run().unwrap_or_else(|e| panic!("{name} twin must answer strings: {e:#}"));
6138 assert!(
6139 value.as_str().is_some(),
6140 "{name} twin must answer STRING, got {}",
6141 value.type_name()
6142 );
6143 }
6144 assert_eq!(
6145 text_trim_string(Value::string(" hello ".to_string()))
6146 .expect("trim twin")
6147 .as_str(),
6148 Some("hello")
6149 );
6150 let pipe_cases: Vec<(&str, Result<Value>)> = vec![
6152 ("TEXT_TRIM", text_trim_string(pipe.clone())),
6153 (
6154 "TEXT_TRIM_PREFIX",
6155 text_trim_prefix_string(pipe.clone(), "v".to_string()),
6156 ),
6157 (
6158 "TEXT_TRIM_SUFFIX",
6159 text_trim_suffix_string(pipe.clone(), ".gz".to_string()),
6160 ),
6161 ("TEXT_TO_UPPER", text_to_upper_string(pipe.clone())),
6162 ("TEXT_TO_LOWER", text_to_lower_string(pipe.clone())),
6163 (
6164 "TEXT_REPLACE",
6165 text_replace_string(pipe.clone(), "a".to_string(), "b".to_string()),
6166 ),
6167 (
6168 "TEXT_REPLACE_REGEX",
6169 text_replace_regex_string(pipe.clone(), "a".to_string(), "b".to_string()),
6170 ),
6171 ];
6172 for (name, result) in pipe_cases {
6173 let err = result.expect_err(&format!("{name} twin must refuse PIPE"));
6174 assert!(
6175 format!("{err:#}").contains("step IO"),
6176 "{name} refusal names the missing context: {err:#}"
6177 );
6178 }
6179 }
6180
6181 #[test]
6182 fn shell_words_join_split_round_trip() {
6183 let words = vec![
6187 "gh".to_string(),
6188 "issue".to_string(),
6189 "comment".to_string(),
6190 "with spaces".to_string(),
6191 "it's".to_string(),
6192 "say \"hi\"".to_string(),
6193 "$HOME".to_string(),
6194 "$(whoami)".to_string(),
6195 "C:\\path\\to".to_string(),
6196 "naïve café".to_string(),
6197 "".to_string(),
6198 ];
6199 let joined = shell_words::join(&words);
6200 let back = shell_words::split(&joined).expect("join output must parse");
6201 assert_eq!(back, words);
6202 assert!(shell_words::split("unbalanced \"quote").is_err());
6203 }
6204
6205 struct FakeView {
6209 exports: HashMap<String, Vec<String>>,
6210 targets: HashMap<String, AliasTargets>,
6211 bindings: HashMap<String, HashMap<String, bool>>,
6212 }
6213
6214 impl ModuleGraphView for FakeView {
6215 fn const_exports(&self, file: &str) -> Option<&[String]> {
6216 self.exports.get(file).map(Vec::as_slice)
6217 }
6218
6219 fn alias_targets(&self, file: &str) -> AliasTargets {
6220 self.targets.get(file).cloned().unwrap_or_default()
6221 }
6222
6223 fn binding(&self, file: &str, name: &str) -> BindingPresence {
6224 match self.bindings.get(file).and_then(|names| names.get(name)) {
6225 Some(true) => BindingPresence::Const,
6226 Some(false) => BindingPresence::Let,
6227 None => BindingPresence::Absent,
6228 }
6229 }
6230 }
6231
6232 fn fake_targets(pairs: &[(&str, &str)]) -> AliasTargets {
6233 let mut targets = AliasTargets::new();
6234 for (alias, file) in pairs {
6235 targets
6236 .entry((*alias).to_string())
6237 .or_default()
6238 .push((Some((*file).to_string()), None));
6239 }
6240 targets
6241 }
6242
6243 fn os_guard(os: &str) -> GuardExpr {
6244 GuardExpr::Predicate(oxdock_parser::Guard::Attr {
6245 ns: oxdock_parser::Ns::Os,
6246 key: None,
6247 val: Some(os.to_string()),
6248 })
6249 }
6250
6251 #[test]
6252 fn chase_resolves_bare_and_single_forward() {
6253 let mut view = FakeView {
6256 exports: HashMap::from([
6257 ("a".to_string(), vec!["N".to_string()]),
6258 ("b".to_string(), vec!["A::N".to_string()]),
6259 ("c".to_string(), vec!["B::N".to_string()]),
6260 ]),
6261 targets: HashMap::from([
6262 ("u".to_string(), fake_targets(&[("B", "b")])),
6263 ("b".to_string(), fake_targets(&[("A", "a")])),
6264 ("c".to_string(), fake_targets(&[("B", "b")])),
6265 ]),
6266 bindings: HashMap::new(),
6267 };
6268 assert_eq!(
6269 chase_const_forward(&view, "a", "N", "U::N").expect("bare"),
6270 vec!["a".to_string()]
6271 );
6272 assert_eq!(
6273 chase_const_forward(&view, "b", "N", "U::N").expect("forward"),
6274 vec!["a".to_string()]
6275 );
6276 view.targets
6277 .insert("u".to_string(), fake_targets(&[("C", "c")]));
6278 assert_eq!(
6279 chase_const_forward(&view, "c", "N", "U::N").expect("chain"),
6280 vec!["a".to_string()]
6281 );
6282 }
6283
6284 #[test]
6285 fn chase_prefers_bare_over_forwards() {
6286 let view = FakeView {
6289 exports: HashMap::from([("b".to_string(), vec!["N".to_string(), "A::N".to_string()])]),
6290 targets: HashMap::from([("b".to_string(), fake_targets(&[("A", "a")]))]),
6291 bindings: HashMap::new(),
6292 };
6293 assert_eq!(
6294 chase_const_forward(&view, "b", "N", "U::N").expect("bare wins"),
6295 vec!["b".to_string()]
6296 );
6297 }
6298
6299 #[test]
6300 fn chase_rejects_split_forwards() {
6301 let view = FakeView {
6304 exports: HashMap::from([(
6305 "b".to_string(),
6306 vec!["A::N".to_string(), "C::N".to_string()],
6307 )]),
6308 targets: HashMap::new(),
6309 bindings: HashMap::new(),
6310 };
6311 let err = format!(
6312 "{}",
6313 chase_const_forward(&view, "b", "N", "U::N").expect_err("split must fail")
6314 );
6315 assert!(err.contains("ambiguous CONST `U::N`"), "{err}");
6316 assert!(err.contains("A::N") && err.contains("C::N"), "{err}");
6317 }
6318
6319 #[test]
6320 fn chase_names_broken_link_detail() {
6321 let view = FakeView {
6324 exports: HashMap::from([
6325 ("b".to_string(), vec!["A::M".to_string()]),
6326 ("c".to_string(), vec!["A::P".to_string()]),
6327 ("d".to_string(), vec!["A::Q".to_string()]),
6328 ("a".to_string(), Vec::new()),
6329 ]),
6330 targets: HashMap::from([
6331 ("b".to_string(), fake_targets(&[("A", "a")])),
6332 ("c".to_string(), fake_targets(&[("A", "a")])),
6333 ("d".to_string(), fake_targets(&[("A", "a")])),
6334 ]),
6335 bindings: HashMap::from([(
6336 "a".to_string(),
6337 HashMap::from([("P".to_string(), true), ("Q".to_string(), false)]),
6338 )]),
6339 };
6340 let err = format!(
6341 "{}",
6342 chase_const_forward(&view, "b", "M", "U::M").expect_err("missing must fail")
6343 );
6344 assert!(err.contains("does not resolve"), "{err}");
6345 assert!(err.contains("no import alias `A` exports `M`"), "{err}");
6346 let err = format!(
6347 "{}",
6348 chase_const_forward(&view, "c", "P", "U::P").expect_err("unexported must fail")
6349 );
6350 assert!(
6351 err.contains("holds `P` as CONST but does not export it"),
6352 "{err}"
6353 );
6354 let err = format!(
6355 "{}",
6356 chase_const_forward(&view, "d", "Q", "U::Q").expect_err("LET must fail")
6357 );
6358 assert!(
6359 err.contains("is a LET binding and cannot be exported"),
6360 "{err}"
6361 );
6362 }
6363
6364 #[test]
6365 fn chase_rejects_cycles() {
6366 let view = FakeView {
6369 exports: HashMap::from([
6370 ("a".to_string(), vec!["B::N".to_string()]),
6371 ("b".to_string(), vec!["A::N".to_string()]),
6372 ]),
6373 targets: HashMap::from([
6374 ("a".to_string(), fake_targets(&[("B", "b")])),
6375 ("b".to_string(), fake_targets(&[("A", "a")])),
6376 ]),
6377 bindings: HashMap::new(),
6378 };
6379 let err = format!(
6380 "{}",
6381 chase_const_forward(&view, "a", "N", "U::N").expect_err("cycle must fail")
6382 );
6383 assert!(err.contains("re-export cycle"), "{err}");
6384 }
6385
6386 #[test]
6387 fn chase_unions_disjoint_guard_branches() {
6388 let mut guarded = AliasTargets::new();
6391 guarded.insert(
6392 "A".to_string(),
6393 vec![
6394 (Some("lin".to_string()), Some(os_guard("linux"))),
6395 (Some("mac".to_string()), Some(os_guard("macos"))),
6396 ],
6397 );
6398 let view = FakeView {
6399 exports: HashMap::from([
6400 ("b".to_string(), vec!["A::N".to_string()]),
6401 ("lin".to_string(), vec!["N".to_string()]),
6402 ("mac".to_string(), vec!["N".to_string()]),
6403 ]),
6404 targets: HashMap::from([("b".to_string(), guarded)]),
6405 bindings: HashMap::new(),
6406 };
6407 assert_eq!(
6408 chase_const_forward(&view, "b", "N", "U::N").expect("disjoint branches"),
6409 vec!["lin".to_string(), "mac".to_string()]
6410 );
6411 }
6412
6413 #[test]
6414 fn holder_classification_sorts_and_rejects() {
6415 let view = FakeView {
6418 exports: HashMap::from([
6419 ("b".to_string(), vec!["N".to_string()]),
6420 ("c".to_string(), vec!["N".to_string()]),
6421 ]),
6422 targets: HashMap::new(),
6423 bindings: HashMap::new(),
6424 };
6425 let unit = fake_targets(&[("B", "b"), ("B", "c")]);
6426 match const_holder_files(&view, &unit, "B", "N") {
6427 ConstHolders::Ambiguous { .. } => {}
6428 other => panic!("overlapping holders must be ambiguous, got {other:?}"),
6429 }
6430 match const_holder_files(&view, &unit, "Z", "N") {
6431 ConstHolders::NoAlias => {}
6432 other => panic!("unknown alias must report NoAlias, got {other:?}"),
6433 }
6434 let unit = fake_targets(&[("B", "b")]);
6435 match const_holder_files(&view, &unit, "B", "N") {
6436 ConstHolders::Found(files) => assert_eq!(files, vec!["b".to_string()]),
6437 other => panic!("single holder must be found, got {other:?}"),
6438 }
6439 }
6440}