#![doc(html_favicon_url = "https://ruma.dev/favicon.ico")]
#![doc(html_logo_url = "https://ruma.dev/images/logo.png")]
//! Procedural macros used by ruma crates.
//!
//! See the documentation for the individual macros for usage details.

#![cfg_attr(feature = "__internal_macro_expand", feature(proc_macro_expand))]
#![warn(missing_docs)]
#![allow(unreachable_pub)]
// https://github.com/rust-lang/rust-clippy/issues/9029
#![allow(clippy::derive_partial_eq_without_eq)]

use proc_macro::TokenStream;
use quote::quote;
use ruma_identifiers_validation::{
    base64_public_key, event_id, mxc_uri, room_alias_id, room_id, room_version_id, server_name,
    server_signing_key_version, user_id,
};
use syn::{DeriveInput, ItemEnum, ItemStruct, parse_macro_input};

mod api;
mod events;
mod identifiers;
mod serde;
mod util;

use self::{
    api::{
        request::{expand_derive_request, expand_request},
        response::{expand_derive_response, expand_response},
    },
    events::{
        event::expand_event,
        event_content::expand_event_content,
        event_enum::{EventEnumInput, expand_event_enum},
        event_enum_from_event::expand_event_enum_from_event,
    },
    identifiers::{constructor::IdentifierConstructor, id_dst::expand_id_dst},
    serde::{
        as_str_as_ref_str::expand_as_str_as_ref_str, debug_as_ref_str::expand_debug_as_ref_str,
        deserialize_from_cow_str::expand_deserialize_from_cow_str,
        display_as_ref_str::expand_display_as_ref_str, enum_as_ref_str::expand_enum_as_ref_str,
        enum_from_string::expand_enum_from_string, eq_as_ref_str::expand_eq_as_ref_str,
        ord_as_ref_str::expand_ord_as_ref_str, serialize_as_ref_str::expand_serialize_as_ref_str,
    },
};

