constructo-runtime 0.1.1

The syntax of Constructo data-values: the lexer, parser and printer that generated code depends on
Documentation
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
//! The syntax trees for data-type declarations and data values.

use crate::codec;
use crate::diagnostics::Pos;
use std::fmt;

/// The declarations of a types file.
#[derive(Debug, Clone, PartialEq, Eq, Default)]
pub struct TypesFile {
    /// The enums, in the order of the file.
    pub enums: Vec<EnumDecl>,
    /// The consts, in the order of the file.
    pub consts: Vec<ConstDecl>,
}

/// `const name<Params>: Type = value;`, in which the parameters and the type may be left out together.
#[derive(Debug, Clone, PartialEq, Eq)]
pub struct ConstDecl {
    /// The name of the const.
    pub name: String,
    /// The position of the name.
    pub pos: Pos,
    /// The type parameters, which are empty if there are none.
    pub params: Vec<TypeParam>,
    /// The declared type, or `None` if it is to be inferred from the value.
    pub ty: Option<Type>,
    /// The value of the const.
    pub value: Value,
}

/// `enum Name<Params> = Variants;`
#[derive(Debug, Clone, PartialEq, Eq)]
pub struct EnumDecl {
    /// The name of the enum.
    pub name: String,
    /// The position of the name.
    pub pos: Pos,
    /// The type parameters, which are empty if there are none.
    pub params: Vec<TypeParam>,
    /// The variants, in the order of the file.
    pub variants: Vec<Variant>,
}

/// A type parameter of an enum or a const, such as the `T` of `enum List<T>`.
#[derive(Debug, Clone, PartialEq, Eq)]
pub struct TypeParam {
    /// The name of the parameter.
    pub name: String,
    /// The position of the name.
    pub pos: Pos,
    /// True for a parameter written with a leading underscore, which is allowed to be unused.
    pub underscore: bool,
}

/// A variant of an enum, which is a constructor and what it takes.
#[derive(Debug, Clone, PartialEq, Eq)]
pub struct Variant {
    /// The name of the constructor.
    pub name: String,
    /// The position of the name.
    pub pos: Pos,
    /// What the constructor takes.
    pub body: VariantBody,
}

/// What the constructor of a variant takes.
#[derive(Debug, Clone, PartialEq, Eq)]
pub enum VariantBody {
    /// A bare constructor such as `Quit`.
    Unit,
    /// A record such as `Move { x: Int, y: Int }`.
    Record(Vec<Field>),
    /// A tuple such as `Write(String)` or `Image(String, hOffset: Nat)`, possibly empty as in `Ping()`.
    Tuple(Vec<Parameter>),
    /// An array of one element type, as in `Users[User]`. It is a different form from `Users([User])`.
    Array(Type),
}

/// A parameter of a tuple constructor. Unnamed parameters come first and can only be bound by position.
#[derive(Debug, Clone, PartialEq, Eq)]
pub struct Parameter {
    /// The name of the parameter, or `None` if it is unnamed.
    pub name: Option<String>,
    /// The position of the parameter.
    pub pos: Pos,
    /// The type of the parameter.
    pub ty: Type,
}

/// A field of a record type.
#[derive(Debug, Clone, PartialEq, Eq)]
pub struct Field {
    /// The name of the field.
    pub name: String,
    /// The position of the name.
    pub pos: Pos,
    /// The type of the field.
    pub ty: Type,
}

/// A type, as it is written in a declaration.
#[derive(Debug, Clone, PartialEq, Eq)]
pub enum Type {
    /// A named type with its arguments, such as `Nat` or `List<Int>`.
    Ref {
        /// The name of the type, as it is written.
        name: String,
        /// The position of the name.
        pos: Pos,
        /// The type arguments, which are empty if there are none.
        args: Vec<Type>,
    },
    /// An array of one element type, such as `[Nat]`.
    Array(Box<Type>),
    /// A record type without a name, such as `{ x: Int }`.
    Record(Vec<Field>),
}

/// A data value.
#[derive(Debug, Clone, PartialEq, Eq)]
pub struct Value {
    /// The position of the start of the value.
    pub pos: Pos,
    /// What the value is.
    pub kind: ValueKind,
}

