1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98 99 100 101 102 103 104 105 106 107 108 109 110 111 112 113 114 115 116 117 118 119 120 121 122 123 124 125 126 127 128 129 130 131 132 133 134 135 136 137 138 139 140 141 142 143 144 145 146 147 148 149 150 151 152 153 154 155 156 157 158 159 160 161 162 163 164 165 166 167 168 169 170 171 172 173 174 175 176 177 178 179 180 181 182 183 184 185 186 187 188 189 190 191 192 193 194 195 196 197 198 199 200 201 202 203 204 205 206 207 208 209 210 211 212 213 214 215 216 217 218 219 220 221 222 223 224 225 226 227 228 229 230 231 232 233 234 235 236 237 238 239 240 241 242 243 244 245 246 247 248 249 250 251 252 253 254 255 256
//! Lets you derive `Display` & `Debug` traits on structs with
//! `0..=1` fields & enums where each variant has `0..=1` fields - see input/output examples below.
//!
//! [](https://github.com/Alorel/delegate-display-rs/actions/workflows/ci.yml?query=branch%3Amaster)
//! [](https://crates.io/crates/delegate-display)
//! [](https://docs.rs/delegate-display)
//! [](https://libraries.io/cargo/delegate-display)
//!
//! # Examples
//!
//! <details><summary>Newtype structs</summary>
//!
#![cfg_attr(doctest, doc = " ````no_test")]
//! ```
//! // Input
//! #[derive(delegate_display::DelegateDisplay)]
//! struct Foo(SomeType);
//!
//! // Output
//! impl fmt::Display for Foo {
//! #[inline]
//! fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
//! fmt::Display::fmt(&self.0, f)
//! }
//! }
//! ````
//!
//! </details>
//!
//! <details><summary>Structs with one field</summary>
//!
#![cfg_attr(doctest, doc = " ````no_test")]
//! ```
//! // Input
//! #[derive(delegate_display::DelegateDebug)]
//! struct Foo { some_field: SomeType }
//!
//! // Output
//! impl fmt::Debug for Foo {
//! #[inline]
//! fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
//! fmt::Debug::fmt(&self.some_field, f)
//! }
//! }
//! ````
//!
//! </details>
//!
//! <details><summary>Enums</summary>
//!
#![cfg_attr(doctest, doc = " ````no_test")]
//! ```
//! // Input
//! enum MyEnum {
//! Foo,
//! Bar(SomeType),
//! Qux { baz: SomeType }
//! }
//!
//! // Output
//! fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
//! match self {
//! Self::Foo => f.write_str("Foo"),
//! Self::Bar(inner) => DebugOrDisplay::fmt(inner, f),
//! Self::Qux { baz } => DebugOrDisplay::fmt(baz, f),
//! }
//! }
//! ````
//!
//! </details>
//!
//! <details><summary>Empty structs & enums</summary>
//!
#![cfg_attr(doctest, doc = " ````no_test")]
//! ```
//! // Input
//! struct Foo;
//! struct Bar{}
//! struct Qux();
//! enum Baz {}
//!
//! // Output
//! fn fmt(&self, _: &mut fmt::Formatter<'_>) -> fmt::Result {
//! Ok(())
//! }
//! ````
//!
//! </details>
//!
//! <details><summary>Custom generic bounds</summary>
//!
//! The attribute names are `ddebug` for `Debug`, `ddisplay` for `Display` and `dboth` for a common config for
//! both. `ddebug` and `ddisplay` take precendence over `dboth`.
//!
//! - `base_bounds` will add whatever trait is being derived as a generic bound to each of the struct/enum's generic params
//! - `bounds(...)` will let you specify specific bounds
//!
#![cfg_attr(doctest, doc = " ````no_test")]
//! ```
//! // Input
//! #[derive(DelegateDisplay, DelegateDebug)]
//! #[dboth(base_bounds)]
//! #[ddisplay(bounds(F: Display, B: Clone + Display))]
//! enum Foo<F, B> {
//! Foo(F),
//! Bar(B),
//! }
//!
//! // Output
//! impl<F: Display, B: Clone + Display> Display for Foo<F, B> { /* ... */}
//! impl<F: Debug, B: Debug> Debug for Foo<F, B> { /* ... */ }
//! ````
//!
//! </details>
//!
//! <details><summary>Typed delegations</summary>
//!
//! Can be useful for further prettifying the output.
//!
//! ```
//! # use delegate_display::DelegateDebug;
//! /// Some type that `Deref`s to the type we want to use in our formatting, in this case, `str`.
//! #[derive(Debug)]
//! struct Wrapper(&'static str);
//! # impl std::ops::Deref for Wrapper {
//! # type Target = str;
//! # fn deref(&self) -> &Self::Target {
//! # self.0
//! # }
//! # }
//!
//! #[derive(DelegateDebug)]
//! #[ddebug(delegate_to(str))] // ignore `Wrapper` and debug the `str` it `Deref`s instead
//! struct Typed(Wrapper);
//!
//! #[derive(DelegateDebug)] // Included for comparison
//! struct Base(Wrapper);
//!
//! assert_eq!(format!("{:?}", Typed(Wrapper("foo"))), "\"foo\"");
//! assert_eq!(format!("{:?}", Base(Wrapper("bar"))), "Wrapper(\"bar\")");
//! ```
//!
//! </details>
//!
//! <details><summary>Invalid inputs</summary>
//!
//! ```compile_fail
//! # use {std::sync::Arc, delegate_display::DelegateDisplay};
//! #[derive(DelegateDisplay, Debug)]
//! #[dboth(delegate_to(String))] // `delegate_to` is not supported on enums
//! enum SomeEnum {
//! Foo(Arc<String>)
//! }
//! ```
//!
//! ```compile_fail
//! #[derive(delegate_display::DelegateDisplay)]
//! #[ddisplay(base_bounds, bounds(T: Display))] // `base_bounds` and `bounds` are mutually exclusive
//! struct Generic<T>(T);
//! ```
//!
//! ```compile_fail
//! #[derive(delegate_display::DelegateDisplay)]
//! #[ddisplay(base_bounds)]
//! #[ddisplay(base_bounds)] // `dbodh` and `ddisplay` can be mixed, but the same option can't be used twice
//! struct Foo<T>(T);
//! ```
//!
//! ```compile_fail
//! #[derive(delegate_display::DelegateDebug)]
//! struct TooManyFields1 {
//! foo: u8,
//! bar: u8, // Only one field permitted
//! }
//! ```
//!
//! ```compile_fail
//! #[derive(delegate_display::DelegateDebug)]
//! struct TooManyFields2(u8, u8); // too many fields
//! ```
//!
//! ```compile_fail
//! #[derive(delegate_display::DelegateDebug)]
//! enum SomeEnum {
//! A, // this is ok
//! B(u8), // this is ok
//! C { foo: u8 }, // this is ok
//! D(u8, u8), // Only one field permitted
//! E { foo: u8, bar: u8 } // Only one field permitted
//! }
//! ```
//!
//! ```compile_fail
//! #[derive(delegate_display::DelegateDebug)]
//! union Foo { bar: u8 } // Unions are not supported
//! ```
//!
//! </details>
#![deny(clippy::correctness, clippy::suspicious)]
#![warn(clippy::complexity, clippy::perf, clippy::style, clippy::pedantic)]
#![allow(
clippy::wildcard_imports,
clippy::default_trait_access,
clippy::single_match_else
)]
#![warn(missing_docs)]
use proc_macro::TokenStream as BaseTokenStream;
mod parse;
mod tokenise;
/// Derive the [Debug](core::fmt::Debug) trait
///
/// See [crate-level documentation](crate) for information on what's acceptable and what's not.
#[proc_macro_derive(DelegateDebug, attributes(ddebug, dboth))]
#[inline]
pub fn derive_debug(tokens: BaseTokenStream) -> BaseTokenStream {
ParsedData::process("Debug", tokens)
}
/// Derive the [Display](core::fmt::Display) trait
///
/// See [crate-level documentation](crate) for information on what's acceptable and what's not.
#[proc_macro_derive(DelegateDisplay, attributes(ddisplay, dboth))]
#[inline]
pub fn derive_display(tokens: BaseTokenStream) -> BaseTokenStream {
ParsedData::process("Display", tokens)
}
struct ParsedData {
ident: syn::Ident,
generics: syn::Generics,
first_field: FirstField,
options: ContainerOptions,
}
enum FieldLike {
Indexed(syn::Type),
Ident(syn::Ident, syn::Type),
}
type EnumData = (syn::Ident, Option<Box<FieldLike>>);
enum FirstField {
Struct(Option<Box<FieldLike>>),
Enum(Vec<EnumData>),
}
#[derive(macroific::attr_parse::AttributeOptions, Default)]
struct ContainerOptions {
pub bounds: syn::punctuated::Punctuated<syn::WherePredicate, syn::Token![,]>,
pub base_bounds: bool,
pub delegate_to: Option<syn::Type>,
}