hao 0.0.19

Read, edit, create and write .net assemblies
Documentation
//! Common .NET types, assemblies and methods, named by enum instead of string.
//!
//! [`WellKnown`] (one variant per namespace, wrapping that namespace's
//! sub-enum such as [`SystemType`]) names types; [`WellKnownModule`] names
//! assemblies; [`WellKnownMethod`] names methods along with their signatures.
//! Anything taking a [`TypeName`] accepts the type enums as well as strings.
//!
//! ```
//! use hao::prelude::*;
//! use hao::prelude::well_known::{ConsoleMethod, SystemType};
//!
//! let mut module = Module::new("Demo", ModuleKind::Dll, TargetRuntime::NetCore(9));
//! let object = module.corlib_type(SystemType::Object)?;
//! assert!(object.full_name_is(SystemType::Object));
//!
//! // Adds `System.Console` and a reference to `Console.WriteLine(string)`.
//! let _write_line = module.import_well_known_method(ConsoleMethod::WriteLineStr)?;
//! assert!(module.find_assembly_ref("System.Console").is_some());
//! # Ok::<(), hao::error::HaoError>(())
//! ```

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 {
        /// No flags.
        const DEFAULT = 0;
        /// Match member names case-insensitively.
        const IGNORE_CASE = 1;
        /// Only members declared on the type itself, not inherited ones.
        const DECLARED_ONLY = 2;
        /// Include instance members.
        const INSTANCE = 4;
        /// Include static members.
        const STATIC = 8;
        /// Include public members.
        const PUBLIC = 16;
        /// Include non-public (private, internal, protected) members.
        const NON_PUBLIC = 32;
        /// Include public and protected static members of base types.
        const FLATTEN_HIERARCHY = 64;
        /// `InvokeMember`: invoke a method.
        const INVOKE_METHOD = 0x100;
        /// `InvokeMember`: call a constructor.
        const CREATE_INSTANCE = 0x200;
        /// `InvokeMember`: read a field.
        const GET_FIELD = 0x400;
        /// `InvokeMember`: write a field.
        const SET_FIELD = 0x800;
        /// `InvokeMember`: read a property.
        const GET_PROPERTY = 0x1000;
        /// `InvokeMember`: write a property.
        const SET_PROPERTY = 0x2000;
        /// COM: call a `PROPPUT` member.
        const PUT_DISP_PROPERTY = 0x4000;
        /// COM: call a `PROPPUTREF` member.
        const PUT_REF_DISP_PROPERTY = 0x8000;
        /// Argument types must match parameter types exactly, without conversions.
        const EXACT_BINDING = 0x1_0000;
        /// Not implemented by the runtime.
        const SUPPRESS_CHANGE_TYPE = 0x2_0000;
        /// Match methods whose parameter count fits once optional parameters are filled with defaults.
        const OPTIONAL_PARAM_BINDING = 0x4_0000;
        /// COM interop: ignore the member's return value.
        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.metadata_full_name();
        (Cow::Borrowed(namespace), Cow::Borrowed(name))
    }
}

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

    #[test]
    fn types_know_their_assembly() {
        // Their namespace's assembly...
        assert_eq!(
            WellKnown::System(SystemType::Object).module(),
            WellKnownModule::SystemRuntime
        );
        // ...unless the table lists them as living elsewhere.
        assert_eq!(
            WellKnown::System(SystemType::Console).module(),
            WellKnownModule::SystemConsole
        );
        assert_eq!(
            WellKnown::SystemCollections(SystemCollectionsType::ArrayList).module(),
            WellKnownModule::SystemRuntime
        );
    }

    #[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));
            // The metadata name round-trips.
            assert_eq!(wk.metadata_full_name(), (namespace, name));
        }
    }

    #[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())
        );
        // References use the metadata name, arity included; `name()` strips it.
        assert_eq!(
            SystemCollectionsGenericType::HashSet_1.type_name(),
            ("System.Collections.Generic".into(), "HashSet`1".into())
        );
        assert_eq!(SystemCollectionsGenericType::HashSet_1.name(), "HashSet");
        // A free-form string splits on the last dot.
        assert_eq!(
            "System.Text.StringBuilder".type_name(),
            ("System.Text".into(), "StringBuilder".into())
        );
    }
}