/// Generates enums to represent the various Matrix event types.
///
/// # Generated types
///
/// This generates the following enums for each kind:
///
/// * `Any{Kind}EventContent`
/// * `Any{Kind}Event`
/// * `{Kind}EventType`
///
/// It also generates the following enums:
///
/// * `AnySync{Kind}Event` for the kinds that have a different format in the `/sync` API:
///   `EphemeralRoom`, `MessageLike` and `State`.
/// * `TimelineEventType` which includes the variants from `MessageLikeEventType` and
///   `StateEventType`
/// * And extra enums for the `State` kind:
///     * `AnyInitialStateEvent` for state events sent during room creation.
///     * `AnyStrippedStateEvent` for state events that are in room state previews when receiving
///       invites.
///     * `AnyStateEventContentChange` a helper type to be able to access the `content` and
///       `prev_content` of a state event.
///
/// This macro also implements the following traits for these enums, where it makes sense:
///
/// * `Serialize`
/// * `Deserialize` or `EventContentFromType`
/// * `{Kind}EventContent`
/// * Conversion from event type to enum variant, like:
///     * `From<{event_content_type}> for Any{Kind}EventContent`
///     * `From<{event_type}> for `Any{Kind}Event`
///
/// By default, the enums generated by this macro get a `#[non_exhaustive]` attribute. This
/// behavior can be controlled by setting the `ruma_unstable_exhaustive_types` compile-time
/// `cfg` setting as `--cfg=ruma_unstable_exhaustive_types` using `RUSTFLAGS` or
/// `.cargo/config.toml` (under `[build]` -> `rustflags = ["..."]`). When that setting is
/// activated, the attribute is not applied so the types are exhaustive.
///
/// # Syntax
///
/// The basic syntax for using this macro is:
///
/// ```ignore
/// event_enum! {
///     enum Kind {
///         "m.first_event_type" => path::to::first_event,
///         "m.second_event_type" => path::to::second_event,
///     }
///
///     // …
/// }
/// ```
///
/// ## Enum Kind
///
/// The kind must be one of these values, which matches the [`EventContent`] macro:
///
/// * `MessageLike` - A message-like event sent in the timeline
/// * `State` - A state event sent in the timeline
/// * `GlobalAccountData` - Global config event
/// * `RoomAccountData` - Per-room config event
/// * `ToDevice` - Event sent directly to a device
/// * `EphemeralRoom` - Event that is not persistent in the room
///
/// ## Event types
///
/// The first part of the event type declaration, before the arrow, is the string matching the
/// `type` of the event, as defined in the Matrix specification. It must match the `type` attribute
/// of the [`EventContent`] definition. Account data event types can end with `.*` in case the end
/// of the event type changes dynamically, see the docs of [`EventContent`] for more details.
///
/// This type is used by the enums to know which variant to deserialize according to the `type` that
/// can be found in the JSON data.
///
/// This macro supports deserialization from a second event type string with the `alias` attribute,
/// which can be useful to support deserializing an event using both its stable and unstable
/// prefixes, like this:
///
/// ```ignore
/// event_enum! {
///     enum MessageLike {
///         #[ruma_enum(alias = "dev.ruma.unstable.foo")]
///         "m.foo" => path::to::foo,
///     }
/// }
/// ```
///
/// By default, this macro tries to generate the event types names from the event type string. It
/// only recognizes strings that start with the `m.` prefix, which matches stable event types from
/// the Matrix specification. From there it generates a base name by capitalizing every word,
/// assuming that words are separated by `.` or `_`. For example, `m.foo.bar` will have the base
/// name `FooBar`.
///
/// If the base name is incorrect, or the event type string uses an unstable prefix, the base name
/// can be provided with the `ident` attribute, for example:
///
/// ```ignore
/// event_enum! {
///     enum MessageLike {
///         #[ruma_enum(ident = FooBar)]
///         "dev.ruma.foo_bar" => path::to::foo_bar,
///     }
/// }
/// ```
///
/// The second part of the event type declaration, after the arrow, is the path of the module where
/// the event types can be found.
///
/// This macro will then assume that all the necessary types are available in the given module to
/// generate the code for the enums, as if the [`EventContent`] macro was used on a type named
/// `{base_name}EventContent`.
///
/// You can use `cargo doc` to find out more details, its `--document-private-items` flag also lets
/// you generate documentation for binaries or private parts of a library.
///
/// # Example
///
/// ```ignore
/// # // HACK: This is "ignore" because of cyclical dependency drama.
/// use ruma_macros::event_enum;
///
/// event_enum! {
///     enum ToDevice {
///         "m.any.event" => super::any_event,
///         #[ruma_enum(alias = "dev.unstable.prefix.other.event")]
///         "m.other.event" => super::other_event,
///         #[cfg(feature = "unstable-mscXXXX")]
///         #[ruma_enum(ident = NewEventEventContent)]
///         "org.matrix.mscXXXX.new_event" => super::new_event,
///     }
///
///     enum State {
///         "m.more.events" => super::more_events,
///         "m.different.event" => super::different_event,
///     }
/// }
/// ```
#[proc_macro]
pub fn event_enum(input: TokenStream) -> TokenStream {
    let input = syn::parse_macro_input!(input as EventEnumInput);
    expand_event_enum(input).into()
}

