flow-types 0.1.0-rc.5

The Flow declaration model with no values: types, declarations and their identities, record and enum shapes, and which types decoding may build.
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
//! std's roles, and the members of a std declaration a Rust rule reads,
//! bound once (`docs/language/spec/stdlib.md`, *`@lang` declarations*).
//!
//! The compiler knows roles, never names: std marks the declaration that
//! plays each [`Role`], and [`crate::std_roles`] (generated from std) says
//! where each one is. A Rust rule that reads a constructor or a field of a
//! std declaration names it through a closed [`Members`] enum, and a
//! [`StdEnum`] or [`StdRecord`] finds every member's position in the
//! declaration once, so nothing compares a member's name again.

use std::fmt;
use std::marker::PhantomData;

use crate::shape::{EnumShape, RecordShape};

flow_span::spelled! {
    /// A type a compiler rule names by the role std marks it with.
    ///
    /// A literal form is a role too: `int_literal` marks the type an integer
    /// literal builds.
    pub enum Role {
        /// How std spells it in `@lang`.
        pub fn spelling(self) -> &'static str;
        /// The one std spells `spelling`, if any.
        pub fn named(&str);
        /// `Int`.
        Int = "int",
        /// `Decimal`.
        Decimal = "decimal",
        /// `Bool`, whose constructors are `false` and `true`.
        Bool = "bool",
        /// `Text`.
        Text = "text",
        /// `Bytes`.
        Bytes = "bytes",
        /// `List<T>`.
        List = "list",
        /// `Dict<K, V>`.
        Dict = "dict",
        /// `Set<T>`.
        Set = "set",
        /// `Unit`.
        Unit = "unit",
        /// `Never`, the type of an expression that never produces a value.
        Never = "never",
        /// `Option<T>`, the only type an external field may leave out.
        Option = "option",
        /// `Result<T, E>`, which `?` and a Tool call's value use.
        Result = "result",
        /// `ToolProblem`, a Tool call's problem.
        ToolProblem = "tool_problem",
        /// `task.Task<T>`.
        Task = "task",
        /// `task.Tagged<E>`.
        TaskTagged = "task_tagged",
        /// `task.Stop<T>`, what `task.stop` answers.
        TaskStopOutcome = "task_stop_outcome",
        /// `task.Call<A, R>`, one call `task.calls` lists.
        TaskCall = "task_call",
        /// `time.Instant`.
        Instant = "instant",
        /// `duration.Duration`.
        Duration = "duration",
        /// `json.Value`, which encodes as the JSON value it stands for.
        JsonValue = "json_value",
        /// `json.DecodeError`, why `json.decode` built no value.
        JsonDecodeError = "json_decode_error",
        /// `json.Problem`, what a `json.DecodeError` found.
        JsonProblem = "json_problem",
        /// `json.Step`, one step of a `json.DecodeError`'s path.
        JsonStep = "json_step",
        /// `json.Names`, which spellings of a name `json.decode` reads.
        JsonNames = "json_names",
        /// `path.Path`.
        Path = "path",
        /// `url.Url`.
        Url = "url",
        /// `media.MediaType`.
        MediaType = "media_type",
        /// `code.RunId`.
        RunId = "run_id",
        /// `code.TaskPath`.
        TaskPath = "task_path",
        /// `code.SourcePath`, a parameter that takes a path in the source.
        SourcePath = "source_path",
        /// `code.TypeMismatch`, why `code.decode` built no value.
        CodeTypeMismatch = "code_type_mismatch",
        /// `code.Step`, one step of a `code.TypeMismatch`'s path.
        CodeStep = "code_step",
        /// The type an integer literal builds.
        IntLiteral = "int_literal",
        /// The type a decimal literal builds.
        DecimalLiteral = "decimal_literal",
        /// The type a text literal builds.
        TextLiteral = "text_literal",
        /// The type a list literal builds.
        ListLiteral = "list_literal",
        /// The type a dict literal builds.
        DictLiteral = "dict_literal",
    }
}

/// The members of one std declaration that a Rust rule reads: its
/// constructors or its fields, as a closed enum. [`members!`](crate::members) declares one.
pub trait Members: Copy + Eq + fmt::Debug + 'static {
    /// The declaration's name, for a [`Mismatch`].
    const OF: &'static str;
    /// Every one, in the enum's order.
    const ALL: &'static [Self];
    /// Its name in the declaration.
    fn name(self) -> &'static str;
    /// Its place in [`Members::ALL`].
    fn ordinal(self) -> usize;
}

