hao 0.0.18

Read, edit, create and write .net assemblies
Documentation
use std::borrow::Cow;

use bitflags::bitflags;

#[macro_use]
mod macros;

mod method;
pub use method::*;

mod module;
pub use module::{AssemblyName, WellKnownModule};

mod namespaces;
pub use namespaces::WellKnown;

mod types;
pub use types::*;

bitflags! {
    /// The values of `System.Reflection.BindingFlags`, for passing to
    /// reflection methods such as `Type.GetMethod(string, BindingFlags)`
    /// (emit with `ldc.i4` via [`bits`](Self::bits)).
    ///
    /// The *type reference* for signatures is separate:
    /// [`SystemReflectionType::BindingFlags`].
    #[derive(Debug, Clone, Copy, PartialEq, Eq)]
    pub struct BindingFlags: i32 {
        const DEFAULT = 0;
        const IGNORE_CASE = 1;
        const DECLARED_ONLY = 2;
        const INSTANCE = 4;
        const STATIC = 8;
        const PUBLIC = 16;
        const NON_PUBLIC = 32;
        const FLATTEN_HIERARCHY = 64;
        const INVOKE_METHOD = 0x100;
        const CREATE_INSTANCE = 0x200;
        const GET_FIELD = 0x400;
        const SET_FIELD = 0x800;
        const GET_PROPERTY = 0x1000;
        const SET_PROPERTY = 0x2000;
        const PUT_DISP_PROPERTY = 0x4000;
        const PUT_REF_DISP_PROPERTY = 0x8000;
        const EXACT_BINDING = 0x1_0000;
        const SUPPRESS_CHANGE_TYPE = 0x2_0000;
        const OPTIONAL_PARAM_BINDING = 0x4_0000;
        const IGNORE_RETURN = 0x100_0000;
    }
}

/// A type named either by a full-name string (`"System.Text.StringBuilder"`) or
/// by a compile-checked [`WellKnown`] value or one of its namespace sub-enums
/// ([`SystemType`], [`SystemRuntimeInteropServicesType`], ...).
///
/// This is what the by-name importers on [`Module`](crate::Module) accept —
/// [`import_type`](crate::Module::import_type),
/// [`import_type_from`](crate::Module::import_type_from),
/// [`corlib_type`](crate::Module::corlib_type),
/// [`import_corlib_method`](crate::Module::import_corlib_method) and friends — so
/// a magic string and a checked `SystemType::String` are interchangeable.
///
/// Implemented for a dotted `&str`/`String` (split on the last `.`), an explicit
/// `(namespace, name)` tuple, and the well-known enums.
///
/// ```
/// # use hao::dotnet::entries::well_known::{TypeName, SystemType};
/// assert_eq!(SystemType::String.type_name(), ("System".into(), "String".into()));
/// assert_eq!("System.Text.StringBuilder".type_name(), ("System.Text".into(), "StringBuilder".into()));
/// assert_eq!(("System", "Object").type_name(), ("System".into(), "Object".into()));
/// ```
pub trait TypeName {
    /// The `(namespace, type name)` pair. The well-known enum implementations
    /// strip any generic arity suffix (`` HashSet`1 `` → `HashSet`); the `&str`
    /// and tuple implementations pass the name through verbatim.
    fn type_name(&self) -> (Cow<'_, str>, Cow<'_, str>);
}

impl TypeName for &str {
    fn type_name(&self) -> (Cow<'_, str>, Cow<'_, str>) {
        let (namespace, name) = self.rsplit_once('.').unwrap_or(("", self));
        (Cow::Borrowed(namespace), Cow::Borrowed(name))
    }
}

impl TypeName for String {
    fn type_name(&self) -> (Cow<'_, str>, Cow<'_, str>) {
        let (namespace, name) = self.rsplit_once('.').unwrap_or(("", self.as_str()));
        (Cow::Borrowed(namespace), Cow::Borrowed(name))
    }
}

/// An explicit `(namespace, name)` pair, e.g. `("System", "Object")`.
impl TypeName for (&str, &str) {
    fn type_name(&self) -> (Cow<'_, str>, Cow<'_, str>) {
        (Cow::Borrowed(self.0), Cow::Borrowed(self.1))
    }
}

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

#[cfg(test)]
mod tests {
    use super::*;

    #[test]
    fn well_known_round_trips() {
        // Including the new namespaces and additions to existing sub-enums.
        for (namespace, name) in [
            ("System", "Console"),
            ("System", "ArgumentNullException"),
            ("System.Text", "StringBuilder"),
            (
                "System.Runtime.InteropServices",
                "UnmanagedCallersOnlyAttribute",
            ),
            ("System.Reflection", "BindingFlags"),
            ("System.Diagnostics", "Stopwatch"),
            ("System.IO", "Path"),
            ("System.Globalization", "CultureInfo"),
            ("System.Collections.Generic", "HashSet`1"),
            ("System", "AppDomain"),
            (
                "System.Runtime.CompilerServices",
                "CallConvSuppressGCTransition",
            ),
            ("System.Runtime.CompilerServices", "CallConvCdecl"),
        ] {
            let wk = WellKnown::from_full_name(namespace, name)
                .unwrap_or_else(|| panic!("{namespace}.{name} should be well known"));
            let stripped = name.split('`').next().unwrap();
            assert_eq!(wk.full_name(), (namespace, stripped));
        }
    }

    #[test]
    fn type_name_impls() {
        assert_eq!(
            SystemType::String.type_name(),
            ("System".into(), "String".into())
        );
        assert_eq!(
            SystemIoType::Path.type_name(),
            ("System.IO".into(), "Path".into())
        );
        assert_eq!(
            SystemRuntimeInteropServicesType::GCHandle.type_name(),
            ("System.Runtime.InteropServices".into(), "GCHandle".into())
        );
        // Generic arity is stripped by `name()`.
        assert_eq!(
            SystemCollectionsGenericType::HashSet_1.type_name(),
            ("System.Collections.Generic".into(), "HashSet".into())
        );
        // A free-form string splits on the last dot.
        assert_eq!(
            "System.Text.StringBuilder".type_name(),
            ("System.Text".into(), "StringBuilder".into())
        );
    }
}