Skip to main content

flow_value/
shape.rs

1//! Records and enum values, by declaration (`types.md`, *Records* and
2//! *Enums*).
3//!
4//! A value holds its parts in **declaration order**, as slots, beside a shared
5//! description of its declaration. The slots are what equality and order read
6//! — field by field in declaration order, and for an enum the constructor's
7//! position first — and the description is what the text form reads: the
8//! type's name, its constructors' names and its fields' names. Two values of
9//! one type share one description, so holding it costs a pointer.
10
11use std::sync::Arc;
12
13use crate::value::{Meta, Value};
14
15/// A record declaration: its name and its fields in declaration order.
16#[derive(Debug, PartialEq, Eq)]
17pub struct RecordShape {
18    name: Arc<str>,
19    fields: Box<[Arc<str>]>,
20}
21
22impl RecordShape {
23    /// Returns the shape of the record `name` declaring `fields`, in order.
24    pub fn new<'a>(name: &str, fields: impl IntoIterator<Item = &'a str>) -> Arc<Self> {
25        Arc::new(RecordShape {
26            name: Arc::from(name),
27            fields: fields.into_iter().map(Arc::from).collect(),
28        })
29    }
30
31    /// Returns the type's declared name.
32    pub fn name(&self) -> &str {
33        &self.name
34    }
35
36    /// Returns the field names, in declaration order.
37    pub fn fields(&self) -> impl ExactSizeIterator<Item = &str> {
38        self.fields.iter().map(|field| &**field)
39    }
40}
41
42/// A record value.
43#[derive(Clone, Debug)]
44pub struct Record {
45    shape: Arc<RecordShape>,
46    fields: Arc<[Value]>,
47    meta: Meta,
48}
49
50impl Record {
51    /// Returns the record of `shape` with `fields` in declaration order, or
52    /// `None` when there is not exactly one value per declared field.
53    pub fn new(shape: Arc<RecordShape>, fields: Vec<Value>) -> Option<Self> {
54        (fields.len() == shape.fields.len()).then(|| Record {
55            meta: Meta::around(&fields),
56            shape,
57            fields: fields.into(),
58        })
59    }
60
61    /// Returns the declaration.
62    pub fn shape(&self) -> &Arc<RecordShape> {
63        &self.shape
64    }
65
66    /// Returns the field values, in declaration order.
67    pub fn fields(&self) -> &[Value] {
68        &self.fields
69    }
70
71    /// Returns the field values when nothing else holds them.
72    /// What it records of its fields.
73    pub(crate) fn meta(&self) -> Meta {
74        self.meta
75    }
76
77    pub(crate) fn fields_mut(&mut self) -> Option<&mut [Value]> {
78        Arc::get_mut(&mut self.fields)
79    }
80
81    /// Returns the field at a declaration index.
82    pub fn field(&self, index: usize) -> Option<&Value> {
83        self.fields.get(index)
84    }
85}
86
87impl Drop for Record {
88    fn drop(&mut self) {
89        if let Some(fields) = self.fields_mut() {
90            crate::value::dismantle(fields.iter_mut());
91        }
92    }
93}
94
95/// What a constructor carries.
96#[derive(Clone, Debug, PartialEq, Eq)]
97pub enum Payload {
98    /// Nothing: `TimedOut`.
99    None,
100    /// This many positional values: `Failed(problem)`.
101    Positional(usize),
102    /// Named fields, in declaration order: `StepFailed { step, last }`.
103    Named(Box<[Arc<str>]>),
104}
105
106impl Payload {
107    /// Returns how many values the payload holds.
108    pub fn arity(&self) -> usize {
109        match self {
110            Payload::None => 0,
111            Payload::Positional(count) => *count,
112            Payload::Named(fields) => fields.len(),
113        }
114    }
115
116    /// Returns named fields, in declaration order.
117    pub fn named<'a>(fields: impl IntoIterator<Item = &'a str>) -> Self {
118        Payload::Named(fields.into_iter().map(Arc::from).collect())
119    }
120}
121
122/// One constructor of an enum declaration.
123#[derive(Clone, Debug, PartialEq, Eq)]
124pub struct Constructor {
125    name: Arc<str>,
126    payload: Payload,
127}
128
129impl Constructor {
130    /// Returns the constructor `name` carrying `payload`.
131    pub fn new(name: &str, payload: Payload) -> Self {
132        Constructor {
133            name: Arc::from(name),
134            payload,
135        }
136    }
137
138    /// Returns the constructor's name.
139    pub fn name(&self) -> &str {
140        &self.name
141    }
142
143    /// Returns what it carries.
144    pub fn payload(&self) -> &Payload {
145        &self.payload
146    }
147}
148
149/// An enum declaration: its name and its constructors in declaration order.
150#[derive(Debug, PartialEq, Eq)]
151pub struct EnumShape {
152    name: Arc<str>,
153    constructors: Box<[Constructor]>,
154}
155
156impl EnumShape {
157    /// Returns the shape of the enum `name` declaring `constructors`, in
158    /// order.
159    pub fn new(name: &str, constructors: impl IntoIterator<Item = Constructor>) -> Arc<Self> {
160        Arc::new(EnumShape {
161            name: Arc::from(name),
162            constructors: constructors.into_iter().collect(),
163        })
164    }
165
166    /// Returns the type's declared name.
167    pub fn name(&self) -> &str {
168        &self.name
169    }
170
171    /// Returns the constructor at a declaration index.
172    pub fn constructor(&self, index: usize) -> Option<&Constructor> {
173        self.constructors.get(index)
174    }
175}
176
177/// An enum value.
178#[derive(Clone, Debug)]
179pub struct Variant {
180    shape: Arc<EnumShape>,
181    index: u32,
182    meta: Meta,
183    payload: Arc<[Value]>,
184}
185
186impl Variant {
187    /// Returns the value of the constructor at a declaration index carrying
188    /// `payload`, or `None` when there is no such constructor or the payload
189    /// does not hold exactly as many values as it declares.
190    pub fn new(shape: Arc<EnumShape>, index: usize, payload: Vec<Value>) -> Option<Self> {
191        let arity = shape.constructor(index)?.payload.arity();
192        let index = u32::try_from(index).ok()?;
193        (payload.len() == arity).then(|| Variant {
194            meta: Meta::around(&payload),
195            shape,
196            index,
197            payload: payload.into(),
198        })
199    }
200
201    /// Returns the declaration.
202    pub fn shape(&self) -> &Arc<EnumShape> {
203        &self.shape
204    }
205
206    /// Returns the constructor's declaration index.
207    pub fn index(&self) -> usize {
208        self.index as usize
209    }
210
211    /// Returns the constructor.
212    pub fn constructor(&self) -> &Constructor {
213        &self.shape.constructors[self.index()]
214    }
215
216    /// Returns the payload values, in declaration order.
217    pub fn payload(&self) -> &[Value] {
218        &self.payload
219    }
220
221    /// Returns the payload values when nothing else holds them.
222    /// What it records of its payload.
223    pub(crate) fn meta(&self) -> Meta {
224        self.meta
225    }
226
227    pub(crate) fn payload_mut(&mut self) -> Option<&mut [Value]> {
228        Arc::get_mut(&mut self.payload)
229    }
230}
231
232impl Drop for Variant {
233    fn drop(&mut self) {
234        if let Some(payload) = self.payload_mut() {
235            crate::value::dismantle(payload.iter_mut());
236        }
237    }
238}