/// Declares a closed [`Members`] enum: a std declaration's constructors or
/// fields that a Rust rule reads, each by the name the declaration gives it.
#[macro_export]
macro_rules! members {
    (
        $(#[$meta:meta])*
        $vis:vis enum $enum:ident of $of:literal {
            $($(#[$doc:meta])* $variant:ident $(= $spelling:literal)?,)+
        }
    ) => {
        $crate::__spelled! {
            $(#[$meta])*
            $vis enum $enum {
                /// Its name in the declaration.
                $vis fn name(self) -> &'static str;
                /// The one the declaration names `name`.
                $vis fn named(&str);
                $($(#[$doc])* $variant $(= $spelling)?,)+
            }
        }

        impl $crate::Members for $enum {
            const OF: &'static str = $of;
            const ALL: &'static [Self] = $enum::ALL;
            fn name(self) -> &'static str {
                $enum::name(self)
            }
            #[expect(
                clippy::as_conversions,
                reason = "a fieldless enum's discriminant is its place in ALL, which fits a usize"
            )]
            fn ordinal(self) -> usize {
                self as usize
            }
        }
    };
}

/// A std declaration that lacks a member a Rust rule reads: std's sources
/// and the Rust that reads them disagree, a bug in this implementation that
/// the bundled std's tests hold away.
#[derive(Clone, Copy, PartialEq, Eq, Debug)]
pub struct Mismatch {
    /// The declaration.
    pub of: &'static str,
    /// The member it lacks.
    pub member: &'static str,
}

impl fmt::Display for Mismatch {
    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
        write!(
            f,
            "std's {} declares no {} that this implementation reads",
            self.of, self.member
        )
    }
}

impl std::error::Error for Mismatch {}

/// Where each of `C`'s members is among a declaration's names, found once.
fn positions<C: Members>(names: &[&str]) -> Result<Box<[usize]>, Mismatch> {
    C::ALL
        .iter()
        .map(|member| {
            names
                .iter()
                .position(|name| *name == member.name())
                .ok_or(Mismatch {
                    of: C::OF,
                    member: member.name(),
                })
        })
        .collect()
}

/// A std enum's constructors of `C`, each with its declaration index.
#[derive(Clone, Debug)]
pub struct StdEnum<C> {
    indices: Box<[usize]>,
    kinds: Box<[Option<C>]>,
}

impl<C: Members> StdEnum<C> {
    /// The constructors of `C` among `names`, an enum's constructor names in
    /// declaration order.
    ///
    /// # Errors
    ///
    /// [`Mismatch`] when the enum lacks one of them.
    pub fn bind<'a>(names: impl IntoIterator<Item = &'a str>) -> Result<Self, Mismatch> {
        let names: Vec<&str> = names.into_iter().collect();
        let indices = positions::<C>(&names)?;
        let mut kinds = vec![None; names.len()].into_boxed_slice();
        for (member, index) in C::ALL.iter().zip(&indices) {
            kinds[*index] = Some(*member);
        }
        Ok(StdEnum { indices, kinds })
    }

    /// The constructors of `C` in `shape`.
    ///
    /// # Errors
    ///
    /// [`Mismatch`] when `shape` lacks one of them.
    pub fn of(shape: &EnumShape) -> Result<Self, Mismatch> {
        Self::bind(shape.constructors().iter().map(crate::Constructor::name))
    }

    /// `ctor`'s declaration index.
    pub fn index(&self, ctor: C) -> usize {
        self.indices[ctor.ordinal()]
    }

    /// Which of `C` the constructor at declaration index `index` is, if any.
    pub fn which(&self, index: usize) -> Option<C> {
        self.kinds.get(index).copied().flatten()
    }
}

/// A std record's fields of `F`, each with its position.
#[derive(Clone, Debug)]
pub struct StdRecord<F> {
    positions: Box<[usize]>,
    members: PhantomData<F>,
}

impl<F: Members> StdRecord<F> {
    /// The fields of `F` among `names`, a record's field names in
    /// declaration order.
    ///
    /// # Errors
    ///
    /// [`Mismatch`] when the record lacks one of them.
    pub fn bind<'a>(names: impl IntoIterator<Item = &'a str>) -> Result<Self, Mismatch> {
        let names: Vec<&str> = names.into_iter().collect();
        Ok(StdRecord {
            positions: positions::<F>(&names)?,
            members: PhantomData,
        })
    }

    /// The fields of `F` in `shape`.
    ///
    /// # Errors
    ///
    /// [`Mismatch`] when `shape` lacks one of them.
    pub fn of(shape: &RecordShape) -> Result<Self, Mismatch> {
        Self::bind(shape.fields())
    }

    /// `field`'s position.
    pub fn position(&self, field: F) -> usize {
        self.positions[field.ordinal()]
    }
}

