Skip to main content

unitype_runtime/
registry.rs

1//! What proves what, and where it runs.
2//!
3//! Nothing here is discovered. An environment loads a module, and the module
4//! registers what it can prove — either programmatically, for code compiled
5//! into this process, or by handing over a manifest, for everything else. That
6//! is the same act in both cases, which is why an embedder and a standalone
7//! binary need no different arrangement.
8//!
9//! Signatures that carry a body register themselves, since a constructive proof
10//! needs no one to supply it.
11
12use std::collections::{BTreeMap, HashMap};
13use std::path::Path;
14use std::sync::Arc;
15
16use unitype_core::canon::sig_hash;
17use unitype_core::check::CheckedWorkspace;
18use unitype_core::value::Value;
19use unitype_core::{Ident, QualifiedName};
20
21use crate::environment::{Environment, Reach};
22use crate::error::ExecError;
23use crate::implementation::{ImplId, Implementation, Manifest, trivial_cost};
24use crate::interpret::BoxFuture;
25
26/// The entry name given to a signature proved by its own body.
27pub const INTRINSIC_ENTRY: &str = "intrinsic";
28
29/// A function compiled into this process.
30pub type NativeFn =
31    Arc<dyn Fn(Vec<Value>) -> BoxFuture<'static, Result<Value, ExecError>> + Send + Sync>;
32
33/// Why something could not be registered.
34#[derive(thiserror::Error, Debug)]
35pub enum RegistryError {
36    /// Two implementations were given the same name.
37    #[error("`{0}` is already registered")]
38    DuplicateImplementation(ImplId),
39    /// Two environments were given the same name.
40    #[error("environment `{0}` is already registered")]
41    DuplicateEnvironment(Ident),
42    /// An implementation named an environment that was never introduced.
43    #[error("`{id}` runs in `{environment}`, which is not a registered environment")]
44    UnknownEnvironment {
45        /// The implementation.
46        id: ImplId,
47        /// The environment it named.
48        environment: Ident,
49    },
50    /// A manifest could not be read.
51    #[error("invalid manifest: {0}")]
52    Manifest(#[from] serde_json::Error),
53    /// A manifest file could not be read from disk.
54    #[error("could not read {path}: {source}")]
55    Io {
56        /// The file.
57        path: String,
58        /// What went wrong.
59        #[source]
60        source: std::io::Error,
61    },
62}
63
64/// Something that was noticed but did not stop registration.
65#[derive(Clone, Debug, PartialEq, Eq)]
66pub enum RegistryWarning {
67    /// An implementation proves a signature the workspace does not have.
68    ProvesNothing {
69        /// The implementation.
70        id: ImplId,
71        /// What it claimed to prove.
72        sig: QualifiedName,
73    },
74    /// An implementation was written against a signature that has since
75    /// changed, so it is proving something nobody is asking any more.
76    Stale {
77        /// The implementation.
78        id: ImplId,
79        /// The signature as it now stands.
80        sig: QualifiedName,
81    },
82}
83
84impl std::fmt::Display for RegistryWarning {
85    fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
86        match self {
87            RegistryWarning::ProvesNothing { id, sig } => {
88                write!(f, "`{id}` claims to prove `{sig}`, which is not declared")
89            }
90            RegistryWarning::Stale { id, sig } => write!(
91                f,
92                "`{id}` was written against an earlier `{sig}`; the proposition has changed"
93            ),
94        }
95    }
96}
97
98/// Everything known about who proves what.
99#[derive(Default)]
100pub struct Registry {
101    environments: BTreeMap<Ident, Environment>,
102    implementations: Vec<Implementation>,
103    by_sig: HashMap<QualifiedName, Vec<usize>>,
104    by_id: HashMap<ImplId, usize>,
105    native: HashMap<String, NativeFn>,
106}
107
108impl Registry {
109    /// A registry that knows only about this process.
110    pub fn new() -> Self {
111        let mut registry = Self::default();
112        registry
113            .add_environment(Environment::here())
114            .expect("a fresh registry has room for it");
115        registry
116    }
117
118    /// Introduces a place implementations can run.
119    pub fn add_environment(&mut self, environment: Environment) -> Result<(), RegistryError> {
120        if self.environments.contains_key(&environment.id) {
121            return Err(RegistryError::DuplicateEnvironment(environment.id));
122        }
123        self.environments
124            .insert(environment.id.clone(), environment);
125        Ok(())
126    }
127
128    /// Records that something proves a proposition.
129    pub fn register(&mut self, implementation: Implementation) -> Result<(), RegistryError> {
130        if self.by_id.contains_key(&implementation.id) {
131            return Err(RegistryError::DuplicateImplementation(implementation.id));
132        }
133        if !self.environments.contains_key(&implementation.environment) {
134            return Err(RegistryError::UnknownEnvironment {
135                id: implementation.id.clone(),
136                environment: implementation.environment.clone(),
137            });
138        }
139
140        let at = self.implementations.len();
141        self.by_id.insert(implementation.id.clone(), at);
142        self.by_sig
143            .entry(implementation.proves.clone())
144            .or_default()
145            .push(at);
146        self.implementations.push(implementation);
147        Ok(())
148    }
149
150    /// Registers a function compiled into this process, under an entry name
151    /// that an implementation can point at.
152    ///
153    /// This is a module registering itself as an execution source, in the case
154    /// where the module happens to be linked in.
155    pub fn register_native<F, Fut>(&mut self, entry: &str, f: F)
156    where
157        F: Fn(Vec<Value>) -> Fut + Send + Sync + 'static,
158        Fut: std::future::Future<Output = Result<Value, ExecError>> + Send + 'static,
159    {
160        self.native
161            .insert(entry.to_string(), Arc::new(move |args| Box::pin(f(args))));
162    }
163
164    /// The same, for a function that does not need to wait for anything.
165    pub fn register_native_sync<F>(&mut self, entry: &str, f: F)
166    where
167        F: Fn(Vec<Value>) -> Result<Value, ExecError> + Send + Sync + 'static,
168    {
169        let f = Arc::new(f);
170        self.native.insert(
171            entry.to_string(),
172            Arc::new(move |args| {
173                let f = Arc::clone(&f);
174                Box::pin(async move { f(args) })
175            }),
176        );
177    }
178
179    /// Registers every signature that carries its own proof.
180    ///
181    /// A body is an implementation already: it needs no environment beyond this
182    /// process and no one to write it. Derived bridges arrive this way.
183    pub fn register_bodies(&mut self, ws: &CheckedWorkspace) -> Result<usize, RegistryError> {
184        let here = Environment::here().id;
185        let mut added = 0;
186        for (name, sig) in ws.workspace().iter_functions() {
187            if sig.body.is_none() {
188                continue;
189            }
190            let id = ImplId::new(format!("{name}#body"));
191            if self.by_id.contains_key(&id) {
192                continue;
193            }
194            let mut implementation = Implementation::new(
195                id,
196                name.clone(),
197                here.clone(),
198                INTRINSIC_ENTRY,
199                trivial_cost(),
200            );
201            implementation.sig_hash = Some(sig_hash(sig));
202            implementation.notes = Some("Proved by its own body.".to_string());
203            self.register(implementation)?;
204            added += 1;
205        }
206        Ok(added)
207    }
208
209    /// Takes in a module's declaration of what it can prove.
210    ///
211    /// Relative paths inside are resolved against `base`, which is the
212    /// directory the declaration came from, so that a manifest means the same
213    /// thing wherever it is loaded from.
214    pub fn load_manifest(&mut self, text: &str, base: &Path) -> Result<usize, RegistryError> {
215        let manifest: Manifest = serde_json::from_str(text)?;
216
217        for mut environment in manifest.environments {
218            resolve_paths(&mut environment.reach, base);
219            // An environment already introduced is not an error here: two
220            // modules may both know they need Python.
221            if !self.environments.contains_key(&environment.id) {
222                self.add_environment(environment)?;
223            }
224        }
225
226        let count = manifest.implementations.len();
227        for implementation in manifest.implementations {
228            self.register(implementation)?;
229        }
230        Ok(count)
231    }
232
233    /// Reads a manifest from a file.
234    pub fn load_manifest_file(&mut self, path: &Path) -> Result<usize, RegistryError> {
235        let text = std::fs::read_to_string(path).map_err(|source| RegistryError::Io {
236            path: path.display().to_string(),
237            source,
238        })?;
239        let base = path.parent().unwrap_or(Path::new("."));
240        self.load_manifest(&text, base)
241    }
242
243    /// Everything that claims to prove a proposition, in registration order.
244    pub fn proofs_of(&self, sig: &QualifiedName) -> Vec<&Implementation> {
245        self.by_sig
246            .get(sig)
247            .map(|indices| indices.iter().map(|i| &self.implementations[*i]).collect())
248            .unwrap_or_default()
249    }
250
251    /// One implementation, by name.
252    pub fn implementation(&self, id: &ImplId) -> Option<&Implementation> {
253        self.by_id.get(id).map(|i| &self.implementations[*i])
254    }
255
256    /// Every implementation, in registration order.
257    pub fn implementations(&self) -> &[Implementation] {
258        &self.implementations
259    }
260
261    /// One environment, by name.
262    pub fn environment(&self, id: &Ident) -> Option<&Environment> {
263        self.environments.get(id)
264    }
265
266    /// Every environment, by name.
267    pub fn environments(&self) -> impl Iterator<Item = &Environment> {
268        self.environments.values()
269    }
270
271    /// A function compiled into this process, by entry name.
272    pub fn native(&self, entry: &str) -> Option<&NativeFn> {
273        self.native.get(entry)
274    }
275
276    /// Checks what is registered against what the workspace actually declares.
277    ///
278    /// Catches the two ways a registry drifts: an implementation proving
279    /// something nobody declares, and one written against a proposition that
280    /// has since changed out from under it.
281    pub fn check_against(&self, ws: &CheckedWorkspace) -> Vec<RegistryWarning> {
282        let mut out = Vec::new();
283        for implementation in &self.implementations {
284            let Some(sig) = ws.sig(&implementation.proves) else {
285                out.push(RegistryWarning::ProvesNothing {
286                    id: implementation.id.clone(),
287                    sig: implementation.proves.clone(),
288                });
289                continue;
290            };
291            if let Some(claimed) = implementation.sig_hash {
292                if claimed != sig_hash(sig) {
293                    out.push(RegistryWarning::Stale {
294                        id: implementation.id.clone(),
295                        sig: implementation.proves.clone(),
296                    });
297                }
298            }
299        }
300        out
301    }
302}
303
304/// Makes a manifest's relative paths mean the same thing wherever it is loaded.
305fn resolve_paths(reach: &mut Reach, base: &Path) {
306    match reach {
307        Reach::Subprocess { cwd, .. } => {
308            if let Some(dir) = cwd {
309                if dir.is_relative() {
310                    *dir = base.join(&*dir);
311                }
312            } else {
313                *cwd = Some(base.to_path_buf());
314            }
315        }
316        Reach::Wasm { module, .. } => {
317            if module.is_relative() {
318                *module = base.join(&*module);
319            }
320        }
321        Reach::Here | Reach::Remote { .. } => {}
322    }
323}
324
325#[cfg(test)]
326mod tests {
327    use super::*;
328    use unitype_core::check::check_workspace;
329    use unitype_core::{BigO, ImplProfile, Workspace};
330
331    fn ws(json: &str) -> CheckedWorkspace {
332        check_workspace(Workspace::from_json(json).expect("reads")).expect("checks")
333    }
334
335    fn q(s: &str) -> QualifiedName {
336        s.parse().unwrap()
337    }
338
339    fn here() -> Ident {
340        Ident::new("here").unwrap()
341    }
342
343    fn sort_workspace() -> CheckedWorkspace {
344        ws(r#"{"universes":[{"name":"demo","functions":[
345            {"name":"sort","params":[{"name":"xs","ty":"[i64]"}],"ret":"[i64]"}]}]}"#)
346    }
347
348    fn proof(id: &str, time: BigO, space: BigO) -> Implementation {
349        Implementation::new(
350            id,
351            q("demo::sort"),
352            here(),
353            id,
354            ImplProfile::new(time, space),
355        )
356    }
357
358    #[test]
359    fn a_fresh_registry_knows_about_this_process() {
360        let registry = Registry::new();
361        assert!(registry.environment(&here()).is_some());
362        assert_eq!(registry.environments().count(), 1);
363    }
364
365    #[test]
366    fn one_proposition_can_have_several_proofs() {
367        let mut registry = Registry::new();
368        registry
369            .register(proof("merge", BigO::ONLogN, BigO::ON))
370            .expect("registers");
371        registry
372            .register(proof("bubble", BigO::ON2, BigO::O1))
373            .expect("registers");
374
375        assert_eq!(registry.proofs_of(&q("demo::sort")).len(), 2);
376        assert!(registry.proofs_of(&q("demo::missing")).is_empty());
377    }
378
379    #[test]
380    fn two_proofs_cannot_share_a_name() {
381        let mut registry = Registry::new();
382        registry
383            .register(proof("same", BigO::ON, BigO::ON))
384            .unwrap();
385        assert!(matches!(
386            registry.register(proof("same", BigO::O1, BigO::O1)),
387            Err(RegistryError::DuplicateImplementation(_))
388        ));
389    }
390
391    #[test]
392    fn a_proof_cannot_run_somewhere_that_was_never_introduced() {
393        let mut registry = Registry::new();
394        let mut nowhere = proof("stray", BigO::ON, BigO::ON);
395        nowhere.environment = Ident::new("mars").unwrap();
396        assert!(matches!(
397            registry.register(nowhere),
398            Err(RegistryError::UnknownEnvironment { .. })
399        ));
400    }
401
402    #[tokio::test]
403    async fn a_module_compiled_in_registers_itself() {
404        let mut registry = Registry::new();
405        registry.register_native_sync("reverse", |args| {
406            let Some(Value::List(items)) = args.into_iter().next() else {
407                return Err(ExecError::Untyped("expected a list".into()));
408            };
409            Ok(Value::List(items.into_iter().rev().collect()))
410        });
411
412        let f = registry.native("reverse").expect("registered");
413        let out = f(vec![Value::List(vec![Value::Int(1), Value::Int(2)])])
414            .await
415            .expect("runs");
416        assert_eq!(out, Value::List(vec![Value::Int(2), Value::Int(1)]));
417    }
418
419    #[test]
420    fn a_signature_with_a_body_needs_nobody_to_prove_it() {
421        let ws = ws(r#"{"universes":[{"name":"demo","functions":[
422            {"name":"sort","params":[{"name":"xs","ty":"[i64]"}],"ret":"[i64]"},
423            {"name":"echo","params":[{"name":"s","ty":"str"}],"ret":"str",
424             "body":{"k":"var","name":"s"}}]}]}"#);
425
426        let mut registry = Registry::new();
427        assert_eq!(registry.register_bodies(&ws).expect("registers"), 1);
428        assert_eq!(registry.proofs_of(&q("demo::echo")).len(), 1);
429        assert!(
430            registry.proofs_of(&q("demo::sort")).is_empty(),
431            "sorting still needs somebody to write it"
432        );
433    }
434
435    #[test]
436    fn registering_bodies_twice_does_not_double_them() {
437        let ws = ws(r#"{"universes":[{"name":"demo","functions":[
438            {"name":"echo","params":[{"name":"s","ty":"str"}],"ret":"str",
439             "body":{"k":"var","name":"s"}}]}]}"#);
440        let mut registry = Registry::new();
441        registry.register_bodies(&ws).unwrap();
442        assert_eq!(registry.register_bodies(&ws).unwrap(), 0);
443        assert_eq!(registry.proofs_of(&q("demo::echo")).len(), 1);
444    }
445
446    #[test]
447    fn a_manifest_introduces_an_environment_and_what_runs_there() {
448        let mut registry = Registry::new();
449        let count = registry
450            .load_manifest(
451                r#"{"environments":[
452                        {"id":"py","language":"python",
453                         "reach":{"k":"subprocess","command":"python3","args":["impls.py"]}}],
454                    "implementations":[
455                        {"id":"demo.sort.bubble","proves":"demo::sort","environment":"py",
456                         "entry":"bubble_sort","cost":{"time":"o_n2","space":"o1"}}]}"#,
457                Path::new("/project/impls"),
458            )
459            .expect("loads");
460
461        assert_eq!(count, 1);
462        assert!(registry.environment(&Ident::new("py").unwrap()).is_some());
463        assert_eq!(registry.proofs_of(&q("demo::sort")).len(), 1);
464    }
465
466    #[test]
467    fn a_manifest_means_the_same_thing_wherever_it_is_loaded_from() {
468        let mut registry = Registry::new();
469        registry
470            .load_manifest(
471                r#"{"environments":[{"id":"py","language":"python",
472                    "reach":{"k":"subprocess","command":"python3","args":["impls.py"]}}]}"#,
473                Path::new("/project/impls"),
474            )
475            .expect("loads");
476
477        let env = registry.environment(&Ident::new("py").unwrap()).unwrap();
478        let Reach::Subprocess { cwd, .. } = &env.reach else {
479            panic!("expected a subprocess");
480        };
481        assert_eq!(
482            cwd.as_deref(),
483            Some(Path::new("/project/impls")),
484            "a relative command should run where its manifest lives"
485        );
486    }
487
488    #[test]
489    fn two_modules_may_both_know_they_need_python() {
490        let manifest = r#"{"environments":[{"id":"py","language":"python",
491            "reach":{"k":"subprocess","command":"python3"}}]}"#;
492        let mut registry = Registry::new();
493        registry.load_manifest(manifest, Path::new(".")).unwrap();
494        assert!(
495            registry.load_manifest(manifest, Path::new(".")).is_ok(),
496            "the second module should not have to know the first went first"
497        );
498    }
499
500    #[test]
501    fn a_proof_of_something_nobody_declares_is_reported() {
502        let ws = sort_workspace();
503        let mut registry = Registry::new();
504        let mut stray = proof("stray", BigO::ON, BigO::ON);
505        stray.proves = q("demo::nonexistent");
506        registry.register(stray).unwrap();
507
508        assert!(matches!(
509            registry.check_against(&ws).as_slice(),
510            [RegistryWarning::ProvesNothing { .. }]
511        ));
512    }
513
514    #[test]
515    fn a_proof_of_a_proposition_that_has_since_changed_is_reported() {
516        let ws = sort_workspace();
517        let mut registry = Registry::new();
518        let mut written_earlier = proof("merge", BigO::ONLogN, BigO::ON);
519        written_earlier.sig_hash = Some(unitype_core::canon::local_hash(
520            &unitype_core::ir::Type::Bool,
521        ));
522        registry.register(written_earlier).unwrap();
523
524        let warnings = registry.check_against(&ws);
525        assert!(
526            matches!(warnings.as_slice(), [RegistryWarning::Stale { .. }]),
527            "{warnings:?}"
528        );
529        assert!(warnings[0].to_string().contains("has changed"));
530    }
531
532    #[test]
533    fn a_proof_that_still_matches_its_proposition_is_not_reported() {
534        let ws = sort_workspace();
535        let mut registry = Registry::new();
536        let mut current = proof("merge", BigO::ONLogN, BigO::ON);
537        current.sig_hash = ws.sig_hash(&q("demo::sort"));
538        registry.register(current).unwrap();
539
540        assert!(registry.check_against(&ws).is_empty());
541    }
542}