Skip to main content

constructo_runtime/
codec.rs

1//! What the codec that `constructo codegen` generates calls and needs no trait for: the error of reading or writing a
2//! value, the setting of how names are written, the parts of a record and a tuple in the order of their declaration,
3//! the numbers, and the builders of a tree.
4//!
5//! The traits and the tables of names and consts are generated with each codec, in the program's own crate, so that
6//! they can be implemented for a type of any crate. What is here is the same for every codec. Its messages are those of
7//! `constructo check`, where the error is one that `check` finds.
8
9use crate::ast::{Argument, Member, TaggedBody, Value, ValueKind};
10use crate::diagnostics::Pos;
11use crate::parser::parse_values;
12use crate::values_text::render;
13use std::fmt;
14
15/// How a codec writes the name of a constructor.
16#[derive(Debug, Clone, Copy, PartialEq, Eq, Default)]
17pub enum Names {
18    /// As the project that the code was generated for writes it: bare, else through a group, else in full.
19    #[default]
20    Project,
21    /// In full, as `com.example.shapes::Circle`, which any project reads.
22    Full,
23}
24
25/// A step of the path from the value that was read or written to the value that an error is about.
26#[derive(Debug, Clone, PartialEq, Eq)]
27pub enum Step {
28    /// A field of a record, or a parameter of a tuple, by name.
29    Field(String),
30    /// A parameter of a tuple that has no name, by its position from 0.
31    Position(usize),
32    /// An element of an array, by its index from 0.
33    Index(usize),
34}
35
36/// An error of reading or of writing a value.
37///
38/// It has the message, and the path in the value, by field and index, which is added to as the error passes out of each
39/// field and element, so that it is built only when there is an error. An error of reading has the position in the
40/// text. An error in the value of a const has the position of the reference to it, and the const is named.
41#[derive(Debug, Clone, PartialEq, Eq)]
42pub struct Error {
43    message: String,
44    pos: Option<Pos>,
45    /// The steps from the innermost out, which is the order in which they are added.
46    path: Vec<Step>,
47    /// The consts that the error is inside, from the outermost in.
48    consts: Vec<String>,
49}
50
51impl Error {
52    /// An error at a position in the text that is read.
53    pub fn at(pos: Pos, message: impl Into<String>) -> Error {
54        Error {
55            message: message.into(),
56            pos: Some(pos),
57            path: Vec::new(),
58            consts: Vec::new(),
59        }
60    }
61
62    /// An error that has no position, as an error of writing has none.
63    pub fn new(message: impl Into<String>) -> Error {
64        Error {
65            message: message.into(),
66            pos: None,
67            path: Vec::new(),
68            consts: Vec::new(),
69        }
70    }
71
72    /// The error with a step in front of its path, as it passes out of the value that the step leads to.
73    pub fn step(mut self, step: Step) -> Error {
74        self.path.push(step);
75        self
76    }
77
78    /// The error inside the value of a const, as it passes out of the reference to the const, at `pos`. The position
79    /// in the text of the const's value means nothing to the reader of the message, so it is replaced by that of the
80    /// reference.
81    pub fn in_const(mut self, name: &str, pos: Pos) -> Error {
82        self.pos = Some(pos);
83        self.consts.insert(0, name.to_string());
84        self
85    }
86
87    /// The message, without the path, the consts or the position.
88    pub fn message(&self) -> &str {
89        &self.message
90    }
91
92    /// The position in the text, if the error is one of reading.
93    pub fn pos(&self) -> Option<Pos> {
94        self.pos
95    }
96
97    /// The path in the value, from the outside in, as in `shapes[0].colour`, which is empty for the value itself.
98    pub fn path(&self) -> String {
99        let mut out = String::new();
100        for step in self.path.iter().rev() {
101            match step {
102                Step::Field(name) => {
103                    if !out.is_empty() {
104                        out.push('.');
105                    }
106                    out.push_str(name);
107                }
108                Step::Position(at) => {
109                    if !out.is_empty() {
110                        out.push('.');
111                    }
112                    out.push_str(&at.to_string());
113                }
114                Step::Index(at) => out.push_str(&format!("[{}]", at)),
115            }
116        }
117        out
118    }
119
120    /// The consts that the error is inside, from the outermost in.
121    pub fn consts(&self) -> &[String] {
122        &self.consts
123    }
124}
125
126/// Shown as `shapes[0].colour: in the value of const c: MESSAGE (line 3, col 12)`, with each part only if there is one.
127impl fmt::Display for Error {
128    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
129        let path = self.path();
130        if !path.is_empty() {
131            write!(f, "{}: ", path)?;
132        }
133        for name in &self.consts {
134            write!(f, "in the value of const {}: ", name)?;
135        }
136        write!(f, "{}", self.message)?;
137        if let Some(pos) = self.pos {
138            write!(f, " ({})", pos)?;
139        }
140        Ok(())
141    }
142}
143
144impl std::error::Error for Error {}
145
146/// The values of a text.
147pub fn parse(text: &str) -> Result<Vec<Value>, Error> {
148    parse_values(text).map_err(|e| Error::at(e.pos, e.message))
149}
150
151/// The one value of a text, which is an error at the start of the text if it has more or fewer.
152pub fn parse_one(text: &str) -> Result<Value, Error> {
153    let mut values = parse(text)?;
154    match values.len() {
155        1 => Ok(values.remove(0)),
156        n => Err(Error::at(
157            Pos { line: 1, col: 1 },
158            format!("Expected one value but found {}", n),
159        )),
160    }
161}
162
163/// The text of the values, each ended by `;` and a new line, as `convert` writes them.
164pub fn write_text(values: &[Value]) -> String {
165    values.iter().map(|value| render(value, false)).collect()
166}
167
168/// The depth of a value inside one at `depth`, which is an error if it is more than `max`. Each value is a level, a
169/// scalar included, as the parser counts them, so a value that is read is never deeper than one that the parser reads,
170/// and one that is written can be read back.
171pub fn enter(depth: u32, max: u32, pos: Option<Pos>) -> Result<u32, Error> {
172    if depth >= max {
173        let message = "Nesting is too deep";
174        return Err(match pos {
175            Some(pos) => Error::at(pos, message),
176            None => Error::new(message),
177        });
178    }
179    Ok(depth + 1)
180}
181
182/// Whether a name is that of a const, which starts with a lower-case letter or `_`, after any qualifier, as a
183/// constructor starts with a capital letter (decision 35).
184pub fn is_const_name(name: &str) -> bool {
185    let local = name.rsplit("::").next().unwrap_or(name);
186    local.starts_with(|c: char| c.is_ascii_lowercase() || c == '_')
187}
188
189/// What a value is, for a message, as `check` says it: `Nat`, `Int`, `Float`, `String`, `an array` or `a record`. A
190/// tagged value is its name as it is written, which a codec can give with its type.
191pub fn found(value: &Value) -> String {
192    match &value.kind {
193        ValueKind::Nat(_) => "Nat".to_string(),
194        ValueKind::Int(_) => "Int".to_string(),
195        ValueKind::Float(_) => "Float".to_string(),
196        ValueKind::Str(_) => "String".to_string(),
197        ValueKind::Array(_) => "an array".to_string(),
198        ValueKind::Record(_) => "a record".to_string(),
199        ValueKind::Tagged { name, .. } => name.clone(),
200    }
201}
202
203/// The error for a value that is not of the type that is expected: `Expected Nat but found String`.
204pub fn expected(what: &str, value: &Value) -> Error {
205    Error::at(value.pos, format!("Expected {} but found {}", what, found(value)))
206}
207
208/// The members of a record, or of a constructor with a record, in the order of `names`, which are the fields. Every
209/// field is required and no other is allowed, and the errors are `check`'s, in its order: a duplicate or an unknown
210/// field at the member, then a missing one at the record. `owner` is the constructor, or `record` for a record
211/// without a name.
212pub fn fields<'a, const N: usize>(
213    members: &'a [Member],
214    names: [&str; N],
215    owner: &str,
216    pos: Pos,
217) -> Result<[&'a Value; N], Error> {
218    let mut slots: [Option<&'a Value>; N] = [None; N];
219    for (index, member) in members.iter().enumerate() {
220        if members[..index].iter().any(|m| m.name == member.name) {
221            return Err(Error::at(member.pos, format!("Duplicate field {}", member.name)));
222        }
223        match names.iter().position(|name| *name == member.name) {
224            Some(at) => slots[at] = Some(&member.value),
225            None => {
226                return Err(Error::at(
227                    member.pos,
228                    format!("Unknown field {} in {}", member.name, owner),
229                ))
230            }
231        }
232    }
233    if let Some(at) = slots.iter().position(Option::is_none) {
234        return Err(Error::at(pos, format!("Missing field {} in {}", names[at], owner)));
235    }
236    Ok(slots.map(|slot| slot.expect("every field has been found")))
237}
238
239/// The arguments of a constructor with a tuple, in the order of its parameters, which are given by their names, or
240/// `None` for a parameter that has none. The arguments without a name bind the parameters in order, and those with a
241/// name bind the parameter of that name, which may be one that could have been bound in order. A named parameter that
242/// is not bound is `None`, and takes the default of its type; an unnamed one is an error. The errors are `check`'s, in
243/// its order.
244pub fn arguments<'a, const N: usize>(
245    args: &'a [Argument],
246    params: [Option<&str>; N],
247    owner: &str,
248    pos: Pos,
249) -> Result<[Option<&'a Value>; N], Error> {
250    let count = || format!("Constructor {} takes {} value(s) but has {}", owner, N, args.len());
251    let mut slots: [Option<&'a Value>; N] = [None; N];
252    for (index, arg) in args.iter().enumerate() {
253        let target = match &arg.name {
254            None if index < N => index,
255            None => return Err(Error::at(arg.pos, count())),
256            Some(name) => match params.iter().position(|p| *p == Some(name.as_str())) {
257                Some(target) => target,
258                None => return Err(Error::at(arg.pos, format!("Unknown argument {} in {}", name, owner))),
259            },
260        };
261        if slots[target].is_some() {
262            let message = match params[target] {
263                Some(name) => format!("Argument {} is given more than once in {}", name, owner),
264                None => format!("Argument {} is given more than once in {}", target + 1, owner),
265            };
266            return Err(Error::at(arg.pos, message));
267        }
268        slots[target] = Some(&arg.value);
269    }
270    if (0..N).any(|at| slots[at].is_none() && params[at].is_none()) {
271        return Err(Error::at(pos, count()));
272    }
273    Ok(slots)
274}
275
276/// A `Nat` from its text. A sign makes a number an `Int`, which is never a `Nat`, as in `check`, and a number that is
277/// too large for a `u64` is an error at it.
278pub fn read_nat(value: &Value) -> Result<u64, Error> {
279    match &value.kind {
280        ValueKind::Nat(text) => text.parse().map_err(|_| does_not_fit(value, text, "Nat")),
281        _ => Err(expected("Nat", value)),
282    }
283}
284
285/// An `Int` from its text, or from that of a `Nat` if `widening` is set. A number that is too large for an `i64` is an
286/// error at it.
287pub fn read_int(value: &Value, widening: bool) -> Result<i64, Error> {
288    match &value.kind {
289        ValueKind::Int(text) => text.parse().map_err(|_| does_not_fit(value, text, "Int")),
290        ValueKind::Nat(text) if widening => text.parse().map_err(|_| does_not_fit(value, text, "Int")),
291        _ => Err(expected("Int", value)),
292    }
293}
294
295/// A `Float` from its text, or from that of a `Nat` or an `Int` if `widening` is set: the nearest `f64`, which is the
296/// one loss that a mapping is allowed. A number too small to be held other than as zero is zero, and one too large
297/// for an `f64`, such as `1.0e400`, is an error at it, since making it infinite would change a finite value into one
298/// that is not. There is no negative zero, so `-0.0` is `0.0`.
299pub fn read_float(value: &Value, widening: bool) -> Result<f64, Error> {
300    let text = match &value.kind {
301        ValueKind::Float(text) => text,
302        ValueKind::Nat(text) | ValueKind::Int(text) if widening => text,
303        _ => return Err(expected("Float", value)),
304    };
305    match text.parse::<f64>() {
306        Ok(number) if number.is_finite() => Ok(if number == 0.0 { 0.0 } else { number }),
307        _ => Err(does_not_fit(value, text, "Float")),
308    }
309}
310
311fn does_not_fit(value: &Value, text: &str, what: &str) -> Error {
312    Error::at(value.pos, format!("The number {} does not fit {}", text, what))
313}
314
315/// Why a type has no default that can be used where an argument is left out.
316#[derive(Debug, Clone, PartialEq, Eq)]
317pub enum NoDefault {
318    /// The enum, by its name, has no default at all, since its first constructor leads back to it.
319    None(String),
320    /// The default has more nodes than the limit of the codec.
321    TooLarge,
322    /// The default of an adopted type was built from the defaults of its arguments, and the function of the adoption
323    /// refused them, for the reason given.
324    Refused(String),
325}
326
327/// Counts a node of a default against what is left of the limit.
328pub fn spend(budget: &mut usize) -> Result<(), NoDefault> {
329    if *budget == 0 {
330        return Err(NoDefault::TooLarge);
331    }
332    *budget -= 1;
333    Ok(())
334}
335
336/// The error for an argument that is left out, at the constructor, where its type has no default that can be used. The
337/// messages are `check`'s, with the codec's limit, and `param` is the name of the parameter.
338pub fn no_default(why: NoDefault, param: &str, limit: usize, pos: Pos) -> Error {
339    let message = match why {
340        NoDefault::None(ty) => format!("Type {} has no default value", ty),
341        NoDefault::TooLarge => format!(
342            "The default value of argument {} has more than {} nodes, which is too large; give argument {}",
343            param, limit, param
344        ),
345        NoDefault::Refused(why) => format!("The default value of argument {} is refused: {}", param, why),
346    };
347    Error::at(pos, message)
348}
349
350/// A string from its value.
351pub fn read_string(value: &Value) -> Result<String, Error> {
352    match &value.kind {
353        ValueKind::Str(text) => Ok(text.clone()),
354        _ => Err(expected("String", value)),
355    }
356}
357
358// The builders of a tree, for writing. A value that a program builds has no position in a text, so each is given the
359// first, which `render` does not write.
360
361fn built(kind: ValueKind) -> Value {
362    Value {
363        pos: Pos { line: 1, col: 1 },
364        kind,
365    }
366}
367
368/// A `Nat`.
369pub fn nat(number: u64) -> Value {
370    built(ValueKind::Nat(number.to_string()))
371}
372
373/// An `Int`, with its sign, which a number that is not negative has as `+`, as `convert` writes it.
374pub fn int(number: i64) -> Value {
375    let text = if number < 0 {
376        number.to_string()
377    } else {
378        format!("+{}", number)
379    };
380    built(ValueKind::Int(text))
381}
382
383/// A `Float`, as the shortest text that reads back as the same `f64`. Rust's own shortest text is used, with `.0` put
384/// in where it has no point, as in `1.0e300`, and a zero is written as `0.0`, since there is no negative zero. A value
385/// that is not finite has no text yet, and is an error.
386pub fn float(number: f64) -> Result<Value, Error> {
387    if !number.is_finite() {
388        return Err(Error::new(format!(
389            "The Float {} cannot be written, since Constructo has no text for it yet",
390            number
391        )));
392    }
393    if number == 0.0 {
394        return Ok(built(ValueKind::Float("0.0".to_string())));
395    }
396    let text = format!("{:?}", number);
397    let text = match text.split_once('e') {
398        Some((digits, exponent)) if !digits.contains('.') => format!("{}.0e{}", digits, exponent),
399        _ if !text.contains('.') => format!("{}.0", text),
400        _ => text,
401    };
402    Ok(built(ValueKind::Float(text)))
403}
404
405/// A `String`.
406pub fn string(text: &str) -> Value {
407    built(ValueKind::Str(text.to_string()))
408}
409
410/// An array.
411pub fn array(items: Vec<Value>) -> Value {
412    built(ValueKind::Array(items))
413}
414
415/// A record without a name, with its members in the order given.
416pub fn record(members: Vec<(&str, Value)>) -> Value {
417    built(ValueKind::Record(make_members(members)))
418}
419
420/// A constructor with no body, or a reference to a const.
421pub fn unit(name: &str) -> Value {
422    built(ValueKind::Tagged {
423        name: name.to_string(),
424        body: None,
425    })
426}
427
428/// A constructor with a record.
429pub fn tagged_record(name: &str, members: Vec<(&str, Value)>) -> Value {
430    tagged(name, TaggedBody::Record(make_members(members)))
431}
432
433/// A constructor with a tuple, each argument with its name if it is written by name.
434pub fn tagged_tuple(name: &str, args: Vec<(Option<&str>, Value)>) -> Value {
435    let args = args
436        .into_iter()
437        .map(|(name, value)| Argument {
438            name: name.map(str::to_string),
439            pos: value.pos,
440            value,
441        })
442        .collect();
443    tagged(name, TaggedBody::Tuple(args))
444}
445
446/// A constructor with an array.
447pub fn tagged_array(name: &str, items: Vec<Value>) -> Value {
448    tagged(name, TaggedBody::Array(items))
449}
450
451fn tagged(name: &str, body: TaggedBody) -> Value {
452    built(ValueKind::Tagged {
453        name: name.to_string(),
454        body: Some(body),
455    })
456}
457
458fn make_members(members: Vec<(&str, Value)>) -> Vec<Member> {
459    members
460        .into_iter()
461        .map(|(name, value)| Member {
462            name: name.to_string(),
463            pos: value.pos,
464            value,
465        })
466        .collect()
467}
468
469#[cfg(test)]
470mod tests {
471    use super::*;
472    use crate::limits::MAX_DEPTH;
473
474    fn one(text: &str) -> Value {
475        parse_one(text).unwrap()
476    }
477
478    fn written(value: &Value) -> String {
479        write_text(std::slice::from_ref(value))
480            .trim_end_matches(";\n")
481            .to_string()
482    }
483
484    fn members(value: &Value) -> &[Member] {
485        match &value.kind {
486            ValueKind::Record(members) => members,
487            ValueKind::Tagged {
488                body: Some(TaggedBody::Record(members)),
489                ..
490            } => members,
491            other => panic!("not a record: {:?}", other),
492        }
493    }
494
495    fn args(value: &Value) -> &[Argument] {
496        match &value.kind {
497            ValueKind::Tagged {
498                body: Some(TaggedBody::Tuple(args)),
499                ..
500            } => args,
501            other => panic!("not a tuple: {:?}", other),
502        }
503    }
504
505    #[test]
506    fn an_error_shows_its_path_its_consts_and_its_position() {
507        let pos = Pos { line: 3, col: 12 };
508        let error = Error::at(Pos { line: 1, col: 5 }, "Expected Nat but found String")
509            .step(Step::Field("colour".into()))
510            .in_const("inner", Pos { line: 1, col: 2 })
511            .step(Step::Index(0))
512            .in_const("outer", pos)
513            .step(Step::Field("shapes".into()));
514        assert_eq!(
515            error.to_string(),
516            "shapes[0].colour: in the value of const outer: in the value of const inner: Expected Nat but found String \
517             (line 3, col 12)"
518        );
519        assert_eq!(error.pos(), Some(pos));
520        assert_eq!(error.consts(), ["outer", "inner"]);
521        assert_eq!(error.message(), "Expected Nat but found String");
522        let written = Error::new("The Float NaN cannot be written").step(Step::Position(1));
523        assert_eq!(written.to_string(), "1: The Float NaN cannot be written");
524        assert_eq!(
525            Error::new("x")
526                .step(Step::Position(0))
527                .step(Step::Field("a".into()))
528                .path(),
529            "a.0"
530        );
531    }
532
533    #[test]
534    fn a_text_has_one_value_or_it_is_an_error() {
535        assert_eq!(written(&one(" Dot ")), "Dot");
536        assert_eq!(
537            parse_one("1; 2").unwrap_err().to_string(),
538            "Expected one value but found 2 (line 1, col 1)"
539        );
540        assert_eq!(
541            parse_one("Dot(").unwrap_err().pos(),
542            parse_values("Dot(").unwrap_err().pos.into()
543        );
544    }
545
546    #[test]
547    fn the_depth_that_is_entered_is_counted_against_the_limit() {
548        assert_eq!(enter(0, 2, None), Ok(1));
549        assert_eq!(enter(1, 2, None), Ok(2));
550        assert_eq!(enter(2, 2, None).unwrap_err().message(), "Nesting is too deep");
551        let pos = Pos { line: 2, col: 3 };
552        assert_eq!(enter(2, 2, Some(pos)).unwrap_err().pos(), Some(pos));
553    }
554
555    /// How deep the value is, counted as `enter` counts it: each value is a level.
556    fn height(value: &Value) -> u32 {
557        let inner = match &value.kind {
558            ValueKind::Array(items) => items.iter().map(height).max(),
559            ValueKind::Record(members) => members.iter().map(|m| height(&m.value)).max(),
560            ValueKind::Tagged { body, .. } => match body {
561                Some(TaggedBody::Record(members)) => members.iter().map(|m| height(&m.value)).max(),
562                Some(TaggedBody::Tuple(args)) => args.iter().map(|a| height(&a.value)).max(),
563                Some(TaggedBody::Array(items)) => items.iter().map(height).max(),
564                None => None,
565            },
566            _ => None,
567        };
568        1 + inner.unwrap_or(0)
569    }
570
571    #[test]
572    fn the_parser_reads_a_value_exactly_as_deep_as_the_limit_of_a_codec() {
573        // Every kind of nesting, so that what a codec writes within its limit the parser reads back.
574        let wrappers: [(&str, &str); 5] = [("[", "]"), ("{ a: ", " }"), ("A(", ")"), ("A { a: ", " }"), ("A[", "]")];
575        for (open, close) in wrappers {
576            let nested = |levels: u32| format!("{}1{}", open.repeat(levels as usize), close.repeat(levels as usize));
577            let deepest = parse_one(&nested(MAX_DEPTH - 1)).unwrap();
578            assert_eq!(height(&deepest), MAX_DEPTH, "{}", open);
579            assert!(parse_one(&nested(MAX_DEPTH)).is_err(), "{}", open);
580        }
581    }
582
583    #[test]
584    fn the_fields_are_given_in_the_order_of_the_declaration() {
585        let value = one("Box { height: 2.0, width: 1.0 }");
586        let [width, height] = fields(members(&value), ["width", "height"], "Box", value.pos).unwrap();
587        assert_eq!((written(width), written(height)), ("1.0".into(), "2.0".into()));
588        let error = |text: &str| {
589            let value = one(text);
590            fields(members(&value), ["width", "height"], "Box", value.pos)
591                .unwrap_err()
592                .to_string()
593        };
594        assert_eq!(
595            error("Box { width: 1.0 }"),
596            "Missing field height in Box (line 1, col 1)"
597        );
598        assert_eq!(
599            error("Box { width: 1.0, height: 1.0, depth: 1.0 }"),
600            "Unknown field depth in Box (line 1, col 32)"
601        );
602        assert_eq!(
603            error("Box { width: 1.0, width: 1.0 }"),
604            "Duplicate field width (line 1, col 19)"
605        );
606        let empty = one("{}");
607        assert!(fields(members(&empty), [], "record", empty.pos).is_ok());
608    }
609
610    #[test]
611    fn the_arguments_bind_in_order_then_by_name() {
612        // Image(String, String, hOffset: Nat, vOffset: Nat, alignment: String), as in the typed examples.
613        let params = [None, None, Some("hOffset"), Some("vOffset"), Some("alignment")];
614        let bind = |text: &str| {
615            let value = one(text);
616            arguments(args(&value), params, "Image", value.pos)
617                .map(|slots| slots.map(|slot| slot.map(written)))
618                .map_err(|e| e.to_string())
619        };
620        let given = |list: [&str; 5]| -> [Option<String>; 5] { list.map(|s| (!s.is_empty()).then(|| s.to_string())) };
621        assert_eq!(
622            bind(r#"Image("a", "b", alignment: "left", hOffset: 1, vOffset: 2)"#),
623            Ok(given([r#""a""#, r#""b""#, "1", "2", r#""left""#]))
624        );
625        assert_eq!(
626            bind(r#"Image("a", "b", 1)"#),
627            Ok(given([r#""a""#, r#""b""#, "1", "", ""]))
628        );
629        assert_eq!(
630            bind(r#"Image("a", "b", 1, 2, "left", hOffset: 3)"#),
631            Err("Argument hOffset is given more than once in Image (line 1, col 31)".into())
632        );
633        assert_eq!(
634            bind(r#"Image("a", "b", colour: "red")"#),
635            Err("Unknown argument colour in Image (line 1, col 17)".into())
636        );
637        assert_eq!(
638            bind(r#"Image("a")"#),
639            Err("Constructor Image takes 5 value(s) but has 1 (line 1, col 1)".into())
640        );
641        assert_eq!(
642            bind(r#"Image("a", "b", 1, 2, "c", 3)"#),
643            Err("Constructor Image takes 5 value(s) but has 6 (line 1, col 28)".into())
644        );
645        let pair = one("Pair(1, 1)");
646        let error = arguments(args(&pair), [None], "Pair", pair.pos).unwrap_err();
647        assert_eq!(error.message(), "Constructor Pair takes 1 value(s) but has 2");
648    }
649
650    #[test]
651    fn a_whole_number_is_read_if_it_fits_and_a_sign_makes_it_an_int() {
652        assert_eq!(read_nat(&one("18446744073709551615")), Ok(u64::MAX));
653        assert_eq!(read_nat(&one("007")), Ok(7));
654        assert_eq!(
655            read_nat(&one("18446744073709551616")).unwrap_err().message(),
656            "The number 18446744073709551616 does not fit Nat"
657        );
658        assert_eq!(
659            read_nat(&one("+1")).unwrap_err().message(),
660            "Expected Nat but found Int"
661        );
662        assert_eq!(
663            read_nat(&one("1.0")).unwrap_err().message(),
664            "Expected Nat but found Float"
665        );
666        assert_eq!(
667            read_nat(&one("\"1\"")).unwrap_err().message(),
668            "Expected Nat but found String"
669        );
670        assert_eq!(read_int(&one("-9223372036854775808"), true), Ok(i64::MIN));
671        assert_eq!(read_int(&one("+9223372036854775807"), true), Ok(i64::MAX));
672        assert_eq!(read_int(&one("-0"), true), Ok(0));
673        assert_eq!(read_int(&one("5"), true), Ok(5));
674        assert_eq!(
675            read_int(&one("5"), false).unwrap_err().message(),
676            "Expected Int but found Nat"
677        );
678        assert_eq!(
679            read_int(&one("9223372036854775808"), true).unwrap_err().message(),
680            "The number 9223372036854775808 does not fit Int"
681        );
682        assert_eq!(
683            read_int(&one("-9223372036854775809"), true).unwrap_err().message(),
684            "The number -9223372036854775809 does not fit Int"
685        );
686    }
687
688    #[test]
689    fn a_float_is_the_nearest_f64_and_one_too_large_is_refused() {
690        assert_eq!(read_float(&one("0.1"), true), Ok(0.1));
691        assert_eq!(read_float(&one("1.5E+2"), true), Ok(150.0));
692        assert_eq!(read_float(&one("-2.5e3"), true), Ok(-2500.0));
693        assert_eq!(read_float(&one("1.50"), true), Ok(1.5));
694        let zero = read_float(&one("-0.0"), true).unwrap();
695        assert!(zero == 0.0 && zero.is_sign_positive());
696        assert_eq!(read_float(&one("1.0e-400"), true), Ok(0.0));
697        assert_eq!(read_float(&one("4.9e-324"), true), Ok(f64::from_bits(1)));
698        assert_eq!(
699            read_float(&one("1.0e400"), true).unwrap_err().message(),
700            "The number 1.0e400 does not fit Float"
701        );
702        let huge = "9".repeat(400);
703        assert_eq!(
704            read_float(&one(&huge), true).unwrap_err().message(),
705            format!("The number {} does not fit Float", huge)
706        );
707        assert_eq!(read_float(&one("3"), true), Ok(3.0));
708        assert_eq!(read_float(&one("-3"), true), Ok(-3.0));
709        assert_eq!(
710            read_float(&one("3"), false).unwrap_err().message(),
711            "Expected Float but found Nat"
712        );
713        assert_eq!(
714            read_float(&one("-3"), false).unwrap_err().message(),
715            "Expected Float but found Int"
716        );
717    }
718
719    #[test]
720    fn a_const_is_named_in_lower_case_after_any_qualifier() {
721        for name in ["null", "_x", "local::unit", "com.example.Shapes::big"] {
722            assert!(is_const_name(name), "{}", name);
723        }
724        for name in ["None", "local::Circle", "com.example.shapes::Circle"] {
725            assert!(!is_const_name(name), "{}", name);
726        }
727    }
728
729    #[test]
730    fn a_default_spends_the_budget_and_says_why_it_cannot_be_used() {
731        let mut budget = 2;
732        assert_eq!(spend(&mut budget), Ok(()));
733        assert_eq!(spend(&mut budget), Ok(()));
734        assert_eq!(spend(&mut budget), Err(NoDefault::TooLarge));
735        let pos = Pos { line: 1, col: 4 };
736        assert_eq!(
737            no_default(NoDefault::None("Chain".into()), "chain", 10, pos).to_string(),
738            "Type Chain has no default value (line 1, col 4)"
739        );
740        assert_eq!(
741            no_default(NoDefault::TooLarge, "chain", 10, pos).message(),
742            "The default value of argument chain has more than 10 nodes, which is too large; give argument chain"
743        );
744        assert_eq!(
745            no_default(NoDefault::Refused("\"\" is not a UUID".into()), "id", 10, pos).message(),
746            "The default value of argument id is refused: \"\" is not a UUID"
747        );
748    }
749
750    #[test]
751    fn a_number_is_written_as_convert_writes_it() {
752        assert_eq!(written(&nat(u64::MAX)), "18446744073709551615");
753        assert_eq!(written(&int(0)), "+0");
754        assert_eq!(written(&int(5)), "+5");
755        assert_eq!(written(&int(i64::MIN)), "-9223372036854775808");
756    }
757
758    #[test]
759    fn a_float_is_written_as_the_shortest_text_that_reads_back() {
760        let cases: [(f64, &str); 10] = [
761            (0.1, "0.1"),
762            (1.5, "1.5"),
763            (100.0, "100.0"),
764            (-2.5, "-2.5"),
765            (0.0, "0.0"),
766            (-0.0, "0.0"),
767            (1e300, "1.0e300"),
768            (1.5e300, "1.5e300"),
769            (1e-7, "1.0e-7"),
770            (f64::MAX, "1.7976931348623157e308"),
771        ];
772        for (number, text) in cases {
773            let value = float(number).unwrap();
774            assert_eq!(written(&value), text);
775            // What is written is a Float that the parser reads, and it reads back as the same number.
776            let back = read_float(&one(text), false).unwrap();
777            assert_eq!(
778                back.to_bits(),
779                if number == 0.0 { 0 } else { number.to_bits() },
780                "{}",
781                text
782            );
783        }
784        for number in [
785            f64::MIN_POSITIVE,
786            f64::from_bits(1),
787            1e16,
788            123456789.125,
789            std::f64::consts::PI,
790        ] {
791            let text = written(&float(number).unwrap());
792            assert_eq!(read_float(&one(&text), false), Ok(number), "{}", text);
793        }
794        for number in [f64::NAN, f64::INFINITY, f64::NEG_INFINITY] {
795            let error = float(number).unwrap_err();
796            assert_eq!(error.pos(), None);
797            assert!(error.message().starts_with("The Float "), "{}", error);
798        }
799    }
800
801    #[test]
802    fn the_builders_make_the_tree_that_the_parser_makes() {
803        let value = tagged_tuple(
804            "Image",
805            vec![
806                (None, string("a\"b")),
807                (Some("hOffset"), nat(1)),
808                (
809                    Some("tags"),
810                    array(vec![unit("None"), tagged_array("Items", vec![int(-1)])]),
811                ),
812                (
813                    Some("at"),
814                    tagged_record("Point", vec![("x", float(1.0).unwrap()), ("y", record(vec![]))]),
815                ),
816            ],
817        );
818        let text = written(&value);
819        assert_eq!(
820            text,
821            r#"Image("a\"b", hOffset: 1, tags: [None, Items[-1]], at: Point { x: 1.0, y: {} })"#
822        );
823        assert_eq!(written(&one(&text)), text);
824    }
825}