members! {
    /// `Option`'s constructors.
    pub enum OptionCtor of "Option" {
        /// `None`.
        None,
        /// `Some(T)`.
        Some,
    }
}

members! {
    /// `Result`'s constructors.
    pub enum ResultCtor of "Result" {
        /// `Ok(T)`.
        Ok,
        /// `Err(E)`.
        Err,
    }
}

members! {
    /// `ToolProblem`'s constructors.
    pub enum ToolProblemCtor of "ToolProblem" {
        /// `NotStarted`.
        NotStarted,
        /// `Interrupted`.
        Interrupted,
        /// `NetworkError`.
        NetworkError,
    }
}

members! {
    /// `task.Stop`'s constructors.
    pub enum StopCtor of "task.Stop" {
        /// `Finished(T)`.
        Finished,
        /// `Stopped`.
        Stopped,
    }
}

members! {
    /// `json.DecodeError`'s fields.
    pub enum DecodeErrorField of "json.DecodeError" {
        /// `path`.
        Path = "path",
        /// `problem`.
        Problem = "problem",
    }
}

members! {
    /// `json.Step`'s constructors.
    pub enum JsonStepCtor of "json.Step" {
        /// `Field`.
        Field,
        /// `Element`.
        Element,
        /// `Key`.
        Key,
        /// `Constructor`.
        Constructor,
    }
}

members! {
    /// `json.Problem`'s constructors.
    pub enum JsonProblemCtor of "json.Problem" {
        /// `Syntax`.
        Syntax,
        /// `Missing`.
        Missing,
        /// `Unknown`.
        Unknown,
        /// `Duplicate`.
        Duplicate,
        /// `Mismatch`.
        Mismatch,
        /// `TooLarge`.
        TooLarge,
    }
}

members! {
    /// `json.Names`'s constructors.
    pub enum JsonNamesCtor of "json.Names" {
        /// `Exact`.
        Exact,
        /// `Relaxed`.
        Relaxed,
    }
}

members! {
    /// `json.Value`'s constructors.
    pub enum JsonValueCtor of "json.Value" {
        /// `Null`.
        Null,
        /// `Bool`.
        Bool,
        /// `Number`.
        Number,
        /// `Text`.
        Text,
        /// `List`.
        List,
        /// `Object`.
        Object,
    }
}

members! {
    /// `task.Call`'s fields.
    pub enum CallField of "task.Call" {
        /// `args`.
        Args = "args",
        /// `answer`.
        Answer = "answer",
        /// `site`.
        Site = "site",
    }
}

members! {
    /// `code.TypeMismatch`'s fields.
    pub enum TypeMismatchField of "code.TypeMismatch" {
        /// `wanted`.
        Wanted = "wanted",
        /// `found`.
        Found = "found",
        /// `path`.
        Path = "path",
    }
}

members! {
    /// `code.Step`'s constructors.
    pub enum CodeStepCtor of "code.Step" {
        /// `Field`.
        Field,
        /// `Element`.
        Element,
        /// `Key`.
        Key,
        /// `Constructor`.
        Constructor,
    }
}

#[cfg(test)]
#[cfg_attr(coverage, coverage(off))]
mod tests {
    use super::*;

    #[test]
    fn a_binding_finds_each_member_once_in_any_order() {
        let bound = StdEnum::<OptionCtor>::bind(["Some", "None"]).expect("both");
        assert_eq!(bound.index(OptionCtor::None), 1);
        assert_eq!(bound.index(OptionCtor::Some), 0);
        assert_eq!(bound.which(1), Some(OptionCtor::None));
        assert_eq!(bound.which(2), None);
    }

    #[test]
    fn a_missing_member_is_a_mismatch_naming_it() {
        let error = StdEnum::<OptionCtor>::bind(["Nothing", "Some"]).expect_err("no None");
        assert_eq!(
            error,
            Mismatch {
                of: "Option",
                member: "None"
            }
        );
        let error = StdRecord::<DecodeErrorField>::bind(["path"]).expect_err("no problem");
        assert_eq!(error.member, "problem");
    }

    #[test]
    fn a_record_binding_gives_each_field_its_position() {
        let bound = StdRecord::<DecodeErrorField>::bind(["problem", "path"]).expect("both");
        assert_eq!(bound.position(DecodeErrorField::Path), 1);
        assert_eq!(bound.position(DecodeErrorField::Problem), 0);
    }
}