/// Generates traits implementations and types for an event content.
///
/// # Trait implementations
///
/// This macro implements the following traits for the type on which it is applied:
///
/// * `{kind}EventContent`
/// * `StaticEventContent`
/// * `StaticStateEventContent`, for the `State` kind.
///
/// # Generated types
///
/// It also generates type aliases and modified clones depending on the kind of event. To generate
/// the base name of those types, the macro simply removes `Content` from the name of the type,
/// which means that to apply this macro to a type, its name must always end with `Content`. And for
/// compatibility with the [`event_enum!`] macro, the name should actually end with `EventContent`.
///
/// Some kinds can generate a modified clone of the event content type. For instance, for an event
/// content type named `FooEventContent`:
///
/// * `RedactedFooEventContent`: the redacted form of the event content, for the `MessageLike` and
///   `State` kinds. It also generates the `RedactContent` implementation which applies the
///   redaction algorithm according to the Matrix specification.
///
///   The generated type implements `Redacted{Kind}EventContent`, `StaticEventContent`, `Serialize`
///   and `Deserialize`.
///
///   The generation only works if the type is a struct with named fields. To keep a field after
///   redaction, the `#[ruma_event(skip_redaction)]` attribute can be applied to that field.
///
///   To skip the generation of this type and trait to implement a custom redaction, or because it
///   is not a struct with named fields, the `#[ruma_event(custom_redacted)]` attribute can be used
///   on the container. The `RedactedFooEventContent` type must still exist and implement the same
///   traits, even if it is only a type alias, and the `RedactContent` trait must still be
///   implemented for those kinds.
/// * `PossiblyRedactedFooEventContent`: the form of the event content that is used when we don't
///   know whether a `State` event is redacted or not. It means that on this type any field that is
///   redacted must be optional, or it must have the `#[serde(default)]` attribute for
///   deserialization.
///
///   The generated type implements `PossiblyRedactedStateEventContent`, `StaticEventContent`,
///   `Serialize` and `Deserialize`.
///
///   The generation uses the rules as the redacted type, using the `#[ruma_event(skip_redaction)]`
///   attribute.
///
///   To skip the generation of this type to use a custom type, the
///   `#[ruma_event(custom_possibly_redacted)]` attribute can be used on the container. The
///   `PossiblyRedactedFooEventContent` type must still exist for the `State` kind and implement the
///   same traits, even if it is only a type alias.
///
/// Event content types of the `MessageLike` kind that use the `Relation` type also need a clone of
/// the event content without the `relates_to` field for use within relations, where nested
/// relations are not meant to be serialized by homeservers. This macro can generate a
/// `FooEventContentWithoutRelation` type if the `#[ruma_event(without_relation)]` attribute is
/// applied on the container. It also generates `From<FooEventContent> for
/// FooEventContentWithoutRelation` and `FooEventContentWithoutRelation::with_relation()`.
///
/// By default, the generated types get a `#[non_exhaustive]` attribute. This behavior can be
/// controlled by setting the `ruma_unstable_exhaustive_types` compile-time `cfg` setting as
/// `--cfg=ruma_unstable_exhaustive_types` using `RUSTFLAGS` or `.cargo/config.toml` (under
/// `[build]` -> `rustflags = ["..."]`). When that setting is activated, the attribute is not
/// applied so the types are exhaustive.
///
/// # Type aliases
///
/// All kinds generate at least one type alias for the full event format. For the same example type
/// named `FooEventContent`, the first type alias generated is `type FooEvent =
/// {Kind}Event<FooEventContent>`.
///
/// The only exception for this is if the type has the `GlobalAccountData + RoomAccountData` kinds,
/// it generates two type aliases with prefixes:
///
/// * `type GlobalFooEvent = GlobalAccountDataEvent<FooEventContent>`
/// * `type RoomFooEvent = RoomAccountDataEvent<FooEventContent>`
///
/// Some kinds generate more type aliases:
///
/// * `type SyncFooEvent = Sync{Kind}Event<FooEventContent>`: an event received via the `/sync` API,
///   for the `MessageLike`, `State` and `EphemeralRoom` kinds
/// * `type OriginalFooEvent = Original{Kind}Event<FooEventContent>`, a non-redacted event, for the
///   `MessageLike` and `State` kinds
/// * `type OriginalSyncFooEvent = OriginalSync{Kind}Event<FooEventContent>`, a non-redacted event
///   received via the `/sync` API, for the `MessageLike` and `State` kinds
/// * `type RedactedFooEvent = Redacted{Kind}Event<RedactedFooEventContent>`, a redacted event, for
///   the `MessageLike` and `State` kinds
/// * `type OriginalSyncFooEvent = RedactedSync{Kind}Event<RedactedFooEventContent>`, a redacted
///   event received via the `/sync` API, for the `MessageLike` and `State` kinds
/// * `type InitialFooEvent = InitialStateEvent<FooEventContent>`, an event sent during room
///   creation, for the `State` kind
/// * `type StrippedFooEvent = StrippedStateEvent<PossiblyRedactedFooEventContent>`, an event that
///   is in a room state preview when receiving an invite, for the `State` kind
///
/// You can use `cargo doc` to find out more details, its `--document-private-items` flag also lets
/// you generate documentation for binaries or private parts of a library.
///
/// # Syntax
///
/// The basic syntax for using this macro is:
///
/// ```ignore
/// #[derive(Clone, Debug, Deserialize, Serialize, EventContent)]
/// #[ruma_event(type = "m.foo_bar", kind = MessageLike)]
/// pub struct FooBarEventContent {
///     data: String,
/// }
/// ```
///
/// ## Container attributes
///
/// The following settings can be used on the container, with the `#[ruma_event(_)]` attribute.
/// `type` and `kind` are always required.
///
/// ### `type = "m.event_type"`
///
/// The `type` of the event according to the Matrix specification, always required. This is usually
/// a string with an `m.` prefix.
///
/// Types with an account data kind can also use the `.*` suffix, if the end of the type changes
/// dynamically. It must be associated with a field that has the `#[ruma_event(type_fragment)]`
/// attribute that will store the end of the event type. Those types have the
/// `StaticEventContent::IsPrefix` type set to `True`.
///
/// ### `kind = Kind`
///
/// The kind of the event, always required. It must be one of these values, which matches the
/// [`event_enum!`] macro:
///
/// * `MessageLike` - A message-like (i.e. non-state) event sent in the timeline
/// * `State` - A state event sent in the timeline
/// * `GlobalAccountData` - Global config event
/// * `RoomAccountData` - Per-room config event
/// * `ToDevice` - Event sent directly to a device
/// * `EphemeralRoom` - Event that is not persistent in the room
///
/// It is possible to implement both account data kinds for the same type by using the syntax `kind
/// = GlobalAccountData + RoomAccountData`.
///
/// ### `alias = "m.event_type"`
///
/// An alternate `type` for the event, used during deserialization. It is usually used for
/// deserializing an event type using both its stable and unstable prefix.
///
/// ### `state_key = StringType`
///
/// The type of the state key of the event, required and only supported if the kind is `State`. This
/// type should be a string type like `String`, `EmptyStateKey` or an identifier type generated with
/// the `IdDst` macro.
///
/// ### `unsigned_type = UnsignedType`
///
/// A custom type to use for the `Unsigned` type of the `StaticStateEventContent` implementation if
/// the kind is `State`. Only necessary if the `StateUnsigned` type is not appropriate for this
/// type.
///
/// ### `custom_redacted`
///
/// If the kind requires a `Redacted{}EventContent` type and a `RedactContent` implementation and it
/// is not possible to generate them with the macro, setting this attribute prevents the macro from
/// trying to generate them. The type and trait must be implemented manually.
///
/// ### `custom_possibly_redacted`
///
/// If the kind requires a `PossiblyRedacted{}EventContent` type and it is not possible to generate
/// it with the macro, setting this attribute prevents the macro from trying to generate it. The
/// type must be implemented manually.
///
/// ### `without_relation`
///
/// If this is set, the macro will try to generate an `{}EventContentWithoutRelation` which is a
/// clone of the current type with the `relates_to` field removed.
///
/// ## Field attributes
///
/// The following settings can be used on the fields of a struct, with the `#[ruma_event(_)]`
/// attribute.
///
/// ### `skip_redaction`
///
/// If a `Redacted{}EventContent` type is generated by the macro, this field will be kept after
/// redaction.
///
/// ### `type_fragment`
///
/// If the event content's kind is account data and its type ends with the `.*`, this field is
/// required and will store the end of the event's type.
///
/// # Example
///
/// An example can be found in the docs at the root of `ruma_events`.
#[proc_macro_derive(EventContent, attributes(ruma_event))]
pub fn derive_event_content(input: TokenStream) -> TokenStream {
    let input = parse_macro_input!(input as DeriveInput);
    expand_event_content(input).unwrap_or_else(syn::Error::into_compile_error).into()
}

