1use std::collections::{BTreeMap, HashMap, HashSet};
2use std::sync::Arc;
3
4use anyhow::Result;
5use oxdock_func_macro::oxdock_func;
6use oxdock_parser::{
7 Field, KEYWORD_INSPECT, SCRIPT_MODULE_NAME, STD_MODULE_NAME, SemaphoreState, Step, TypeTag,
8 Value, base_name, qualify, render_structural, split_qualified,
9};
10use oxdock_pipe::PipeHandle;
11use oxdock_process::{CommandStdin, DefaultProcessManager, ProcessManager};
12
13use super::io::StreamHandle;
14use super::state::ExecState;
15use super::steps::StepCtx;
16use super::typing::TypeDescriptor;
17
18#[derive(Debug, Clone, Copy, PartialEq, Eq)]
24pub enum FuncKind {
25 Script,
26 HostCtx,
27 HostPure,
28}
29
30impl FuncKind {
31 pub fn label(&self) -> &'static str {
32 match self {
33 FuncKind::Script => "script",
34 FuncKind::HostCtx | FuncKind::HostPure => "host",
35 }
36 }
37}
38
39#[derive(Debug, Clone)]
57pub struct FuncParam {
58 pub name: String,
59 pub param_type: Option<TypeTag>,
60 pub allowed: Option<&'static [&'static str]>,
61 pub docs: &'static str,
62 pub options: Option<&'static [ParamOption]>,
63 pub optional: bool,
64}
65
66pub fn required_arity(params: &[FuncParam]) -> usize {
71 params
72 .iter()
73 .rev()
74 .take_while(|param| param.optional)
75 .fold(params.len(), |count, _| count - 1)
76}
77
78pub fn fill_optional_args(params: &[FuncParam], mut values: Vec<Value>) -> Vec<Value> {
83 assert!(
84 values.len() <= params.len(),
85 "arity gate must run before fill_optional_args"
86 );
87 assert!(
88 values.len() >= required_arity(params),
89 "arity gate must run before fill_optional_args"
90 );
91 while values.len() < params.len() {
92 values.push(Value::map(BTreeMap::new()));
93 }
94 values
95}
96
97#[derive(Debug, Clone)]
104pub struct ParamOption {
105 pub name: &'static str,
106 pub value: TypeTag,
107 pub required: bool,
108 pub default: Option<&'static str>,
109}
110
111#[derive(Debug, Clone)]
117pub struct FuncMeta {
118 pub name: String,
119 pub module: String,
123 pub kind: FuncKind,
124 pub params: Option<Vec<FuncParam>>,
125 pub returns: Option<TypeTag>,
126 pub rpn: bool,
127 pub summary: &'static str,
128 pub docs: &'static str,
129 pub examples: &'static [crate::Example],
135}
136
137pub type PureFn = Arc<dyn Fn(Vec<Value>) -> Result<Value> + Send + Sync>;
140
141pub type NativeFn<P> = Arc<dyn Fn(&mut StepCtx<P>, Vec<Value>) -> Result<Value> + Send + Sync>;
143
144pub trait OxDockFn<P: ProcessManager> {
148 fn registration() -> HostRegistration<P>;
151}
152
153pub enum HostRegistration<P: ProcessManager> {
159 Stateful {
160 name: String,
161 meta: FuncMeta,
162 func: NativeFn<P>,
163 },
164 Pure {
165 name: String,
166 meta: FuncMeta,
167 func: PureFn,
168 },
169}
170
171impl<P: ProcessManager> Clone for HostRegistration<P> {
174 fn clone(&self) -> Self {
175 match self {
176 HostRegistration::Stateful { name, meta, func } => HostRegistration::Stateful {
177 name: name.clone(),
178 meta: meta.clone(),
179 func: Arc::clone(func),
180 },
181 HostRegistration::Pure { name, meta, func } => HostRegistration::Pure {
182 name: name.clone(),
183 meta: meta.clone(),
184 func: Arc::clone(func),
185 },
186 }
187 }
188}
189
190impl<P: ProcessManager> HostRegistration<P> {
191 pub fn meta(&self) -> &FuncMeta {
194 match self {
195 HostRegistration::Stateful { meta, .. } => meta,
196 HostRegistration::Pure { meta, .. } => meta,
197 }
198 }
199}
200
201#[derive(Debug, Clone)]
205pub(super) struct FuncDefData {
206 pub(super) params: Vec<(String, TypeTag)>,
207 pub(super) body: Vec<Step>,
208}
209
210pub(super) enum FuncBody<P: ProcessManager> {
213 Script(FuncDefData),
214 Pure(PureFn),
215 Ctx(NativeFn<P>),
216}
217
218impl<P: ProcessManager> Clone for FuncBody<P> {
220 fn clone(&self) -> Self {
221 match self {
222 FuncBody::Script(def) => FuncBody::Script(def.clone()),
223 FuncBody::Pure(func) => FuncBody::Pure(Arc::clone(func)),
224 FuncBody::Ctx(func) => FuncBody::Ctx(Arc::clone(func)),
225 }
226 }
227}
228
229pub(super) struct FuncEntry<P: ProcessManager> {
233 pub(super) meta: FuncMeta,
234 pub(super) body: FuncBody<P>,
235}
236
237impl<P: ProcessManager> Clone for FuncEntry<P> {
239 fn clone(&self) -> Self {
240 Self {
241 meta: self.meta.clone(),
242 body: self.body.clone(),
243 }
244 }
245}
246
247struct ScopeFrame<P: ProcessManager> {
250 defined: HashSet<String>,
251 shadowed: Vec<(String, FuncEntry<P>)>,
252}
253
254impl<P: ProcessManager> Clone for ScopeFrame<P> {
256 fn clone(&self) -> Self {
257 Self {
258 defined: self.defined.clone(),
259 shadowed: self.shadowed.clone(),
260 }
261 }
262}
263
264pub type PureTable = HashMap<String, HashMap<String, PureFn>>;
274
275pub struct FunctionRegistry<P: ProcessManager> {
276 entries: HashMap<String, FuncEntry<P>>,
277 scopes: Vec<ScopeFrame<P>>,
278 pure_shared: Arc<PureTable>,
279}
280
281impl<P: ProcessManager> FunctionRegistry<P> {
282 pub(super) fn with_builtins() -> Self {
283 let mut reg = Self {
284 entries: HashMap::new(),
285 pure_shared: Arc::new(HashMap::new()),
286 scopes: vec![ScopeFrame {
287 defined: HashSet::new(),
288 shadowed: Vec::new(),
289 }],
290 };
291 for host in Self::builtin_registrations() {
295 match host {
296 HostRegistration::Stateful { name, meta, func } => {
297 reg.insert_qualified(STD_MODULE_NAME, name, meta, FuncBody::Ctx(func));
298 }
299 HostRegistration::Pure { name, meta, func } => {
300 reg.insert_qualified(STD_MODULE_NAME, name, meta, FuncBody::Pure(func));
301 }
302 }
303 }
304 reg
305 }
306
307 pub(super) fn builtin_registrations() -> Vec<HostRegistration<P>> {
312 vec![
313 Int::registration(),
314 Float::registration(),
315 FormatByteCount::registration(),
316 ParseByteCount::registration(),
317 FormatDuration::registration(),
318 ParseDuration::registration(),
319 Types::registration(),
320 TypeDescribe::registration(),
321 Glob::registration(),
322 LoadToml::registration(),
323 LoadJson::registration(),
324 ParseToml::registration(),
325 ParseJson::registration(),
326 PathType::registration(),
327 PathWritable::registration(),
328 IsExec::registration(),
329 HasKey::registration(),
330 MapSet::registration(),
331 MergeMaps::registration(),
332 Base64Encode::registration(),
333 Base64Decode::registration(),
334 Rand::registration(),
335 ToJson::registration(),
336 TypeOf::registration(),
337 Functions::registration(),
338 Describe::registration(),
339 IsTerminal::registration(),
340 Eof::registration(),
341 SemaphoreNew::registration(),
342 SemaphoreTryAcquire::registration(),
343 SemaphoreAvailable::registration(),
344 ]
345 }
346
347 pub(super) fn keys(&self) -> HashSet<String> {
350 self.entries.keys().cloned().collect()
351 }
352
353 pub(super) fn get(&self, name: &str) -> Option<FuncEntry<P>> {
355 self.entries.get(name).cloned()
356 }
357
358 fn insert_native(&mut self, name: String, meta: FuncMeta, body: FuncBody<P>) {
359 self.entries.insert(name, FuncEntry { meta, body });
360 self.rebuild_pure_shared();
361 }
362
363 fn rebuild_pure_shared(&mut self) {
367 let mut table: PureTable = HashMap::new();
368 for (name, entry) in &self.entries {
369 let FuncBody::Pure(ref func) = entry.body else {
370 continue;
371 };
372 if let Some((module, base)) = split_qualified(name) {
373 table
374 .entry(module.to_string())
375 .or_default()
376 .insert(base.to_string(), Arc::clone(func));
377 }
378 }
379 self.pure_shared = Arc::new(table);
380 }
381
382 fn insert_qualified(
386 &mut self,
387 module: &str,
388 base: String,
389 mut meta: FuncMeta,
390 body: FuncBody<P>,
391 ) {
392 meta.name = qualify(module, &base);
393 meta.module = module.to_string();
394 if self.entries.contains_key(&meta.name) {
399 panic!("duplicate function registration `{}`", meta.name);
400 }
401 self.insert_native(meta.name.clone(), meta, body);
402 }
403
404 pub(super) fn register_host(
405 &mut self,
406 module: &str,
407 name: String,
408 mut meta: FuncMeta,
409 func: NativeFn<P>,
410 ) {
411 meta.kind = FuncKind::HostCtx;
412 self.insert_qualified(module, name, meta, FuncBody::Ctx(func));
413 }
414
415 pub(super) fn register_pure_host(
416 &mut self,
417 module: &str,
418 name: String,
419 mut meta: FuncMeta,
420 func: PureFn,
421 ) {
422 meta.kind = FuncKind::HostPure;
423 self.insert_qualified(module, name, meta, FuncBody::Pure(func));
424 }
425
426 pub(super) fn define_script(
431 &mut self,
432 name: &str,
433 params: &[(String, TypeTag)],
434 body: &[Step],
435 ) -> Result<()> {
436 let qualified = qualify(SCRIPT_MODULE_NAME, name);
437 let shadowable = matches!(
438 self.entries.get(&qualified).map(|entry| &entry.body),
439 Some(FuncBody::Script(_))
440 );
441 let reserved = self
444 .entries
445 .keys()
446 .any(|key| split_qualified(key).is_some_and(|(_, base)| base == name));
447 if reserved && !shadowable {
448 anyhow::bail!("cannot shadow reserved function `{name}`");
449 }
450 if self
451 .scopes
452 .last()
453 .is_some_and(|frame| frame.defined.contains(&qualified))
454 {
455 anyhow::bail!("duplicate function `{name}` in same scope");
456 }
457 let old = self.entries.insert(
458 qualified.clone(),
459 FuncEntry {
460 meta: FuncMeta {
461 name: qualified.clone(),
462 module: SCRIPT_MODULE_NAME.to_string(),
463 kind: FuncKind::Script,
464 params: Some(
465 params
466 .iter()
467 .map(|(name, param_type)| FuncParam {
468 name: name.clone(),
469 param_type: Some(param_type.clone()),
470 allowed: None,
471 docs: "",
474 options: None,
475 optional: false,
476 })
477 .collect(),
478 ),
479 returns: None,
480 rpn: false,
481 summary: "DSL-defined function.",
482 docs: "Defined via FUNC in script.",
483 examples: &[],
484 },
485 body: FuncBody::Script(FuncDefData {
486 params: params.to_vec(),
487 body: body.to_vec(),
488 }),
489 },
490 );
491 if let Some(frame) = self.scopes.last_mut() {
492 frame.defined.insert(qualified.clone());
493 if let Some(old) = old {
494 frame.shadowed.push((qualified, old));
495 }
496 }
497 Ok(())
498 }
499
500 pub(super) fn push_scope(&mut self) {
503 self.scopes.push(ScopeFrame {
504 defined: HashSet::new(),
505 shadowed: Vec::new(),
506 });
507 }
508
509 pub(super) fn pop_scope(&mut self) {
512 let Some(frame) = self.scopes.pop() else {
513 return;
514 };
515 for name in frame.defined {
516 self.entries.remove(&name);
517 }
518 for (name, old) in frame.shadowed {
519 self.entries.insert(name, old);
520 }
521 }
522
523 pub(super) fn contains_script(&self, name: &str) -> bool {
527 matches!(
528 self.entries.get(name).map(|entry| &entry.body),
529 Some(FuncBody::Script(_))
530 )
531 }
532
533 fn clone_pure_fn(&self, name: &str) -> Option<PureFn> {
536 match self.entries.get(name)?.body {
537 FuncBody::Pure(ref func) => Some(Arc::clone(func)),
538 _ => None,
539 }
540 }
541
542 pub(super) fn pure_shared(&self) -> Arc<PureTable> {
546 Arc::clone(&self.pure_shared)
547 }
548
549 pub(super) fn all_metas(&self) -> Vec<FuncMeta> {
552 self.entries_metas()
553 }
554
555 fn clone_ctx_fn(&self, name: &str) -> Option<NativeFn<P>> {
558 match self.entries.get(name)?.body {
559 FuncBody::Ctx(ref func) => Some(Arc::clone(func)),
560 _ => None,
561 }
562 }
563
564 fn meta(&self, name: &str) -> Option<FuncMeta> {
565 self.entries.get(name).map(|entry| entry.meta.clone())
566 }
567
568 fn native_metas(&self) -> Vec<FuncMeta> {
569 let mut out: Vec<FuncMeta> = Vec::new();
570 for entry in self.entries.values() {
571 if !matches!(entry.body, FuncBody::Script(_)) {
572 out.push(entry.meta.clone());
573 }
574 }
575 out.sort_by(|a, b| a.name.cmp(&b.name));
576 out
577 }
578
579 fn entries_metas(&self) -> Vec<FuncMeta> {
582 let mut out: Vec<FuncMeta> = self
583 .entries
584 .values()
585 .map(|entry| entry.meta.clone())
586 .collect();
587 out.sort_by(|a, b| a.name.cmp(&b.name));
588 out
589 }
590}
591
592impl<P: ProcessManager> Clone for FunctionRegistry<P> {
593 fn clone(&self) -> Self {
594 Self {
595 entries: self.entries.clone(),
596 scopes: self.scopes.clone(),
597 pure_shared: Arc::clone(&self.pure_shared),
598 }
599 }
600}
601
602pub fn builtin_function_names() -> HashSet<String> {
609 let mut names = FunctionRegistry::<DefaultProcessManager>::with_builtins().keys();
610 names.insert(KEYWORD_INSPECT.to_string());
611 names
612}
613
614pub fn builtin_function_metas() -> Vec<FuncMeta> {
618 FunctionRegistry::<DefaultProcessManager>::with_builtins().native_metas()
619}
620
621pub fn std_module_table() -> oxdock_parser::ModuleTable {
626 let functions: HashSet<String> = builtin_function_metas()
628 .into_iter()
629 .map(|meta| base_name(&meta.name).to_string())
630 .collect();
631 oxdock_parser::ModuleTable {
632 modules: HashMap::from([(
633 STD_MODULE_NAME.to_string(),
634 Some(oxdock_parser::ModuleFuncs { functions }),
635 )]),
636 }
637}
638
639#[oxdock_func(pure, returns = TypeTag::Int)]
652#[example(
653 name = "convert",
654 code = r###"
655 IMPORT [STD]
656 LET $n: INT = INT("42")
657 ASSERT_EQ $n 42
658 LET $flag: INT = INT(true)
659 ASSERT_EQ $flag 1
660 "###
661)]
662fn int(
663 #[union(Int, Float, String, Bool)]
665 val: Value,
666) -> Result<Value> {
667 super::args::int_from_value(val)
668}
669
670#[oxdock_func(pure, returns = TypeTag::Float)]
675#[example(
676 name = "convert",
677 code = r###"
678 IMPORT [STD]
679 LET $f: FLOAT = FLOAT("1.5")
680 ASSERT_EQ $f 1.5
681 LET $whole: FLOAT = FLOAT(2)
682 ASSERT_EQ $whole 2.0
683 "###
684)]
685fn float(
686 #[union(Float, Int, String)]
688 val: Value,
689) -> Result<Value> {
690 super::args::float_from_value(val)
691}
692
693#[oxdock_func(pure, returns = TypeTag::String)]
698#[example(
699 name = "format and round-trip",
700 code = r###"
701 # Byte counts render in the largest exact unit.
702 IMPORT [STD]
703 LET $pretty: STRING = FORMAT_BYTE_COUNT(1_048_576)
704 ASSERT_EQ $pretty "1MiB"
705
706 # The pair round-trips through the parser.
707 LET $back: INT = PARSE_BYTE_COUNT($pretty)
708 ASSERT_EQ $back 1_048_576
709 "###
710)]
711fn format_byte_count(
712 bytes: i64,
714) -> Result<Value> {
715 if bytes < 0 {
716 return Err(anyhow::anyhow!(
717 "FORMAT_BYTE_COUNT needs a non-negative byte count, got {bytes}"
718 ));
719 }
720 Ok(Value::string(oxdock_parser::command::format_byte_count(
721 bytes as u64,
722 )))
723}
724
725#[oxdock_func(pure, returns = TypeTag::Int)]
760#[example(
761 name = "parse",
762 code = r###"
763 IMPORT [STD]
764 LET $n: INT = PARSE_BYTE_COUNT("10KB")
765 ASSERT_EQ $n 10_000
766 LET $identity: INT = PARSE_BYTE_COUNT(512)
767 ASSERT_EQ $identity 512
768 "###
769)]
770fn parse_byte_count(
771 #[union(Int, Float, String)]
773 text: Value,
774) -> Result<Value> {
775 if let Some(n) = text.as_i64() {
776 if n < 0 {
777 return Err(anyhow::anyhow!(
778 "PARSE_BYTE_COUNT needs a non-negative byte count, got {n}"
779 ));
780 }
781 return Ok(Value::int(n));
782 }
783 if let Some(f) = text.as_f64() {
784 if f.is_finite() && f.fract() == 0.0 && f >= 0.0 && f <= i64::MAX as f64 {
785 return Ok(Value::int(f as i64));
786 }
787 return Err(anyhow::anyhow!(
788 "PARSE_BYTE_COUNT needs an integral byte count, got {f:?}"
789 ));
790 }
791 let Some(s) = text.as_str() else {
792 return Err(anyhow::anyhow!(
793 "PARSE_BYTE_COUNT needs a token or number, found {text:?}"
794 ));
795 };
796 let n = oxdock_parser::command::parse_byte_count(s)?;
797 let n = i64::try_from(n)
798 .map_err(|_| anyhow::anyhow!("PARSE_BYTE_COUNT out of INT range: {s:?}"))?;
799 Ok(Value::int(n))
800}
801
802#[oxdock_func(pure, returns = TypeTag::String)]
807#[example(
808 name = "format and round-trip",
809 code = r###"
810 # Durations render in the largest exact unit.
811 IMPORT [STD]
812 LET $pretty: STRING = FORMAT_DURATION(90_000)
813 ASSERT_EQ $pretty "90s"
814
815 # The pair round-trips through the parser.
816 LET $back: INT = PARSE_DURATION($pretty)
817 ASSERT_EQ $back 90_000
818 "###
819)]
820fn format_duration(
821 millis: i64,
823) -> Result<Value> {
824 if millis < 0 {
825 return Err(anyhow::anyhow!(
826 "FORMAT_DURATION needs non-negative milliseconds, got {millis}"
827 ));
828 }
829 Ok(Value::string(oxdock_parser::command::format_duration(
830 &std::time::Duration::from_millis(millis as u64),
831 )))
832}
833
834#[oxdock_func(pure, returns = TypeTag::Int)]
840#[example(
841 name = "parse",
842 code = r###"
843 # A bare number means seconds, like TIMEOUT.
844 IMPORT [STD]
845 LET $ms: INT = PARSE_DURATION("2m")
846 ASSERT_EQ $ms 120_000
847
848 # Milliseconds stay exact.
849 LET $exact: INT = PARSE_DURATION("1500ms")
850 ASSERT_EQ $exact 1_500
851
852 # One optional space separates number from unit.
853 LET $spaced: INT = PARSE_DURATION("1 h")
854 ASSERT_EQ $spaced 3_600_000
855 "###
856)]
857fn parse_duration(
858 text: String,
860) -> Result<Value> {
861 let duration = oxdock_parser::command::parse_duration(&text)?;
862 let millis = i64::try_from(duration.as_millis())
863 .map_err(|_| anyhow::anyhow!("PARSE_DURATION out of INT range: {text:?}"))?;
864 Ok(Value::int(millis))
865}
866
867#[oxdock_func(rpn, returns = TypeTag::ListOf(std::sync::Arc::new(TypeTag::String)))]
872#[example(
873 name = "match",
874 code = r###"
875 IMPORT [STD]
876 WRITE "notes-a.md" "a"
877 WRITE "notes-b.md" "b"
878 WRITE "other.txt" "c"
879 LET $found: LIST<STRING> = GLOB("notes-*.md")
880 ASSERT_EQ $found.0 "notes-a.md"
881 ASSERT_EQ $found.1 "notes-b.md"
882 "###
883)]
884fn glob<P: ProcessManager>(
885 cx: &mut StepCtx<P>,
886 #[union(String, Path)]
888 pattern: Value,
889) -> Result<Value> {
890 let text = super::args::string_or_path_text(&pattern)?;
891 super::args::glob_from_value(&[Value::string(text)], cx)
892}
893
894#[oxdock_func(rpn, returns = TypeTag::MapOf(std::sync::Arc::new(TypeTag::Any)))]
899#[example(
900 name = "load",
901 code = r###"
902 IMPORT [STD]
903 WRITE "cfg.toml" "title = \"demo\""
904 LET $cfg: MAP<ANY> = LOAD_TOML("cfg.toml")
905 ASSERT_EQ $cfg.title "demo"
906 "###
907)]
908fn load_toml<P: ProcessManager>(
909 cx: &mut StepCtx<P>,
910 #[union(String, Path)]
912 path: Value,
913) -> Result<Value> {
914 let text = super::args::string_or_path_text(&path)?;
915 super::args::load_toml_from_value(&[Value::string(text)], cx)
916}
917
918#[oxdock_func(rpn, returns = TypeTag::Any)]
926#[example(
927 name = "load",
928 code = r###"
929 IMPORT [STD]
930 WRITE "data.json" "{\"a\": 1}"
931 LET $doc: MAP<ANY> = LOAD_JSON("data.json")
932 ASSERT_EQ $doc.a 1
933 "###
934)]
935fn load_json<P: ProcessManager>(
936 cx: &mut StepCtx<P>,
937 #[union(String, Path)]
939 path: Value,
940) -> Result<Value> {
941 let text = super::args::string_or_path_text(&path)?;
942 super::args::load_json_from_value(&[Value::string(text)], cx)
943}
944
945#[oxdock_func(pure, returns = TypeTag::MapOf(std::sync::Arc::new(TypeTag::Any)))]
951#[example(
952 name = "parse",
953 code = r###"
954 IMPORT [STD]
955 LET $doc: MAP<ANY> = PARSE_TOML("title = \"demo\"")
956 ASSERT_EQ $doc.title "demo"
957 "###
958)]
959fn parse_toml(
960 text: String,
962) -> Result<Value> {
963 super::args::parse_toml_from_value(Value::string(text))
964}
965
966#[oxdock_func(pure, returns = TypeTag::Any)]
975#[example(
976 name = "parse",
977 code = r###"
978 # Parse in-memory JSON text with the same conversion as file loading.
979 IMPORT [STD]
980 LET $body: STRING = "{\"a\": 1}"
981 LET $doc: ANY = PARSE_JSON($body)
982 ASSERT_EQ $doc.a 1
983
984 # Top-level arrays parse to LIST, which is why the return is ANY.
985 LET $items: LIST<ANY> = PARSE_JSON("[1, 2]")
986 ASSERT_EQ $items.0 1
987 ASSERT_EQ $items.1 2
988 "###
989)]
990fn parse_json(
991 text: String,
993) -> Result<Value> {
994 super::args::parse_json_from_value(Value::string(text))
995}
996
997#[oxdock_func(returns = TypeTag::String)]
1003#[example(
1004 name = "describe",
1005 code = r###"
1006 IMPORT [STD]
1007 WRITE "entry.txt" "words"
1008 LET $kind: STRING = PATH_TYPE("entry.txt")
1009 ASSERT_EQ $kind "file"
1010 LET $missing: STRING = PATH_TYPE("no-such-entry.txt")
1011 ASSERT_EQ $missing "absent"
1012 "###
1013)]
1014fn path_type<P: ProcessManager>(
1015 cx: &mut StepCtx<P>,
1016 #[union(String, Path)]
1018 path: Value,
1019) -> Result<Value> {
1020 let text = super::args::string_or_path_text(&path)?;
1021 super::args::path_type_from_value(&[Value::string(text)], cx)
1022}
1023
1024#[oxdock_func(returns = TypeTag::Bool)]
1033#[example(
1034 name = "probe",
1035 code = r###"
1036 # An absent nested path is writable when its ancestor is.
1037 IMPORT [STD]
1038 LET $fresh: BOOL = PATH_WRITABLE("probe-check/nested/file.txt")
1039 ASSERT_EQ $fresh true
1040
1041 # The empty string never aliases the working directory.
1042 LET $empty: BOOL = PATH_WRITABLE("")
1043 ASSERT_EQ $empty false
1044 "###
1045)]
1046fn path_writable<P: ProcessManager>(
1047 cx: &mut StepCtx<P>,
1048 #[union(String, Path)]
1050 path: Value,
1051) -> Result<Value> {
1052 let text = super::args::string_or_path_text(&path)?;
1053 super::args::path_writable_from_value(&[Value::string(text)], cx)
1054}
1055
1056#[oxdock_func(returns = TypeTag::Bool)]
1069#[example(
1070 name = "probe",
1071 code = r###"
1072 # Missing tools read false instead of failing the run.
1073 IMPORT [STD]
1074 LET $missing: BOOL = IS_EXEC("no-such-tool-xyz")
1075 ASSERT_EQ $missing false
1076
1077 # Plain files are not executable on any platform.
1078 WRITE tool.txt payload
1079 LET $plain: BOOL = IS_EXEC("tool.txt")
1080 ASSERT_EQ $plain false
1081 "###
1082)]
1083fn is_exec<P: ProcessManager>(
1084 cx: &mut StepCtx<P>,
1085 #[union(String, Path)]
1087 name: Value,
1088) -> Result<Value> {
1089 let text = super::args::string_or_path_text(&name)?;
1090 super::args::is_exec_from_value(&[Value::string(text)], cx)
1091}
1092
1093#[oxdock_func(pure, returns = TypeTag::Bool)]
1099#[example(
1100 name = "probe",
1101 code = r###"
1102 IMPORT [STD]
1103 LET $m: MAP<ANY> = PARSE_JSON("{\"a\": 1}")
1104 LET $hit: BOOL = HAS_KEY($m, "a")
1105 ASSERT_EQ $hit true
1106 LET $miss: BOOL = HAS_KEY($m, "b")
1107 ASSERT_EQ $miss false
1108 "###
1109)]
1110fn has_key(
1111 map: BTreeMap<String, Value>,
1113 key: String,
1115) -> Result<Value> {
1116 super::args::has_key_from_value(Value::map(map), &key)
1117}
1118
1119#[oxdock_func(pure, returns = TypeTag::MapOf(std::sync::Arc::new(TypeTag::Any)))]
1125#[example(
1126 name = "insert",
1127 code = r###"
1128 IMPORT [STD]
1129 LET $m: MAP<ANY> = MAP_SET({seed: 0}, "a", 1)
1130 ASSERT_EQ $m.a 1
1131 "###
1132)]
1133fn map_set(
1134 map: BTreeMap<String, Value>,
1136 key: String,
1138 value: Value,
1140) -> Result<Value> {
1141 super::args::map_set_from_value(Value::map(map), key, value)
1142}
1143
1144#[oxdock_func(returns = TypeTag::Float, summary = "Draw a random FLOAT uniformly from [0, 1), optionally seeded.")]
1152#[example(
1153 name = "seeded draw",
1154 code = r###"
1155 # A seed draws the same value on every run.
1156 IMPORT [STD]
1157 LET $one: FLOAT = RAND({seed: 7})
1158 LET $two: FLOAT = RAND({seed: 7})
1159 ASSERT_EQ $one $two
1160 "###
1161)]
1162#[example(
1163 name = "unseeded draw",
1164 code = r###"
1165 # Scale a unit draw into a backoff delay between 1 and 11 seconds.
1166 IMPORT [STD]
1167 LET $draw: FLOAT = RAND()
1168 LET $delay: FLOAT = 1.0 + $draw * 10.0
1169 IF $delay < 1.0 {
1170 EXIT 1
1171 }
1172 IF $delay >= 11.0 {
1173 EXIT 1
1174 }
1175 ECHO "retrying in {{ $delay }}s"
1176 "###
1177)]
1178fn rand<P: ProcessManager>(
1179 cx: &mut StepCtx<P>,
1180 #[options("seed?: INT")]
1182 #[optional]
1183 options: BTreeMap<String, Value>,
1184) -> Result<Value> {
1185 let _ = cx;
1186 let seed = options
1189 .get("seed")
1190 .map(|value| value.as_i64().expect("check_options verified INT"));
1191 super::args::rand_float_from_value(seed)
1192}
1193
1194#[oxdock_func(pure, returns = TypeTag::String)]
1200#[example(
1201 name = "encode",
1202 code = r###"
1203 # Encode text to standard base64.
1204 IMPORT [STD]
1205 LET $encoded: STRING = BASE64_ENCODE("hello")
1206 ASSERT_EQ $encoded "aGVsbG8="
1207 "###
1208)]
1209fn base64_encode(
1210 text: String,
1212) -> Result<Value> {
1213 super::args::base64_encode_from_value(Value::string(text))
1214}
1215
1216#[oxdock_func(pure, returns = TypeTag::String)]
1223#[example(
1224 name = "decode",
1225 code = r###"
1226 # Decode standard base64 back to text.
1227 IMPORT [STD]
1228 LET $decoded: STRING = BASE64_DECODE("aGVsbG8=")
1229 ASSERT_EQ $decoded "hello"
1230 "###
1231)]
1232fn base64_decode(
1233 text: String,
1235) -> Result<Value> {
1236 super::args::base64_decode_from_value(Value::string(text))
1237}
1238
1239#[oxdock_func(pure, returns = TypeTag::String)]
1246#[example(
1247 name = "encode",
1248 code = r###"
1249 IMPORT [STD]
1250 LET $json: STRING = TO_JSON({a: 1})
1251 ASSERT_EQ $json "{\"a\":1}\n"
1252 "###
1253)]
1254fn to_json(
1255 #[union(String, Int, Float, Bool, List, Map)]
1257 value: Value,
1258) -> Result<Value> {
1259 super::args::to_json_from_value(value)
1260}
1261
1262#[oxdock_func(pure, returns = TypeTag::String)]
1270#[example(
1271 name = "name the word",
1272 code = r###"
1273 IMPORT [STD]
1274 LET $word: STRING = TYPE_OF(42)
1275 ASSERT_EQ $word "INT"
1276 "###
1277)]
1278fn type_of(
1279 value: Value,
1281) -> Result<Value> {
1282 super::args::type_of_from_value(value)
1283}
1284
1285#[oxdock_func(pure, returns = TypeTag::MapOf(std::sync::Arc::new(TypeTag::Any)))]
1293#[example(
1294 name = "merge",
1295 code = r###"
1296 IMPORT [STD]
1297 LET $m: MAP<ANY> = MERGE_MAPS([{a: 1}, {b: 2}], "overwrite")
1298 ASSERT_EQ $m.a 1
1299 ASSERT_EQ $m.b 2
1300 "###
1301)]
1302fn merge_maps(
1303 maps: Vec<BTreeMap<String, Value>>,
1305 #[values("fail_on_duplicate", "overwrite")]
1307 policy: String,
1308) -> Result<Value> {
1309 super::args::merge_maps_from_value(
1310 Value::list(maps.into_iter().map(Value::map).collect()),
1311 policy,
1312 )
1313}
1314
1315#[oxdock_func(returns = TypeTag::ListOf(std::sync::Arc::new(TypeTag::String)))]
1320#[example(
1321 name = "list",
1322 code = r###"
1323 IMPORT [STD]
1324 LET $names: LIST<STRING> = FUNCTIONS()
1325 ASSERT_CONTAINS $names "STD::INT"
1326 "###
1327)]
1328fn functions<P: ProcessManager>(cx: &mut StepCtx<P>) -> Result<Value> {
1329 let mut names: Vec<String> = cx
1330 .state
1331 .list_functions()
1332 .into_iter()
1333 .map(|meta| meta.name)
1334 .collect();
1335 names.sort();
1336 names.dedup();
1337 Ok(Value::list(names.into_iter().map(Value::string).collect()))
1338}
1339
1340#[oxdock_func(
1355 returns = TypeTag::Record(std::sync::Arc::from([Field {
1356 name: "name".to_string(),
1357 ty: TypeTag::String,
1358 docs: "Qualified function name.",
1359 optional: false,
1360 }, Field {
1361 name: "module".to_string(),
1362 ty: TypeTag::String,
1363 docs: "Owning module.",
1364 optional: false,
1365 }, Field {
1366 name: "kind".to_string(),
1367 ty: TypeTag::String,
1368 docs: "Origin label (`host` or `script`).",
1369 optional: false,
1370 }, Field {
1371 name: "params".to_string(),
1372 ty: TypeTag::ListOf(std::sync::Arc::new(TypeTag::MapOf(std::sync::Arc::new(
1373 TypeTag::Any,
1374 )))),
1375 docs: "Parameter entries (empty for parameterless functions).",
1376 optional: false,
1377 }, Field {
1378 name: "returns".to_string(),
1379 ty: TypeTag::String,
1380 docs: "Structural return shape (empty when untagged).",
1381 optional: false,
1382 }, Field {
1383 name: "rpn".to_string(),
1384 ty: TypeTag::Bool,
1385 docs: "True when callable in RPN position.",
1386 optional: false,
1387 }, Field {
1388 name: "summary".to_string(),
1389 ty: TypeTag::String,
1390 docs: "One-line description.",
1391 optional: false,
1392 }]))
1393 summary = "Describe one function by qualified name."
1394)]
1395#[example(
1396 name = "describe",
1397 code = r###"
1398 IMPORT [STD]
1399 LET $info: MAP<ANY> = DESCRIBE("STD::INT")
1400 ASSERT_EQ $info.name "STD::INT"
1401 ASSERT_EQ $info.returns "INT"
1402 "###
1403)]
1404fn describe<P: ProcessManager>(
1405 cx: &mut StepCtx<P>,
1406 name: String,
1408) -> Result<Value> {
1409 if split_qualified(&name).is_none() && name != KEYWORD_INSPECT {
1410 anyhow::bail!(
1411 "unknown function `{name}`: DESCRIBE requires a qualified name (e.g. `STD::{name}`)"
1412 );
1413 }
1414 cx.state
1415 .describe_function(&name)
1416 .ok_or_else(|| anyhow::anyhow!("unknown function {name}"))
1417}
1418
1419#[oxdock_func(returns = TypeTag::ListOf(std::sync::Arc::new(TypeTag::String)))]
1425#[example(
1426 name = "list",
1427 code = r###"
1428 IMPORT [STD]
1429 LET $names: LIST<STRING> = TYPES()
1430 ASSERT_CONTAINS $names "STRING"
1431 "###
1432)]
1433fn types<P: ProcessManager>(cx: &mut StepCtx<P>) -> Result<Value> {
1434 Ok(Value::list(
1435 cx.state
1436 .type_names()
1437 .into_iter()
1438 .map(Value::string)
1439 .collect(),
1440 ))
1441}
1442
1443#[oxdock_func(returns = TypeTag::Record(std::sync::Arc::from([Field {
1449 name: "name".to_string(),
1450 ty: TypeTag::String,
1451 docs: "Queried type name.",
1452 optional: false,
1453}, Field {
1454 name: "summary".to_string(),
1455 ty: TypeTag::String,
1456 docs: "One-line description.",
1457 optional: false,
1458}, Field {
1459 name: "docs".to_string(),
1460 ty: TypeTag::String,
1461 docs: "Full documentation text.",
1462 optional: false,
1463}])))]
1464#[example(
1465 name = "describe",
1466 code = r###"
1467 IMPORT [STD]
1468 LET $info: MAP<ANY> = TYPE_DESCRIBE("STRING")
1469 ASSERT_EQ $info.name "STRING"
1470 "###
1471)]
1472fn type_describe<P: ProcessManager>(
1473 cx: &mut StepCtx<P>,
1474 name: String,
1476) -> Result<Value> {
1477 if let Some(descriptor) = cx.state.describe_type(&name) {
1478 let mut map = BTreeMap::new();
1479 map.insert(
1480 "name".to_string(),
1481 Value::string(descriptor.name.to_string()),
1482 );
1483 map.insert(
1484 "summary".to_string(),
1485 Value::string(descriptor.summary.to_string()),
1486 );
1487 map.insert(
1488 "docs".to_string(),
1489 Value::string(descriptor.docs.to_string()),
1490 );
1491 return Ok(Value::map(map));
1492 }
1493 if let Some(target) = cx.state.alias_target(&name) {
1496 let mut map = BTreeMap::new();
1497 map.insert("name".to_string(), Value::string(name.clone()));
1498 map.insert(
1499 "summary".to_string(),
1500 Value::string(format!("Script type alias for {target}.")),
1501 );
1502 map.insert(
1503 "docs".to_string(),
1504 Value::string(format!(
1505 "Declared with TYPE {name} = {target}. The alias expands structurally at every declaration."
1506 )),
1507 );
1508 return Ok(Value::map(map));
1509 }
1510 Err(anyhow::anyhow!("unknown type {name}"))
1511}
1512
1513#[oxdock_func(returns = TypeTag::Bool)]
1527#[example(
1528 name = "null stdin",
1529 code = r###"
1530 # A null stdin is never a terminal, in every harness.
1531 IMPORT [STD]
1532 LET $term: BOOL = IS_TERMINAL("stdin")
1533 ASSERT_EQ $term false
1534 "###
1535)]
1536fn is_terminal<P: ProcessManager>(
1537 cx: &mut StepCtx<P>,
1538 #[values("stdin", "stdout", "stderr")]
1540 stream_name: String,
1541) -> Result<Value> {
1542 use std::io::IsTerminal;
1543 let terminal = match stream_name.as_str() {
1544 "stdin" => {
1545 if cx.stdin_pipe.is_some() {
1550 false
1551 } else {
1552 match &cx.stdin {
1553 CommandStdin::Null => false,
1554 #[cfg(not(miri))]
1555 CommandStdin::OsPipe(_) => false,
1556 CommandStdin::Stream(_) => false,
1557 CommandStdin::Inherit => std::io::stdin().is_terminal(),
1558 }
1559 }
1560 }
1561 "stdout" => {
1562 if cx.out_pipe.is_some() {
1563 false
1565 } else if cx.state.io.stdout().is_some() {
1566 false
1569 } else {
1570 match &cx.out {
1571 None => std::io::stdout().is_terminal(),
1573 #[cfg(not(miri))]
1575 Some(StreamHandle::Os(_)) => false,
1576 Some(StreamHandle::Stream(_)) => std::io::stdout().is_terminal(),
1586 }
1587 }
1588 }
1589 "stderr" => {
1590 if cx.state.io.stderr().is_some() {
1591 false
1593 } else {
1594 match &cx.err {
1595 None => std::io::stderr().is_terminal(),
1597 #[cfg(not(miri))]
1599 Some(StreamHandle::Os(_)) => false,
1600 Some(StreamHandle::Stream(_)) => false,
1603 }
1604 }
1605 }
1606 _ => anyhow::bail!(
1607 "IS_TERMINAL expects \"stdin\", \"stdout\", or \"stderr\", got {stream_name:?}"
1612 ),
1613 };
1614 Ok(Value::bool(terminal))
1615}
1616
1617#[oxdock_func(returns = TypeTag::Semaphore)]
1625#[example(
1626 name = "mint",
1627 code = r###"
1628 # Mint a semaphore admitting at most two holders.
1629 IMPORT [STD]
1630 LET $sem: SEMAPHORE = SEMAPHORE_NEW(2)
1631
1632 # A fresh semaphore reports its full cap as available.
1633 LET $free: INT = SEMAPHORE_AVAILABLE($sem)
1634 ASSERT_EQ $free 2
1635 "###
1636)]
1637fn semaphore_new<P: ProcessManager>(
1638 cx: &mut StepCtx<P>,
1639 max: i64,
1641) -> Result<Value> {
1642 let _ = cx;
1643 if max <= 0 {
1644 return Err(anyhow::anyhow!(
1645 "SEMAPHORE_NEW() requires a positive max, got {max}"
1646 ));
1647 }
1648 Ok(Value::semaphore(max as usize))
1649}
1650
1651#[oxdock_func(returns = TypeTag::Record(std::sync::Arc::from([Field {
1660 name: "held".to_string(),
1661 ty: TypeTag::Bool,
1662 docs: "`true` with the permit under `permit`, `false` with no `permit` key.",
1663 optional: false,
1664}, Field {
1665 name: "permit".to_string(),
1666 ty: TypeTag::Permit,
1667 docs: "Permit handle; read only when `held`.",
1668 optional: true,
1669}])))]
1670#[example(
1671 name = "acquire",
1672 code = r###"
1673 # First acquire holds with a permit to bind.
1674 IMPORT [STD]
1675 LET $sem: SEMAPHORE = SEMAPHORE_NEW(1)
1676 LET $first: MAP<held: BOOL, permit?: PERMIT> = SEMAPHORE_TRY_ACQUIRE($sem)
1677 ASSERT_EQ $first.held true
1678 LET $permit: PERMIT = $first.permit
1679
1680 # A capped semaphore answers held false with no permit key.
1681 LET $second: MAP<held: BOOL, permit?: PERMIT> = SEMAPHORE_TRY_ACQUIRE($sem)
1682 ASSERT_EQ $second.held false
1683 LET $has_permit: BOOL = HAS_KEY($second, "permit")
1684 ASSERT_EQ $has_permit false
1685 "###
1686)]
1687fn semaphore_try_acquire<P: ProcessManager>(
1688 cx: &mut StepCtx<P>,
1689 sem: Arc<SemaphoreState>,
1691) -> Result<Value> {
1692 let _ = cx;
1693 let mut map = BTreeMap::new();
1694 if sem.try_acquire() {
1695 map.insert("held".to_string(), Value::bool(true));
1696 map.insert("permit".to_string(), Value::permit(&sem));
1697 } else {
1698 map.insert("held".to_string(), Value::bool(false));
1699 }
1700 Ok(Value::map(map))
1701}
1702
1703#[oxdock_func(pure, returns = TypeTag::Int)]
1710#[example(
1711 name = "readout",
1712 code = r###"
1713 # Hold one permit on a cap of two.
1714 IMPORT [STD]
1715 LET $sem: SEMAPHORE = SEMAPHORE_NEW(2)
1716 LET $acq: MAP<held: BOOL, permit?: PERMIT> = SEMAPHORE_TRY_ACQUIRE($sem)
1717 ASSERT_EQ $acq.held true
1718
1719 # One held permit leaves exactly one free.
1720 LET $free: INT = SEMAPHORE_AVAILABLE($sem)
1721 ASSERT_EQ $free 1
1722 "###
1723)]
1724fn semaphore_available(
1725 sem: Arc<SemaphoreState>,
1727) -> Result<Value> {
1728 Ok(Value::int(sem.available() as i64))
1729}
1730
1731#[oxdock_func(returns = TypeTag::Bool)]
1742#[example(
1743 name = "drain to end",
1744 code = r###"
1745 # Capture two lines, then drain to end of stream with no sentinel line.
1746 IMPORT [STD]
1747 LET $cap: PIPE
1748 WITH_IO [stdout=$cap] {
1749 ECHO "one"
1750 ECHO "two"
1751 }
1752
1753 # The loop exits on close, and the count proves both lines drained.
1754 LET $n: INT = 0
1755 WHILE !EOF($cap) {
1756 WITH_IO [stdin=$cap] READ_LINE $line
1757 $n = $n + 1
1758 }
1759 ASSERT_EQ $n 2
1760 "###
1761)]
1762fn eof<P: ProcessManager>(
1763 cx: &mut StepCtx<P>,
1764 pipe: PipeHandle,
1766) -> Result<Value> {
1767 let info = cx.state.io.inspect_pipe(&pipe);
1768 Ok(Value::bool(info.closed && info.buffered == 0))
1769}
1770
1771fn meta_to_value(meta: &FuncMeta) -> Value {
1772 let mut map = BTreeMap::new();
1773 map.insert("name".to_string(), Value::string(meta.name.clone()));
1774 map.insert("module".to_string(), Value::string(meta.module.clone()));
1775 map.insert(
1776 "kind".to_string(),
1777 Value::string(meta.kind.label().to_string()),
1778 );
1779 let params = match &meta.params {
1780 Some(params) => Value::list(
1781 params
1782 .iter()
1783 .map(|p| {
1784 let mut entry = BTreeMap::new();
1785 entry.insert("name".to_string(), Value::string(p.name.clone()));
1786 entry.insert(
1787 "param_type".to_string(),
1788 Value::string(
1789 p.param_type
1790 .as_ref()
1791 .map(render_structural)
1792 .unwrap_or_default(),
1793 ),
1794 );
1795 entry.insert(
1796 "allowed".to_string(),
1797 Value::string(
1798 p.allowed
1799 .map(|values| values.join(", "))
1800 .unwrap_or_default(),
1801 ),
1802 );
1803 entry.insert("docs".to_string(), Value::string(String::new()));
1804 entry.insert("optional".to_string(), Value::bool(p.optional));
1805 entry.insert(
1806 "options".to_string(),
1807 match p.options {
1808 Some(keys) => Value::list(
1809 keys.iter()
1810 .map(|key| {
1811 let mut option = BTreeMap::new();
1812 option.insert(
1813 "name".to_string(),
1814 Value::string(key.name.to_string()),
1815 );
1816 option.insert(
1817 "value_type".to_string(),
1818 Value::string(render_structural(&key.value)),
1819 );
1820 option.insert(
1821 "required".to_string(),
1822 Value::bool(key.required),
1823 );
1824 option.insert(
1825 "default".to_string(),
1826 Value::string(
1827 key.default.unwrap_or_default().to_string(),
1828 ),
1829 );
1830 Value::map(option)
1831 })
1832 .collect(),
1833 ),
1834 None => Value::string(String::new()),
1835 },
1836 );
1837 Value::map(entry)
1838 })
1839 .collect(),
1840 ),
1841 None => Value::list(Vec::new()),
1845 };
1846 map.insert("params".to_string(), params);
1847 map.insert(
1848 "returns".to_string(),
1849 Value::string(
1850 meta.returns
1851 .as_ref()
1852 .map(render_structural)
1853 .unwrap_or_default(),
1854 ),
1855 );
1856 map.insert("rpn".to_string(), Value::bool(meta.rpn));
1857 map.insert(
1858 "summary".to_string(),
1859 Value::string(meta.summary.to_string()),
1860 );
1861 Value::map(map)
1862}
1863
1864#[derive(Debug, Clone)]
1868pub struct RecordSchema {
1869 pub name: &'static str,
1870 pub fields: std::sync::Arc<[Field]>,
1871}
1872
1873#[derive(Clone)]
1877pub struct HostModule<P: ProcessManager> {
1878 pub name: String,
1879 pub funcs: Vec<HostRegistration<P>>,
1880 pub types: Vec<&'static TypeDescriptor>,
1881 pub record_schemas: Vec<RecordSchema>,
1882 pub states: Vec<ModuleState>,
1889}
1890
1891#[derive(Clone)]
1895pub struct ModuleState {
1896 id: std::any::TypeId,
1897 state: std::sync::Arc<dyn std::any::Any + Send + Sync>,
1898}
1899
1900pub type PreRunInspector = dyn Fn(&[Step]) -> Result<()> + Send + Sync;
1904
1905#[derive(Clone)]
1911pub struct PreRunCheck {
1912 check: Arc<PreRunInspector>,
1913}
1914
1915impl PreRunCheck {
1916 pub fn new(check: impl Fn(&[Step]) -> Result<()> + Send + Sync + 'static) -> Self {
1918 Self {
1919 check: Arc::new(check),
1920 }
1921 }
1922
1923 pub fn run(&self, steps: &[Step]) -> Result<()> {
1925 (self.check)(steps)
1926 }
1927}
1928
1929impl<P: ProcessManager> HostModule<P> {
1930 pub fn with_state<T: Send + Sync + 'static>(mut self, state: std::sync::Arc<T>) -> Self {
1933 self.states.push(ModuleState {
1934 id: std::any::TypeId::of::<T>(),
1935 state,
1936 });
1937 self
1938 }
1939
1940 pub fn check_pre_run(&self, steps: &[Step]) -> Result<()> {
1944 for state in &self.states {
1945 if let Some(check) = state.state.downcast_ref::<PreRunCheck>() {
1946 check.run(steps)?;
1947 }
1948 }
1949 Ok(())
1950 }
1951}
1952
1953impl<P: ProcessManager> ExecState<P> {
1954 pub fn register_module(&mut self, module: HostModule<P>) {
1957 for registration in module.funcs {
1958 match registration {
1959 HostRegistration::Stateful { name, meta, func } => {
1960 self.functions.register_host(&module.name, name, meta, func);
1961 }
1962 HostRegistration::Pure { name, meta, func } => {
1963 self.functions
1964 .register_pure_host(&module.name, name, meta, func);
1965 }
1966 }
1967 }
1968 for descriptor in module.types {
1969 self.register_type(descriptor);
1970 }
1971 for schema in module.record_schemas {
1972 self.register_record_schema(schema.name, schema.fields);
1973 }
1974 for state in module.states {
1975 self.module_states
1976 .insert((module.name.clone(), state.id), state.state);
1977 }
1978 }
1979
1980 pub fn list_functions(&self) -> Vec<FuncMeta> {
1982 let mut out: Vec<FuncMeta> = self.functions.entries_metas().into_iter().collect();
1983 if !out.iter().any(|m| m.name == KEYWORD_INSPECT) {
1985 out.push(FuncMeta {
1986 name: KEYWORD_INSPECT.to_string(),
1987 module: STD_MODULE_NAME.to_string(),
1988 kind: FuncKind::HostCtx,
1989 params: None,
1990 returns: Some(TypeTag::Map),
1991 rpn: false,
1992 summary: "Inspect a variable binding.",
1993 docs: "INSPECT($var): dedicated AST node taking a variable, not a value.",
1994 examples: &[],
1995 });
1996 }
1997 out.sort_by(|a, b| a.name.cmp(&b.name));
1998 out
1999 }
2000
2001 pub fn describe_function(&self, name: &str) -> Option<Value> {
2003 if let Some(meta) = self.functions.meta(name) {
2004 return Some(meta_to_value(&meta));
2005 }
2006 if name == KEYWORD_INSPECT {
2008 return Some(meta_to_value(&FuncMeta {
2009 name: KEYWORD_INSPECT.to_string(),
2010 module: STD_MODULE_NAME.to_string(),
2011 kind: FuncKind::HostCtx,
2012 params: None,
2013 returns: Some(TypeTag::Map),
2014 rpn: false,
2015 summary: "Inspect a variable binding.",
2016 docs: "INSPECT($var): dedicated AST node taking a variable, not a value.",
2017 examples: &[],
2018 }));
2019 }
2020 None
2021 }
2022
2023 pub(super) fn clone_native_pure(&self, name: &str) -> Option<PureFn> {
2024 self.functions.clone_pure_fn(name)
2025 }
2026
2027 pub fn pure_function_table(&self) -> Arc<PureTable> {
2032 self.functions.pure_shared()
2033 }
2034
2035 pub(super) fn clone_native_ctx(&self, name: &str) -> Option<NativeFn<P>> {
2036 self.functions.clone_ctx_fn(name)
2037 }
2038
2039 pub(super) fn native_meta(&self, name: &str) -> Option<FuncMeta> {
2040 self.functions.meta(name)
2041 }
2042}
2043
2044#[cfg(test)]
2045mod tests {
2046 use super::*;
2047
2048 #[test]
2049 fn describe_entry_renders_union_spellings() {
2050 let union = oxdock_parser::union_tag!(String, Pipe);
2056 let meta = FuncMeta {
2057 name: "T::F".to_string(),
2058 module: "T".to_string(),
2059 kind: FuncKind::HostPure,
2060 params: Some(vec![FuncParam {
2061 name: "text".to_string(),
2062 param_type: Some(union.clone()),
2063 allowed: None,
2064 docs: "",
2065 options: None,
2066 optional: false,
2067 }]),
2068 returns: Some(union),
2069 rpn: false,
2070 summary: "test-only",
2071 docs: "test-only",
2072 examples: &[],
2073 };
2074 let value = meta_to_value(&meta);
2075 let map = value.as_map().expect("describe value is a map");
2076 let params = map
2077 .get("params")
2078 .expect("params key")
2079 .as_list()
2080 .expect("params is a list");
2081 let first = params[0].as_map().expect("entry is a map");
2082 assert_eq!(
2083 first.get("param_type").and_then(Value::as_str),
2084 Some("STRING|PIPE"),
2085 "param renders the set"
2086 );
2087 assert_eq!(
2088 map.get("returns").and_then(Value::as_str),
2089 Some("STRING|PIPE"),
2090 "returns render the set"
2091 );
2092 }
2093
2094 #[test]
2095 fn describe_entry_carries_optional_flag() {
2096 let meta = FuncMeta {
2100 name: "T::F".to_string(),
2101 module: "T".to_string(),
2102 kind: FuncKind::HostPure,
2103 params: Some(vec![
2104 FuncParam {
2105 name: "url".to_string(),
2106 param_type: Some(TypeTag::String),
2107 allowed: None,
2108 docs: "",
2109 options: None,
2110 optional: false,
2111 },
2112 FuncParam {
2113 name: "options".to_string(),
2114 param_type: Some(TypeTag::Map),
2115 allowed: None,
2116 docs: "",
2117 options: None,
2118 optional: true,
2119 },
2120 ]),
2121 returns: Some(TypeTag::String),
2122 rpn: false,
2123 summary: "test-only",
2124 docs: "test-only",
2125 examples: &[],
2126 };
2127 let value = meta_to_value(&meta);
2128 let map = value.as_map().expect("describe value is a map");
2129 let params = map
2130 .get("params")
2131 .expect("params key")
2132 .as_list()
2133 .expect("params is a list");
2134 assert_eq!(params.len(), 2);
2135 let first = params[0].as_map().expect("entry is a map");
2136 let second = params[1].as_map().expect("entry is a map");
2137 assert_eq!(
2138 first.get("optional").and_then(Value::as_bool),
2139 Some(false),
2140 "required param must read false"
2141 );
2142 assert_eq!(
2143 second.get("optional").and_then(Value::as_bool),
2144 Some(true),
2145 "omittable param must read true"
2146 );
2147 }
2148}