Skip to main content

unitype_runtime/
implementation.rs

1//! A proof: something that answers a proposition.
2//!
3//! An implementation is not the code — it is the claim that some code, in some
4//! environment, answers a particular signature, together with what that costs.
5//! The code itself lives wherever the environment says.
6//!
7//! A signature may have any number of these. That is the arrangement the whole
8//! system is built around: `sort` can be proved by a Rust mergesort and a
9//! Python bubble sort at the same time, and choosing between them at the moment
10//! of the call is a policy decision rather than an architectural one.
11
12use std::fmt;
13
14use serde::{Deserialize, Serialize};
15use unitype_core::canon::TypeId;
16use unitype_core::{BigO, Ident, ImplProfile, Metadata, QualifiedName};
17
18/// What an implementation is called.
19#[derive(Clone, Debug, PartialEq, Eq, Hash, PartialOrd, Ord, Serialize, Deserialize)]
20#[serde(transparent)]
21pub struct ImplId(pub String);
22
23impl ImplId {
24    /// Names an implementation.
25    pub fn new(id: impl Into<String>) -> Self {
26        Self(id.into())
27    }
28
29    /// The name as text.
30    pub fn as_str(&self) -> &str {
31        &self.0
32    }
33}
34
35impl fmt::Display for ImplId {
36    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
37        f.write_str(&self.0)
38    }
39}
40
41impl From<&str> for ImplId {
42    fn from(s: &str) -> Self {
43        Self::new(s)
44    }
45}
46
47/// A claim that something proves a proposition.
48#[derive(Clone, Debug, PartialEq, Serialize, Deserialize)]
49pub struct Implementation {
50    /// What this implementation is called.
51    pub id: ImplId,
52    /// The proposition it claims to prove.
53    pub proves: QualifiedName,
54    /// The address of that proposition when this was registered.
55    ///
56    /// Present, it catches an implementation that was written against a
57    /// signature which has since changed — a proof of something that is no
58    /// longer being asked.
59    #[serde(default, skip_serializing_if = "Option::is_none")]
60    pub sig_hash: Option<TypeId>,
61    /// The environment it runs in.
62    pub environment: Ident,
63    /// What to invoke there. What this means is the environment's business: a
64    /// key for a compiled-in function, a name the harness dispatches on.
65    pub entry: String,
66    /// What it claims to cost.
67    pub cost: ImplProfile,
68    /// Anything worth knowing about it.
69    #[serde(default, skip_serializing_if = "Option::is_none")]
70    pub notes: Option<String>,
71    /// Non-identifying annotations.
72    #[serde(default, skip_serializing_if = "Metadata::is_empty")]
73    pub meta: Metadata,
74}
75
76impl Implementation {
77    /// An implementation with a cost and nothing else said about it.
78    pub fn new(
79        id: impl Into<ImplId>,
80        proves: QualifiedName,
81        environment: Ident,
82        entry: impl Into<String>,
83        cost: ImplProfile,
84    ) -> Self {
85        Self {
86            id: id.into(),
87            proves,
88            sig_hash: None,
89            environment,
90            entry: entry.into(),
91            cost,
92            notes: None,
93            meta: Metadata::default(),
94        }
95    }
96
97    /// How this implementation sorts against another, cheapest first.
98    ///
99    /// Time, then space, then name — the last only so that two runs of the same
100    /// workspace agree about which of two equals comes first.
101    pub fn cost_key(&self) -> (u8, u8, &str) {
102        (
103            self.cost.time.sort_key(),
104            self.cost.space.sort_key(),
105            self.id.as_str(),
106        )
107    }
108
109    /// The same, weighing memory ahead of time.
110    pub fn memory_key(&self) -> (u8, u8, &str) {
111        (
112            self.cost.space.sort_key(),
113            self.cost.time.sort_key(),
114            self.id.as_str(),
115        )
116    }
117}
118
119/// A set of implementations declared together, as a file or a message.
120///
121/// This is what "registering as an execution source" looks like written down: a
122/// module announcing which propositions it can prove and where.
123#[derive(Clone, Debug, PartialEq, Serialize, Deserialize)]
124pub struct Manifest {
125    /// The format version.
126    #[serde(default = "default_version")]
127    pub version: String,
128    /// Environments this manifest introduces.
129    #[serde(default, skip_serializing_if = "Vec::is_empty")]
130    pub environments: Vec<crate::environment::Environment>,
131    /// The proofs on offer.
132    #[serde(default, skip_serializing_if = "Vec::is_empty")]
133    pub implementations: Vec<Implementation>,
134}
135
136/// The manifest format this build reads and writes.
137pub const MANIFEST_VERSION: &str = "1.0";
138
139fn default_version() -> String {
140    MANIFEST_VERSION.to_string()
141}
142
143impl Default for Manifest {
144    fn default() -> Self {
145        Self {
146            version: default_version(),
147            environments: Vec::new(),
148            implementations: Vec::new(),
149        }
150    }
151}
152
153/// A cost profile for something that does no real work.
154///
155/// Rearranging fields is constant in both, which is what a derived bridge does.
156pub fn trivial_cost() -> ImplProfile {
157    ImplProfile {
158        time: BigO::O1,
159        space: BigO::O1,
160        notes: None,
161    }
162}
163
164#[cfg(test)]
165mod tests {
166    use super::*;
167
168    fn impl_with(id: &str, time: BigO, space: BigO) -> Implementation {
169        Implementation::new(
170            id,
171            "demo::sort".parse().unwrap(),
172            Ident::new("here").unwrap(),
173            id,
174            ImplProfile::new(time, space),
175        )
176    }
177
178    #[test]
179    fn the_cheaper_proof_sorts_first() {
180        let merge = impl_with("merge", BigO::ONLogN, BigO::ON);
181        let bubble = impl_with("bubble", BigO::ON2, BigO::O1);
182        assert!(
183            merge.cost_key() < bubble.cost_key(),
184            "asked for speed, mergesort wins"
185        );
186        assert!(
187            bubble.memory_key() < merge.memory_key(),
188            "asked for memory, bubble sort wins"
189        );
190    }
191
192    #[test]
193    fn a_proof_that_will_not_say_what_it_costs_sorts_last() {
194        let stated = impl_with("stated", BigO::OExp, BigO::OExp);
195        let vague = impl_with("vague", BigO::Custom("depends".into()), BigO::O1);
196        assert!(
197            stated.cost_key() < vague.cost_key(),
198            "a stated cost, however bad, beats no answer"
199        );
200    }
201
202    #[test]
203    fn equally_good_proofs_are_ordered_the_same_way_every_time() {
204        let a = impl_with("alpha", BigO::ON, BigO::ON);
205        let b = impl_with("beta", BigO::ON, BigO::ON);
206        assert!(a.cost_key() < b.cost_key());
207    }
208
209    #[test]
210    fn a_manifest_round_trips_through_json() {
211        let manifest = Manifest {
212            version: MANIFEST_VERSION.to_string(),
213            environments: vec![crate::environment::Environment::subprocess(
214                "py",
215                "python",
216                "python3",
217                &["-u"],
218            )],
219            implementations: vec![impl_with("bubble", BigO::ON2, BigO::O1)],
220        };
221        let text = serde_json::to_string(&manifest).unwrap();
222        assert_eq!(serde_json::from_str::<Manifest>(&text).unwrap(), manifest);
223    }
224
225    #[test]
226    fn a_manifest_reads_the_way_someone_would_write_one() {
227        let manifest: Manifest = serde_json::from_str(
228            r#"{
229                "environments": [
230                    {"id":"py","language":"python",
231                     "reach":{"k":"subprocess","command":"python3","args":["impls.py"]}}],
232                "implementations": [
233                    {"id":"demo.sort.py-bubble","proves":"demo::sort","environment":"py",
234                     "entry":"bubble_sort",
235                     "cost":{"time":"o_n2","space":"o1","notes":"in place"}}]
236            }"#,
237        )
238        .expect("reads");
239
240        assert_eq!(manifest.version, MANIFEST_VERSION);
241        assert_eq!(manifest.implementations[0].cost.time, BigO::ON2);
242        assert_eq!(manifest.environments[0].reach.kind(), "subprocess");
243    }
244}