hao 0.0.19

Read, edit, create and write .net assemblies
Documentation
//! The table macros for this module:
//! - `well_known_namespaces!` generates the `WellKnown` enum (with each type's
//!   namespace and assembly) and, per sub-enum, the `from_type_name`/`name`/
//!   `TypeName` impls.
//! - `well_known_methods!` (with its `wk_sig_type!`/`wk_is_instance!`
//!   helpers) generates `WellKnownMethod` and the per-type method sub-enums,
//!   as static metadata.

/// Declares the well-known namespaces: one row per .NET namespace, naming the
/// assembly its types live in and the sub-enum (in `types.rs`) that lists them.
///
/// ```ignore
/// well_known_namespaces! {
///     // "<namespace>" in <WellKnownModule> [(<Type> in <WellKnownModule>, ..)] => Variant(SubEnum)
///     "System" in SystemRuntime (Console in SystemConsole) => System(SystemType),
///     "System.Reflection" in SystemRuntime => SystemReflection(SystemReflectionType),
/// }
/// ```
///
/// - `"<namespace>"` is the .NET namespace, e.g. `"System.Collections"`.
/// - `in <WellKnownModule>` is the .NET (Core) reference assembly the
///   namespace's types live in.
/// - `(<Type> in <WellKnownModule>, ..)` (optional) lists the namespace's types
///   that live in a different assembly, by sub-enum variant: `Console` is in
///   `System.Console`, not `System.Runtime` like the rest of `System`. Check
///   the reference pack (`packs/Microsoft.NETCore.App.Ref`) when adding types.
/// - `Variant(SubEnum)` becomes `WellKnown::Variant(SubEnum)`.
///
/// Generated: [`WellKnown`](crate::dotnet::entries::well_known::WellKnown) with
/// `from_full_name`, `full_name`, `namespace`, `type_name` and `module` (the
/// type's assembly: its own if listed, otherwise its namespace's), and
/// per sub-enum `from_type_name`, `name` and `TypeName`.
macro_rules! well_known_namespaces {
    ( $(
        $ns:literal in $module:ident $( ( $( $ty:ident in $ty_module:ident ),+ $(,)? ) )?
            => $variant:ident($sub:ident)
    ),+ $(,)? ) => {
        /// A well-known .NET type, grouped by namespace. `full_name`,
        /// `type_name` and the sub-enums' `name` strip the generic arity suffix
        /// (``Nullable`1`` -> `Nullable`); `from_full_name` expects it.
        #[derive(Debug, Copy, Clone, PartialEq)]
        #[cfg_attr(feature = "reflect", derive(facet::Facet), repr(C))]
        pub enum WellKnown {
            $(
                #[doc = concat!("A type in the `", $ns, "` namespace.")]
                $variant($sub),
            )+
        }

        impl WellKnown {
            /// The well-known type `namespace.name`, if hao knows it. A generic
            /// type's `name` must carry its arity suffix, as in metadata (``List`1``).
            pub fn from_full_name(namespace: &str, name: &str) -> Option<Self> {
                Some(match namespace {
                    $( $ns => Self::$variant($sub::from_type_name(name)?), )+
                    _ => return None,
                })
            }

            /// The `(namespace, name)` pair as it appears in metadata, with a
            /// generic type's arity suffix: `("System", "Nullable`1")`. This is
            /// what references and name comparisons use, and what
            /// [`from_full_name`](Self::from_full_name) parses.
            pub fn metadata_full_name(&self) -> (&'static str, &'static str) {
                match self {
                    $( Self::$variant(ty) => ($ns, ty.metadata_name()), )+
                }
            }

            /// The `(namespace, name)` pair for display, without the arity
            /// suffix: `("System", "Nullable")`. Use
            /// [`metadata_full_name`](Self::metadata_full_name) to refer to the type.
            pub fn full_name(&self) -> (&'static str, &'static str) {
                match self {
                    $( Self::$variant(ty) => ($ns, ty.name()), )+
                }
            }

            /// The namespace, e.g. `"System"`.
            pub fn namespace(&self) -> &'static str {
                self.full_name().0
            }

            /// The type name without arity, e.g. `"Nullable"`.
            pub fn type_name(&self) -> &'static str {
                self.full_name().1
            }

            /// The well-known (.NET reference) assembly this type lives in: its
            /// namespace's, unless the namespace table lists the type as living
            /// elsewhere (`Console` is in `System.Console`, not `System.Runtime`
            /// like the rest of `System`).
            pub fn module(&self) -> WellKnownModule {
                match self {
                    $(
                        Self::$variant(ty) => match ty {
                            $( $( $sub::$ty => WellKnownModule::$ty_module, )+ )?
                            #[allow(unreachable_patterns)]
                            _ => WellKnownModule::$module,
                        },
                    )+
                }
            }
        }

        $(
            impl $sub {
                /// Parses a metadata type name into this well-known type. A
                /// generic type needs its arity suffix (``List`1``).
                pub fn from_type_name(name: &str) -> Option<Self> {
                    name.parse().ok()
                }

                /// The type name without the generic arity suffix, for display.
                pub fn name(&self) -> &'static str {
                    strip_arity(self.into())
                }

                /// The type name as it appears in metadata, with a generic
                /// type's arity suffix (``List`1``).
                pub fn metadata_name(&self) -> &'static str {
                    self.into()
                }
            }

            impl TypeName for $sub {
                fn type_name(&self) -> (Cow<'_, str>, Cow<'_, str>) {
                    let (namespace, name) = WellKnown::$variant(*self).metadata_full_name();
                    (Cow::Borrowed(namespace), Cow::Borrowed(name))
                }
            }
        )+
    };
}

