Skip to main content

meta_language/translation/
types.rs

1//! Portable-core types.
2//!
3//! Numeric types keep their source semantics apart:
4//! `nat` and `int` are unbounded, `fixed` is a Rust machine integer whose
5//! arithmetic aborts on overflow, and `float` is a JavaScript Number, an
6//! IEEE-754 binary64. Data types are named by their qualified path.
7//!
8//! Mirrors `js/src/translation/types.js`; the serialised form is the same JSON
9//! object (`{ "kind": "fixed", "bits": 32, "signed": true }`).
10
11use serde::{Deserialize, Serialize};
12
13use super::Span;
14use super::primitive_value_rules::accept_immutable_product_kind;
15use super::structured_type_rules::{
16    accept_optional_absence, accept_type_identity, merge_optional_absence,
17    render_portable_type_identity, wrap_portable_reference_identity,
18};
19
20fn default_absence() -> std::string::String {
21    "both".to_owned()
22}
23fn is_false(value: impl std::ops::Not<Output = bool>) -> bool {
24    !value
25}
26
27/// A present product model must be a string; null cannot erase its semantics.
28pub(crate) fn deserialize_tuple_product_model<'de, D: serde::Deserializer<'de>>(
29    deserializer: D,
30) -> Result<Option<std::string::String>, D::Error> {
31    std::string::String::deserialize(deserializer)
32        .map(Some)
33        .map_err(|error| {
34            <D::Error as serde::de::Error>::custom(format!("invalid tuple product model: {error}"))
35        })
36}
37
38/// One named field of a structural record.
39#[derive(Clone, Debug, PartialEq, Eq, Serialize, Deserialize)]
40pub struct TypeField {
41    /// The source field name.
42    pub name: std::string::String,
43    /// The field's recursively structured type.
44    #[serde(rename = "type")]
45    pub ty: Type,
46}
47
48/// A portable-core type, or a surface type reference before resolution.
49#[derive(Clone, Debug, PartialEq, Eq, Serialize, Deserialize)]
50#[serde(tag = "kind", rename_all = "camelCase")]
51pub enum Type {
52    Nat,
53    Int,
54    Bool,
55    String,
56    Unit,
57    /// A JavaScript Number: an IEEE-754 binary64.
58    Float,
59    Fixed {
60        bits: u32,
61        signed: bool,
62    },
63    /// A resolved data type, named by its qualified path.
64    Data {
65        name: std::string::String,
66    },
67    /// A JavaScript array, optionally retaining a shared reference identity.
68    Array {
69        element: Box<Self>,
70        #[serde(default, skip_serializing_if = "is_false")]
71        reference: bool,
72    },
73    /// A binding whose value lives in a shared reference cell.
74    Cell {
75        element: Box<Self>,
76    },
77    /// Absence retains the distinction between JavaScript null and undefined.
78    Option {
79        element: Box<Self>,
80        #[serde(default = "default_absence")]
81        absence: std::string::String,
82    },
83    /// A surface absence type; checked Links admission retains its old refusal.
84    Absence {
85        absence: std::string::String,
86    },
87    /// A positional product type; value nodes retain the explicit frozen facet.
88    Tuple {
89        elements: Vec<Self>,
90    },
91    /// Ordered source alternatives retain their separate child identities.
92    Union {
93        alternatives: Vec<Self>,
94    },
95    /// Named fields, whose declaration order does not affect type identity.
96    Record {
97        fields: Vec<TypeField>,
98        #[serde(default, skip_serializing_if = "is_false")]
99        open: bool,
100        #[serde(default, skip_serializing_if = "is_false")]
101        reference: bool,
102    },
103    /// An insertion-ordered mapping, optionally retaining a shared reference identity.
104    Map {
105        key: Box<Self>,
106        value: Box<Self>,
107        #[serde(default, skip_serializing_if = "is_false")]
108        reference: bool,
109    },
110    /// An insertion-ordered set, optionally retaining a shared reference identity.
111    Set {
112        element: Box<Self>,
113        #[serde(default, skip_serializing_if = "is_false")]
114        reference: bool,
115    },
116    /// The parameter and return types of a callable value.
117    Function {
118        params: Vec<Self>,
119        ret: Box<Self>,
120    },
121    /// A surface reference to a declared type, resolved by the checker.
122    Named {
123        path: Vec<std::string::String>,
124        #[serde(default, skip_serializing_if = "Option::is_none")]
125        span: Option<Span>,
126    },
127    /// The type of a numeral whose type the context has not fixed yet.
128    Literal,
129    /// A proof hypothesis bound by a case split (proof plans only).
130    Hypothesis,
131    /// The lines a program has printed, newest first: only the targets whose
132    /// programs are pure carry them, as a value (see `output`).
133    Output,
134}
135
136pub const NAT: Type = Type::Nat;
137pub const INT: Type = Type::Int;
138pub const BOOL: Type = Type::Bool;
139pub const STRING: Type = Type::String;
140pub const UNIT: Type = Type::Unit;
141pub const FLOAT: Type = Type::Float;
142
143#[must_use]
144pub const fn fixed(bits: u32, signed: bool) -> Type {
145    Type::Fixed { bits, signed }
146}
147
148#[must_use]
149pub fn array(element: Type) -> Type {
150    Type::Array {
151        element: Box::new(element),
152        reference: false,
153    }
154}
155
156/// Constructs and flattens an optional type using the shared absence policy.
157#[must_use]
158pub fn option(element: Type, absence: impl Into<std::string::String>) -> Type {
159    let absence = absence.into();
160    match element {
161        Type::Option {
162            element,
163            absence: inner,
164        } => option(*element, merge_optional_absence(&inner, &absence)),
165        element => Type::Option {
166            element: Box::new(element),
167            absence,
168        },
169    }
170}
171
172#[must_use]
173pub fn data(name: impl Into<std::string::String>) -> Type {
174    Type::Data { name: name.into() }
175}
176
177impl Type {
178    /// Membership in the selected recursive scalar Copy product model.
179    #[must_use]
180    pub fn immutable_product_type(&self) -> bool {
181        accept_immutable_product_kind(self.kind())
182            && match self {
183                Self::Tuple { elements } => elements.iter().all(Self::immutable_product_type),
184                _ => true,
185            }
186    }
187
188    /// Immediate child types, in representation order.
189    #[must_use]
190    pub fn children(&self) -> Vec<&Self> {
191        match self {
192            Self::Array { element, .. }
193            | Self::Option { element, .. }
194            | Self::Set { element, .. }
195            | Self::Cell { element } => {
196                vec![element]
197            }
198            Self::Tuple { elements } => elements.iter().collect(),
199            Self::Union { alternatives } => alternatives.iter().collect(),
200            Self::Record { fields, .. } => fields.iter().map(|field| &field.ty).collect(),
201            Self::Map { key, value, .. } => vec![key, value],
202            Self::Function { params, ret } => {
203                params.iter().chain(std::iter::once(ret.as_ref())).collect()
204            }
205            _ => Vec::new(),
206        }
207    }
208
209    /// Adapts children through the host checker without duplicating type rules.
210    /// Record fields are put into their canonical UTF-16 name order.
211    ///
212    /// # Errors
213    /// Returns an error from the supplied child adapter.
214    pub fn map_children<E>(
215        &self,
216        mut map: impl FnMut(&Self) -> Result<Self, E>,
217    ) -> Result<Self, E> {
218        Ok(match self {
219            Self::Array { element, .. } => Self::Array {
220                element: Box::new(map(element)?),
221                reference: self.is_reference(),
222            },
223            Self::Cell { element } => Self::Cell {
224                element: Box::new(map(element)?),
225            },
226            Self::Option { element, absence } => Self::Option {
227                element: Box::new(map(element)?),
228                absence: absence.clone(),
229            },
230            Self::Set { element, .. } => Self::Set {
231                element: Box::new(map(element)?),
232                reference: self.is_reference(),
233            },
234            Self::Tuple { elements } => Self::Tuple {
235                elements: elements.iter().map(&mut map).collect::<Result<_, _>>()?,
236            },
237            Self::Union { alternatives } => Self::Union {
238                alternatives: alternatives
239                    .iter()
240                    .map(&mut map)
241                    .collect::<Result<_, _>>()?,
242            },
243            Self::Record { fields, open, .. } => {
244                let mut fields: Vec<_> = fields
245                    .iter()
246                    .map(|field| {
247                        Ok(TypeField {
248                            name: field.name.clone(),
249                            ty: map(&field.ty)?,
250                        })
251                    })
252                    .collect::<Result<_, E>>()?;
253                fields.sort_by(|first, second| {
254                    first.name.encode_utf16().cmp(second.name.encode_utf16())
255                });
256                Self::Record {
257                    fields,
258                    open: *open,
259                    reference: self.is_reference(),
260                }
261            }
262            Self::Map { key, value, .. } => Self::Map {
263                key: Box::new(map(key)?),
264                value: Box::new(map(value)?),
265                reference: self.is_reference(),
266            },
267            Self::Function { params, ret } => Self::Function {
268                params: params.iter().map(&mut map).collect::<Result<_, _>>()?,
269                ret: Box::new(map(ret)?),
270            },
271            other => other.clone(),
272        })
273    }
274
275    /// The type's identity: `nat`, `i32`, `data:Tree`.
276    #[must_use]
277    pub fn key(&self) -> std::string::String {
278        let (detail, children) = match self {
279            Self::Fixed { bits, signed } => (
280                format!("{}{bits}", if *signed { 'i' } else { 'u' }),
281                Vec::new(),
282            ),
283            Self::Data { name } => (name.clone(), Vec::new()),
284            Self::Array { element, .. } | Self::Set { element, .. } | Self::Cell { element } => {
285                (std::string::String::new(), vec![element.key()])
286            }
287            Self::Option { element, absence } => {
288                let mut absence = absence.clone();
289                let mut current = element.as_ref();
290                while let Self::Option {
291                    element,
292                    absence: inner,
293                } = current
294                {
295                    absence = merge_optional_absence(inner, &absence);
296                    current = element;
297                }
298                (absence, vec![current.key()])
299            }
300            Self::Tuple { elements } => (
301                std::string::String::new(),
302                elements.iter().map(Self::key).collect(),
303            ),
304            Self::Union { alternatives } => (
305                std::string::String::new(),
306                alternatives.iter().map(Self::key).collect(),
307            ),
308            Self::Record { fields, open, .. } => {
309                let mut sorted: Vec<_> = fields.iter().collect();
310                sorted.sort_by(|first, second| {
311                    first.name.encode_utf16().cmp(second.name.encode_utf16())
312                });
313                let children = sorted
314                    .iter()
315                    .map(|field| {
316                        serde_json::to_string(&[field.name.clone(), field.ty.key()])
317                            .expect("string pairs serialize")
318                    })
319                    .collect();
320                (
321                    if *open {
322                        "open:".to_owned()
323                    } else {
324                        std::string::String::new()
325                    },
326                    children,
327                )
328            }
329            Self::Map { key, value, .. } => {
330                (std::string::String::new(), vec![key.key(), value.key()])
331            }
332            Self::Function { params, ret } => (ret.key(), params.iter().map(Self::key).collect()),
333            _ => (std::string::String::new(), Vec::new()),
334        };
335        wrap_portable_reference_identity(
336            &render_portable_type_identity(self.kind(), &detail, &children),
337            self.is_reference(),
338        )
339    }
340
341    /// Whether a structural value retains a shared mutable reference identity.
342    #[must_use]
343    pub const fn is_reference(&self) -> bool {
344        match self {
345            Self::Array { reference, .. }
346            | Self::Record { reference, .. }
347            | Self::Map { reference, .. }
348            | Self::Set { reference, .. } => *reference,
349            _ => false,
350        }
351    }
352
353    /// Copy the host type while writing its existing structural identity field.
354    /// Selection of this representation belongs to the generated rules.
355    #[must_use]
356    pub fn with_reference(&self, reference: bool) -> Self {
357        let mut result = self.clone();
358        match &mut result {
359            Self::Array {
360                reference: value, ..
361            }
362            | Self::Record {
363                reference: value, ..
364            }
365            | Self::Map {
366                reference: value, ..
367            }
368            | Self::Set {
369                reference: value, ..
370            } => *value = reference,
371            _ => {}
372        }
373        result
374    }
375
376    /// The `kind` discriminant as the JavaScript runtime spells it.
377    #[must_use]
378    pub const fn kind(&self) -> &'static str {
379        match self {
380            Self::Nat => "nat",
381            Self::Int => "int",
382            Self::Bool => "bool",
383            Self::String => "string",
384            Self::Unit => "unit",
385            Self::Float => "float",
386            Self::Fixed { .. } => "fixed",
387            Self::Data { .. } => "data",
388            Self::Array { .. } => "array",
389            Self::Cell { .. } => "cell",
390            Self::Option { .. } => "option",
391            Self::Absence { .. } => "absence",
392            Self::Tuple { .. } => "tuple",
393            Self::Union { .. } => "union",
394            Self::Record { .. } => "record",
395            Self::Map { .. } => "map",
396            Self::Set { .. } => "set",
397            Self::Function { .. } => "function",
398            Self::Named { .. } => "named",
399            Self::Literal => "literal",
400            Self::Hypothesis => "hypothesis",
401            Self::Output => "output",
402        }
403    }
404
405    #[must_use]
406    pub fn same(&self, other: &Self) -> bool {
407        accept_type_identity(&self.key(), &other.key())
408    }
409
410    /// Whether this optional type admits a particular absence case.
411    #[must_use]
412    pub fn accepts_absence(&self, actual: &str) -> bool {
413        match self {
414            Self::Option { absence, .. } => accept_optional_absence(absence, actual),
415            _ => false,
416        }
417    }
418
419    #[must_use]
420    pub const fn is_numeric(&self) -> bool {
421        matches!(self, Self::Nat | Self::Int | Self::Fixed { .. })
422    }
423
424    #[must_use]
425    pub const fn is_float(&self) -> bool {
426        matches!(self, Self::Float)
427    }
428
429    /// True for the types `<` orders: the integers and Numbers.
430    #[must_use]
431    pub const fn is_ordered(&self) -> bool {
432        self.is_numeric() || self.is_float()
433    }
434
435    /// True when every value of the type is a non-negative integer.
436    #[must_use]
437    pub const fn is_natural(&self) -> bool {
438        matches!(self, Self::Nat | Self::Fixed { signed: false, .. })
439    }
440
441    #[must_use]
442    pub const fn is_literal(&self) -> bool {
443        matches!(self, Self::Literal)
444    }
445
446    /// The element type of an array.
447    #[must_use]
448    pub fn element(&self) -> Option<&Self> {
449        match self {
450            Self::Array { element, .. } => Some(element),
451            _ => None,
452        }
453    }
454
455    /// The data type's qualified name.
456    #[must_use]
457    pub fn data_name(&self) -> Option<&str> {
458        match self {
459            Self::Data { name } => Some(name),
460            _ => None,
461        }
462    }
463}
464
465/// Inclusive bounds of a machine-integer type.
466#[must_use]
467pub fn fixed_bounds(bits: u32, signed: bool) -> (i128, u128) {
468    if signed {
469        let max = (1u128 << (bits - 1)) - 1;
470        let min = -i128::try_from(max).unwrap_or(i128::MAX) - 1;
471        (min, max)
472    } else if bits >= 128 {
473        (0, u128::MAX)
474    } else {
475        (0, (1u128 << bits) - 1)
476    }
477}
478
479/// `u8` … `i128`, `usize`, `isize` (the pointer-sized types are 64 bits).
480#[must_use]
481pub fn rust_fixed_type(name: &str) -> Option<Type> {
482    let signed = match name.as_bytes().first() {
483        Some(b'u') => false,
484        Some(b'i') => true,
485        _ => return None,
486    };
487    let bits = match &name[1..] {
488        "8" => 8,
489        "16" => 16,
490        "32" => 32,
491        "64" | "size" => 64,
492        "128" => 128,
493        _ => return None,
494    };
495    Some(fixed(bits, signed))
496}