/// The kinds of a data value.
#[derive(Debug, Clone, PartialEq, Eq)]
pub enum ValueKind {
    /// The literals keep their text, so that checking them against a type can decide how to interpret them.
    /// An unsigned integer literal, such as `42`.
    Nat(String),
    /// A signed integer literal, such as `+8` or `-1`.
    Int(String),
    /// A floating-point literal, such as `3.0` or `-2.5e3`.
    Float(String),
    /// A string literal, with its escapes decoded.
    Str(String),
    /// An array, such as `[1, 2]`.
    Array(Vec<Value>),
    /// A record without a constructor, such as `{ x: 1 }`.
    Record(Vec<Member>),
    /// A constructor, optionally followed by a record, a tuple or an array, as in `Quit`, `Move { x: 1 }`,
    /// `Write("hi")` or `Users[u1, u2]`.
    /// A name that starts with a lower-case letter or `_` is a reference to a const, which takes no body, and any other
    /// name is a constructor.
    Tagged {
        /// The name, as it is written, which may be qualified.
        name: String,
        /// What follows the name, or `None` if nothing does.
        body: Option<TaggedBody>,
    },
}

/// What follows the name of a constructor in a value.
#[derive(Debug, Clone, PartialEq, Eq)]
pub enum TaggedBody {
    /// A record, such as the `{ x: 1 }` of `Move { x: 1 }`.
    Record(Vec<Member>),
    /// A tuple, possibly empty as in `Ping()`. Positional arguments come before any named ones.
    Tuple(Vec<Argument>),
    /// An array, possibly empty as in `Users[]`. It has no names, so every element is an ordinary value.
    Array(Vec<Value>),
}

/// An argument of a tuple constructor, which is either positional or given by the name of a parameter.
#[derive(Debug, Clone, PartialEq, Eq)]
pub struct Argument {
    /// The name of the parameter, or `None` if the argument is positional.
    pub name: Option<String>,
    /// The position of the argument.
    pub pos: Pos,
    /// The value of the argument.
    pub value: Value,
}

/// A member of a record value, `name: value`.
#[derive(Debug, Clone, PartialEq, Eq)]
pub struct Member {
    /// The name of the member.
    pub name: String,
    /// The position of the name.
    pub pos: Pos,
    /// The value of the member.
    pub value: Value,
}

impl fmt::Display for Type {
    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
        match self {
            Type::Ref { name, args, .. } => {
                write!(f, "{}", name)?;
                if !args.is_empty() {
                    let args: Vec<String> = args.iter().map(|t| t.to_string()).collect();
                    write!(f, "<{}>", args.join(", "))?;
                }
                Ok(())
            }
            Type::Array(element) => write!(f, "[{}]", element),
            Type::Record(fields) if fields.is_empty() => write!(f, "{{}}"),
            Type::Record(fields) => {
                let fields: Vec<String> = fields
                    .iter()
                    .map(|field| format!("{}: {}", field.name, field.ty))
                    .collect();
                write!(f, "{{ {} }}", fields.join(", "))
            }
        }
    }
}

impl Value {
    /// The name of a tagged value, as it is written, such as `Follow` for `Follow` or `Preferences` for
    /// `Preferences { ... }`, whatever follows the name. A name that starts with a lower-case letter or `_`, such as
    /// `true`, is a reference to a const, which is not resolved. `None` for any other kind of value.
    pub fn tag(&self) -> Option<&str> {
        match &self.kind {
            ValueKind::Tagged { name, .. } => Some(name),
            _ => None,
        }
    }

    /// The members of a record, either untagged, as in `{ x: 1 }`, or after a tag, as in `Move { x: 1 }`. `None` for
    /// any other kind of value.
    pub fn members(&self) -> Option<&[Member]> {
        match &self.kind {
            ValueKind::Record(members)
            | ValueKind::Tagged {
                body: Some(TaggedBody::Record(members)),
                ..
            } => Some(members),
            _ => None,
        }
    }

    /// The value of the member called `name` of a record, as for `members`. `None` if the value is not a record or
    /// has no such member. A duplicate member is not an error here: the first is found.
    pub fn field(&self, name: &str) -> Option<&Value> {
        self.members()?.iter().find(|m| m.name == name).map(|m| &m.value)
    }

    /// The value of the member called `name` of a record, as for `field`, or an error at this value that says why
    /// there is none, in the words of `check`: `Missing field layout in Preferences`, or for a value that is not a
    /// record, `Expected a record but found Nat`. A duplicate member is not an error here: the first is found.
    pub fn require_field(&self, name: &str) -> Result<&Value, codec::Error> {
        let Some(members) = self.members() else {
            return Err(codec::expected("a record", self));
        };
        match members.iter().find(|m| m.name == name) {
            Some(member) => Ok(&member.value),
            None => {
                let owner = self.tag().unwrap_or("record");
                Err(codec::Error::at(
                    self.pos,
                    format!("Missing field {} in {}", name, owner),
                ))
            }
        }
    }

    // The `as_` accessors convert a value that should be of one kind, and are an error at the value if it is not, in
    // the words of `check`, such as `Expected String but found Nat`.