/// Expands a well-known assembly's public-key token keyword to its 8 bytes.
/// `Microsoft` is `b03f5f7f11d50a3a` (Microsoft's key), the token almost every
/// .NET (Core) `System.*` reference assembly carries; `Ecma` is
/// `b77a5c561934e089` (the ECMA key), .NET Framework's `mscorlib` and core
/// libraries; `NetStandard` is `cc7b13ffcd2ddd51`, `netstandard`'s; and
/// `CoreLib` is CoreCLR's `System.Private.CoreLib`.
macro_rules! wk_module_token {
    (Microsoft) => {
        [0xb0, 0x3f, 0x5f, 0x7f, 0x11, 0xd5, 0x0a, 0x3a]
    };
    (Ecma) => {
        [0xb7, 0x7a, 0x5c, 0x56, 0x19, 0x34, 0xe0, 0x89]
    };
    (NetStandard) => {
        [0xcc, 0x7b, 0x13, 0xff, 0xcd, 0x2d, 0xdd, 0x51]
    };
    (CoreLib) => {
        [0x7c, 0xec, 0x85, 0xd7, 0xbe, 0xa7, 0x79, 0x8e]
    };
}

/// Generates [`WellKnownModule`] (one variant per well-known assembly) and its
/// `assembly_name`/`public_key_token` impls from a declarative table. Each row
/// is `Variant => "Assembly.Name" : <TokenKeyword>` (see [`wk_module_token!`]).
macro_rules! well_known_modules {
    ( $( $variant:ident => $name:literal : $token:ident ),+ $(,)? ) => {
        /// A well-known .NET assembly a module references. Carries the stable
        /// assembly name and public-key token; the version is version-dependent
        /// and supplied separately (see [`AssemblyName`] impls, e.g.
        /// `(WellKnownModule, Version)`).
        #[allow(non_camel_case_types)]
        #[derive(Debug, Copy, Clone, PartialEq, Eq, Hash, EnumString, IntoStaticStr)]
        #[cfg_attr(feature = "reflect", derive(facet::Facet), repr(u8))]
        pub enum WellKnownModule {
            $(
                #[doc = concat!("`", $name, "`")]
                $variant,
            )+
        }

        impl WellKnownModule {
            /// The assembly's simple name, e.g. `"System.Runtime"`.
            pub fn assembly_name(&self) -> &'static str {
                match self {
                    $( Self::$variant => $name, )+
                }
            }

            /// The well-known assembly with simple name `name`, if it is one.
            pub fn from_assembly_name(name: &str) -> Option<Self> {
                match name {
                    $( $name => Some(Self::$variant), )+
                    _ => None,
                }
            }

            /// The assembly's 8-byte public-key token (stable across .NET versions).
            pub fn public_key_token(&self) -> [u8; 8] {
                match self {
                    $( Self::$variant => wk_module_token!($token), )+
                }
            }
        }
    };
}