/// Generates trait implementations for Matrix event types.
///
/// This macro parses the name of the type on which it is applied to decide what to do, which means
/// that it only works on a fixed list of types. It also requires the type to be a struct with named
/// fields, with one of these fields named `content`.
///
/// This macro implements at least `Deserialize` for the type on which it is applied.
///
/// If the type is an `OriginalSync` or `RedactedSync` event, this implements conversion
/// helpers to the non-sync version of the event type. For example if the event type is
/// `OriginalSyncMessageLikeEvent`, this will generate `From<OriginalMessageLikeEvent> for
/// OriginalSyncMessageLikeEvent` and `OriginalSyncMessageLikeEvent::into_full_event()`.
///
/// If the type is a non-stripped timeline event, i.e. a struct with an `event_id` field, this
/// implements `PartialEq`, `Eq`, `PartialOrd` and `Ord` by comparing the `event_id` fields.
///
/// ## Field attributes
///
/// The following settings can be used on the fields of the struct, with the `#[ruma_event(_)]`
/// attribute.
///
/// ### `default`
///
/// If the field is missing, its `Default` implementation is used.
///
/// ### `default_on_error`
///
/// If an error occurs during deserialization of the value of this field, its `Default`
/// implementation is used. The error is logged with the [tracing] crate at the debug level, which
/// means that it must be a dependency of the crate where the macro is used.
///
/// ### `rename = "serialized_name"`
///
/// Use a different name when the field is serialized. The name is used both during serialization
/// and deserialization.
///
/// ### `alias = "alt_name"`
///
/// Allow a different name for the field during deserialization. This can be used several times for
/// different aliases.
///
/// You can use `cargo doc` to find out more details, its `--document-private-items` flag also lets
/// you generate documentation for binaries or private parts of a library.
///
/// [tracing]: https://crates.io/crates/tracing
#[proc_macro_derive(Event, attributes(ruma_event))]
pub fn derive_event(input: TokenStream) -> TokenStream {
    let input = parse_macro_input!(input as DeriveInput);
    expand_event(input).unwrap_or_else(syn::Error::into_compile_error).into()
}