    /// The text of a string.
    pub fn as_str(&self) -> Result<&str, codec::Error> {
        match &self.kind {
            ValueKind::Str(text) => Ok(text),
            _ => Err(codec::expected("String", self)),
        }
    }

    /// The elements of an array, either untagged, as in `[1, 2]`, or after a tag, as in `Users[u1, u2]`.
    pub fn as_array(&self) -> Result<&[Value], codec::Error> {
        match &self.kind {
            ValueKind::Array(items)
            | ValueKind::Tagged {
                body: Some(TaggedBody::Array(items)),
                ..
            } => Ok(items),
            _ => Err(codec::expected("an array", self)),
        }
    }

    /// A `Bool` of the prelude: `True` or `False`, or `true` or `false`, which are the prelude's consts for them, or
    /// the full names `constructo.prelude::True` and `constructo.prelude::False`, which a codec writes with
    /// `Names::Full`. These names are known here, although the syntax knows no types, because a `Bool` is too common
    /// for every reader to work this out again. They are accepted even when the prelude is not loaded.
    pub fn as_bool(&self) -> Result<bool, codec::Error> {
        match &self.kind {
            ValueKind::Tagged { name, body: None } => match name.as_str() {
                "true" | "True" | "constructo.prelude::True" => Ok(true),
                "false" | "False" | "constructo.prelude::False" => Ok(false),
                _ => Err(codec::expected("Bool", self)),
            },
            _ => Err(codec::expected("Bool", self)),
        }
    }

    /// A `Nat`, as a `u64`. A number that is too large is an error at it.
    pub fn as_u64(&self) -> Result<u64, codec::Error> {
        codec::read_nat(self)
    }

    /// An `Int`, or a `Nat` widened to one, as an `i64`. A number that is too large is an error at it.
    pub fn as_i64(&self) -> Result<i64, codec::Error> {
        codec::read_int(self, true)
    }

    /// A `Float`, or a `Nat` or an `Int` widened to one, as the nearest `f64`. A number too large for an `f64` is an
    /// error at it.
    pub fn as_f64(&self) -> Result<f64, codec::Error> {
        codec::read_float(self, true)
    }

    /// Collects the names that the value uses on their own or as the tag of a body, with their positions. Any of them
    /// may refer to a const, which is for the caller to decide.
    pub fn names<'a>(&'a self, out: &mut Vec<(&'a str, Pos)>) {
        match &self.kind {
            ValueKind::Array(items) => items.iter().for_each(|item| item.names(out)),
            ValueKind::Record(members) => members.iter().for_each(|m| m.value.names(out)),
            ValueKind::Tagged { name, body } => {
                out.push((name, self.pos));
                match body {
                    Some(TaggedBody::Record(members)) => members.iter().for_each(|m| m.value.names(out)),
                    Some(TaggedBody::Tuple(items)) => items.iter().for_each(|item| item.value.names(out)),
                    Some(TaggedBody::Array(items)) => items.iter().for_each(|item| item.names(out)),
                    None => {}
                }
            }
            ValueKind::Nat(_) | ValueKind::Int(_) | ValueKind::Float(_) | ValueKind::Str(_) => {}
        }
    }
}

#[cfg(test)]
mod tests {
    use crate::codec::parse_one;

    #[test]
    fn a_tag_is_the_name_whatever_follows_it() {
        assert_eq!(parse_one("Follow").unwrap().tag(), Some("Follow"));
        assert_eq!(parse_one("Move { x: 1 }").unwrap().tag(), Some("Move"));
        assert_eq!(parse_one("Write(\"hi\")").unwrap().tag(), Some("Write"));
        assert_eq!(parse_one("true").unwrap().tag(), Some("true"));
        assert_eq!(parse_one("\"Follow\"").unwrap().tag(), None);
        assert_eq!(parse_one("{ x: 1 }").unwrap().tag(), None);
    }

    #[test]
    fn members_are_those_of_a_record_tagged_or_not() {
        let names = |text: &str| {
            parse_one(text)
                .unwrap()
                .members()
                .map(|ms| ms.iter().map(|m| m.name.clone()).collect::<Vec<_>>())
        };
        assert_eq!(names("{ x: 1, y: 2 }"), Some(vec!["x".to_string(), "y".to_string()]));
        assert_eq!(names("Move { x: 1 }"), Some(vec!["x".to_string()]));
        assert_eq!(names("Move {}"), Some(vec![]));
        assert_eq!(names("Move"), None);
        assert_eq!(names("Move(1)"), None);
        assert_eq!(names("[1]"), None);
    }