/// Expands a type token to a [`WellKnownSigType`](crate::dotnet::entries::well_known::WellKnownSigType):
/// static metadata, a constant expression.
macro_rules! wk_sig_type {
    (void) => { WellKnownSigType::Void };
    (bool) => { WellKnownSigType::Bool };
    (char) => { WellKnownSigType::Char };
    (i32) => { WellKnownSigType::I32 };
    (i64) => { WellKnownSigType::I64 };
    (f64) => { WellKnownSigType::F64 };
    (nint) => { WellKnownSigType::NInt };
    (string) => { WellKnownSigType::String };
    (object) => { WellKnownSigType::Object };
    ({ $wk:expr }) => { WellKnownSigType::Class($wk) };
    // A value type, wrapped in parens: (valuetype { WellKnown::... })
    ((valuetype { $wk:expr })) => { WellKnownSigType::ValueType($wk) };
    // An array, in brackets: [object], [{ WellKnown::... }]
    ([$($inner:tt)+]) => { WellKnownSigType::Array(&wk_sig_type!($($inner)+)) };
}

macro_rules! wk_is_instance {
    (Static) => {
        false
    };
    (Instance) => {
        true
    };
}

/// Declares the well-known method vocabulary: a table of method groups, one per
/// declaring type, each listing methods with their .NET name and signature.
///
/// ```ignore
/// well_known_methods! {
///     // Group(SubEnum) = <declaring WellKnown type> => { .. }
///     Console(ConsoleMethod) = WellKnown::System(SystemType::Console) => {
///         // Variant = Static|Instance "<.NET name>" (<params>) -> <ret>;
///         WriteLineStr = Static "WriteLine" (string) -> void;
///         ReadLine     = Static "ReadLine"  ()       -> string;
///     }
///     Object(ObjectMethod) = WellKnown::System(SystemType::Object) => {
///         GetType = Instance "GetType" () -> { WellKnown::System(SystemType::Type) };
///     }
/// }
/// ```
///
/// A group:
///
/// - `Group(SubEnum)` becomes the variant `WellKnownMethod::Group(SubEnum)` and
///   the per-type enum `SubEnum` (`ConsoleMethod`), whose variants are the
///   group's methods. A bare `SubEnum` value converts into `WellKnownMethod`.
/// - `= <expr>` is the declaring type, a [`WellKnown`](crate::dotnet::entries::well_known::WellKnown) expression.
///   The assembly it lives in comes from the type
///   ([`WellKnown::module`](crate::dotnet::entries::well_known::WellKnown::module)).
///
/// A method: `Variant = Static|Instance "<.NET name>" (<param>, ..) -> <ret>;`,
/// where `<.NET name>` is the metadata name (`"get_Name"` for a property
/// getter, `".ctor"` for a constructor, which is `Instance`). Each parameter and
/// the return type is one token tree, expanded by `wk_sig_type!` into a
/// `WellKnownSigType`:
///
/// - primitives: `void`, `bool`, `char`, `i32`, `i64`, `f64`, `nint`
/// - `string`, `object`
/// - a class type: `{ WellKnown::... }`
/// - a value type: `(valuetype { WellKnown::... })`
/// - an array: `[<any of these>]`, e.g. `[object]` or `[{ WellKnown::... }]`
///
/// Generated: [`WellKnownMethod`](crate::dotnet::entries::well_known::WellKnownMethod) with `declaring`,
/// `method_name`, `is_instance`, `params`, `ret` and `param_count`;
/// each sub-enum with the same per-method helpers; and
/// `From<SubEnum> for WellKnownMethod`. All of it is static metadata: nothing
/// here touches a module. [`Module::import_well_known_method`](crate::dotnet::module::Module::import_well_known_method)
/// turns a method into references in a module.
macro_rules! well_known_methods {
    ( $(
        $group:ident($sub:ident) = $declaring:expr => {
            $( $variant:ident = $kind:ident $name:literal ( $($param:tt),* $(,)? ) -> $ret:tt ; )+
        }
    )+ ) => {
        /// A common BCL method, keyed by declaring type. Each variant wraps a
        /// per-type method sub-enum, e.g.
        /// `WellKnownMethod::Console(ConsoleMethod::WriteLineStr)`.
        #[derive(Debug, Copy, Clone, PartialEq, Eq)]
        #[cfg_attr(feature = "reflect", derive(facet::Facet), repr(C))]
        pub enum WellKnownMethod {
            $(
                #[doc = concat!("A method of `", stringify!($group), "`.")]
                $group($sub),
            )+
        }

        impl WellKnownMethod {
            /// The declaring type, as a [`WellKnown`] (which is itself a `TypeName`).
            pub fn declaring(self) -> WellKnown {
                match self { $( Self::$group(_) => $declaring, )+ }
            }


            /// The .NET method name, e.g. `"WriteLine"`, `".ctor"`, or a property
            /// getter like `"get_NewLine"`.
            pub fn method_name(self) -> &'static str {
                match self { $( Self::$group(m) => m.method_name(), )+ }
            }

            /// Whether the method is an instance method (vs. static).
            /// Constructors are instance methods.
            pub fn is_instance(self) -> bool {
                match self { $( Self::$group(m) => m.is_instance(), )+ }
            }

            /// The parameter types (`this` not included).
            pub fn params(self) -> &'static [WellKnownSigType] {
                match self { $( Self::$group(m) => m.params(), )+ }
            }

            /// The return type.
            pub fn ret(self) -> WellKnownSigType {
                match self { $( Self::$group(m) => m.ret(), )+ }
            }

            /// The number of declared parameters (`this` not counted).
            pub fn param_count(self) -> usize {
                self.params().len()
            }
        }

        // A bare method sub-enum coerces to its `WellKnownMethod`, so
        // `import_well_known_method(MathMethod::MaxI32)` works without spelling
        // out the group (mirroring how a `SystemType` is a `TypeName`).
        $(
            impl From<$sub> for WellKnownMethod {
                fn from(method: $sub) -> Self {
                    WellKnownMethod::$group(method)
                }
            }
        )+

        $(
            #[doc = concat!(
                "Well-known methods of `", stringify!($group), "`, for [`WellKnownMethod::",
                stringify!($group), "`]. Each variant's doc is its signature."
            )]
            #[derive(Debug, Copy, Clone, PartialEq, Eq)]
            #[cfg_attr(feature = "reflect", derive(facet::Facet), repr(u8))]
            pub enum $sub {
                $(
                    #[doc = concat!(
                        stringify!($kind), " `", $name, "(", stringify!($($param),*), ") -> ",
                        stringify!($ret), "`"
                    )]
                    $variant,
                )+
            }

            impl $sub {
                fn method_name(self) -> &'static str {
                    match self { $( Self::$variant => $name, )+ }
                }
                fn is_instance(self) -> bool {
                    match self { $( Self::$variant => wk_is_instance!($kind), )+ }
                }
                fn params(self) -> &'static [WellKnownSigType] {
                    match self { $( Self::$variant => &[ $( wk_sig_type!($param) ),* ], )+ }
                }
                fn ret(self) -> WellKnownSigType {
                    match self { $( Self::$variant => wk_sig_type!($ret), )+ }
                }
            }
        )+
    };
}