/// Generates `From` implementations for an enum for all its variants.
#[proc_macro_derive(EventEnumFromEvent)]
pub fn derive_from_event_to_enum(input: TokenStream) -> TokenStream {
    let input = parse_macro_input!(input as DeriveInput);
    expand_event_enum_from_event(input).unwrap_or_else(syn::Error::into_compile_error).into()
}

/// Generate methods and trait impl's for DST identifier type.
///
/// This macro generates an `Owned*` wrapper type for the identifier type. This wrapper type is
/// variable, by default it'll use [`Box`], but it can be changed at compile time
/// by setting `--cfg=ruma_identifiers_storage=...` using `RUSTFLAGS` or `.cargo/config.toml` (under
/// `[build]` -> `rustflags = ["..."]`). Currently the only supported value is `Arc`, that uses
/// [`Arc`](std::sync::Arc) as a wrapper type.
///
/// This macro implements:
///
/// * Conversions to and from string types, `AsRef<[u8]>` and `AsRef<str>`, as well as `as_str()`
///   and `as_bytes()` methods. The borrowed type can be converted from a borrowed string without
///   allocation.
/// * Conversions to and from borrowed and owned type.
/// * `Deref`, `AsRef` and `Borrow` to the borrowed type for the owned type.
/// * `PartialEq` implementations for testing equality with string types and owned and borrowed
///   types.
///
/// # Attributes
///
/// * `#[ruma_api(validate = PATH)]`: the path to a function to validate the string during parsing
///   and deserialization. By default, the types implement `From` string types, when this is set
///   they implement `TryFrom`.
///
/// # Examples
///
/// ```ignore
/// # // HACK: This is "ignore" because of cyclical dependency drama.
/// use ruma_macros::IdDst;
///
/// #[derive(PartialEq, Eq, PartialOrd, Ord, Hash, IdDst)]
/// #[ruma_id(validate = ruma_identifiers_validation::user_id::validate)]
/// pub struct UserId(str);
/// ```
#[proc_macro_derive(IdDst, attributes(ruma_id))]
pub fn derive_id_dst(input: TokenStream) -> TokenStream {
    let input = parse_macro_input!(input as ItemStruct);
    expand_id_dst(input).unwrap_or_else(syn::Error::into_compile_error).into()
}

/// Compile-time checked `EventId` construction.
#[proc_macro]
pub fn event_id(input: TokenStream) -> TokenStream {
    let id_ctor = parse_macro_input!(input as IdentifierConstructor);
    id_ctor.validate_and_expand_str_conversion("&EventId", event_id::validate).into()
}

/// Compile-time checked `RoomAliasId` construction.
#[proc_macro]
pub fn room_alias_id(input: TokenStream) -> TokenStream {
    let id_ctor = parse_macro_input!(input as IdentifierConstructor);
    id_ctor.validate_and_expand_str_conversion("&RoomAliasId", room_alias_id::validate).into()
}

/// Compile-time checked `RoomId` construction.
#[proc_macro]
pub fn room_id(input: TokenStream) -> TokenStream {
    let id_ctor = parse_macro_input!(input as IdentifierConstructor);
    id_ctor.validate_and_expand_str_conversion("&RoomId", room_id::validate).into()
}

/// Compile-time checked `RoomVersionId` construction.
#[proc_macro]
pub fn room_version_id(input: TokenStream) -> TokenStream {
    let id_ctor = parse_macro_input!(input as IdentifierConstructor);
    id_ctor.validate_and_expand_str_conversion("RoomVersionId", room_version_id::validate).into()
}

/// Compile-time checked `ServerSigningKeyVersion` construction.
#[proc_macro]
pub fn server_signing_key_version(input: TokenStream) -> TokenStream {
    let id_ctor = parse_macro_input!(input as IdentifierConstructor);
    id_ctor
        .validate_and_expand_str_conversion(
            "&ServerSigningKeyVersion",
            server_signing_key_version::validate,
        )
        .into()
}

