Skip to content

Layout's #182

New issue

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

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

Already on GitHub? # to your account

Closed
wants to merge 4 commits into from
Closed
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
2 changes: 2 additions & 0 deletions macros/src/type/mod.rs
Original file line number Diff line number Diff line change
Expand Up @@ -130,6 +130,7 @@ pub fn derive(input: proc_macro::TokenStream) -> syn::Result<proc_macro::TokenSt
const _: () = {
const SID: #crate_ref::SpectaID = #sid;
const IMPL_LOCATION: #crate_ref::ImplLocation = #impl_location;
const MODULE_PATH: #crate_ref::ModulePath = #crate_ref::internal::construct::module_path(module_path!());
const DEFINITION_GENERICS: &[#crate_ref::DataType] = &[#(#definition_generics),*];

#[automatically_derived]
Expand Down Expand Up @@ -162,6 +163,7 @@ pub fn derive(input: proc_macro::TokenStream) -> syn::Result<proc_macro::TokenSt
#deprecated,
SID,
IMPL_LOCATION,
MODULE_PATH,
<Self as #crate_ref::Type>::inline(type_map, generics)
)
}
Expand Down
4 changes: 3 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, ImplLocation, ModulePath, SpectaID};

/// A NamedDataTypeImpl includes extra information which is only available for [NamedDataType]'s that come from a real Rust type.
#[derive(Debug, Clone, PartialEq)]
Expand All @@ -9,6 +9,8 @@ pub struct NamedDataTypeExt {
pub(crate) sid: SpectaID,
/// The code location where this type is implemented. Used for error reporting.
pub(crate) impl_location: ImplLocation,
/// The Rust module where the type was defined.
pub(crate) module_path: ModulePath,
}

