Skip to main content

constructo_runtime/
ast.rs

1//! The syntax trees for data-type declarations and data values.
2
3use crate::codec;
4use crate::diagnostics::Pos;
5use std::fmt;
6
7/// The declarations of a types file.
8#[derive(Debug, Clone, PartialEq, Eq, Default)]
9pub struct TypesFile {
10    /// The enums, in the order of the file.
11    pub enums: Vec<EnumDecl>,
12    /// The consts, in the order of the file.
13    pub consts: Vec<ConstDecl>,
14}
15
16/// `const name<Params>: Type = value;`, in which the parameters and the type may be left out together.
17#[derive(Debug, Clone, PartialEq, Eq)]
18pub struct ConstDecl {
19    /// The name of the const.
20    pub name: String,
21    /// The position of the name.
22    pub pos: Pos,
23    /// The type parameters, which are empty if there are none.
24    pub params: Vec<TypeParam>,
25    /// The declared type, or `None` if it is to be inferred from the value.
26    pub ty: Option<Type>,
27    /// The value of the const.
28    pub value: Value,
29}
30
31/// `enum Name<Params> = Variants;`
32#[derive(Debug, Clone, PartialEq, Eq)]
33pub struct EnumDecl {
34    /// The name of the enum.
35    pub name: String,
36    /// The position of the name.
37    pub pos: Pos,
38    /// The type parameters, which are empty if there are none.
39    pub params: Vec<TypeParam>,
40    /// The variants, in the order of the file.
41    pub variants: Vec<Variant>,
42}
43
44/// A type parameter of an enum or a const, such as the `T` of `enum List<T>`.
45#[derive(Debug, Clone, PartialEq, Eq)]
46pub struct TypeParam {
47    /// The name of the parameter.
48    pub name: String,
49    /// The position of the name.
50    pub pos: Pos,
51    /// True for a parameter written with a leading underscore, which is allowed to be unused.
52    pub underscore: bool,
53}
54
55/// A variant of an enum, which is a constructor and what it takes.
56#[derive(Debug, Clone, PartialEq, Eq)]
57pub struct Variant {
58    /// The name of the constructor.
59    pub name: String,
60    /// The position of the name.
61    pub pos: Pos,
62    /// What the constructor takes.
63    pub body: VariantBody,
64}
65
66/// What the constructor of a variant takes.
67#[derive(Debug, Clone, PartialEq, Eq)]
68pub enum VariantBody {
69    /// A bare constructor such as `Quit`.
70    Unit,
71    /// A record such as `Move { x: Int, y: Int }`.
72    Record(Vec<Field>),
73    /// A tuple such as `Write(String)` or `Image(String, hOffset: Nat)`, possibly empty as in `Ping()`.
74    Tuple(Vec<Parameter>),
75    /// An array of one element type, as in `Users[User]`. It is a different form from `Users([User])`.
76    Array(Type),
77}
78
79/// A parameter of a tuple constructor. Unnamed parameters come first and can only be bound by position.
80#[derive(Debug, Clone, PartialEq, Eq)]
81pub struct Parameter {
82    /// The name of the parameter, or `None` if it is unnamed.
83    pub name: Option<String>,
84    /// The position of the parameter.
85    pub pos: Pos,
86    /// The type of the parameter.
87    pub ty: Type,
88}
89
90/// A field of a record type.
91#[derive(Debug, Clone, PartialEq, Eq)]
92pub struct Field {
93    /// The name of the field.
94    pub name: String,
95    /// The position of the name.
96    pub pos: Pos,
97    /// The type of the field.
98    pub ty: Type,
99}
100
101/// A type, as it is written in a declaration.
102#[derive(Debug, Clone, PartialEq, Eq)]
103pub enum Type {
104    /// A named type with its arguments, such as `Nat` or `List<Int>`.
105    Ref {
106        /// The name of the type, as it is written.
107        name: String,
108        /// The position of the name.
109        pos: Pos,
110        /// The type arguments, which are empty if there are none.
111        args: Vec<Type>,
112    },
113    /// An array of one element type, such as `[Nat]`.
114    Array(Box<Type>),
115    /// A record type without a name, such as `{ x: Int }`.
116    Record(Vec<Field>),
117}
118
119/// A data value.
120#[derive(Debug, Clone, PartialEq, Eq)]
121pub struct Value {
122    /// The position of the start of the value.
123    pub pos: Pos,
124    /// What the value is.
125    pub kind: ValueKind,
126}
127
128/// The kinds of a data value.
129#[derive(Debug, Clone, PartialEq, Eq)]
130pub enum ValueKind {
131    /// The literals keep their text, so that checking them against a type can decide how to interpret them.
132    /// An unsigned integer literal, such as `42`.
133    Nat(String),
134    /// A signed integer literal, such as `+8` or `-1`.
135    Int(String),
136    /// A floating-point literal, such as `3.0` or `-2.5e3`.
137    Float(String),
138    /// A string literal, with its escapes decoded.
139    Str(String),
140    /// An array, such as `[1, 2]`.
141    Array(Vec<Value>),
142    /// A record without a constructor, such as `{ x: 1 }`.
143    Record(Vec<Member>),
144    /// A constructor, optionally followed by a record, a tuple or an array, as in `Quit`, `Move { x: 1 }`,
145    /// `Write("hi")` or `Users[u1, u2]`.
146    /// A name that starts with a lower-case letter or `_` is a reference to a const, which takes no body, and any other
147    /// name is a constructor.
148    Tagged {
149        /// The name, as it is written, which may be qualified.
150        name: String,
151        /// What follows the name, or `None` if nothing does.
152        body: Option<TaggedBody>,
153    },
154}
155
156/// What follows the name of a constructor in a value.
157#[derive(Debug, Clone, PartialEq, Eq)]
158pub enum TaggedBody {
159    /// A record, such as the `{ x: 1 }` of `Move { x: 1 }`.
160    Record(Vec<Member>),
161    /// A tuple, possibly empty as in `Ping()`. Positional arguments come before any named ones.
162    Tuple(Vec<Argument>),
163    /// An array, possibly empty as in `Users[]`. It has no names, so every element is an ordinary value.
164    Array(Vec<Value>),
165}
166
167/// An argument of a tuple constructor, which is either positional or given by the name of a parameter.
168#[derive(Debug, Clone, PartialEq, Eq)]
169pub struct Argument {
170    /// The name of the parameter, or `None` if the argument is positional.
171    pub name: Option<String>,
172    /// The position of the argument.
173    pub pos: Pos,
174    /// The value of the argument.
175    pub value: Value,
176}
177
178/// A member of a record value, `name: value`.
179#[derive(Debug, Clone, PartialEq, Eq)]
180pub struct Member {
181    /// The name of the member.
182    pub name: String,
183    /// The position of the name.
184    pub pos: Pos,
185    /// The value of the member.
186    pub value: Value,
187}
188
189impl fmt::Display for Type {
190    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
191        match self {
192            Type::Ref { name, args, .. } => {
193                write!(f, "{}", name)?;
194                if !args.is_empty() {
195                    let args: Vec<String> = args.iter().map(|t| t.to_string()).collect();
196                    write!(f, "<{}>", args.join(", "))?;
197                }
198                Ok(())
199            }
200            Type::Array(element) => write!(f, "[{}]", element),
201            Type::Record(fields) if fields.is_empty() => write!(f, "{{}}"),
202            Type::Record(fields) => {
203                let fields: Vec<String> = fields
204                    .iter()
205                    .map(|field| format!("{}: {}", field.name, field.ty))
206                    .collect();
207                write!(f, "{{ {} }}", fields.join(", "))
208            }
209        }
210    }
211}
212
213impl Value {
214    /// The name of a tagged value, as it is written, such as `Follow` for `Follow` or `Preferences` for
215    /// `Preferences { ... }`, whatever follows the name. A name that starts with a lower-case letter or `_`, such as
216    /// `true`, is a reference to a const, which is not resolved. `None` for any other kind of value.
217    pub fn tag(&self) -> Option<&str> {
218        match &self.kind {
219            ValueKind::Tagged { name, .. } => Some(name),
220            _ => None,
221        }
222    }
223
224    /// The members of a record, either untagged, as in `{ x: 1 }`, or after a tag, as in `Move { x: 1 }`. `None` for
225    /// any other kind of value.
226    pub fn members(&self) -> Option<&[Member]> {
227        match &self.kind {
228            ValueKind::Record(members)
229            | ValueKind::Tagged {
230                body: Some(TaggedBody::Record(members)),
231                ..
232            } => Some(members),
233            _ => None,
234        }
235    }
236
237    /// The value of the member called `name` of a record, as for `members`. `None` if the value is not a record or
238    /// has no such member. A duplicate member is not an error here: the first is found.
239    pub fn field(&self, name: &str) -> Option<&Value> {
240        self.members()?.iter().find(|m| m.name == name).map(|m| &m.value)
241    }
242
243    /// The value of the member called `name` of a record, as for `field`, or an error at this value that says why
244    /// there is none, in the words of `check`: `Missing field layout in Preferences`, or for a value that is not a
245    /// record, `Expected a record but found Nat`. A duplicate member is not an error here: the first is found.
246    pub fn require_field(&self, name: &str) -> Result<&Value, codec::Error> {
247        let Some(members) = self.members() else {
248            return Err(codec::expected("a record", self));
249        };
250        match members.iter().find(|m| m.name == name) {
251            Some(member) => Ok(&member.value),
252            None => {
253                let owner = self.tag().unwrap_or("record");
254                Err(codec::Error::at(
255                    self.pos,
256                    format!("Missing field {} in {}", name, owner),
257                ))
258            }
259        }
260    }
261
262    // The `as_` accessors convert a value that should be of one kind, and are an error at the value if it is not, in
263    // the words of `check`, such as `Expected String but found Nat`.
264
265    /// The text of a string.
266    pub fn as_str(&self) -> Result<&str, codec::Error> {
267        match &self.kind {
268            ValueKind::Str(text) => Ok(text),
269            _ => Err(codec::expected("String", self)),
270        }
271    }
272
273    /// The elements of an array, either untagged, as in `[1, 2]`, or after a tag, as in `Users[u1, u2]`.
274    pub fn as_array(&self) -> Result<&[Value], codec::Error> {
275        match &self.kind {
276            ValueKind::Array(items)
277            | ValueKind::Tagged {
278                body: Some(TaggedBody::Array(items)),
279                ..
280            } => Ok(items),
281            _ => Err(codec::expected("an array", self)),
282        }
283    }
284
285    /// A `Bool` of the prelude: `True` or `False`, or `true` or `false`, which are the prelude's consts for them, or
286    /// the full names `constructo.prelude::True` and `constructo.prelude::False`, which a codec writes with
287    /// `Names::Full`. These names are known here, although the syntax knows no types, because a `Bool` is too common
288    /// for every reader to work this out again. They are accepted even when the prelude is not loaded.
289    pub fn as_bool(&self) -> Result<bool, codec::Error> {
290        match &self.kind {
291            ValueKind::Tagged { name, body: None } => match name.as_str() {
292                "true" | "True" | "constructo.prelude::True" => Ok(true),
293                "false" | "False" | "constructo.prelude::False" => Ok(false),
294                _ => Err(codec::expected("Bool", self)),
295            },
296            _ => Err(codec::expected("Bool", self)),
297        }
298    }
299
300    /// A `Nat`, as a `u64`. A number that is too large is an error at it.
301    pub fn as_u64(&self) -> Result<u64, codec::Error> {
302        codec::read_nat(self)
303    }
304
305    /// An `Int`, or a `Nat` widened to one, as an `i64`. A number that is too large is an error at it.
306    pub fn as_i64(&self) -> Result<i64, codec::Error> {
307        codec::read_int(self, true)
308    }
309
310    /// A `Float`, or a `Nat` or an `Int` widened to one, as the nearest `f64`. A number too large for an `f64` is an
311    /// error at it.
312    pub fn as_f64(&self) -> Result<f64, codec::Error> {
313        codec::read_float(self, true)
314    }
315
316    /// Collects the names that the value uses on their own or as the tag of a body, with their positions. Any of them
317    /// may refer to a const, which is for the caller to decide.
318    pub fn names<'a>(&'a self, out: &mut Vec<(&'a str, Pos)>) {
319        match &self.kind {
320            ValueKind::Array(items) => items.iter().for_each(|item| item.names(out)),
321            ValueKind::Record(members) => members.iter().for_each(|m| m.value.names(out)),
322            ValueKind::Tagged { name, body } => {
323                out.push((name, self.pos));
324                match body {
325                    Some(TaggedBody::Record(members)) => members.iter().for_each(|m| m.value.names(out)),
326                    Some(TaggedBody::Tuple(items)) => items.iter().for_each(|item| item.value.names(out)),
327                    Some(TaggedBody::Array(items)) => items.iter().for_each(|item| item.names(out)),
328                    None => {}
329                }
330            }
331            ValueKind::Nat(_) | ValueKind::Int(_) | ValueKind::Float(_) | ValueKind::Str(_) => {}
332        }
333    }
334}
335
336#[cfg(test)]
337mod tests {
338    use crate::codec::parse_one;
339
340    #[test]
341    fn a_tag_is_the_name_whatever_follows_it() {
342        assert_eq!(parse_one("Follow").unwrap().tag(), Some("Follow"));
343        assert_eq!(parse_one("Move { x: 1 }").unwrap().tag(), Some("Move"));
344        assert_eq!(parse_one("Write(\"hi\")").unwrap().tag(), Some("Write"));
345        assert_eq!(parse_one("true").unwrap().tag(), Some("true"));
346        assert_eq!(parse_one("\"Follow\"").unwrap().tag(), None);
347        assert_eq!(parse_one("{ x: 1 }").unwrap().tag(), None);
348    }
349
350    #[test]
351    fn members_are_those_of_a_record_tagged_or_not() {
352        let names = |text: &str| {
353            parse_one(text)
354                .unwrap()
355                .members()
356                .map(|ms| ms.iter().map(|m| m.name.clone()).collect::<Vec<_>>())
357        };
358        assert_eq!(names("{ x: 1, y: 2 }"), Some(vec!["x".to_string(), "y".to_string()]));
359        assert_eq!(names("Move { x: 1 }"), Some(vec!["x".to_string()]));
360        assert_eq!(names("Move {}"), Some(vec![]));
361        assert_eq!(names("Move"), None);
362        assert_eq!(names("Move(1)"), None);
363        assert_eq!(names("[1]"), None);
364    }
365
366    #[test]
367    fn a_field_is_found_by_its_name() {
368        let value = parse_one("Prefs { layout: Icons, start: \"/home\", start: \"/tmp\" }").unwrap();
369        assert_eq!(value.field("layout").and_then(|v| v.tag()), Some("Icons"));
370        assert_eq!(value.field("start").and_then(|v| v.as_str().ok()), Some("/home"));
371        assert!(value.field("missing").is_none());
372        assert!(parse_one("[1]").unwrap().field("layout").is_none());
373    }
374
375    #[test]
376    fn a_required_field_is_found_or_says_why_not() {
377        let value = parse_one("Prefs {\n  layout: Icons,\n  start: \"/home\",\n  start: \"/tmp\" }").unwrap();
378        assert_eq!(value.require_field("layout").unwrap().tag(), Some("Icons"));
379        assert_eq!(value.require_field("start").unwrap().as_str().unwrap(), "/home");
380        let missing = value.require_field("missing").unwrap_err();
381        assert_eq!(missing.message(), "Missing field missing in Prefs");
382        assert_eq!(missing.pos(), Some(value.pos));
383        let untagged = parse_one("{ x: 1 }").unwrap().require_field("y").unwrap_err();
384        assert_eq!(untagged.message(), "Missing field y in record");
385        let not_a_record = parse_one("\n  42").unwrap().require_field("x").unwrap_err();
386        assert_eq!(not_a_record.message(), "Expected a record but found Nat");
387        assert_eq!(not_a_record.pos().map(|p| (p.line, p.col)), Some((2, 3)));
388        let tagged_tuple = parse_one("Prefs(1)").unwrap().require_field("x").unwrap_err();
389        assert_eq!(tagged_tuple.message(), "Expected a record but found Prefs");
390    }
391
392    /// The message of the error of a conversion that fails.
393    fn refused<T: std::fmt::Debug>(result: Result<T, crate::codec::Error>) -> String {
394        result.unwrap_err().message().to_string()
395    }
396
397    #[test]
398    fn a_string_is_its_text() {
399        assert_eq!(parse_one("\"a\\nb\"").unwrap().as_str().unwrap(), "a\nb");
400        assert_eq!(
401            refused(parse_one("Follow").unwrap().as_str()),
402            "Expected String but found Follow"
403        );
404        assert_eq!(
405            refused(parse_one("42").unwrap().as_str()),
406            "Expected String but found Nat"
407        );
408    }
409
410    #[test]
411    fn an_array_is_its_elements_tagged_or_not() {
412        assert_eq!(parse_one("[1, 2]").unwrap().as_array().unwrap().len(), 2);
413        assert_eq!(parse_one("Users[1]").unwrap().as_array().unwrap().len(), 1);
414        assert_eq!(
415            refused(parse_one("Users").unwrap().as_array()),
416            "Expected an array but found Users"
417        );
418        assert_eq!(
419            refused(parse_one("{ x: [1] }").unwrap().as_array()),
420            "Expected an array but found a record"
421        );
422    }
423
424    #[test]
425    fn a_bool_is_true_or_false_by_either_name() {
426        for (text, truth) in [
427            ("true", true),
428            ("True", true),
429            ("constructo.prelude::True", true),
430            ("false", false),
431            ("False", false),
432            ("constructo.prelude::False", false),
433        ] {
434            assert_eq!(parse_one(text).unwrap().as_bool().unwrap(), truth);
435        }
436        assert_eq!(
437            refused(parse_one("Yes").unwrap().as_bool()),
438            "Expected Bool but found Yes"
439        );
440        assert_eq!(
441            refused(parse_one("other.project::True").unwrap().as_bool()),
442            "Expected Bool but found other.project::True"
443        );
444        assert_eq!(
445            refused(parse_one("True(1)").unwrap().as_bool()),
446            "Expected Bool but found True"
447        );
448        assert_eq!(
449            refused(parse_one("\"true\"").unwrap().as_bool()),
450            "Expected Bool but found String"
451        );
452    }
453
454    #[test]
455    fn a_number_is_read_with_widening_and_must_fit() {
456        assert_eq!(parse_one("42").unwrap().as_u64().unwrap(), 42);
457        assert_eq!(refused(parse_one("-1").unwrap().as_u64()), "Expected Nat but found Int");
458        assert_eq!(
459            refused(parse_one("18446744073709551616").unwrap().as_u64()),
460            "The number 18446744073709551616 does not fit Nat"
461        );
462        assert_eq!(parse_one("-7").unwrap().as_i64().unwrap(), -7);
463        assert_eq!(parse_one("7").unwrap().as_i64().unwrap(), 7);
464        assert_eq!(
465            refused(parse_one("1.5").unwrap().as_i64()),
466            "Expected Int but found Float"
467        );
468        assert_eq!(parse_one("2.5").unwrap().as_f64().unwrap(), 2.5);
469        assert_eq!(parse_one("-3").unwrap().as_f64().unwrap(), -3.0);
470        assert_eq!(
471            refused(parse_one("\"1\"").unwrap().as_f64()),
472            "Expected Float but found String"
473        );
474    }
475}