/// Compile-time checked `ServerName` construction.
#[proc_macro]
pub fn server_name(input: TokenStream) -> TokenStream {
    let id_ctor = parse_macro_input!(input as IdentifierConstructor);
    id_ctor.validate_and_expand_str_conversion("&ServerName", server_name::validate).into()
}

/// Compile-time checked `MxcUri` construction.
#[proc_macro]
pub fn mxc_uri(input: TokenStream) -> TokenStream {
    let id_ctor = parse_macro_input!(input as IdentifierConstructor);
    id_ctor.validate_and_expand_str_conversion("&MxcUri", mxc_uri::validate).into()
}

/// Compile-time checked `UserId` construction.
///
/// The user ID is validated using the same rules as `UserId::validate_strict()`.
#[proc_macro]
pub fn user_id(input: TokenStream) -> TokenStream {
    let id_ctor = parse_macro_input!(input as IdentifierConstructor);
    id_ctor.validate_and_expand_str_conversion("&UserId", user_id::validate).into()
}

/// Compile-time checked `Base64PublicKey` construction.
#[proc_macro]
pub fn base64_public_key(input: TokenStream) -> TokenStream {
    let id_ctor = parse_macro_input!(input as IdentifierConstructor);
    id_ctor
        .validate_and_expand_str_conversion("&Base64PublicKey", base64_public_key::validate)
        .into()
}

/// Derive the `AsRef<str>` trait for an enum.
///
/// The enum can contain unit variants, or tuple or struct variants containing a single field
/// which is a newtype struct around a type implementing `Deref` with a `Target` of `str`.
#[doc = include_str!(concat!(env!("CARGO_MANIFEST_DIR"), "/src/doc/ruma_enum_attributes.md"))]
///
/// ## Example
///
/// ```
/// # use ruma_macros::AsRefStr;
/// #[derive(AsRefStr)]
/// #[ruma_enum(rename_all = "lowercase")]
/// pub enum MyEnum {
///     Unit,
///     #[ruma_enum(rename = "unstable_other_unit")]
///     OtherUnit,
///     Struct {
///         inner: PrivOwnedStr,
///     },
///     Tuple(PrivOwnedStr),
/// }
///
/// pub struct PrivOwnedStr(Box<str>);
/// ```
#[proc_macro_derive(AsRefStr, attributes(ruma_enum))]
pub fn derive_enum_as_ref_str(input: TokenStream) -> TokenStream {
    let input = parse_macro_input!(input as ItemEnum);
    expand_enum_as_ref_str(&input).unwrap_or_else(syn::Error::into_compile_error).into()
}

/// Derive the `From<T: AsRef<str> + Into<Box<str>>>` trait for an enum.
///
/// The enum can contain any number of unit variants, and must contain a single tuple or struct
/// variant containing a single field which is a newtype struct around a `Box<str>`. This tuple or
/// struct variant will be used as a fallback to catch any string that doesn't match any of the unit
/// variants.
///
/// The string to convert from must match exactly the expected string representation of a unit
/// variants to be converted to it. If there is a difference of case, it will match the fallback
/// variant instead.
#[doc = include_str!(concat!(env!("CARGO_MANIFEST_DIR"), "/src/doc/ruma_enum_attributes.md"))]
/// * `#[ruma_enum(alias = "value")]` - Allow this variant to be converted from a string that is not
///   its main string representation, which is `value`. This attribute can be used several times to
///   match more strings.
///
/// _Note that for this macro, there is no difference between `rename` and `alias`. It only matters
/// when used with [`AsRefStr`]._
///
/// ## Example
///
/// ```
/// # use ruma_macros::FromString;
/// #[derive(FromString)]
/// #[ruma_enum(rename_all = "lowercase")]
/// pub enum MyEnum {
///     Unit,
///     #[ruma_enum(rename = "stable_other_unit", alias = "unstable_other_unit")]
///     OtherUnit,
///     #[doc(hidden)]
///     _Custom(PrivOwnedStr),
/// }
///
/// pub struct PrivOwnedStr(Box<str>);
/// ```
#[proc_macro_derive(FromString, attributes(ruma_enum))]
pub fn derive_enum_from_string(input: TokenStream) -> TokenStream {
    let input = parse_macro_input!(input as ItemEnum);
    expand_enum_from_string(&input).unwrap_or_else(syn::Error::into_compile_error).into()
}

// FIXME: The following macros aren't actually interested in type details beyond name (and possibly
//        generics in the future). They probably shouldn't use `DeriveInput`.

