flow_types/role.rs
1//! std's roles, and the members of a std declaration a Rust rule reads,
2//! bound once (`docs/language/spec/stdlib.md`, *`@lang` declarations*).
3//!
4//! The compiler knows roles, never names: std marks the declaration that
5//! plays each [`Role`], and [`crate::std_roles`] (generated from std) says
6//! where each one is. A Rust rule that reads a constructor or a field of a
7//! std declaration names it through a closed [`Members`] enum, and a
8//! [`StdEnum`] or [`StdRecord`] finds every member's position in the
9//! declaration once, so nothing compares a member's name again.
10
11use std::fmt;
12use std::marker::PhantomData;
13
14use crate::shape::{EnumShape, RecordShape};
15
16flow_span::spelled! {
17 /// A type a compiler rule names by the role std marks it with.
18 ///
19 /// A literal form is a role too: `int_literal` marks the type an integer
20 /// literal builds.
21 pub enum Role {
22 /// How std spells it in `@lang`.
23 pub fn spelling(self) -> &'static str;
24 /// The one std spells `spelling`, if any.
25 pub fn named(&str);
26 /// `Int`.
27 Int = "int",
28 /// `Decimal`.
29 Decimal = "decimal",
30 /// `Bool`, whose constructors are `false` and `true`.
31 Bool = "bool",
32 /// `Text`.
33 Text = "text",
34 /// `Bytes`.
35 Bytes = "bytes",
36 /// `List<T>`.
37 List = "list",
38 /// `Dict<K, V>`.
39 Dict = "dict",
40 /// `Set<T>`.
41 Set = "set",
42 /// `Unit`.
43 Unit = "unit",
44 /// `Never`, the type of an expression that never produces a value.
45 Never = "never",
46 /// `Option<T>`, the only type an external field may leave out.
47 Option = "option",
48 /// `Result<T, E>`, which `?` and a Tool call's value use.
49 Result = "result",
50 /// `ToolProblem`, a Tool call's problem.
51 ToolProblem = "tool_problem",
52 /// `task.Task<T>`.
53 Task = "task",
54 /// `task.Tagged<E>`.
55 TaskTagged = "task_tagged",
56 /// `task.Stop<T>`, what `task.stop` answers.
57 TaskStopOutcome = "task_stop_outcome",
58 /// `task.Call<A, R>`, one call `task.calls` lists.
59 TaskCall = "task_call",
60 /// `time.Instant`.
61 Instant = "instant",
62 /// `duration.Duration`.
63 Duration = "duration",
64 /// `json.Value`, which encodes as the JSON value it stands for.
65 JsonValue = "json_value",
66 /// `json.DecodeError`, why `json.decode` built no value.
67 JsonDecodeError = "json_decode_error",
68 /// `json.Problem`, what a `json.DecodeError` found.
69 JsonProblem = "json_problem",
70 /// `json.Step`, one step of a `json.DecodeError`'s path.
71 JsonStep = "json_step",
72 /// `json.Names`, which spellings of a name `json.decode` reads.
73 JsonNames = "json_names",
74 /// `path.Path`.
75 Path = "path",
76 /// `url.Url`.
77 Url = "url",
78 /// `media.MediaType`.
79 MediaType = "media_type",
80 /// `code.RunId`.
81 RunId = "run_id",
82 /// `code.TaskPath`.
83 TaskPath = "task_path",
84 /// `code.SourcePath`, a parameter that takes a path in the source.
85 SourcePath = "source_path",
86 /// `code.TypeMismatch`, why `code.decode` built no value.
87 CodeTypeMismatch = "code_type_mismatch",
88 /// `code.Step`, one step of a `code.TypeMismatch`'s path.
89 CodeStep = "code_step",
90 /// The type an integer literal builds.
91 IntLiteral = "int_literal",
92 /// The type a decimal literal builds.
93 DecimalLiteral = "decimal_literal",
94 /// The type a text literal builds.
95 TextLiteral = "text_literal",
96 /// The type a list literal builds.
97 ListLiteral = "list_literal",
98 /// The type a dict literal builds.
99 DictLiteral = "dict_literal",
100 }
101}
102
103/// The members of one std declaration that a Rust rule reads: its
104/// constructors or its fields, as a closed enum. [`members!`](crate::members) declares one.
105pub trait Members: Copy + Eq + fmt::Debug + 'static {
106 /// The declaration's name, for a [`Mismatch`].
107 const OF: &'static str;
108 /// Every one, in the enum's order.
109 const ALL: &'static [Self];
110 /// Its name in the declaration.
111 fn name(self) -> &'static str;
112 /// Its place in [`Members::ALL`].
113 fn ordinal(self) -> usize;
114}
115
116/// Declares a closed [`Members`] enum: a std declaration's constructors or
117/// fields that a Rust rule reads, each by the name the declaration gives it.
118#[macro_export]
119macro_rules! members {
120 (
121 $(#[$meta:meta])*
122 $vis:vis enum $enum:ident of $of:literal {
123 $($(#[$doc:meta])* $variant:ident $(= $spelling:literal)?,)+
124 }
125 ) => {
126 $crate::__spelled! {
127 $(#[$meta])*
128 $vis enum $enum {
129 /// Its name in the declaration.
130 $vis fn name(self) -> &'static str;
131 /// The one the declaration names `name`.
132 $vis fn named(&str);
133 $($(#[$doc])* $variant $(= $spelling)?,)+
134 }
135 }
136
137 impl $crate::Members for $enum {
138 const OF: &'static str = $of;
139 const ALL: &'static [Self] = $enum::ALL;
140 fn name(self) -> &'static str {
141 $enum::name(self)
142 }
143 #[expect(
144 clippy::as_conversions,
145 reason = "a fieldless enum's discriminant is its place in ALL, which fits a usize"
146 )]
147 fn ordinal(self) -> usize {
148 self as usize
149 }
150 }
151 };
152}
153
154/// A std declaration that lacks a member a Rust rule reads: std's sources
155/// and the Rust that reads them disagree, a bug in this implementation that
156/// the bundled std's tests hold away.
157#[derive(Clone, Copy, PartialEq, Eq, Debug)]
158pub struct Mismatch {
159 /// The declaration.
160 pub of: &'static str,
161 /// The member it lacks.
162 pub member: &'static str,
163}
164
165impl fmt::Display for Mismatch {
166 fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
167 write!(
168 f,
169 "std's {} declares no {} that this implementation reads",
170 self.of, self.member
171 )
172 }
173}
174
175impl std::error::Error for Mismatch {}
176
177/// Where each of `C`'s members is among a declaration's names, found once.
178fn positions<C: Members>(names: &[&str]) -> Result<Box<[usize]>, Mismatch> {
179 C::ALL
180 .iter()
181 .map(|member| {
182 names
183 .iter()
184 .position(|name| *name == member.name())
185 .ok_or(Mismatch {
186 of: C::OF,
187 member: member.name(),
188 })
189 })
190 .collect()
191}
192
193/// A std enum's constructors of `C`, each with its declaration index.
194#[derive(Clone, Debug)]
195pub struct StdEnum<C> {
196 indices: Box<[usize]>,
197 kinds: Box<[Option<C>]>,
198}
199
200impl<C: Members> StdEnum<C> {
201 /// The constructors of `C` among `names`, an enum's constructor names in
202 /// declaration order.
203 ///
204 /// # Errors
205 ///
206 /// [`Mismatch`] when the enum lacks one of them.
207 pub fn bind<'a>(names: impl IntoIterator<Item = &'a str>) -> Result<Self, Mismatch> {
208 let names: Vec<&str> = names.into_iter().collect();
209 let indices = positions::<C>(&names)?;
210 let mut kinds = vec![None; names.len()].into_boxed_slice();
211 for (member, index) in C::ALL.iter().zip(&indices) {
212 kinds[*index] = Some(*member);
213 }
214 Ok(StdEnum { indices, kinds })
215 }
216
217 /// The constructors of `C` in `shape`.
218 ///
219 /// # Errors
220 ///
221 /// [`Mismatch`] when `shape` lacks one of them.
222 pub fn of(shape: &EnumShape) -> Result<Self, Mismatch> {
223 Self::bind(shape.constructors().iter().map(crate::Constructor::name))
224 }
225
226 /// `ctor`'s declaration index.
227 pub fn index(&self, ctor: C) -> usize {
228 self.indices[ctor.ordinal()]
229 }
230
231 /// Which of `C` the constructor at declaration index `index` is, if any.
232 pub fn which(&self, index: usize) -> Option<C> {
233 self.kinds.get(index).copied().flatten()
234 }
235}
236
237/// A std record's fields of `F`, each with its position.
238#[derive(Clone, Debug)]
239pub struct StdRecord<F> {
240 positions: Box<[usize]>,
241 members: PhantomData<F>,
242}
243
244impl<F: Members> StdRecord<F> {
245 /// The fields of `F` among `names`, a record's field names in
246 /// declaration order.
247 ///
248 /// # Errors
249 ///
250 /// [`Mismatch`] when the record lacks one of them.
251 pub fn bind<'a>(names: impl IntoIterator<Item = &'a str>) -> Result<Self, Mismatch> {
252 let names: Vec<&str> = names.into_iter().collect();
253 Ok(StdRecord {
254 positions: positions::<F>(&names)?,
255 members: PhantomData,
256 })
257 }
258
259 /// The fields of `F` in `shape`.
260 ///
261 /// # Errors
262 ///
263 /// [`Mismatch`] when `shape` lacks one of them.
264 pub fn of(shape: &RecordShape) -> Result<Self, Mismatch> {
265 Self::bind(shape.fields())
266 }
267
268 /// `field`'s position.
269 pub fn position(&self, field: F) -> usize {
270 self.positions[field.ordinal()]
271 }
272}
273
274members! {
275 /// `Option`'s constructors.
276 pub enum OptionCtor of "Option" {
277 /// `None`.
278 None,
279 /// `Some(T)`.
280 Some,
281 }
282}
283
284members! {
285 /// `Result`'s constructors.
286 pub enum ResultCtor of "Result" {
287 /// `Ok(T)`.
288 Ok,
289 /// `Err(E)`.
290 Err,
291 }
292}
293
294members! {
295 /// `ToolProblem`'s constructors.
296 pub enum ToolProblemCtor of "ToolProblem" {
297 /// `NotStarted`.
298 NotStarted,
299 /// `Interrupted`.
300 Interrupted,
301 /// `NetworkError`.
302 NetworkError,
303 }
304}
305
306members! {
307 /// `task.Stop`'s constructors.
308 pub enum StopCtor of "task.Stop" {
309 /// `Finished(T)`.
310 Finished,
311 /// `Stopped`.
312 Stopped,
313 }
314}
315
316members! {
317 /// `json.DecodeError`'s fields.
318 pub enum DecodeErrorField of "json.DecodeError" {
319 /// `path`.
320 Path = "path",
321 /// `problem`.
322 Problem = "problem",
323 }
324}
325
326members! {
327 /// `json.Step`'s constructors.
328 pub enum JsonStepCtor of "json.Step" {
329 /// `Field`.
330 Field,
331 /// `Element`.
332 Element,
333 /// `Key`.
334 Key,
335 /// `Constructor`.
336 Constructor,
337 }
338}
339
340members! {
341 /// `json.Problem`'s constructors.
342 pub enum JsonProblemCtor of "json.Problem" {
343 /// `Syntax`.
344 Syntax,
345 /// `Missing`.
346 Missing,
347 /// `Unknown`.
348 Unknown,
349 /// `Duplicate`.
350 Duplicate,
351 /// `Mismatch`.
352 Mismatch,
353 /// `TooLarge`.
354 TooLarge,
355 }
356}
357
358members! {
359 /// `json.Names`'s constructors.
360 pub enum JsonNamesCtor of "json.Names" {
361 /// `Exact`.
362 Exact,
363 /// `Relaxed`.
364 Relaxed,
365 }
366}
367
368members! {
369 /// `json.Value`'s constructors.
370 pub enum JsonValueCtor of "json.Value" {
371 /// `Null`.
372 Null,
373 /// `Bool`.
374 Bool,
375 /// `Number`.
376 Number,
377 /// `Text`.
378 Text,
379 /// `List`.
380 List,
381 /// `Object`.
382 Object,
383 }
384}
385
386members! {
387 /// `task.Call`'s fields.
388 pub enum CallField of "task.Call" {
389 /// `args`.
390 Args = "args",
391 /// `answer`.
392 Answer = "answer",
393 /// `site`.
394 Site = "site",
395 }
396}
397
398members! {
399 /// `code.TypeMismatch`'s fields.
400 pub enum TypeMismatchField of "code.TypeMismatch" {
401 /// `wanted`.
402 Wanted = "wanted",
403 /// `found`.
404 Found = "found",
405 /// `path`.
406 Path = "path",
407 }
408}
409
410members! {
411 /// `code.Step`'s constructors.
412 pub enum CodeStepCtor of "code.Step" {
413 /// `Field`.
414 Field,
415 /// `Element`.
416 Element,
417 /// `Key`.
418 Key,
419 /// `Constructor`.
420 Constructor,
421 }
422}
423
424#[cfg(test)]
425#[cfg_attr(coverage, coverage(off))]
426mod tests {
427 use super::*;
428
429 #[test]
430 fn a_binding_finds_each_member_once_in_any_order() {
431 let bound = StdEnum::<OptionCtor>::bind(["Some", "None"]).expect("both");
432 assert_eq!(bound.index(OptionCtor::None), 1);
433 assert_eq!(bound.index(OptionCtor::Some), 0);
434 assert_eq!(bound.which(1), Some(OptionCtor::None));
435 assert_eq!(bound.which(2), None);
436 }
437
438 #[test]
439 fn a_missing_member_is_a_mismatch_naming_it() {
440 let error = StdEnum::<OptionCtor>::bind(["Nothing", "Some"]).expect_err("no None");
441 assert_eq!(
442 error,
443 Mismatch {
444 of: "Option",
445 member: "None"
446 }
447 );
448 let error = StdRecord::<DecodeErrorField>::bind(["path"]).expect_err("no problem");
449 assert_eq!(error.member, "problem");
450 }
451
452 #[test]
453 fn a_record_binding_gives_each_field_its_position() {
454 let bound = StdRecord::<DecodeErrorField>::bind(["problem", "path"]).expect("both");
455 assert_eq!(bound.position(DecodeErrorField::Path), 1);
456 assert_eq!(bound.position(DecodeErrorField::Problem), 0);
457 }
458}