tenvy_derive 1.0.1

The derive macro for `tenvy`, a parser of environment variables
Documentation
mod attrs;
mod newtype;
mod opaque;
mod struct_named;
mod unit;

use syn::{
    Data, DeriveInput, Error, Fields, GenericParam, Generics, parse_macro_input, parse_quote,
};

/// Derive an implementation of [`Tenvy`] for your structure.
///
/// `#[derive(Tenvy)]` specially treats structures with named fields, unit structures, or newtypes.
/// Derivation for other types, including enumerations, delegates to an adapter via
/// [`#[tenvy(via)]`][via]. Some customization is available via [attributes].
///
/// [`Tenvy`]: ./trait.Tenvy.html
/// [attributes]: #attributes
///
/// # Structures with named fields
///
/// `#[derive(Tenvy)]` on structures with named fields parses each field by nesting using the
/// field's name. This name is automatically uppercased.
///
/// ```
/// # use tenvy_derive::Tenvy;
/// #[derive(Tenvy)]
/// struct Environment {
///     database_url: String,
///     workers: Option<u8>,
/// }
/// ```
///
/// generates
///
/// ```
/// # use tenvy::*;
/// # struct Environment {
/// #     database_url: String,
/// #     workers: Option<u8>,
/// # }
/// impl Tenvy for Environment {
///     fn from_env(env: &Env) -> Result<Self, Error> {
///         Ok(Self {
///             database_url: env.field("DATABASE_URL")?,
///             workers: env.field("WORKERS")?,
///         })
///     }
/// }
/// ```
///
/// # Tuple structures
///
/// `#[derive(Tenvy)]` without [`#[tenvy(via)]`][via] on tuple structures with exactly one field
/// delegates implementation to the inner type. With [`#[tenvy(via)]`][via], the adapter is
/// expected to produce `Self`, not the inner type.
///
/// ```
/// # use tenvy_derive::Tenvy;
/// #[derive(Tenvy)]
/// struct Seconds(u8);
/// ```
///
/// generates
///
/// ```
/// # use tenvy::*;
/// # struct Seconds(u8);
/// impl Tenvy for Seconds {
///     fn from_env(env: &Env) -> Result<Self, Error> {
///         u8::from_env(env).map(Self)
///     }
/// }
/// ```
///
/// If the tuple structure has no fields, the generated implementation always succeeds.
///
/// ```
/// # use tenvy_derive::Tenvy;
/// #[derive(Tenvy)]
/// struct NoSettings();
/// ```
///
/// generates
///
/// ```
/// # use tenvy::*;
/// # struct NoSettings();
/// impl Tenvy for NoSettings {
///     fn from_env(env: &Env) -> Result<Self, Error> {
///         Ok(Self())
///     }
/// }
/// ```
///
/// # Unit structures
///
/// `#[derive(Tenvy)]` on unit structures generates an implementation that always succeeds.
///
/// ```
/// # use tenvy_derive::Tenvy;
/// #[derive(Tenvy)]
/// struct NoSettings;
/// ```
///
/// generates
///
/// ```
/// # use tenvy::*;
/// # struct NoSettings;
/// impl Tenvy for NoSettings {
///     fn from_env(env: &Env) -> Result<Self, Error> {
///         Ok(Self)
///     }
/// }
/// ```
///
/// # Other types
///
/// Enumerations, unions, and tuple structures with more than one field require the
/// [`#[tenvy(via)]`][via] attribute. [`#[tenvy(default)]`][default] is also applicable.
///
/// ```
/// # use tenvy::*;
/// # use tenvy_derive::Tenvy;
/// use std::str::FromStr;
///
/// #[derive(Tenvy)]
/// #[tenvy(via = tenvy::FromStr)]
/// enum Color {
///     Orange,
///     Blue,
/// };
///
/// #[derive(Debug, thiserror::Error)]
/// #[error("expected `orange` and `blue`")]
/// struct InvalidColor;
///
/// impl FromStr for Color {
///     type Err = InvalidColor;
///
///     fn from_str(color: &str) -> Result<Self, Self::Err> {
///         match color {
///             "orange" => Ok(Self::Orange),
///             "blue" => Ok(Self::Blue),
///             _ => Err(InvalidColor),
///         }
///     }
/// }
/// ```
///
/// # Attributes
///
/// ## `#[tenvy(default)]` and `#[tenvy(default = <expr>)]`
/// [default]: #tenvydefault-and-tenvydefault--expr
///
/// If parsing the value fails with [`Error::Missing`], use the provided default value
/// (`#[tenvy(default = <expr>)]`) or [`Default::default`]`()` (`#[tenvy(default)]`).
///
/// Can be applied to structure fields, newtypes, unit structures, tuple structures with at least
/// one field, enumerations, and unions.
///
/// [`Error::Missing`]: ./enum.Error.html#variant.Missing
///
/// ```
/// # use tenvy_derive::Tenvy;
/// #[derive(Tenvy)]
/// #[tenvy(default = Self(2))]
/// struct Retries(u8);
/// ```
///
/// ```
/// # use tenvy_derive::Tenvy;
/// #[derive(Tenvy)]
/// struct Application {
///     #[tenvy(default = 5432)]
///     port: u16,
///     #[tenvy(default)]
///     use_https: bool,
/// }
/// ```
///
/// ## `#[tenvy(rename = "<name>")]`
/// [rename]: #tenvyrename--name
///
/// By default, the derive macro uses a field's uppercased name when parsing. This attribute
/// overrides the used name. Can be applied to fields only. Mutually exclusive with
/// [`#[tenvy(flatten)]`][flatten].
///
/// ```
/// # use tenvy_derive::Tenvy;
/// #[derive(Tenvy)]
/// struct Environment {
///     #[tenvy(rename = "TIMEOUT_MS")]
///     timeout: u16,
/// }
/// ```
///
/// ## `#[tenvy(flatten)]`
/// [flatten]: #tenvyflatten
///
/// By default, the derive macro parses fields in a nested context. With this attribute, the value
/// is parsed in the same context. Can be applied to fields only. Mutually exclusive with
/// [`#[tenvy(rename = "<name>")]`][rename].
///
/// ```
/// # use tenvy_derive::Tenvy;
/// #[derive(Tenvy)]
/// struct Environment {
///     database: Database,
/// }
///
/// #[derive(Tenvy)]
/// struct Database {
///     #[tenvy(flatten)] // Parsed from `DATABASE`
///     url: String,
///     table: String,
/// }
/// ```
///
/// ## `#[tenvy(via = <type>)]`
/// [via]: #tenvyvia--type
///
/// Delegate parsing to an adapter type. An adapter is a type which implements [`Tenvy`], but
/// parses a different type instead of itself. Notable adapters are:
///
/// - [`tenvy::From<T>`](./struct.From.html)
/// - [`tenvy::TryFrom<T>`](./struct.TryFrom.html)
/// - [`tenvy::FromStr`](./struct.FromStr.html)
///
/// Can be applied to structure fields, newtypes, unit structures, tuple structures with at least
/// one field, enumerations, and unions.
///
/// ```
/// # use tenvy_derive::Tenvy;
/// // Parse to `u8`, then use `Percent: TryFrom<u8>`
/// #[derive(Tenvy)]
/// #[tenvy(via = tenvy::TryFrom<u8>)]
/// struct Percent(u8);
/// # impl TryFrom<u8> for Percent {
/// #   type Error = std::convert::Infallible;
/// #   fn try_from(x: u8) -> Result<Self, Self::Error> { Ok(Self(x)) }
/// # }
/// ```
///
/// ```
/// # use tenvy_derive::Tenvy;
/// use std::time::Duration;
///
/// #[derive(Tenvy)]
/// struct Seconds(u64);
/// # impl From<Seconds> for Duration { fn from(_: Seconds) -> Self { Self::ZERO } }
///
/// #[derive(Tenvy)]
/// struct Environment {
///     // Parse to `Seconds`, then use `Duration: From<Seconds>`
///     #[tenvy(via = tenvy::From<Seconds>)]
///     timeout: Duration,
/// }
/// ```
#[proc_macro_derive(Tenvy, attributes(tenvy))]
pub fn my_macro(input: proc_macro::TokenStream) -> proc_macro::TokenStream {
    let input = parse_macro_input!(input as DeriveInput);

    let derived = match input.data {
        Data::Struct(data) => match data.fields {
            Fields::Named(fields) => {
                struct_named::derive(input.ident, input.generics, input.attrs, fields)
            }
            Fields::Unnamed(fields) if fields.unnamed.len() == 0 => {
                unit::derive(input.ident, input.generics, input.attrs, unit::Kind::Tuple)
            }
            Fields::Unnamed(mut fields) if fields.unnamed.len() == 1 => newtype::derive(
                input.ident,
                input.generics,
                input.attrs,
                fields.unnamed.pop().unwrap(),
            ),
            Fields::Unnamed(_) => opaque::derive(
                input.ident,
                input.generics,
                input.attrs,
                data.struct_token.span,
                opaque::Kind::Tuple,
            ),
            Fields::Unit => {
                unit::derive(input.ident, input.generics, input.attrs, unit::Kind::Unit)
            }
        },
        Data::Enum(data) => opaque::derive(
            input.ident,
            input.generics,
            input.attrs,
            data.enum_token.span,
            opaque::Kind::Enum,
        ),
        Data::Union(data) => opaque::derive(
            input.ident,
            input.generics,
            input.attrs,
            data.union_token.span,
            opaque::Kind::Union,
        ),
    };

    proc_macro::TokenStream::from(derived.unwrap_or_else(Error::into_compile_error))
}

fn add_bound(mut generics: Generics) -> Generics {
    for param in &mut generics.params {
        if let GenericParam::Type(type_param) = param {
            type_param.bounds.push(parse_quote!(::tenvy::Tenvy));
        }
    }

    generics
}