/// Derive the `as_str()` method using the `AsRef<str>` implementation of the type.
#[proc_macro_derive(AsStrAsRefStr)]
pub fn derive_as_str_as_ref_str(input: TokenStream) -> TokenStream {
    let input = parse_macro_input!(input as DeriveInput);
    expand_as_str_as_ref_str(&input.ident).unwrap_or_else(syn::Error::into_compile_error).into()
}

/// Derive the `fmt::Display` trait using the `AsRef<str>` implementation of the type.
#[proc_macro_derive(DisplayAsRefStr)]
pub fn derive_display_as_ref_str(input: TokenStream) -> TokenStream {
    let input = parse_macro_input!(input as DeriveInput);
    expand_display_as_ref_str(&input.ident).unwrap_or_else(syn::Error::into_compile_error).into()
}

/// Derive the `fmt::Debug` trait using the `AsRef<str>` implementation of the type.
#[proc_macro_derive(DebugAsRefStr)]
pub fn derive_debug_as_ref_str(input: TokenStream) -> TokenStream {
    let input = parse_macro_input!(input as DeriveInput);
    expand_debug_as_ref_str(&input.ident).unwrap_or_else(syn::Error::into_compile_error).into()
}

/// Derive the `Serialize` trait using the `AsRef<str>` implementation of the type.
#[proc_macro_derive(SerializeAsRefStr)]
pub fn derive_serialize_as_ref_str(input: TokenStream) -> TokenStream {
    let input = parse_macro_input!(input as DeriveInput);
    expand_serialize_as_ref_str(&input.ident).unwrap_or_else(syn::Error::into_compile_error).into()
}

/// Derive the `Deserialize` trait using the `From<Cow<str>>` implementation of the type.
#[proc_macro_derive(DeserializeFromCowStr)]
pub fn derive_deserialize_from_cow_str(input: TokenStream) -> TokenStream {
    let input = parse_macro_input!(input as DeriveInput);
    expand_deserialize_from_cow_str(&input.ident)
        .unwrap_or_else(syn::Error::into_compile_error)
        .into()
}

/// Derive the `Ord` and `PartialOrd` traits using the `AsRef<str>` implementation of the type.
#[proc_macro_derive(OrdAsRefStr)]
pub fn derive_ord_as_ref_str(input: TokenStream) -> TokenStream {
    let input = parse_macro_input!(input as DeriveInput);
    expand_ord_as_ref_str(&input.ident).unwrap_or_else(syn::Error::into_compile_error).into()
}

/// Derive the `PartialEq` and `Eq` traits using the `AsRef<str>` implementation of the type.
#[proc_macro_derive(EqAsRefStr)]
pub fn derive_eq_as_ref_str(input: TokenStream) -> TokenStream {
    let input = parse_macro_input!(input as DeriveInput);
    expand_eq_as_ref_str(&input.ident).unwrap_or_else(syn::Error::into_compile_error).into()
}