impl NamedDataTypeExt {
Expand Down
16 changes: 14 additions & 2 deletions src/internal.rs
Original file line number Diff line number Diff line change
Expand Up @@ -12,6 +12,9 @@ pub use ctor;
#[cfg(feature = "functions")]
pub use specta_macros::fn_datatype;

mod intersperse;
pub use intersperse::*;

use crate::{DataType, Field, SpectaID, Type, TypeMap};

/// Functions used to construct `crate::datatype` types (they have private fields so can't be constructed directly).
Expand All @@ -20,7 +23,7 @@ use crate::{DataType, Field, SpectaID, Type, TypeMap};
pub mod construct {
use std::borrow::Cow;

use crate::{datatype::*, ImplLocation, SpectaID};
use crate::{datatype::*, ImplLocation, ModulePath, SpectaID};

pub const fn field(
optional: bool,
Expand Down Expand Up @@ -120,13 +123,18 @@ pub mod construct {
deprecated: Option<DeprecatedType>,
sid: SpectaID,
impl_location: ImplLocation,
module_path: ModulePath,
inner: DataType,
) -> NamedDataType {
NamedDataType {
name,
docs,
deprecated,
ext: Some(NamedDataTypeExt { sid, impl_location }),
ext: Some(NamedDataTypeExt {
sid,
impl_location,
module_path,
}),
inner,
}
}
Expand Down Expand Up @@ -155,6 +163,10 @@ pub mod construct {
ImplLocation(loc)
}

pub const fn module_path(path: &'static str) -> ModulePath {
ModulePath(path)
}

/// Compute an SID hash for a given type.
/// This will produce a type hash from the arguments.
/// This hashing function was derived from https://stackoverflow.com/a/71464396
Expand Down
119 changes: 119 additions & 0 deletions src/internal/intersperse.rs
Original file line number Diff line number Diff line change
@@ -0,0 +1,119 @@
//! A nightly-only standard library method.
//! Once it is stablised we should remove this!
//! https://github.com/rust-lang/rust/issues/79524

use std::iter::Peekable;

#[derive(Debug, Clone)]
pub struct Intersperse<I: Iterator>
where
I::Item: Clone,
{
separator: I::Item,
iter: Peekable<I>,
needs_sep: bool,
}

impl<I: Iterator> Intersperse<I>
where
I::Item: Clone,
{
pub(crate) fn new(iter: I, separator: I::Item) -> Self {
Self {
iter: iter.peekable(),
separator,
needs_sep: false,
}
}
}

pub trait IntersperseIter: Iterator {
fn _intersperse(self, separator: Self::Item) -> Intersperse<Self>
where
Self: Sized,
Self::Item: Clone,
{
Intersperse::new(self, separator)
}
}

impl<I: Iterator> IntersperseIter for I {}

impl<I> Iterator for Intersperse<I>
where
I: Iterator,
I::Item: Clone,
{
type Item = I::Item;

#[inline]
fn next(&mut self) -> Option<I::Item> {
if self.needs_sep && self.iter.peek().is_some() {
self.needs_sep = false;
Some(self.separator.clone())
} else {
self.needs_sep = true;
self.iter.next()
}
}

fn fold<B, F>(self, init: B, f: F) -> B
where
Self: Sized,
F: FnMut(B, Self::Item) -> B,
{
let separator = self.separator;
intersperse_fold(
self.iter,
init,
f,
move || separator.clone(),
self.needs_sep,
)
}

fn size_hint(&self) -> (usize, Option<usize>) {
intersperse_size_hint(&self.iter, self.needs_sep)
}
}

fn intersperse_size_hint<I>(iter: &I, needs_sep: bool) -> (usize, Option<usize>)
where
I: Iterator,
{
let (lo, hi) = iter.size_hint();
let next_is_elem = !needs_sep;
(
lo.saturating_sub(next_is_elem as usize).saturating_add(lo),
hi.and_then(|hi| hi.saturating_sub(next_is_elem as usize).checked_add(hi)),
)
}

fn intersperse_fold<I, B, F, G>(
mut iter: I,
init: B,
mut f: F,
mut separator: G,
needs_sep: bool,
) -> B
where
I: Iterator,
F: FnMut(B, I::Item) -> B,
G: FnMut() -> I::Item,
{
let mut accum = init;

if !needs_sep {
if let Some(x) = iter.next() {
accum = f(accum, x);
} else {
return accum;
}
}

iter.fold(accum, |mut accum, x| {
accum = f(accum, separator());
accum = f(accum, x);
accum
})
}
89 changes: 88 additions & 1 deletion src/lang/ts/export_config.rs
Original file line number Diff line number Diff line change
@@ -1,6 +1,9 @@
use std::{borrow::Cow, io, path::PathBuf};

use crate::DeprecatedType;
use crate::{
internal::IntersperseIter, DataTypeReference, DeprecatedType, NamedDataTypeExt, SpectaID,
TypeMap,
};

use super::comments;

Expand All @@ -17,6 +20,82 @@ pub type CommentFormatterFn = fn(CommentFormatterArgs) -> String; // TODO: Retur
/// The signature for a function responsible for formatter a Typescript file.
pub type FormatterFn = fn(PathBuf) -> io::Result<()>;

#[derive(Debug, Clone)]
pub enum Layout {
/// Typescript `namespace`s will be used to represent Rust module hierarchy.
Namespaces,
/// `module::submodule::Type` will become `module_submodule_Type`
PrefixNames,
/// All types will be exported inline into the root namespace of the TS file.
/// This method does *not* support duplicate type names.
Flat,
}

impl Layout {
pub(crate) fn construct_name_from_ext(
&self,
name: &Cow<'static, str>,
sid: Option<SpectaID>,
ext: &Option<NamedDataTypeExt>,
) -> Cow<'static, str> {
// TODO: Move name santisation code into this function!
match self {
Self::Namespaces => match ext {
Some(ext) => ext
.module_path
.segments()
._intersperse(".")
.chain([".", name])
.collect::<String>()
.into(),
None => todo!(
"Type '{:?}' missing ext. This is either a bug or your using 'DataTypeFrom'.",
sid.map(|s| s.to_string()).unwrap_or(name.to_string())
),
},
Self::PrefixNames => match ext {
Some(ext) => ext
.module_path
.segments()
._intersperse("_")
.chain(["_", name])
.collect::<String>()
.into(),
None => todo!(
"Type '{:?}' missing ext. This is either a bug or your using 'DataTypeFrom'.",
sid.map(|s| s.to_string()).unwrap_or(name.to_string())
),
},
Self::Flat => name.clone(),
}
}

pub(crate) fn construct_name_from_ref(
&self,
name: &Cow<'static, str>,
r: &DataTypeReference,
type_map: &TypeMap,
) -> Cow<'static, str> {
match self {
Self::Namespaces => {
let ty = type_map
.get(r.sid())
.unwrap_or_else(|| panic!("Type '{:?}' not found in type map", r.sid()));

self.construct_name_from_ext(name, Some(r.sid), &ty.ext)
}
Self::PrefixNames => {
let ty = type_map
.get(r.sid())
.unwrap_or_else(|| panic!("Type '{:?}' not found in type map", r.sid()));

self.construct_name_from_ext(name, Some(r.sid), &ty.ext)
}
Self::Flat => name.clone(),
}
}
}

/// Options for controlling the behavior of the Typescript exporter.
#[derive(Debug, Clone)]
pub struct ExportConfig {
Expand All @@ -26,6 +105,8 @@ pub struct ExportConfig {
pub(crate) comment_exporter: Option<CommentFormatterFn>,
/// How the resulting file should be formatted.
pub(crate) formatter: Option<FormatterFn>,
/// How the resulting file should be laid out.
pub(crate) layout: Layout,
}

impl ExportConfig {
Expand Down Expand Up @@ -64,6 +145,11 @@ impl ExportConfig {
self
}

pub fn layout(mut self, layout: Layout) -> Self {
self.layout = layout;
self
}

/// Run the specified formatter on the given path.
pub fn run_format(&self, path: PathBuf) -> io::Result<()> {
if let Some(formatter) = self.formatter {
Expand All @@ -79,6 +165,7 @@ impl Default for ExportConfig {
bigint: Default::default(),
comment_exporter: Some(comments::js_doc),
formatter: None,
layout: Layout::Flat,
}
}
}
Expand Down
34 changes: 21 additions & 13 deletions src/lang/ts/mod.rs
Original file line number Diff line number Diff line change
Expand Up @@ -135,6 +135,10 @@ fn export_datatype_inner(
.unwrap_or_else(|| PathItem::Type(name.clone())),
);
let name = sanitise_type_name(ctx.clone(), NamedLocation::Type, name)?;
let name = ctx
.cfg
.layout
.construct_name_from_ext(&name.into(), None, ext);

let generics = item
.generics()
Expand Down Expand Up @@ -270,20 +274,24 @@ pub(crate) fn datatype_inner(ctx: ExportContext, typ: &DataType, type_map: &Type
variants.dedup();
variants.join(" | ")
}
DataType::Reference(DataTypeReference { name, generics, .. }) => match &generics[..] {
[] => name.to_string(),
generics => {
let generics = generics
.iter()
.map(|(_, v)| {
datatype_inner(ctx.with(PathItem::Type(name.clone())), v, type_map)
})
.collect::<Result<Vec<_>>>()?
.join(", ");

format!("{name}<{generics}>")
DataType::Reference(r @ DataTypeReference { name, generics, .. }) => {
let name = ctx.cfg.layout.construct_name_from_ref(name, r, type_map);

match &generics[..] {
[] => name.to_string(),
generics => {
let generics = generics
.iter()
.map(|(_, v)| {
datatype_inner(ctx.with(PathItem::Type(name.clone())), v, type_map)
})
.collect::<Result<Vec<_>>>()?
.join(", ");

format!("{name}<{generics}>")
}
}
},
}
DataType::Generic(GenericType(ident)) => ident.to_string(),
})
}
Expand Down
2 changes: 2 additions & 0 deletions src/lib.rs
Original file line number Diff line number Diff line change
Expand Up @@ -22,6 +22,7 @@ pub mod export;
#[cfg_attr(docsrs, doc(cfg(feature = "functions")))]
pub mod functions;
mod lang;
mod registry;
mod selection;
mod serde;
mod static_types;
Expand All @@ -33,6 +34,7 @@ pub use crate::serde::*;
pub use datatype::*;
pub use lang::*;
pub use r#type::*;
pub use registry::Registry;
pub use selection::*;
pub use static_types::*;

Expand Down
Loading