Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

#203 - Nuanced types #206

Draft
wants to merge 4 commits into
base: main
Choose a base branch
from
Draft
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
13 changes: 13 additions & 0 deletions examples/demo.rs
Original file line number Diff line number Diff line change
@@ -0,0 +1,13 @@
use specta::{datatype::TypeImpl, Type};

#[derive(Type)]
pub struct Demo {
a: String,
}

fn main() {
// let a = TypeImpl::new::<String>();
// let b = TypeImpl::new::<i32>();
// let c = TypeImpl::new::<Demo>();
// println!("{a:?}\n{b:?}\n{c:?}");
}
6 changes: 6 additions & 0 deletions src/datatype/list.rs
Original file line number Diff line number Diff line change
Expand Up @@ -6,6 +6,8 @@ pub struct List {
pub(crate) ty: Box<DataType>,
// Length is set for `[Type; N]` arrays.
pub(crate) length: Option<usize>,
// Are each elements unique? Eg. `HashSet` or `BTreeSet`
pub(crate) unique: bool,
}

impl List {
Expand All @@ -16,4 +18,8 @@ impl List {
pub fn length(&self) -> Option<usize> {
self.length
}

pub fn unique(&self) -> bool {
self.unique
}
}
1 change: 1 addition & 0 deletions src/datatype/literal.rs
Original file line number Diff line number Diff line change
Expand Up @@ -22,6 +22,7 @@ pub enum LiteralType {
String(String),
char(char),
/// Standalone `null` without a known type
// TODO: Remove this
None,
}

Expand Down
37 changes: 37 additions & 0 deletions src/datatype/map.rs
Original file line number Diff line number Diff line change
@@ -0,0 +1,37 @@
use crate::DataType;

#[derive(Debug, Clone, PartialEq)]

pub struct Map {
// TODO: Box these fields together as an internal optimization.
// The type of the map keys.
pub(crate) key_ty: Box<DataType>,
// The type of the map values.
pub(crate) value_ty: Box<DataType>,
// Are each elements unique? Eg. `HashSet` or `BTreeSet`
pub(crate) unique: bool,
}

impl Map {
// TODO: `inline` vs `reference` is a thing people downstream need to think about.
// TODO: Should this need `generics`
// pub fn new<K: Type, V: Type>(type_map: &mut TypeMap, generics: &[DataType]) -> Self {
// Self {
// key_ty: Box::new(K::inline(type_map, generics)),
// value_ty: Box::new(V::inline(type_map, generics)),
// unique: false,
// }
// }

pub fn key_ty(&self) -> &DataType {
&self.key_ty
}

pub fn value_ty(&self) -> &DataType {
&self.value_ty
}

pub fn unique(&self) -> bool {
self.unique
}
}
31 changes: 19 additions & 12 deletions src/datatype/mod.rs
Original file line number Diff line number Diff line change
Expand Up @@ -7,19 +7,23 @@ mod r#enum;
mod fields;
mod list;
mod literal;
mod map;
mod named;
mod primitive;
pub mod reference;
mod r#struct;
mod tuple;
mod r#type;

pub use fields::*;
pub use list::*;
pub use literal::*;
pub use map::*;
pub use named::*;
pub use primitive::*;
pub use r#enum::*;
pub use r#struct::*;
pub use r#type::*;
pub use tuple::*;

use crate::SpectaID;
Expand All @@ -29,30 +33,33 @@ use crate::SpectaID;
/// A language exporter takes this general format and converts it into a language specific syntax.
#[derive(Debug, Clone, PartialEq)]
pub enum DataType {
// Always inlined
Any,
Unknown,
Primitive(PrimitiveType),
Literal(LiteralType),
/// Either a `Set` or a `Vec`
List(List),
Nullable(Box<DataType>),
Map(Box<(DataType, DataType)>),
// Anonymous Reference types
Struct(StructType),
Map(Map),
Enum(EnumType),
Tuple(TupleType),
// Result
Result(Box<(DataType, DataType)>),
// A reference type that has already been defined
Reference(DataTypeReference),
Generic(GenericType),

// TODO: Can we avoid these being nestable
Nullable(Box<DataType>),

// TODO: Should we keep this - https://github.com/oscartbeaumont/specta/issues/192
Result(Box<(DataType, DataType)>),

// TODO: Remove these
Any,
Unknown,
Struct(StructType),
// TODO: Introduce this
// Named(NamedDataType)
}

impl DataType {
pub fn generics(&self) -> Option<&Vec<GenericType>> {
match self {
Self::Struct(s) => Some(s.generics()),
// Self::Struct(s) => Some(s.generics()),
Self::Enum(e) => Some(e.generics()),
_ => None,
}
Expand Down
9 changes: 8 additions & 1 deletion src/datatype/named.rs
Original file line number Diff line number Diff line change
@@ -1,6 +1,6 @@
use std::borrow::Cow;

use crate::{DataType, DeprecatedType, ImplLocation, SpectaID};
use crate::{DataType, DeprecatedType, EnumType, ImplLocation, SpectaID, StructType};

/// A NamedDataTypeImpl includes extra information which is only available for [NamedDataType]'s that come from a real Rust type.
#[derive(Debug, Clone, PartialEq)]
Expand Down Expand Up @@ -38,6 +38,13 @@ pub struct NamedDataType {
pub inner: DataType,
}

// // TODO: Rename this
// #[derive(Debug, Clone, PartialEq)]
// pub enum NamedDataTypeTODO {
// Struct(StructType),
// Enum(EnumType), // TODO
// }

impl NamedDataType {
pub fn name(&self) -> &Cow<'static, str> {
&self.name
Expand Down
2 changes: 1 addition & 1 deletion src/datatype/reference.rs
Original file line number Diff line number Diff line change
Expand Up @@ -12,7 +12,7 @@ pub struct Reference {

pub fn inline<T: Type + ?Sized>(type_map: &mut TypeMap, generics: &[DataType]) -> Reference {
Reference {
inner: T::inline(type_map, generics),
inner: T::inline(type_map, generics).ty,
}
}

Expand Down
41 changes: 41 additions & 0 deletions src/datatype/type.rs
Original file line number Diff line number Diff line change
@@ -0,0 +1,41 @@
use std::{any::TypeId, panic::Location};

use crate::{internal::type_id::non_static_type_id, DataType, Type};

#[derive(Debug)]
pub struct TypeImpl {
name: &'static str,
tid: TypeId,
file: &'static str,
line: u32,
column: u32,
// TODO: Not `pub`
pub ty: DataType,
}

// TODO: Debug impl + ordering

impl TypeImpl {
// TODO: Do we make this private for the macro only??? Probs
// TODO: Anyone could call this on any type but the `caller` information will be inconsistent.
#[track_caller]
pub fn new<T: Type>(ty: DataType) -> Self {
let caller = Location::caller();
Self {
name: std::any::type_name::<T>(),
tid: non_static_type_id::<T>(),
file: caller.file(),
line: caller.line(),
column: caller.column(),
ty,
}
}

// TODO: Field accessors

// TODO: Iterator for module path derived from `name` field

pub fn is<T: Type>() -> bool {
todo!();
}
}
31 changes: 31 additions & 0 deletions src/internal.rs
Original file line number Diff line number Diff line change
Expand Up @@ -249,3 +249,34 @@ mod functions {
}
#[cfg(feature = "functions")]
pub use functions::*;

// This code is taken from `erased-serde` - https://github.com/dtolnay/erased-serde/blob/master/src/any.rs
#[allow(unsafe_code)]
pub(crate) mod type_id {
use std::{any::TypeId, marker::PhantomData};

trait NonStaticAny {
fn get_type_id(&self) -> TypeId
where
Self: 'static;
}

impl<T: ?Sized> NonStaticAny for PhantomData<T> {
fn get_type_id(&self) -> TypeId
where
Self: 'static,
{
TypeId::of::<T>()
}
}

pub fn non_static_type_id<T: ?Sized>() -> TypeId {
let non_static_thing = PhantomData::<T>;
let thing = unsafe {
std::mem::transmute::<&dyn NonStaticAny, &(dyn NonStaticAny + 'static)>(
&non_static_thing,
)
};
NonStaticAny::get_type_id(thing)
}
}
6 changes: 3 additions & 3 deletions src/lang/ts/mod.rs
Original file line number Diff line number Diff line change
Expand Up @@ -59,7 +59,7 @@ pub fn inline_ref<T: Type>(_: &T, conf: &ExportConfig) -> Output {
/// Eg. `{ demo: string; };`
pub fn inline<T: Type>(conf: &ExportConfig) -> Output {
let mut type_map = TypeMap::default();
let ty = T::inline(&mut type_map, &[]);
let ty = T::inline(&mut type_map, &[]).ty;
is_valid_ty(&ty, &type_map)?;
let result = datatype(conf, &ty, &type_map);

Expand Down Expand Up @@ -255,8 +255,8 @@ pub(crate) fn datatype_inner(ctx: ExportContext, typ: &DataType, type_map: &Type
format!(
// We use this isn't of `Record<K, V>` to avoid issues with circular references.
"{{ [key in {}]: {} }}",
datatype_inner(ctx.clone(), &def.0, type_map)?,
datatype_inner(ctx, &def.1, type_map)?
datatype_inner(ctx.clone(), def.key_ty(), type_map)?,
datatype_inner(ctx, def.value_ty(), type_map)?
)
}
// We use `T[]` instead of `Array<T>` to avoid issues with circular references.
Expand Down
2 changes: 1 addition & 1 deletion src/lib.rs
Original file line number Diff line number Diff line change
@@ -1,5 +1,5 @@
#![doc = include_str!("./docs.md")]
#![forbid(unsafe_code)]
#![deny(unsafe_code)]
#![warn(clippy::all, clippy::unwrap_used, clippy::panic)] // TODO: missing_docs
#![allow(clippy::module_inception)]
#![cfg_attr(docsrs, feature(doc_cfg))]
Expand Down
16 changes: 9 additions & 7 deletions src/serde.rs
Original file line number Diff line number Diff line change
Expand Up @@ -4,7 +4,7 @@ use thiserror::Error;

use crate::{
internal::{skip_fields, skip_fields_named},
DataType, EnumRepr, EnumType, EnumVariants, GenericType, List, LiteralType, PrimitiveType,
DataType, EnumRepr, EnumType, EnumVariants, GenericType, List, LiteralType, Map, PrimitiveType,
SpectaID, StructFields, TypeMap,
};

Expand Down Expand Up @@ -35,8 +35,8 @@ fn is_valid_ty_internal(
match dt {
DataType::Nullable(ty) => is_valid_ty(ty, type_map)?,
DataType::Map(ty) => {
is_valid_map_key(&ty.0, type_map)?;
is_valid_ty_internal(&ty.1, type_map, checked_references)?;
is_valid_map_key(ty.key_ty(), type_map)?;
is_valid_ty_internal(ty.value_ty(), type_map, checked_references)?;
}
DataType::Struct(ty) => match ty.fields() {
StructFields::Unit => {}
Expand Down Expand Up @@ -251,12 +251,14 @@ fn resolve_generics(mut dt: DataType, generics: &Vec<(GenericType, DataType)>) -
DataType::List(v) => DataType::List(List {
ty: Box::new(resolve_generics(*v.ty, generics)),
length: v.length,
unique: v.unique,
}),
DataType::Nullable(v) => DataType::Nullable(Box::new(resolve_generics(*v, generics))),
DataType::Map(v) => DataType::Map(Box::new({
let (k, v) = *v;
(resolve_generics(k, generics), resolve_generics(v, generics))
})),
DataType::Map(v) => DataType::Map(Map {
key_ty: Box::new(resolve_generics(*v.key_ty, generics)),
value_ty: Box::new(resolve_generics(*v.value_ty, generics)),
unique: v.unique,
}),
DataType::Struct(ref mut v) => match &mut v.fields {
StructFields::Unit => dt,
StructFields::Unnamed(f) => {
Expand Down
10 changes: 5 additions & 5 deletions src/static_types.rs
Original file line number Diff line number Diff line change
@@ -1,6 +1,6 @@
use std::fmt::Debug;

use crate::{DataType, Type, TypeMap};
use crate::{DataType, Type, TypeImpl, TypeMap};

/// Easily convert a non-Specta type into a Specta compatible type.
/// This will be typed as `any` in Typescript.
Expand Down Expand Up @@ -34,8 +34,8 @@ use crate::{DataType, Type, TypeMap};
pub struct Any<T = ()>(T);

impl<T> Type for Any<T> {
fn inline(_: &mut TypeMap, _: &[DataType]) -> DataType {
DataType::Any
fn inline(_: &mut TypeMap, _: &[DataType]) -> TypeImpl {
TypeImpl::new::<Self>(DataType::Any)
}
}

Expand Down Expand Up @@ -97,8 +97,8 @@ impl<T: serde::Serialize> serde::Serialize for Any<T> {
pub struct Unknown<T = ()>(T);

impl<T> Type for Unknown<T> {
fn inline(_: &mut TypeMap, _: &[DataType]) -> DataType {
DataType::Unknown
fn inline(_: &mut TypeMap, _: &[DataType]) -> TypeImpl {
TypeImpl::new::<Self>(DataType::Unknown)
}
}

Expand Down
Loading