    #[test]
    fn a_field_is_found_by_its_name() {
        let value = parse_one("Prefs { layout: Icons, start: \"/home\", start: \"/tmp\" }").unwrap();
        assert_eq!(value.field("layout").and_then(|v| v.tag()), Some("Icons"));
        assert_eq!(value.field("start").and_then(|v| v.as_str().ok()), Some("/home"));
        assert!(value.field("missing").is_none());
        assert!(parse_one("[1]").unwrap().field("layout").is_none());
    }

    #[test]
    fn a_required_field_is_found_or_says_why_not() {
        let value = parse_one("Prefs {\n  layout: Icons,\n  start: \"/home\",\n  start: \"/tmp\" }").unwrap();
        assert_eq!(value.require_field("layout").unwrap().tag(), Some("Icons"));
        assert_eq!(value.require_field("start").unwrap().as_str().unwrap(), "/home");
        let missing = value.require_field("missing").unwrap_err();
        assert_eq!(missing.message(), "Missing field missing in Prefs");
        assert_eq!(missing.pos(), Some(value.pos));
        let untagged = parse_one("{ x: 1 }").unwrap().require_field("y").unwrap_err();
        assert_eq!(untagged.message(), "Missing field y in record");
        let not_a_record = parse_one("\n  42").unwrap().require_field("x").unwrap_err();
        assert_eq!(not_a_record.message(), "Expected a record but found Nat");
        assert_eq!(not_a_record.pos().map(|p| (p.line, p.col)), Some((2, 3)));
        let tagged_tuple = parse_one("Prefs(1)").unwrap().require_field("x").unwrap_err();
        assert_eq!(tagged_tuple.message(), "Expected a record but found Prefs");
    }

    /// The message of the error of a conversion that fails.
    fn refused<T: std::fmt::Debug>(result: Result<T, crate::codec::Error>) -> String {
        result.unwrap_err().message().to_string()
    }

    #[test]
    fn a_string_is_its_text() {
        assert_eq!(parse_one("\"a\\nb\"").unwrap().as_str().unwrap(), "a\nb");
        assert_eq!(
            refused(parse_one("Follow").unwrap().as_str()),
            "Expected String but found Follow"
        );
        assert_eq!(
            refused(parse_one("42").unwrap().as_str()),
            "Expected String but found Nat"
        );
    }

    #[test]
    fn an_array_is_its_elements_tagged_or_not() {
        assert_eq!(parse_one("[1, 2]").unwrap().as_array().unwrap().len(), 2);
        assert_eq!(parse_one("Users[1]").unwrap().as_array().unwrap().len(), 1);
        assert_eq!(
            refused(parse_one("Users").unwrap().as_array()),
            "Expected an array but found Users"
        );
        assert_eq!(
            refused(parse_one("{ x: [1] }").unwrap().as_array()),
            "Expected an array but found a record"
        );
    }

    #[test]
    fn a_bool_is_true_or_false_by_either_name() {
        for (text, truth) in [
            ("true", true),
            ("True", true),
            ("constructo.prelude::True", true),
            ("false", false),
            ("False", false),
            ("constructo.prelude::False", false),
        ] {
            assert_eq!(parse_one(text).unwrap().as_bool().unwrap(), truth);
        }
        assert_eq!(
            refused(parse_one("Yes").unwrap().as_bool()),
            "Expected Bool but found Yes"
        );
        assert_eq!(
            refused(parse_one("other.project::True").unwrap().as_bool()),
            "Expected Bool but found other.project::True"
        );
        assert_eq!(
            refused(parse_one("True(1)").unwrap().as_bool()),
            "Expected Bool but found True"
        );
        assert_eq!(
            refused(parse_one("\"true\"").unwrap().as_bool()),
            "Expected Bool but found String"
        );
    }

    #[test]
    fn a_number_is_read_with_widening_and_must_fit() {
        assert_eq!(parse_one("42").unwrap().as_u64().unwrap(), 42);
        assert_eq!(refused(parse_one("-1").unwrap().as_u64()), "Expected Nat but found Int");
        assert_eq!(
            refused(parse_one("18446744073709551616").unwrap().as_u64()),
            "The number 18446744073709551616 does not fit Nat"
        );
        assert_eq!(parse_one("-7").unwrap().as_i64().unwrap(), -7);
        assert_eq!(parse_one("7").unwrap().as_i64().unwrap(), 7);
        assert_eq!(
            refused(parse_one("1.5").unwrap().as_i64()),
            "Expected Int but found Float"
        );
        assert_eq!(parse_one("2.5").unwrap().as_f64().unwrap(), 2.5);
        assert_eq!(parse_one("-3").unwrap().as_f64().unwrap(), -3.0);
        assert_eq!(
            refused(parse_one("\"1\"").unwrap().as_f64()),
            "Expected Float but found String"
        );
    }
}