use std::fmt;
use std::marker::PhantomData;
use crate::shape::{EnumShape, RecordShape};
flow_span::spelled! {
pub enum Role {
pub fn spelling(self) -> &'static str;
pub fn named(&str);
Int = "int",
Decimal = "decimal",
Bool = "bool",
Text = "text",
Bytes = "bytes",
List = "list",
Dict = "dict",
Set = "set",
Unit = "unit",
Never = "never",
Option = "option",
Result = "result",
ToolProblem = "tool_problem",
Task = "task",
TaskTagged = "task_tagged",
TaskStopOutcome = "task_stop_outcome",
TaskCall = "task_call",
Instant = "instant",
Duration = "duration",
JsonValue = "json_value",
JsonDecodeError = "json_decode_error",
JsonProblem = "json_problem",
JsonStep = "json_step",
JsonNames = "json_names",
Path = "path",
Url = "url",
MediaType = "media_type",
RunId = "run_id",
TaskPath = "task_path",
SourcePath = "source_path",
CodeTypeMismatch = "code_type_mismatch",
CodeStep = "code_step",
IntLiteral = "int_literal",
DecimalLiteral = "decimal_literal",
TextLiteral = "text_literal",
ListLiteral = "list_literal",
DictLiteral = "dict_literal",
}
}
pub trait Members: Copy + Eq + fmt::Debug + 'static {
const OF: &'static str;
const ALL: &'static [Self];
fn name(self) -> &'static str;
fn ordinal(self) -> usize;
}
#[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 {
$vis fn name(self) -> &'static str;
$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
}
}
};
}
#[derive(Clone, Copy, PartialEq, Eq, Debug)]
pub struct Mismatch {
pub of: &'static str,
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 {}
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()
}
#[derive(Clone, Debug)]
pub struct StdEnum<C> {
indices: Box<[usize]>,
kinds: Box<[Option<C>]>,
}
impl<C: Members> StdEnum<C> {
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 })
}
pub fn of(shape: &EnumShape) -> Result<Self, Mismatch> {
Self::bind(shape.constructors().iter().map(crate::Constructor::name))
}
pub fn index(&self, ctor: C) -> usize {
self.indices[ctor.ordinal()]
}
pub fn which(&self, index: usize) -> Option<C> {
self.kinds.get(index).copied().flatten()
}
}
#[derive(Clone, Debug)]
pub struct StdRecord<F> {
positions: Box<[usize]>,
members: PhantomData<F>,
}
impl<F: Members> StdRecord<F> {
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,
})
}
pub fn of(shape: &RecordShape) -> Result<Self, Mismatch> {
Self::bind(shape.fields())
}
pub fn position(&self, field: F) -> usize {
self.positions[field.ordinal()]
}
}
members! {
pub enum OptionCtor of "Option" {
None,
Some,
}
}
members! {
pub enum ResultCtor of "Result" {
Ok,
Err,
}
}
members! {
pub enum ToolProblemCtor of "ToolProblem" {
NotStarted,
Interrupted,
NetworkError,
}
}
members! {
pub enum StopCtor of "task.Stop" {
Finished,
Stopped,
}
}
members! {
pub enum DecodeErrorField of "json.DecodeError" {
Path = "path",
Problem = "problem",
}
}
members! {
pub enum JsonStepCtor of "json.Step" {
Field,
Element,
Key,
Constructor,
}
}
members! {
pub enum JsonProblemCtor of "json.Problem" {
Syntax,
Missing,
Unknown,
Duplicate,
Mismatch,
TooLarge,
}
}
members! {
pub enum JsonNamesCtor of "json.Names" {
Exact,
Relaxed,
}
}
members! {
pub enum JsonValueCtor of "json.Value" {
Null,
Bool,
Number,
Text,
List,
Object,
}
}
members! {
pub enum CallField of "task.Call" {
Args = "args",
Answer = "answer",
Site = "site",
}
}
members! {
pub enum TypeMismatchField of "code.TypeMismatch" {
Wanted = "wanted",
Found = "found",
Path = "path",
}
}
members! {
pub enum CodeStepCtor of "code.Step" {
Field,
Element,
Key,
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);
}
}