/// Shorthand for the derives [`AsRefStr`], [`FromString`], [`DisplayAsRefStr`], [`DebugAsRefStr`],
/// [`SerializeAsRefStr`], [`DeserializeFromCowStr`], [`EqAsRefStr`] and [`OrdAsRefStr`].
///
/// The enum can contain any number of unit variants, and must contain a single tuple or struct
/// variant containing a single field which is a newtype struct around a `Box<str>`. This tuple or
/// struct variant will be used as a fallback to catch any string that doesn't match any of the unit
/// variants.
///
/// This will generate the following implementations:
///
/// * `AsRef<str>` to convert variants to their string representation, and the following
///   implementations based on it:
///   * `fn as_str(&self) -> &str`
///   * `fmt::Display`
///   * `fmt::Debug`
///   * `Serialize`
///   * `Ord` and `PartialOrd`
///   * `Eq` and `PartialEq`
/// * `From<T: AsRef<str> + Into<Box<str>>>` to convert a string to variants, and a `Deserialize`
///   implementation based on it. The string to convert from must match exactly the expected string
///   representation of a unit variants to be converted to it. If there is a difference of case, it
///   will match the fallback variant instead.
#[doc = include_str!(concat!(env!("CARGO_MANIFEST_DIR"), "/src/doc/ruma_enum_attributes.md"))]
/// * `#[ruma_enum(alias = "value")]` - Allow this variant to be converted from a string that is not
///   its main string representation, which is `value`. This attribute can be used several times to
///   match more strings.
///
/// ## Example
///
/// ```ignore
/// # // HACK: This is "ignore" because of cyclical dependency drama.
/// #[derive(StringEnum)]
/// #[ruma_enum(rename_all = "lowercase")]
/// pub enum MyEnum {
///     Unit,
///     #[ruma_enum(rename = "stable_other_unit", alias = "unstable_other_unit")]
///     OtherUnit,
///     #[doc(hidden)]
///     _Custom(PrivOwnedStr),
/// }
///
/// pub struct PrivOwnedStr(Box<str>);
/// ```
#[proc_macro_derive(StringEnum, attributes(ruma_enum))]
pub fn derive_string_enum(input: TokenStream) -> TokenStream {
    fn expand_all(input: ItemEnum) -> syn::Result<proc_macro2::TokenStream> {
        let as_ref_str_impl = expand_enum_as_ref_str(&input)?;
        let from_string_impl = expand_enum_from_string(&input)?;
        let as_str_impl = expand_as_str_as_ref_str(&input.ident)?;
        let display_impl = expand_display_as_ref_str(&input.ident)?;
        let debug_impl = expand_debug_as_ref_str(&input.ident)?;
        let serialize_impl = expand_serialize_as_ref_str(&input.ident)?;
        let deserialize_impl = expand_deserialize_from_cow_str(&input.ident)?;
        let eq_and_partial_eq_impl = expand_eq_as_ref_str(&input.ident)?;
        let ord_and_partial_ord_impl = expand_ord_as_ref_str(&input.ident)?;

        Ok(quote! {
            #as_ref_str_impl
            #from_string_impl
            #as_str_impl
            #display_impl
            #debug_impl
            #serialize_impl
            #deserialize_impl
            #eq_and_partial_eq_impl
            #ord_and_partial_ord_impl
        })
    }

    let input = parse_macro_input!(input as ItemEnum);
    expand_all(input).unwrap_or_else(syn::Error::into_compile_error).into()
}

/// A derive macro that generates no code, but registers the serde attribute so both `#[serde(...)]`
/// and `#[cfg_attr(..., serde(...))]` are accepted on the type, its fields and (in case the input
/// is an enum) variants fields.
#[doc(hidden)]
#[proc_macro_derive(_FakeDeriveSerde, attributes(serde))]
pub fn fake_derive_serde(_input: TokenStream) -> TokenStream {
    TokenStream::new()
}

/// > ⚠ If this is the only documentation you see, please navigate to the docs for
/// > `ruma_common::api::request`, where actual documentation can be found.
#[proc_macro_attribute]
pub fn request(attrs: TokenStream, item: TokenStream) -> TokenStream {
    let mut request_attrs = api::request::RequestAttrs::default();
    let attrs_parser = syn::meta::parser(|meta| request_attrs.try_merge(meta));
    parse_macro_input!(attrs with attrs_parser);

    let item = parse_macro_input!(item);

    expand_request(request_attrs, item).into()
}

/// > ⚠ If this is the only documentation you see, please navigate to the docs for
/// > `ruma_common::api::response`, where actual documentation can be found.
#[proc_macro_attribute]
pub fn response(attrs: TokenStream, item: TokenStream) -> TokenStream {
    let mut response_attrs = api::response::ResponseAttrs::default();
    let attrs_parser = syn::meta::parser(|meta| response_attrs.try_merge(meta));
    parse_macro_input!(attrs with attrs_parser);

    let item = parse_macro_input!(item);

    expand_response(response_attrs, item).into()
}

/// Internal helper that the request macro delegates most of its work to.
#[proc_macro_derive(Request, attributes(ruma_api))]
pub fn derive_request(input: TokenStream) -> TokenStream {
    let input = parse_macro_input!(input);
    expand_derive_request(input).unwrap_or_else(syn::Error::into_compile_error).into()
}

/// Internal helper that the response macro delegates most of its work to.
#[proc_macro_derive(Response, attributes(ruma_api))]
pub fn derive_response(input: TokenStream) -> TokenStream {
    let input = parse_macro_input!(input);
    expand_derive_response(input).unwrap_or_else(syn::Error::into_compile_error).into()
}

/// A derive macro that generates no code, but registers the ruma_api attribute so both
/// `#[ruma_api(...)]` and `#[cfg_attr(..., ruma_api(...))]` are accepted on the type, its fields
/// and (in case the input is an enum) variants fields.
#[doc(hidden)]
#[proc_macro_derive(_FakeDeriveRumaApi, attributes(ruma_api))]
pub fn fake_derive_ruma_api(_input: TokenStream) -> TokenStream {
    TokenStream::new()
}
