Skip to content

GlazeWM is a tiling window manager for macOS and Windows inspired by i3wm.

refactor: add `SubEnum` and `EnumFromInner` proc macros (#1109)

Miitto2d12e1dd5911
diff --git a/Cargo.lock b/Cargo.lock
index 95177706..412022e8 100644
--- a/Cargo.lock
+++ b/Cargo.lock
@@ -2317,6 +2317,7 @@ dependencies = [
"wm-cli",
"wm-common",
"wm-ipc-client",
+ "wm-macros",
"wm-platform",
]
@@ -2360,6 +2361,15 @@ dependencies = [
"wm-common",
]
+[[package]]
+name = "wm-macros"
+version = "0.1.0"
+dependencies = [
+ "proc-macro2",
+ "quote",
+ "syn 2.0.103",
+]
+
[[package]]
name = "wm-platform"
version = "0.0.0"
diff --git a/Cargo.toml b/Cargo.toml
index 3dc5ae9a..546e237f 100644
--- a/Cargo.toml
+++ b/Cargo.toml
@@ -16,3 +16,5 @@ tokio-tungstenite = "0.26"
tracing = "0.1"
tracing-subscriber = { version = "0.3", features = ["env-filter"] }
uuid = { version = "1", features = ["v4", "serde"] }
+
+wm-macros = { path = "packages/wm-macros" }
diff --git a/packages/wm-macros/Cargo.toml b/packages/wm-macros/Cargo.toml
new file mode 100644
index 00000000..268d1a44
--- /dev/null
+++ b/packages/wm-macros/Cargo.toml
@@ -0,0 +1,12 @@
+[package]
+name = "wm-macros"
+version = "0.1.0"
+edition = "2024"
+
+[lib]
+proc-macro = true
+
+[dependencies]
+syn = "2.0.103"
+quote = "1.0"
+proc-macro2 = "1.0"
diff --git a/packages/wm-macros/src/common/attributes.rs b/packages/wm-macros/src/common/attributes.rs
new file mode 100644
index 00000000..96bd915d
--- /dev/null
+++ b/packages/wm-macros/src/common/attributes.rs
@@ -0,0 +1,46 @@
+//! Utilities for working with [syn::Attribute]
+
+pub mod prelude {
+ pub use super::FindAttributes;
+}
+
+/// Trait for filtering lists of [syn::Attribute] by name and type.
+pub trait FindAttributes {
+ /// Find attributes by name. E.g. `#[name]`, `#[name(...)]` or `#[name =
+ /// <value>]`
+ fn find_attrs(
+ &self,
+ name: &str,
+ ) -> impl Iterator<Item = &syn::Attribute>;
+ /// Find list attributes by name. E.g. `#[name(...)]`
+ fn find_list_attrs(
+ &self,
+ name: &str,
+ ) -> impl Iterator<Item = &syn::MetaList> {
+ self
+ .find_attrs(name)
+ .filter_map(|attr| attr.meta.require_list().ok())
+ }
+}
+
+impl FindAttributes for Vec<syn::Attribute> {
+ fn find_attrs(
+ &self,
+ name: &str,
+ ) -> impl Iterator<Item = &syn::Attribute> {
+ self.iter().filter(move |attr| {
+ attr.path().get_ident().is_some_and(|ident| ident == name)
+ })
+ }
+}
+
+impl FindAttributes for &[syn::Attribute] {
+ fn find_attrs(
+ &self,
+ name: &str,
+ ) -> impl Iterator<Item = &syn::Attribute> {
+ self.iter().filter(move |attr| {
+ attr.path().get_ident().is_some_and(|ident| ident == name)
+ })
+ }
+}
diff --git a/packages/wm-macros/src/common/branch.rs b/packages/wm-macros/src/common/branch.rs
new file mode 100644
index 00000000..8412b520
--- /dev/null
+++ b/packages/wm-macros/src/common/branch.rs
@@ -0,0 +1,477 @@
+//! Types and traits for branching and combining parsing operations.
+//! Implements functionality similar to `nom`s alternatives and
+//! combinators, but for `syn::parse::ParseStream`.
+
+use crate::prelude::*;
+
+/// Trait for tuples where all items can be parsed from a
+/// parse stream.
+pub trait ParseableTuple
+where
+ Self: Sized,
+{
+ type FirstItem: syn::parse::Parse;
+
+ /// Parses all items in the tuple `T` from the stream in the order they
+ /// appear in the tuple, and parses `Sep` in between each item. Returns
+ /// all parsed items in a tuple, or the first error to occur.
+ ///
+ /// Do not use this directly, use the [Ordered] type instead,
+ fn parse_tuple<Sep>(
+ stream: syn::parse::ParseStream,
+ ) -> syn::Result<Self>
+ where
+ Sep: syn::parse::Parse;
+}
+
+/// Trait for tuples where all items can be peeked and parsed from a parse
+/// stream.
+// Used with [Unordered]
+#[allow(dead_code)]
+pub trait PeekableTuple
+where
+ Self: Sized,
+{
+ /// Iterates until all items in the tuple `T` have been parsed, or an
+ /// error occurs. Parsing is attempted in the order of the items in
+ /// the tuple, although if an item is not found, it may be skipped and
+ /// reattempted for the next item(s).
+ ///
+ /// Do not use this directly, use the [Unordered] type instead.
+ fn peek_parse_tuple<Sep>(
+ stream: syn::parse::ParseStream,
+ ) -> syn::Result<Self>
+ where
+ Sep: syn::parse::Parse + crate::common::peekable::Peekable;
+}
+
+macro_rules! replace_expr {
+ ($idc:expr, $sub:expr) => {
+ $sub
+ };
+}
+
+macro_rules! get_first_item {
+ ($first:tt, $($types:tt),+) => {
+ $first
+ };
+}
+
+macro_rules! impl_for_tuple {
+ ($($types:tt),+ | $($numbers:tt),+) => {
+ // Generic ensures that all types in the tuple implement `syn::parse::Parse`.
+ impl<$($types),+> ParseableTuple for ($($types,)+) where $($types : syn::parse::Parse),+ {
+ type FirstItem = get_first_item!($($types),+);
+
+ fn parse_tuple<Sep>(stream: syn::parse::ParseStream) -> syn::Result<Self> where Sep: syn::parse::Parse {
+ $(
+ // Also check if the stream is empty to allow for missing trailing Optional items
+ if $numbers != 0 && !stream.is_empty() {
+ stream.parse::<Sep>()?;
+ }
+
+ #[allow(non_snake_case)]
+ let $types = stream.parse::<$types>()?;
+ )+
+
+ // Pack the parsed items into a tuple
+ Ok(($($types),+))
+ }
+ }
+
+ // Generic ensures that all types in the tuple implement `syn::parse::Parse` and `Peekable`.
+ impl<$($types),+> PeekableTuple for ($($types,)+) where $($types : syn::parse::Parse + crate::common::peekable::Peekable),+{
+
+ fn peek_parse_tuple<Sep>(stream: syn::parse::ParseStream) -> syn::Result<Self>
+ where Sep: syn::parse::Parse + crate::common::peekable::Peekable
+ {
+ use crate::common::peekable::prelude::*;
+
+ // Creates a tuple with the same number of items as the tuple, but with each item being
+ // `None`.
+ let mut output: ($(Option<$types>,)+) = ($(replace_expr!($types, None),)+);
+
+ // Iterate while any of the items in the tuple are `None`.
+ while $(output.$numbers.is_none())||+ {
+ let lookahead = stream.lookahead1();
+
+ $(
+ if output.$numbers.is_none() && lookahead.tpeek::<$types>() {
+
+ output.$numbers = Some(stream.parse::<$types>()?);
+ }
+ // Insert an else before the next item in the tuple, to create `else if` on subsequent
+ // unpacking
+ )else+
+ else {
+ return Err(lookahead.error());
+ }
+
+ // If we havn't yet parsed all items in the tuple, parse the separator.
+ // Also check if the stream is empty, which allows missing Optional items to be skipped
+ // TODO: Better handling of [Optional] items, so that we can handle them without needing
+ // the stream to end.
+ if !stream.is_empty() && $(output.$numbers.is_none())||+ {
+ stream.parse::<Sep>()?;
+ }
+ }
+
+ Ok(($(
+ // Saftey, the output is guaranteed to have all items otherwise the loop would have errored
+ // out.
+ output.$numbers.unwrap(),
+ )+))
+ }
+ }
+ };
+}
+
+// Implement the `ParseableTuple` and `PeekableTuple` traits for tuples of
+// different sizes.
+impl_for_tuple!(T, U | 0, 1);
+impl_for_tuple!(T, U, V | 0, 1, 2);
+impl_for_tuple!(T, U, V, W | 0, 1, 2, 3);
+impl_for_tuple!(T, U, V, W, X | 0, 1, 2, 3, 4);
+impl_for_tuple!(T, U, V, W, X, Y | 0, 1, 2, 3, 4, 5);
+
+/// Type wrapper to parse all items in tuple `T` in order, using
+/// `Sep` as the separator between items.
+///
+/// # Example
+/// Parse [syn::Ident] and [syn::LitStr] from the stream, which are
+/// separated by a comma. E.g. `some_name, "some string"`. If the order is
+/// reversed, it will fail to parse.
+/// ```
+/// fn example(stream: syn::parse::ParseStream) -> syn::Result<()> {
+/// type T = (syn::Ident, syn::LitStr);
+///
+/// stream.parse::<Ordered<T, syn::Token![,]>>()?;
+/// }
+///
+/// fn main() {
+/// # use quote::quote;
+/// let tokens = quote! { some_name, "some string" }.into();
+/// let error = quote! { "some string", some_name }.into();
+///
+/// assert!(example(tokens).is_ok());
+/// assert!(example(error).is_err());
+/// }
+/// ```
+pub struct Ordered<T, Sep>
+where
+ T: ParseableTuple,
+ Sep: syn::parse::Parse,
+{
+ pub items: T,
+ sep: std::marker::PhantomData<Sep>,
+}
+
+impl<T, Sep> syn::parse::Parse for Ordered<T, Sep>
+where
+ T: ParseableTuple,
+ Sep: syn::parse::Parse,
+{
+ fn parse(input: syn::parse::ParseStream) -> syn::Result<Self> {
+ let output = T::parse_tuple::<Sep>(input)? as T;
+ Ok(Self {
+ items: output,
+ sep: std::marker::PhantomData,
+ })
+ }
+}
+
+/// Implement [Peekable] for [Ordered] if the first item in the
+/// tuple is peekable, by forwarding the implementation to the first item.
+impl<T, FirstItem, Sep> crate::common::peekable::Peekable
+ for Ordered<T, Sep>
+where
+ T: ParseableTuple<FirstItem = FirstItem>,
+ Sep: syn::parse::Parse,
+ FirstItem: crate::common::peekable::Peekable,
+{
+ fn display() -> &'static str {
+ FirstItem::display()
+ }
+
+ fn peek<S>(stream: S) -> bool
+ where
+ S: crate::common::peekable::PeekableStream,
+ {
+ FirstItem::peek(stream)
+ }
+}
+
+impl<T, Sep> core::ops::Deref for Ordered<T, Sep>
+where
+ T: ParseableTuple,
+ Sep: syn::parse::Parse,
+{
+ type Target = T;
+
+ fn deref(&self) -> &Self::Target {
+ &self.items
+ }
+}
+
+/// Type wrapper to parse all items in tuple `T` in any order, using `Sep`
+/// as the separator between items.
+///
+/// # Example
+/// Parse [syn::Ident] and [syn::LitStr] from the stream in any order,
+/// which are separated by a comma. E.g. `some_name, "some string"` or
+/// `"some string", some_name`.
+/// ```
+/// fn example(stream: proc_macro::TokenStream) -> syn::Result<(syn::Ident, syn::LitStr)> {
+/// type T = (syn::Ident, syn::LitStr);
+///
+/// stream.parse2::<Unordered<T, syn::Token![,]>>().map(|Unordered(t, _)| t)
+/// }
+///
+/// fn main() {
+/// # use quote::quote;
+/// let normal = quote! { some_name, "some string" }.into();
+/// let reversed = quote! { "some string", some_name }.into();
+/// let error = quote! {some_name, other_name}.into();
+///
+/// assert!(example(normal).is_ok());
+/// assert!(example(reversed).is_ok());
+/// assert!(example(error).is_err());
+/// }
+/// ```
+// Util function that will be used in future.
+#[allow(dead_code)]
+pub struct Unordered<T, Sep>
+where
+ T: PeekableTuple,
+ Sep: syn::parse::Parse + crate::common::peekable::Peekable,
+{
+ pub items: T,
+ sep: std::marker::PhantomData<Sep>,
+}
+
+impl<T, Sep> syn::parse::Parse for Unordered<T, Sep>
+where
+ T: PeekableTuple,
+ Sep: syn::parse::Parse + crate::common::peekable::Peekable,
+{
+ fn parse(input: syn::parse::ParseStream) -> syn::Result<Self> {
+ let output = T::peek_parse_tuple::<Sep>(input)? as T;
+ Ok(Self {
+ items: output,
+ sep: std::marker::PhantomData,
+ })
+ }
+}
+
+impl<T, Sep> core::ops::Deref for Unordered<T, Sep>
+where
+ T: PeekableTuple,
+ Sep: syn::parse::Parse + crate::common::peekable::Peekable,
+{
+ type Target = T;
+
+ fn deref(&self) -> &Self::Target {
+ &self.items
+ }
+}
+
+/// Type wrapper to parse `If` if it is present, otherwise parse `Else`.
+/// `If` must be peekable so it can be checked if it is present before
+/// parsing.
+///
+/// # Example
+/// Parse [syn::Ident] if it is present, otherwise parse [syn::LitStr].
+/// ```
+/// type IfElseType = IfElse<syn::Ident, syn::LitStr>;
+///
+/// fn example(stream: syn::parse::ParseStream) -> syn::Result<IfElseType> {
+/// stream.parse::<IfElseType>()
+/// }
+///
+/// fn main() {
+/// # use quote::quote;
+/// let if_tokens = quote! { some_name }.into();
+/// let else_tokens = quote! { "some string" }.into();
+///
+/// assert!(example(if_tokens).is_ok_and(|if_else| if_else.is_if()));
+/// assert!(example(else_tokens).is_ok_and(|if_else| if_else.is_else()));
+/// }
+pub enum IfElse<If, Else>
+where
+ If: syn::parse::Parse + crate::common::peekable::Peekable,
+ Else: syn::parse::Parse,
+{
+ If(If),
+ Else(Else),
+}
+
+// Methods are used in doc tests, but linter doesn't pick that up.
+#[allow(dead_code)]
+impl<If, Else> IfElse<If, Else>
+where
+ If: syn::parse::Parse + crate::common::peekable::Peekable,
+ Else: syn::parse::Parse,
+{
+ pub fn is_if(&self) -> bool {
+ matches!(self, Self::If(_))
+ }
+
+ pub fn is_else(&self) -> bool {
+ matches!(self, Self::Else(_))
+ }
+}
+
+impl<If, Else> syn::parse::Parse for IfElse<If, Else>
+where
+ If: syn::parse::Parse + crate::common::peekable::Peekable,
+ Else: syn::parse::Parse,
+{
+ fn parse(input: syn::parse::ParseStream) -> syn::Result<Self> {
+ if input.tpeek::<If>() {
+ Ok(Self::If(input.parse()?))
+ } else {
+ Ok(Self::Else(input.parse()?))
+ }
+ }
+}
+
+/// Type wrapper to parse `T` only if it is present, otherwise returns
+/// None.
+///
+/// To be used in combination with [Ordered] then all optional items must
+/// be last in the tuple, and the stream must end to indicate that the
+/// optional items will not be present.
+///
+/// To be used in combination with [Unordered] the stream must end to
+/// indicate that the [Optional]s will not be present.
+///
+/// # Example
+/// Parse [syn::Ident] if it is present, otherwise return None.
+/// ```
+/// type OptionalType = Optional<syn::Ident>;
+/// fn example(stream: syn::parse::ParseStream) -> syn::Result<OptionalType> {
+/// stream.parse::<OptionalType>()
+/// }
+///
+/// fn main() {
+/// # use quote::quote;
+/// let present = quote! { some_name }.into();
+/// let not_present = quote! {}.into();
+/// let other_present = quote! { "some_string" }.into();
+///
+/// assert!(example(present).is_ok_and(|opt| opt.is_some()));
+/// assert!(example(not_present).is_ok_and(|opt| opt.is_none()));
+/// assert!(example(other_present).is_ok_and(|opt| opt.is_none()));
+/// }
+/// ```
+/// Used in combination with [Ordered] to parse a [syn::Ident] and
+/// optionally a [syn::LitStr]:
+/// ```
+/// type OrderedOptionalType = Ordered<(syn::Ident, Optional<syn::LitStr>),
+/// syn::Token![,]>;
+///
+/// fn example(stream: syn::parse::ParseStream) ->
+/// syn::Result<OrderedOptionalType> {
+/// stream.parse::<OrderedOptionalType>()
+/// }
+///
+/// fn main() {
+/// let present = quote! { some_name, "some string" }.into();
+/// let missing = quote! { some_name }.into();
+/// // Will error since the stream did not end after the Ordered to indicate no optionals.
+/// let error = quote! { some_name, not_a_string }.into();
+///
+/// assert!(example(present).is_ok_and(|Ordered { items: (ident, string), ..}| string.is_some()));
+/// assert!(example(missing).is_ok_and(|Ordered { items: (ident, string), ..}| string.is_none()));
+/// assert!(example(error).is_err());
+/// }
+/// ```
+/// Used in combination with [Unordered] it can be used to parse a
+/// [syn::Ident] and optionally a [syn::LitStr] in any order:
+/// ```
+/// type UnorderedOptionalType = Unordered<(syn::Ident, Optional<syn::LitStr>), syn::Token![,]>;
+///
+/// fn example(stream: syn::parse::ParseStream) -> syn::Result<UnorderedOptionalType> {
+/// stream.parse::<UnorderedOptionalType>()
+/// }
+///
+/// fn main() {
+/// let present = quote! { some_name, "some string" }.into();
+/// let not_present = quote! { some_name }.into();
+/// let backwards = quote! { "some string", some_name }.into();
+/// // Will error since the stream did not end after the Unordered to indicate no optionals.
+/// let error = quote! { some_name, not_a_string }.into();
+///
+/// assert!(example(present).is_ok_and(|Unordered { items: (ident, string), ..}| string.is_some()));
+/// assert!(example(not_present).is_ok_and(|Unordered { items: (ident, string), ..}| string.is_none()));
+/// assert!(example(backwards).is_ok_and(|Unordered { items: (ident, string), ..}| string.is_some()));
+/// assert!(example(error).is_err());
+/// }
+/// ```
+pub enum Optional<T>
+where
+ T: syn::parse::Parse + crate::common::peekable::Peekable,
+{
+ Some(T),
+ None,
+}
+
+impl<T> syn::parse::Parse for Optional<T>
+where
+ T: syn::parse::Parse + crate::common::peekable::Peekable,
+{
+ fn parse(input: syn::parse::ParseStream) -> syn::Result<Self> {
+ if input.is_empty() {
+ return Ok(Self::None);
+ }
+
+ if input.tpeek::<T>() {
+ Ok(Self::Some(input.parse()?))
+ } else {
+ Ok(Self::None)
+ }
+ }
+}
+
+impl<T> crate::common::peekable::Peekable for Optional<T>
+where
+ T: syn::parse::Parse + crate::common::peekable::Peekable,
+{
+ fn display() -> &'static str {
+ T::display()
+ }
+
+ fn peek<S>(stream: S) -> bool
+ where
+ S: crate::common::peekable::PeekableStream,
+ {
+ if stream.is_empty() {
+ return true;
+ }
+
+ T::peek(stream)
+ }
+}
+
+// Methods are used in doc tests, but linter doesn't pick that up.
+#[allow(dead_code)]
+impl<T> Optional<T>
+where
+ T: syn::parse::Parse + crate::common::peekable::Peekable,
+{
+ pub fn is_some(&self) -> bool {
+ matches!(self, Self::Some(_))
+ }
+
+ pub fn is_none(&self) -> bool {
+ matches!(self, Self::None)
+ }
+
+ #[allow(clippy::wrong_self_convention)]
+ pub fn to_opt(self) -> Option<T> {
+ match self {
+ Self::Some(value) => Some(value),
+ Self::None => None,
+ }
+ }
+}
diff --git a/packages/wm-macros/src/common/error_handling.rs b/packages/wm-macros/src/common/error_handling.rs
new file mode 100644
index 00000000..fe618d1e
--- /dev/null
+++ b/packages/wm-macros/src/common/error_handling.rs
@@ -0,0 +1,116 @@
+//! Utilities for simplifying error handling and diagnostics.
+
+pub mod prelude {
+ // ToSpanError is not used yet, but will be used in the future.
+ // TODO: Remove unused_imports allow
+ #[allow(unused_imports)]
+ pub use super::{EmitError, ThenError, ToError, ToSpanError};
+}
+
+/// Extends the `bool` type with a method that returns an error if the
+/// value is `true`.
+pub trait ThenError<E>
+where
+ Self: Sized,
+{
+ /// Returns `Err(error)` if the value is `true`, otherwise returns
+ /// `Ok(self)`.
+ ///
+ /// # Example
+ /// ```
+ /// # fn example(string: &str, string_span: syn::Span) -> syn::Result<()> {
+ /// string.is_empty().then_error(string_span.error("Expected a non-empty string"))?;
+ /// # }
+ /// ```
+ fn then_error(self, error: E) -> Result<Self, E>;
+}
+
+impl<E> ThenError<E> for bool {
+ fn then_error(self, error: E) -> Result<Self, E> {
+ if self { Err(error) } else { Ok(self) }
+ }
+}
+
+/// Extension trait for any type that can be tokenized to create a
+/// [syn::Error] at its location.
+pub trait ToError {
+ /// Create a [syn::Error] at the span of this object with the given
+ /// message.
+ ///
+ /// # Example
+ /// ```
+ /// # fn example(ident: syn::Ident) -> syn::Result<()> {
+ /// return Err(ident.error("Didn't expect an identifier here"));
+ /// # }
+ /// ```
+ fn error<D: core::fmt::Display>(&self, message: D) -> syn::Error;
+}
+
+impl<T> ToError for T
+where
+ T: quote::ToTokens,
+{
+ fn error<D: core::fmt::Display>(&self, message: D) -> syn::Error {
+ syn::Error::new_spanned(self, message)
+ }
+}
+
+// Very likely to be used in future.
+// TODO: Remove dead code allow
+#[allow(dead_code)]
+/// Extension trait for any [syn::spanned::Spanned] type that creates a
+/// [syn::Error] at its location. Use [ToError] where possible, as it
+/// creates more accurately spanned errors.
+pub trait ToSpanError {
+ /// Creates a [syn::Error] at the location of this span with the given
+ /// message.
+ ///
+ /// If the object can be tokenized, prefer using [ToError] instead, as it
+ /// gives more accurately spanned errors.
+ ///
+ /// # Example
+ /// ```
+ /// # fn example(stream: syn::parse::ParseStream) -> syn::Result<()> {
+ /// return Err(stream.span().serror("Expected ..."));
+ /// # }
+ /// ```
+ fn serror<D: core::fmt::Display>(&self, message: D) -> syn::Error;
+}
+
+impl<T> ToSpanError for T
+where
+ T: syn::spanned::Spanned,
+{
+ fn serror<D: core::fmt::Display>(&self, message: D) -> syn::Error {
+ syn::Error::new(self.span(), message)
+ }
+}
+
+// Very likely to be used in future.
+// TODO: Remove dead code allow
+#[allow(dead_code)]
+pub trait EmitError {
+ /// Directly emits a warning message at the span of this object.
+ fn emit_warning<D: Into<String>>(&self, message: D);
+ /// Emits a help message at the span of this object.
+ fn emit_help<D: Into<String>>(&self, message: D);
+ /// Emits a note message at the span of this object.
+ fn emit_note<D: Into<String>>(&self, message: D);
+}
+
+impl<T> EmitError for T
+where
+ T: syn::spanned::Spanned,
+{
+ fn emit_warning<D: Into<String>>(&self, message: D) {
+ self.span().unwrap().warning(message).emit();
+ }
+
+ fn emit_help<D: Into<String>>(&self, message: D) {
+ self.span().unwrap().help(message).emit();
+ }
+
+ fn emit_note<D: Into<String>>(&self, message: D) {
+ self.span().unwrap().note(message).emit();
+ }
+}
diff --git a/packages/wm-macros/src/common/mod.rs b/packages/wm-macros/src/common/mod.rs
new file mode 100644
index 00000000..eb79885c
--- /dev/null
+++ b/packages/wm-macros/src/common/mod.rs
@@ -0,0 +1,16 @@
+/// Utilitirs for parsing attributes
+pub mod attributes;
+/// Utilities for parsing alternitives and combinators
+pub mod branch;
+/// Extension traits and utilities to make error handling more succinct
+pub mod error_handling;
+/// Utilitirs for parsing a named parameter (`name = vaue`)
+pub mod named_parameter;
+/// Type for a parsable type within parenthesis
+pub mod parenthesized;
+/// Trait to get a `Peek` object from compatible syn types
+pub mod peekable;
+/// An owned version of a `syn::LitStr`
+pub mod spanned_string;
+
+pub(crate) use peekable::custom_keyword;
diff --git a/packages/wm-macros/src/common/named_parameter.rs b/packages/wm-macros/src/common/named_parameter.rs
new file mode 100644
index 00000000..b5eef79e
--- /dev/null
+++ b/packages/wm-macros/src/common/named_parameter.rs
@@ -0,0 +1,62 @@
+//! Types for parsing `name = value` patterns.
+
+/// Type to represent a `name = value` pair, where `name` can be peeked and
+/// both `name` and `value` can be parsed.
+///
+/// # Example
+/// Parse a name-value pair of [syn::Ident] and [syn::LitStr].
+/// ```
+/// type NamedParam = NamedParameter<syn::Ident, syn::LitStr>;
+///
+/// fn example(stream: syn::parse::ParseStream) -> syn::Result<NamedParam> {
+/// stream.parse::<NamedParam>()
+/// }
+///
+/// fn main() {
+/// # use quote::quote;
+/// let tokens = quote! { some_name = "some_value" }.into();
+///
+/// assert!(example(tokens).is_ok());
+/// }
+/// ```
+// Will be used in future.
+#[allow(dead_code)]
+pub struct NamedParameter<Name, Param>
+where
+ Name: syn::parse::Parse + crate::common::peekable::Peekable,
+ Param: syn::parse::Parse,
+{
+ pub name: Name,
+ pub param: Param,
+}
+
+impl<Name, Param> syn::parse::Parse for NamedParameter<Name, Param>
+where
+ Name: syn::parse::Parse + crate::common::peekable::Peekable,
+ Param: syn::parse::Parse,
+{
+ fn parse(input: syn::parse::ParseStream) -> syn::Result<Self> {
+ let name = input.parse()?;
+ input.parse::<syn::Token![=]>()?;
+ let param = input.parse()?;
+ Ok(Self { name, param })
+ }
+}
+
+impl<Name, Param> crate::common::peekable::Peekable
+ for NamedParameter<Name, Param>
+where
+ Name: syn::parse::Parse + crate::common::peekable::Peekable,
+ Param: syn::parse::Parse,
+{
+ fn peek<S>(stream: S) -> bool
+ where
+ S: crate::common::peekable::PeekableStream,
+ {
+ Name::peek(stream)
+ }
+
+ fn display() -> &'static str {
+ Name::display()
+ }
+}
diff --git a/packages/wm-macros/src/common/parenthesized.rs b/packages/wm-macros/src/common/parenthesized.rs
new file mode 100644
index 00000000..0f8301e7
--- /dev/null
+++ b/packages/wm-macros/src/common/parenthesized.rs
@@ -0,0 +1,56 @@
+//! Type wrappers for parsing content that is within delimiters, such as
+//! parenthesis or brackets.
+
+/// Type wrapper for parsing content within parenthesis.
+///
+/// # Example
+/// Parse a [syn::Ident] within parenthesis:
+/// ```
+/// type ParenthesizedIdent = wm_macros::Parenthesized<syn::Ident>;
+/// fn example(stream: syn::parse::ParseStream) -> syn::Result<ParenthesizedIdent> {
+/// stream.parse::<ParenthesizedIdent>()
+/// }
+///
+/// fn main() {
+/// # use quote::quote;
+/// let tokens = quote! { (some_name) }.into();
+///
+/// assert!(example(tokens).is_ok());
+/// }
+/// ```
+// Util type that will be used in future
+#[allow(dead_code)]
+pub struct Parenthesized<T>(pub T)
+where
+ T: syn::parse::Parse;
+
+impl<T> syn::parse::Parse for Parenthesized<T>
+where
+ T: syn::parse::Parse,
+{
+ fn parse(input: syn::parse::ParseStream) -> syn::Result<Self> {
+ let content;
+ syn::parenthesized!(content in input);
+ Ok(Parenthesized(content.parse()?))
+ }
+}
+
+impl<T> core::ops::Deref for Parenthesized<T>
+where
+ T: syn::parse::Parse,
+{
+ type Target = T;
+
+ fn deref(&self) -> &Self::Target {
+ &self.0
+ }
+}
+
+impl<T> core::ops::DerefMut for Parenthesized<T>
+where
+ T: syn::parse::Parse,
+{
+ fn deref_mut(&mut self) -> &mut Self::Target {
+ &mut self.0
+ }
+}
diff --git a/packages/wm-macros/src/common/peekable.rs b/packages/wm-macros/src/common/peekable.rs
new file mode 100644
index 00000000..945e2e8c
--- /dev/null
+++ b/packages/wm-macros/src/common/peekable.rs
@@ -0,0 +1,288 @@
+//! Custom peek implementation to support generics and custom peek
+//! functions.
+
+// Syn has a `Peek` trait, but it works weirdly. There is `syn::Ident` the
+// type which implements `Parse` and `syn::Ident` the function which
+// implements `Peek`. This file is for implementing a custom method of
+// peeking using the type itself rather than a function using the same name
+// as a type. This allows peeking to work nicer with generics.
+
+pub mod prelude {
+ pub use super::{Peekable, TPeek};
+}
+
+/// Trait for any stream that can peek at the next token.
+pub trait PeekableStream {
+ fn is_empty(&self) -> bool;
+ fn peek<T: syn::parse::Peek>(&self, token: T) -> bool;
+}
+
+impl PeekableStream for &syn::parse::ParseStream<'_> {
+ fn peek<T: syn::parse::Peek>(&self, token: T) -> bool {
+ (*self).peek(token)
+ }
+ fn is_empty(&self) -> bool {
+ (*self).is_empty()
+ }
+}
+
+impl PeekableStream for syn::parse::ParseStream<'_> {
+ fn peek<T: syn::parse::Peek>(&self, token: T) -> bool {
+ (*self).peek(token)
+ }
+
+ fn is_empty(&self) -> bool {
+ (*self).is_empty()
+ }
+}
+impl PeekableStream for syn::parse::ParseBuffer<'_> {
+ fn peek<T: syn::parse::Peek>(&self, token: T) -> bool {
+ self.peek(token)
+ }
+
+ fn is_empty(&self) -> bool {
+ self.is_empty()
+ }
+}
+impl PeekableStream for syn::parse::Lookahead1<'_> {
+ fn peek<T: syn::parse::Peek>(&self, token: T) -> bool {
+ self.peek(token)
+ }
+
+ fn is_empty(&self) -> bool {
+ self.peek(syn::parse::End)
+ }
+}
+impl PeekableStream for &syn::parse::Lookahead1<'_> {
+ fn peek<T: syn::parse::Peek>(&self, token: T) -> bool {
+ (*self).peek(token)
+ }
+
+ fn is_empty(&self) -> bool {
+ (*self).peek(syn::parse::End)
+ }
+}
+
+/// Custom trait for types that can be peeked.
+pub trait Peekable {
+ /// Gets the type's `Peek` implementation, since in syn the type
+ /// implements `Parse` but there is a function with the same path that
+ /// implements `Peek`. So this trait is used to get the function (`Peek`)
+ /// from the type (`Parse`).
+ ///
+ /// # Examble
+ /// ```
+ /// fn peek_then_parse<T: Parse + Peekable>(stream: syn::parse::ParseStream) -> syn::Result<T> {
+ /// if stream.peek(T::peekable()) {
+ /// let value = stream.parse::<T>()?;
+ /// }
+ /// }
+ /// ```
+ fn peek<T>(stream: T) -> bool
+ where
+ T: PeekableStream;
+ // Useful for debugging and custom error messages.
+ #[allow(dead_code)]
+ fn display() -> &'static str;
+}
+
+/// Trait for the types in syn that have a corresponding function that
+/// implements [syn::parse::Peek]. E.g. it implements a method for
+/// [syn::Ident] the type that returns [syn::Ident] the function.
+pub trait SynPeek {
+ fn peekable() -> impl syn::parse::Peek;
+ // To be forwarded to [Peekable]
+ #[allow(dead_code)]
+ fn display() -> &'static str;
+}
+
+/// Implement [Peekable] for [SynPeek]
+impl<T: SynPeek> Peekable for T {
+ fn peek<S>(stream: S) -> bool
+ where
+ S: PeekableStream,
+ {
+ stream.peek(T::peekable())
+ }
+
+ fn display() -> &'static str {
+ T::display()
+ }
+}
+
+/// Helper fucntion to get the display string for a peekable type.
+// Used in a macro call
+#[allow(dead_code)]
+pub fn get_peek_display<T: syn::parse::Peek>(_peek: T) -> &'static str {
+ use syn::token::Token;
+ T::Token::display()
+}
+
+/// Extends the [PeekableStream] trait with a method to peek at a type
+/// rather than a value.
+///
+/// # Example
+/// ```
+/// # fn example(stream: syn::parse::ParseStream) -> syn::Result<()> {
+/// // Allows for
+/// stream.tpeek::<syn::Ident>()?;
+/// // Rather than
+/// stream.peek(syn::Ident)?;
+/// # }
+pub trait TPeek<'a> {
+ fn tpeek<T>(&'a self) -> bool
+ where
+ T: Peekable;
+}
+
+impl<'a, T> TPeek<'a> for T
+where
+ &'a T: PeekableStream + 'a,
+{
+ fn tpeek<U>(&'a self) -> bool
+ where
+ U: Peekable,
+ {
+ U::peek(self)
+ }
+}
+
+/// Custom keyword macro to define a syn custom keyword that also
+/// implements Peekable.
+macro_rules! custom_keyword {
+ ($name:ident) => {
+ syn::custom_keyword!($name);
+
+ impl $crate::common::peekable::SynPeek for $name {
+ fn peekable() -> impl syn::parse::Peek {
+ $name
+ }
+
+ fn display() -> &'static str {
+ crate::common::peekable::get_peek_display(Self::peekable())
+ }
+ }
+ };
+}
+pub(crate) use custom_keyword;
+
+/// Macro for implementing [SynPeek] for a type that implements
+/// [syn::parse::Peek].
+macro_rules! impl_syn_peek {
+ ($($name:tt)+) => {
+ impl SynPeek for $($name)+ {
+ fn peekable() -> impl syn::parse::Peek {
+ $($name)+
+ }
+
+ fn display() -> &'static str {
+ crate::common::peekable::get_peek_display(Self::peekable())
+ }
+ }
+ };
+}
+
+impl_syn_peek!(syn::Ident);
+impl_syn_peek!(syn::LitStr);
+// TODO: Other syn types
+
+// Copied from syn::Token!
+impl_syn_peek!(syn::Token![abstract]);
+impl_syn_peek!(syn::Token![as]);
+impl_syn_peek!(syn::Token![async]);
+impl_syn_peek!(syn::Token![auto]);
+impl_syn_peek!(syn::Token![await]);
+impl_syn_peek!(syn::Token![become]);
+impl_syn_peek!(syn::Token![box]);
+impl_syn_peek!(syn::Token![break]);
+impl_syn_peek!(syn::Token![const]);
+impl_syn_peek!(syn::Token![continue]);
+impl_syn_peek!(syn::Token![crate]);
+impl_syn_peek!(syn::Token![default]);
+impl_syn_peek!(syn::Token![do]);
+impl_syn_peek!(syn::Token![dyn]);
+impl_syn_peek!(syn::Token![else]);
+impl_syn_peek!(syn::Token![enum]);
+impl_syn_peek!(syn::Token![extern]);
+impl_syn_peek!(syn::Token![final]);
+impl_syn_peek!(syn::Token![fn]);
+impl_syn_peek!(syn::Token![for]);
+impl_syn_peek!(syn::Token![if]);
+impl_syn_peek!(syn::Token![impl]);
+impl_syn_peek!(syn::Token![in]);
+impl_syn_peek!(syn::Token![let]);
+impl_syn_peek!(syn::Token![loop]);
+impl_syn_peek!(syn::Token![macro]);
+impl_syn_peek!(syn::Token![match]);
+impl_syn_peek!(syn::Token![mod]);
+impl_syn_peek!(syn::Token![move]);
+impl_syn_peek!(syn::Token![mut]);
+impl_syn_peek!(syn::Token![override]);
+impl_syn_peek!(syn::Token![priv]);
+impl_syn_peek!(syn::Token![pub]);
+impl_syn_peek!(syn::Token![ref]);
+impl_syn_peek!(syn::Token![return]);
+impl_syn_peek!(syn::Token![Self]);
+impl_syn_peek!(syn::Token![self]);
+impl_syn_peek!(syn::Token![static]);
+impl_syn_peek!(syn::Token![struct]);
+impl_syn_peek!(syn::Token![super]);
+impl_syn_peek!(syn::Token![trait]);
+impl_syn_peek!(syn::Token![try]);
+impl_syn_peek!(syn::Token![type]);
+impl_syn_peek!(syn::Token![typeof]);
+impl_syn_peek!(syn::Token![union]);
+impl_syn_peek!(syn::Token![unsafe]);
+impl_syn_peek!(syn::Token![unsized]);
+impl_syn_peek!(syn::Token![use]);
+impl_syn_peek!(syn::Token![virtual]);
+impl_syn_peek!(syn::Token![where]);
+impl_syn_peek!(syn::Token![while]);
+impl_syn_peek!(syn::Token![yield]);
+impl_syn_peek!(syn::Token![&]);
+impl_syn_peek!(syn::Token![&&]);
+impl_syn_peek!(syn::Token![&=]);
+impl_syn_peek!(syn::Token![@]);
+impl_syn_peek!(syn::Token![^]);
+impl_syn_peek!(syn::Token![^=]);
+impl_syn_peek!(syn::Token![:]);
+impl_syn_peek!(syn::Token![,]);
+impl_syn_peek!(syn::Token![$]);
+impl_syn_peek!(syn::Token![.]);
+impl_syn_peek!(syn::Token![..]);
+impl_syn_peek!(syn::Token![...]);
+impl_syn_peek!(syn::Token![..=]);
+impl_syn_peek!(syn::Token![=]);
+impl_syn_peek!(syn::Token![==]);
+impl_syn_peek!(syn::Token![=>]);
+impl_syn_peek!(syn::Token![>=]);
+impl_syn_peek!(syn::Token![>]);
+impl_syn_peek!(syn::Token![<-]);
+impl_syn_peek!(syn::Token![<=]);
+impl_syn_peek!(syn::Token![<]);
+impl_syn_peek!(syn::Token![-]);
+impl_syn_peek!(syn::Token![-=]);
+impl_syn_peek!(syn::Token![!=]);
+impl_syn_peek!(syn::Token![!]);
+impl_syn_peek!(syn::Token![|]);
+impl_syn_peek!(syn::Token![|=]);
+impl_syn_peek!(syn::Token![||]);
+impl_syn_peek!(syn::Token![::]);
+impl_syn_peek!(syn::Token![%]);
+impl_syn_peek!(syn::Token![%=]);
+impl_syn_peek!(syn::Token![+]);
+impl_syn_peek!(syn::Token![+=]);
+impl_syn_peek!(syn::Token![#]);
+impl_syn_peek!(syn::Token![?]);
+impl_syn_peek!(syn::Token![->]);
+impl_syn_peek!(syn::Token![;]);
+impl_syn_peek!(syn::Token![<<]);
+impl_syn_peek!(syn::Token![<<=]);
+impl_syn_peek!(syn::Token![>>]);
+impl_syn_peek!(syn::Token![>>=]);
+impl_syn_peek!(syn::Token![/]);
+impl_syn_peek!(syn::Token![/=]);
+impl_syn_peek!(syn::Token![*]);
+impl_syn_peek!(syn::Token![*=]);
+impl_syn_peek!(syn::Token![~]);
+impl_syn_peek!(syn::Token![_]);
diff --git a/packages/wm-macros/src/common/spanned_string.rs b/packages/wm-macros/src/common/spanned_string.rs
new file mode 100644
index 00000000..08ff2e6b
--- /dev/null
+++ b/packages/wm-macros/src/common/spanned_string.rs
@@ -0,0 +1,56 @@
+//! Type for a String with an associated source code span.
+
+/// A String with an associated source code span.
+/// An owned version of a syn::LitStr.
+#[derive(Debug, Clone)]
+pub struct SpannedString {
+ pub value: String,
+ pub span: proc_macro2::Span,
+}
+
+impl SpannedString {
+ pub fn new(value: String, span: proc_macro2::Span) -> Self {
+ SpannedString { value, span }
+ }
+
+ pub fn from_lit_str(lit_str: syn::LitStr) -> Self {
+ SpannedString {
+ value: lit_str.value(),
+ span: lit_str.span(),
+ }
+ }
+}
+
+impl From<SpannedString> for String {
+ fn from(spanned_string: SpannedString) -> Self {
+ spanned_string.value
+ }
+}
+
+impl From<&SpannedString> for syn::LitStr {
+ fn from(spanned_string: &SpannedString) -> Self {
+ syn::LitStr::new(&spanned_string.value, spanned_string.span)
+ }
+}
+
+impl From<syn::LitStr> for SpannedString {
+ fn from(lit_str: syn::LitStr) -> Self {
+ SpannedString::from_lit_str(lit_str)
+ }
+}
+
+/// Parse a `SpannedString` from a `syn::LitStr`.
+impl syn::parse::Parse for SpannedString {
+ fn parse(input: syn::parse::ParseStream) -> syn::Result<Self> {
+ let lit_str: syn::LitStr = input.parse()?;
+ Ok(lit_str.into())
+ }
+}
+
+/// Convert a `SpannedString` to a `syn::LitStr` for token generation.
+impl quote::ToTokens for SpannedString {
+ fn to_tokens(&self, tokens: &mut proc_macro2::TokenStream) {
+ let lit_str: syn::LitStr = self.into();
+ lit_str.to_tokens(tokens);
+ }
+}
diff --git a/packages/wm-macros/src/enum_from_inner/mod.rs b/packages/wm-macros/src/enum_from_inner/mod.rs
new file mode 100644
index 00000000..6fd58745
--- /dev/null
+++ b/packages/wm-macros/src/enum_from_inner/mod.rs
@@ -0,0 +1,88 @@
+//! Macro to derive `From` and `TryFrom` implementations for enum variants
+
+use quote::ToTokens as _;
+
+use crate::prelude::*;
+
+/// Macro to derive `From` and `TryFrom` implementations for enum variants
+/// Derives `From<T>` for each variant with format `Enum::Variant(T)`, and
+/// implements `TryFrom<Enum>` for each variant, returning an error if the
+/// variant does not match.
+pub fn enum_from_inner(
+ input: proc_macro::TokenStream,
+) -> proc_macro::TokenStream {
+ let input = syn::parse_macro_input!(input as syn::DeriveInput);
+
+ let name = &input.ident;
+
+ let enum_data = match input.data {
+ syn::Data::Enum(data) => data,
+ _ => {
+ return name
+ .error("This macro can only be used on enums")
+ .to_compile_error()
+ .into();
+ }
+ };
+
+ let variants = enum_data.variants.iter().map(|variant| {
+ let ident = &variant.ident;
+ let inner_type = match &variant.fields {
+ syn::Fields::Unnamed(fields) if fields.unnamed.len() == 1 => {
+ &fields.unnamed[0].ty
+ }
+ // Don't error on Unit variants, just do nothing.
+ syn::Fields::Unit => {
+ return quote::quote! {};
+ }
+ _ => {
+ return variant
+ .error("Enum variants must have exactly one unnamed field")
+ .to_compile_error();
+ }
+ };
+
+ let error = format!(
+ "Cannot convert this variant of enum `{}` to {}",
+ name,
+ // syn::Type doesn't print well, so convert it to a token stream
+ // which works well enough.
+ inner_type.to_token_stream()
+ );
+
+ quote::quote! {
+ impl From<#inner_type> for #name {
+ fn from(value: #inner_type) -> Self {
+ #name::#ident(value)
+ }
+ }
+
+ impl TryFrom<#name> for #inner_type {
+ type Error = &'static str;
+
+ fn try_from(value: #name) -> Result<Self, Self::Error> {
+ match value {
+ #name::#ident(inner) => Ok(inner),
+ _ => Err(#error),
+ }
+ }
+ }
+
+ impl<'a> TryFrom<&'a #name> for &'a #inner_type {
+ type Error = &'static str;
+
+ fn try_from(value: &'a #name) -> Result<Self, Self::Error> {
+ match value {
+ #name::#ident(inner) => Ok(inner),
+ _ => Err(#error),
+ }
+ }
+ }
+ }
+ });
+
+ quote::quote! {
+ #(#variants)*
+ }
+ .into()
+}
diff --git a/packages/wm-macros/src/lib.rs b/packages/wm-macros/src/lib.rs
new file mode 100644
index 00000000..61690bc1
--- /dev/null
+++ b/packages/wm-macros/src/lib.rs
@@ -0,0 +1,119 @@
+// Enable proc macro diagnostics to allow emitting warnings and errors in
+// line
+#![feature(proc_macro_diagnostic)]
+
+mod common;
+mod enum_from_inner;
+mod subenum;
+use proc_macro::TokenStream;
+
+mod prelude {
+ pub use crate::common::{
+ attributes::prelude::*, error_handling::prelude::*,
+ peekable::prelude::*,
+ };
+}
+
+/// Creates subenums from a main enum, and defines
+/// * `impl From<SubEnum> for MainEnum`
+/// * `impl TryFrom<MainEnum> for SubEnum`
+/// * `impl TryFrom<SubEnumOne> for SubEnumTwo` where `SubEnumOne` and
+/// `SubEnumTwo` share variant(s).
+///
+/// Accepts a defaults block of attributes to be added to every subenum
+/// ```
+/// #[subenum(defaults, {
+/// /// Subenum of [X]
+/// #[derive(Clone, Debug)]
+/// })]
+/// ```
+///
+/// And any number of subenum declarations, which are defined as
+/// ```
+/// #[subenum(SubenumName, {
+/// /// Subset of [X] that can be checked for equality.
+/// #[derive(PartialEq)] // Will also derive [Clone] and [Debug] from the defaults block
+/// })]
+/// ```
+///
+/// # Example
+/// ```
+/// /// Your main enum documentation
+/// // Note that the defaults block does not apply to the main enum itself.
+/// #[derive(Clone, Debug, wm_macros::SubEnum)]
+/// #[subenum(defaults, {
+/// /// Subenum of [MainEnum]
+/// #[derive(Clone, Debug)]
+/// })]
+/// #[subenum(Similar, {
+/// /// Subset of [MainEnum] that can be checked for equality.
+/// #[derive(PartialEq)] // Will also derive [Clone] and [Debug] from the defaults block
+/// })]
+/// #[subenum(Hashable, {
+/// /// Subset of [MainEnum] that can be hashed.
+/// #[derive(Hash)] // Will also derive [Clone] and [Debug] from the defaults block
+/// })]
+/// pub enum MainEnum {
+/// Path(PathBuf),
+/// #[subenum(Similar, Hashable)]
+/// Length(i32),
+/// #[subenum(Hashable)]
+/// Name(String)
+/// }
+///
+/// let name = String::from("example");
+/// let name_enum = MainEnum::from(name);
+///
+/// // Try to convert MainEnum to Hashable.
+/// let hashable_name = Hashable::try_from(name_enum).unwrap(); // Will succeed, as `Name` is present in the `Hashable` subenum.
+/// hashable_name.hash();
+///
+/// let similar_name = Similar::try_from(hashable_name.clone());
+/// assert!(similar_name.is_err()); // Will fail, as `Name` is not present in the `Similar` subenum.
+///
+/// // And convert it back (infallible).
+/// let name_enum: MainEnum = hashable_name.into();
+///
+/// let length = 42;
+/// let length_enum: MainEnum = length.into();
+///
+/// let similar_length = Similar::try_from(length_enum).unwrap();
+///
+/// let other_length = Hashable::Length(42);
+/// let other_similar_length = Similar::try_from(other_length).unwrap(); // Convert between subenums that share variants.
+///
+/// assert_eq!(similar_length, other_similar_length);
+/// ```
+#[proc_macro_derive(SubEnum, attributes(subenum))]
+pub fn sub_enum(input: TokenStream) -> TokenStream {
+ subenum::sub_enum(input)
+}
+
+/// Creates `impl From<Inner> for Enum` and `impl TryFrom<Enum> for Inner`
+///
+/// # Example
+/// ```
+/// struct One;
+/// struct Two;
+///
+/// #[derive(wm_macros::EnumFromInner)]
+/// enum MyEnum {
+/// One(One),
+/// Two(Two),
+/// }
+///
+/// let one = One;
+/// let my_enum: MyEnum = one.into(); // Converts One into MyEnum::One(One)
+///
+/// let one = my_enum.try_into().unwrap(); // Attempts to convert MyEnum::One(One) into One
+///
+/// let two = Two;
+/// let my_enum: MyEnum = two.into(); // Converts Two into MyEnum::Two(Two)
+///
+/// let one = my_enum.try_into(); // Will fail, as MyEnum::Two(Two) cannot be converted to One
+/// assert!(one.is_err());
+/// ```
+#[proc_macro_derive(EnumFromInner)]
+pub fn enum_from_inner(input: TokenStream) -> TokenStream {
+ enum_from_inner::enum_from_inner(input)
+}
diff --git a/packages/wm-macros/src/subenum/enum_attrs.rs b/packages/wm-macros/src/subenum/enum_attrs.rs
new file mode 100644
index 00000000..e5a1c591
--- /dev/null
+++ b/packages/wm-macros/src/subenum/enum_attrs.rs
@@ -0,0 +1,71 @@
+use crate::{common::branch::Ordered, prelude::*};
+
+mod kw {
+ crate::common::custom_keyword!(defaults);
+}
+
+/// Collects all `#[subenum(...)]` attributes from the given iterator of
+/// attributes and returns a list of `Subenum` instances.
+pub fn collect_sub_enums<'a>(
+ attrs: impl Iterator<Item = &'a syn::MetaList>,
+) -> syn::Result<Vec<Subenum>> {
+ attrs
+ .map(|attr| attr.parse_args())
+ .collect::<syn::Result<Vec<_>>>()
+}
+
+/// Each subenum can either be a declaration with a name and attribute
+/// block, or a defaults block to append to every subenum.
+pub enum Subenum {
+ Defaults(proc_macro2::TokenStream),
+ Declaration(SubenumDeclaration),
+}
+
+impl syn::parse::Parse for Subenum {
+ fn parse(input: syn::parse::ParseStream) -> syn::Result<Self> {
+ type Defaults = Ordered<(kw::defaults, AttrBlock), syn::Token![,]>;
+ if input.tpeek::<Defaults>() {
+ let Ordered {
+ items: (_, AttrBlock { attrs }),
+ ..
+ } = input.parse::<Defaults>()?;
+ return Ok(Self::Defaults(attrs));
+ }
+
+ let declaration: SubenumDeclaration = input.parse()?;
+ Ok(Self::Declaration(declaration))
+ }
+}
+
+/// Parser for `<name>, {...}` where name is the name of the subenum, and
+/// the block contents are passed through as is.
+pub struct SubenumDeclaration {
+ pub name: syn::Ident,
+ pub attrs: proc_macro2::TokenStream,
+}
+
+impl syn::parse::Parse for SubenumDeclaration {
+ fn parse(input: syn::parse::ParseStream) -> syn::Result<Self> {
+ type Declaration = Ordered<(syn::Ident, AttrBlock), syn::Token![,]>;
+
+ let Ordered {
+ items: (name, AttrBlock { attrs }),
+ ..
+ } = input.parse::<Declaration>()?;
+ Ok(Self { name, attrs })
+ }
+}
+
+/// Block of arbitray tokens that are contained within { ... }
+struct AttrBlock {
+ pub attrs: proc_macro2::TokenStream,
+}
+
+impl syn::parse::Parse for AttrBlock {
+ fn parse(input: syn::parse::ParseStream) -> syn::Result<Self> {
+ let content;
+ let _ = syn::braced!(content in input);
+ let attrs: proc_macro2::TokenStream = content.parse()?;
+ Ok(Self { attrs })
+ }
+}
diff --git a/packages/wm-macros/src/subenum/mod.rs b/packages/wm-macros/src/subenum/mod.rs
new file mode 100644
index 00000000..e6c49c72
--- /dev/null
+++ b/packages/wm-macros/src/subenum/mod.rs
@@ -0,0 +1,309 @@
+use enum_attrs::{Subenum, SubenumDeclaration};
+
+use crate::prelude::*;
+
+const SUBENUM_ATTR_NAME: &str = "subenum";
+
+mod enum_attrs;
+mod variant_attr;
+
+pub fn sub_enum(
+ input: proc_macro::TokenStream,
+) -> proc_macro::TokenStream {
+ let input = syn::parse_macro_input!(input as syn::DeriveInput);
+
+ let attrs = &input.attrs;
+
+ let sub_enums = match enum_attrs::collect_sub_enums(
+ attrs.find_list_attrs(SUBENUM_ATTR_NAME),
+ ) {
+ Ok(sub_enums) => sub_enums,
+ Err(err) => return err.to_compile_error().into(),
+ };
+
+ let enum_data = match input.data {
+ syn::Data::Enum(data) => data,
+ _ => {
+ return input
+ .ident
+ .error("This macro can only be used on enums")
+ .to_compile_error()
+ .into();
+ }
+ };
+
+ let variants = match enum_data
+ .variants
+ .iter()
+ .map(variant_attr::parse_variant)
+ .collect::<syn::Result<Vec<_>>>()
+ {
+ Ok(variants) => variants,
+ Err(err) => return err.to_compile_error().into(),
+ };
+
+ // Filter to get the default blocks and combine them into a single token
+ // stream.
+ let defaults = sub_enums
+ .iter()
+ .filter_map(|sub| match &sub {
+ Subenum::Defaults(attrs) => Some(attrs.clone()),
+ _ => None,
+ })
+ .reduce(|mut acc, el| {
+ acc.extend(el);
+ acc
+ })
+ .unwrap_or_default();
+
+ let sub_enums = sub_enums
+ .into_iter()
+ .filter_map(|sub| match sub {
+ Subenum::Declaration(decl) => Some(decl),
+ Subenum::Defaults(_) => None,
+ })
+ .collect::<Vec<_>>();
+
+ for variant in &variants {
+ for enum_name in &variant.enums {
+ if !sub_enums.iter().any(|sub_enum| sub_enum.name == *enum_name) {
+ enum_name.emit_warning(
+ "Variant references a subenum that is not defined.",
+ );
+ }
+ }
+ }
+
+ let sub_enums = combine_variants(sub_enums, variants, &defaults);
+
+ let sub_enum_to_main_impls = sub_enums
+ .iter()
+ .map(|sub_enum| from_sub_to_main_impl(&input.ident, sub_enum));
+
+ let main_to_sub_impls = sub_enums
+ .iter()
+ .map(|sub| try_from_main_to_sub_impl(&input.ident, sub));
+
+ struct SharedVariant {
+ sub_enum_a: syn::Ident,
+ sub_enum_b: syn::Ident,
+ variants: Vec<Variant>,
+ }
+
+ // Find all sub enums that have a shared variant, so we can make
+ // `TryFrom` impls between them.
+ let mut shared_variants: Vec<SharedVariant> = Vec::new();
+ for i in 0..sub_enums.len() {
+ for j in (i + 1)..sub_enums.len() {
+ let sub_enum_a = &sub_enums[i];
+ let sub_enum_b = &sub_enums[j];
+
+ for variant_a in &sub_enum_a.variants {
+ if sub_enum_b.variants.iter().any(|v| v.name == variant_a.name) {
+ if let Some(shared) = shared_variants.iter_mut().find(|sv| {
+ sv.sub_enum_a == sub_enum_a.name
+ && sv.sub_enum_b == sub_enum_b.name
+ }) {
+ shared.variants.push(variant_a.clone());
+ } else {
+ shared_variants.push(SharedVariant {
+ sub_enum_a: sub_enum_a.name.clone(),
+ sub_enum_b: sub_enum_b.name.clone(),
+ variants: vec![variant_a.clone()],
+ });
+ }
+ }
+ }
+ }
+ }
+
+ let shared_variants = shared_variants.iter().map(|shared| {
+ let a = &shared.sub_enum_a;
+ let b = &shared.sub_enum_b;
+
+ let variants_a_b = shared.variants.iter().map(|v| {
+ let var_name = &v.name;
+ quote::quote! {
+ #a::#var_name(v) => Ok(#b::#var_name(v))
+ }
+ });
+
+ let variants_b_a = shared.variants.iter().map(|v| {
+ let var_name = &v.name;
+ quote::quote! {
+ #b::#var_name(v) => Ok(#a::#var_name(v))
+ }
+ });
+
+ let eror_a_b = format!(
+ "Cannot convert this variant of sub enum `{a}` to sub enum `{b}`."
+ );
+
+ let eror_b_a = format!(
+ "Cannot convert this variant of sub enum `{b}` to sub enum `{a}`."
+ );
+
+ quote::quote! {
+ impl TryFrom<#a> for #b {
+ type Error = &'static str;
+
+ fn try_from(value: #a) -> Result<Self, Self::Error> {
+ match value {
+ #(#variants_a_b),*,
+ _ => Err(#eror_a_b),
+ }
+ }
+ }
+
+ impl TryFrom<#b> for #a {
+ type Error = &'static str;
+
+ fn try_from(value: #b) -> Result<Self, Self::Error> {
+ match value {
+ #(#variants_b_a),*,
+ _ => Err(#eror_b_a),
+ }
+ }
+ }
+ }
+ });
+
+ quote::quote! {
+ #(#sub_enums)*
+
+ #(#sub_enum_to_main_impls)*
+
+ #(#main_to_sub_impls)*
+
+ #(#shared_variants)*
+ }
+ .into()
+}
+
+/// Holds the final data for creating a sub enum.
+struct SubEnum<'a> {
+ pub name: syn::Ident,
+ pub defaults: &'a proc_macro2::TokenStream,
+ pub attrs: proc_macro2::TokenStream,
+ pub variants: Vec<Variant>,
+}
+
+/// Final representation of a sub enum variant, which includes its name and
+/// the contained type.
+#[derive(Debug, Clone)]
+struct Variant {
+ pub name: syn::Ident,
+ pub contained: syn::Type,
+}
+
+impl<'a> quote::ToTokens for SubEnum<'a> {
+ fn to_tokens(&self, tokens: &mut proc_macro2::TokenStream) {
+ let name = &self.name;
+ let defaults = &self.defaults;
+ let attrs = &self.attrs;
+ let variants = &self.variants;
+
+ tokens.extend(quote::quote! {
+ #defaults
+ #attrs
+ pub enum #name {
+ #(#variants),*
+ }
+ });
+ }
+}
+
+impl quote::ToTokens for Variant {
+ fn to_tokens(&self, tokens: &mut proc_macro2::TokenStream) {
+ let variant_name = &self.name;
+ let contained = &self.contained;
+ tokens.extend(quote::quote! {
+ #variant_name(#contained)
+ });
+ }
+}
+
+/// Combine the sub enum declarations with its enum variants
+fn combine_variants(
+ sub_enums: Vec<SubenumDeclaration>,
+ variants: Vec<variant_attr::SubenumVariant>,
+ defaults: &proc_macro2::TokenStream,
+) -> Vec<SubEnum<'_>> {
+ sub_enums
+ .into_iter()
+ .map(|sub_enum| {
+ let mut combined_variants = Vec::new();
+ for variant in &variants {
+ if variant.enums.contains(&sub_enum.name) {
+ combined_variants.push(Variant {
+ name: variant.name.clone(),
+ contained: variant.contained.clone(),
+ });
+ }
+ }
+ SubEnum {
+ defaults,
+ name: sub_enum.name,
+ attrs: sub_enum.attrs,
+ variants: combined_variants,
+ }
+ })
+ .collect()
+}
+
+/// Create a `impl From<sub_enum> for name` block
+fn from_sub_to_main_impl(
+ name: &syn::Ident,
+ sub_enum: &SubEnum,
+) -> proc_macro2::TokenStream {
+ let sub_name = &sub_enum.name;
+
+ let variants = sub_enum.variants.iter().map(|v| {
+ let var_name = &v.name;
+ quote::quote! {
+ #sub_name::#var_name(v) => #name::#var_name(v)
+ }
+ });
+
+ quote::quote! {
+ impl From<#sub_name> for #name {
+ fn from(value: #sub_name) -> Self {
+ match value {
+ #(#variants),*
+ }
+ }
+ }
+ }
+}
+
+/// Create a `impl TryFrom<name> for sub_enum` block
+fn try_from_main_to_sub_impl(
+ name: &syn::Ident,
+ sub_enum: &SubEnum,
+) -> proc_macro2::TokenStream {
+ let sub_name = &sub_enum.name;
+
+ let variants = sub_enum.variants.iter().map(|v| {
+ let var_name = &v.name;
+ quote::quote! {
+ #name::#var_name(v) => Ok(#sub_name::#var_name(v))
+ }
+ });
+
+ let error = format!(
+ "Cannot convert this variant of sub enum `{sub_name}` to main enum `{name}`."
+ );
+
+ quote::quote! {
+ impl TryFrom<#name> for #sub_name {
+ type Error = &'static str;
+
+ fn try_from(value: #name) -> Result<Self, Self::Error> {
+ match value {
+ #(#variants),*,
+ _ => Err(#error),
+ }
+ }
+ }
+ }
+}
diff --git a/packages/wm-macros/src/subenum/variant_attr.rs b/packages/wm-macros/src/subenum/variant_attr.rs
new file mode 100644
index 00000000..38576392
--- /dev/null
+++ b/packages/wm-macros/src/subenum/variant_attr.rs
@@ -0,0 +1,55 @@
+use syn::punctuated::Punctuated;
+
+use crate::prelude::*;
+
+/// Holds the parsed data for a single subenum variant.
+pub struct SubenumVariant {
+ pub name: syn::Ident,
+ pub contained: syn::Type,
+ pub enums: Vec<syn::Ident>,
+}
+
+/// Parse a single subenum variant from a [syn::Variant].
+pub fn parse_variant(
+ variant: &syn::Variant,
+) -> syn::Result<SubenumVariant> {
+ let name = variant.ident.clone();
+ let mut contained_iter = variant.fields.iter();
+ let contained = contained_iter
+ .next()
+ .map(|field| field.ty.clone())
+ .ok_or_else(|| {
+ variant.error("Subenum variants must have a contained type")
+ })?;
+
+ contained_iter.next().is_some().then_error(
+ variant.error("Subenum variants must have exactly one contained type"),
+ )?;
+
+ let enums = if let Some(enums) = variant
+ .attrs
+ .find_list_attrs(crate::subenum::SUBENUM_ATTR_NAME)
+ .map(|attr| {
+ attr.parse_args_with(
+ Punctuated::<syn::Ident, syn::Token![,]>::parse_terminated,
+ )
+ })
+ .reduce(|acc, el| {
+ acc.and_then(|mut acc| {
+ el.map(|el| {
+ acc.extend(el);
+ acc
+ })
+ })
+ }) {
+ enums.map(|list| list.iter().cloned().collect::<Vec<_>>())?
+ } else {
+ vec![]
+ };
+
+ Ok(SubenumVariant {
+ name,
+ enums,
+ contained,
+ })
+}
diff --git a/packages/wm/Cargo.toml b/packages/wm/Cargo.toml
index 660163f4..ad1dd7a4 100644
--- a/packages/wm/Cargo.toml
+++ b/packages/wm/Cargo.toml
@@ -38,3 +38,4 @@ wm-common = { path = "../wm-common" }
wm-cli = { path = "../wm-cli" }
wm-platform = { path = "../wm-platform" }
wm-ipc-client = { path = "../wm-ipc-client" }
+wm-macros.workspace = true
diff --git a/packages/wm/src/models/container.rs b/packages/wm/src/models/container.rs
index 0cfe74c6..086e623c 100644
--- a/packages/wm/src/models/container.rs
+++ b/packages/wm/src/models/container.rs
@@ -23,81 +23,88 @@ use crate::{
};
/// A container of any type.
-#[derive(Clone, Debug, EnumAsInner, Delegate)]
+///
+/// Uses:
+///
+/// * [`wm_macros::SubEnum`] to define subtypes of containers.
+/// * [`wm_macros::EnumFromInner`] to define conversions between the enum
+/// and wrapped types.
+/// * [`ambassador::Delegate`] to delegate common getters to the contained
+/// types. E.g. implements [`CommonGetters`] for [Container] by
+/// forwarding the call to the item contained in the enum variant.
+///
+/// # Example
+/// Conversion between the different container types:
+/// ```
+/// fn example(split: SplitContainer) {
+/// // Convert a `SplitContainer` into a `Container`
+/// let container: Container = split.into(); // Will be a `Container::Split`
+///
+/// // Could also have gone straight to a [TilingContainer] from SplitContainer
+/// // let tiling: TilingContainer = split.into(); // Will be a `TilingContainer::Split`
+///
+/// // Try to convert a [Container] into a sub container type ([TilingContainer] in this case).
+/// let tiling: TilingContainer = container.try_into().unwrap(); // Will be a `TilingContainer::Split`
+/// tiling.tiling_size(); // Can use methods from the `TilingSizeGetters` trait.
+///
+/// // Try to convert a one sub container type into another. ([TilingContainer] to [DirectionContainer] in this case).
+/// let direction: DirectionContainer = tiling.try_into().unwrap(); // Will be a `DirectionContainer::Split`
+/// direction.tiling_direction(); // Can use methods from the `TilingDirectionGetters` trait.
+///
+/// // Covert a sub container back into a [Container]
+/// let container: Container = direction.into(); // Will be a `Container::Split`
+/// }
+/// ```
+#[derive(
+ Clone,
+ Debug,
+ EnumAsInner,
+ wm_macros::EnumFromInner,
+ Delegate,
+ wm_macros::SubEnum,
+)]
#[delegate(CommonGetters)]
#[delegate(PositionGetters)]
+#[subenum(defaults, {
+ /// Subenum of [Container]
+ #[derive(Clone, Debug, EnumAsInner, Delegate, wm_macros::EnumFromInner)]
+ #[delegate(CommonGetters)]
+ #[delegate(PositionGetters)]
+})]
+#[subenum(TilingContainer, {
+ /// Subset of containers that implement the following traits:
+ /// * `CommonGetters`
+ /// * `PositionGetters`
+ /// * `TilingSizeGetters`
+ #[delegate(TilingSizeGetters)]
+})]
+#[subenum(WindowContainer, {
+ /// Subset of containers that implement the following traits:
+ /// * `CommonGetters`
+ /// * `PositionGetters`
+ /// * `WindowGetters`
+ #[delegate(WindowGetters)]
+})]
+#[subenum(DirectionContainer, {
+ /// Subset of containers that implement the following traits:
+ /// * `CommonGetters`
+ /// * `PositionGetters`
+ /// * `DirectionGetters`
+ #[delegate(TilingDirectionGetters)]
+})]
pub enum Container {
Root(RootContainer),
Monitor(Monitor),
+ #[subenum(DirectionContainer)]
Workspace(Workspace),
+ #[subenum(TilingContainer, DirectionContainer)]
Split(SplitContainer),
+ #[subenum(TilingContainer, WindowContainer)]
TilingWindow(TilingWindow),
+ #[subenum(WindowContainer)]
NonTilingWindow(NonTilingWindow),
}
-impl From<RootContainer> for Container {
- fn from(value: RootContainer) -> Self {
- Container::Root(value)
- }
-}
-
-impl From<Monitor> for Container {
- fn from(value: Monitor) -> Self {
- Container::Monitor(value)
- }
-}
-
-impl From<Workspace> for Container {
- fn from(value: Workspace) -> Self {
- Container::Workspace(value)
- }
-}
-
-impl From<SplitContainer> for Container {
- fn from(value: SplitContainer) -> Self {
- Container::Split(value)
- }
-}
-
-impl From<NonTilingWindow> for Container {
- fn from(value: NonTilingWindow) -> Self {
- Container::NonTilingWindow(value)
- }
-}
-
-impl From<TilingWindow> for Container {
- fn from(value: TilingWindow) -> Self {
- Container::TilingWindow(value)
- }
-}
-
-impl From<TilingContainer> for Container {
- fn from(tiling_container: TilingContainer) -> Self {
- match tiling_container {
- TilingContainer::Split(c) => Container::Split(c),
- TilingContainer::TilingWindow(c) => Container::TilingWindow(c),
- }
- }
-}
-
-impl From<WindowContainer> for Container {
- fn from(window_container: WindowContainer) -> Self {
- match window_container {
- WindowContainer::NonTilingWindow(c) => Container::NonTilingWindow(c),
- WindowContainer::TilingWindow(c) => Container::TilingWindow(c),
- }
- }
-}
-
-impl From<DirectionContainer> for Container {
- fn from(direction_container: DirectionContainer) -> Self {
- match direction_container {
- DirectionContainer::Split(c) => Container::Split(c),
- DirectionContainer::Workspace(c) => Container::Workspace(c),
- }
- }
-}
-
impl PartialEq for Container {
fn eq(&self, other: &Self) -> bool {
self.id() == other.id()
@@ -106,43 +113,6 @@ impl PartialEq for Container {
impl Eq for Container {}
-/// Subset of containers that implement the following traits:
-/// * `CommonGetters`
-/// * `PositionGetters`
-/// * `TilingSizeGetters`
-#[derive(Clone, Debug, EnumAsInner, Delegate)]
-#[delegate(CommonGetters)]
-#[delegate(PositionGetters)]
-#[delegate(TilingSizeGetters)]
-pub enum TilingContainer {
- Split(SplitContainer),
- TilingWindow(TilingWindow),
-}
-
-impl From<SplitContainer> for TilingContainer {
- fn from(value: SplitContainer) -> Self {
- TilingContainer::Split(value)
- }
-}
-
-impl From<TilingWindow> for TilingContainer {
- fn from(value: TilingWindow) -> Self {
- TilingContainer::TilingWindow(value)
- }
-}
-
-impl TryFrom<Container> for TilingContainer {
- type Error = &'static str;
-
- fn try_from(container: Container) -> Result<Self, Self::Error> {
- match container {
- Container::Split(c) => Ok(TilingContainer::Split(c)),
- Container::TilingWindow(c) => Ok(TilingContainer::TilingWindow(c)),
- _ => Err("Cannot convert type to `TilingContainer`."),
- }
- }
-}
-
impl PartialEq for TilingContainer {
fn eq(&self, other: &Self) -> bool {
self.id() == other.id()
@@ -151,60 +121,6 @@ impl PartialEq for TilingContainer {
impl Eq for TilingContainer {}
-/// Subset of containers that implement the following traits:
-/// * `CommonGetters`
-/// * `PositionGetters`
-/// * `WindowGetters`
-#[derive(Clone, Debug, EnumAsInner, Delegate)]
-#[delegate(CommonGetters)]
-#[delegate(PositionGetters)]
-#[delegate(WindowGetters)]
-pub enum WindowContainer {
- TilingWindow(TilingWindow),
- NonTilingWindow(NonTilingWindow),
-}
-
-impl From<TilingWindow> for WindowContainer {
- fn from(value: TilingWindow) -> Self {
- WindowContainer::TilingWindow(value)
- }
-}
-
-impl From<NonTilingWindow> for WindowContainer {
- fn from(value: NonTilingWindow) -> Self {
- WindowContainer::NonTilingWindow(value)
- }
-}
-
-impl TryFrom<Container> for WindowContainer {
- type Error = &'static str;
-
- fn try_from(container: Container) -> Result<Self, Self::Error> {
- match container {
- Container::TilingWindow(c) => Ok(WindowContainer::TilingWindow(c)),
- Container::NonTilingWindow(c) => {
- Ok(WindowContainer::NonTilingWindow(c))
- }
- _ => Err("Cannot convert type to a `WindowContainer`."),
- }
- }
-}
-
-impl TryFrom<TilingContainer> for WindowContainer {
- type Error = &'static str;
-
- fn try_from(container: TilingContainer) -> Result<Self, Self::Error> {
- match container {
- TilingContainer::TilingWindow(c) => {
- Ok(WindowContainer::TilingWindow(c))
- }
- TilingContainer::Split(_) => {
- Err("Cannot convert type to a `WindowContainer`.")
- }
- }
- }
-}
-
impl PartialEq for WindowContainer {
fn eq(&self, other: &Self) -> bool {
self.id() == other.id()
@@ -236,56 +152,6 @@ impl std::fmt::Display for WindowContainer {
}
}
-/// Subset of containers that implement the following traits:
-/// * `CommonGetters`
-/// * `PositionGetters`
-/// * `TilingDirectionGetters`
-#[derive(Clone, Debug, EnumAsInner, Delegate)]
-#[delegate(CommonGetters)]
-#[delegate(PositionGetters)]
-#[delegate(TilingDirectionGetters)]
-pub enum DirectionContainer {
- Workspace(Workspace),
- Split(SplitContainer),
-}
-
-impl From<Workspace> for DirectionContainer {
- fn from(value: Workspace) -> Self {
- DirectionContainer::Workspace(value)
- }
-}
-
-impl From<SplitContainer> for DirectionContainer {
- fn from(value: SplitContainer) -> Self {
- DirectionContainer::Split(value)
- }
-}
-
-impl TryFrom<Container> for DirectionContainer {
- type Error = &'static str;
-
- fn try_from(container: Container) -> Result<Self, Self::Error> {
- match container {
- Container::Workspace(c) => Ok(DirectionContainer::Workspace(c)),
- Container::Split(c) => Ok(DirectionContainer::Split(c)),
- _ => Err("Cannot convert type to a `DirectionContainer`."),
- }
- }
-}
-
-impl TryFrom<TilingContainer> for DirectionContainer {
- type Error = &'static str;
-
- fn try_from(container: TilingContainer) -> Result<Self, Self::Error> {
- match container {
- TilingContainer::Split(c) => Ok(DirectionContainer::Split(c)),
- TilingContainer::TilingWindow(_) => {
- Err("Cannot convert type to a `DirectionContainer`.")
- }
- }
- }
-}
-
impl PartialEq for DirectionContainer {
fn eq(&self, other: &Self) -> bool {
self.id() == other.id()