hao 0.0.19

Read, edit, create and write .net assemblies
Documentation
use super::{
    well_known::{SystemType, TypeName, WellKnown},
    AssemblyRef, CustomAttribute, Entry, EntryName, Method, ModuleDef, TypeDef,
};
use crate::{
    dotnet::signature::{MemberRefSig, TypeSig},
    sync::Shared,
    Module,
};

/// A type token: a type defined here, one referenced from elsewhere, or a
/// constructed one. Used for base types, interfaces and attribute/IL operands.
#[derive(Debug, Clone, PartialEq, Eq)]
#[cfg_attr(feature = "reflect", derive(facet::Facet))]
#[cfg_attr(feature = "reflect", repr(C))]
pub enum TypeDefOrRef {
    /// A type defined in this module.
    TypeDef(Entry<TypeDef>),
    /// A type from another assembly or module.
    TypeRef(Entry<TypeRef>),
    /// A constructed type (generic instance, array, pointer).
    TypeSpec(Entry<TypeSpec>),
}

impl TypeDefOrRef {
    /// `Namespace.Name` (or the signature for type specs).
    pub fn full_name(&self) -> String {
        match self {
            Self::TypeDef(t) => t.get().full_name(),
            Self::TypeRef(t) => t.get().full_name(),
            Self::TypeSpec(t) => format!("{:?}", t.get().signature),
        }
    }

    /// The type's name without namespace (the signature for type specs).
    pub fn name(&self) -> String {
        match self {
            Self::TypeDef(t) => t.get().name.clone(),
            Self::TypeRef(t) => t.get().name.clone(),
            Self::TypeSpec(_) => self.full_name(),
        }
    }

    /// The type's namespace; empty for type specs and nested types.
    pub fn namespace(&self) -> String {
        match self {
            Self::TypeDef(t) => t.get().namespace.clone(),
            Self::TypeRef(t) => t.get().namespace.clone(),
            Self::TypeSpec(_) => String::new(),
        }
    }

    /// Whether this is the type `ty`, by namespace and name. Always `false` for type specs.
    pub fn full_name_is(&self, ty: impl TypeName) -> bool {
        match self {
            Self::TypeDef(t) => t.get().full_name_is(ty),
            Self::TypeRef(t) => t.get().full_name_is(ty),
            Self::TypeSpec(_) => false,
        }
    }

    /// Whether this is `System.<system_type>`, e.g. `SystemType::Object`.
    pub fn is_system_type(&self, system_type: SystemType) -> bool {
        self.full_name_is(WellKnown::System(system_type))
    }

    /// The type definition, looking through resolved assembly references.
    pub fn resolve(&self) -> Option<Entry<TypeDef>> {
        match self {
            Self::TypeDef(t) => Some(t.clone()),
            Self::TypeRef(t) => t.get().resolve(),
            Self::TypeSpec(_) => None,
        }
    }
}

/// Where a [`TypeRef`] is defined.
#[derive(Debug, Clone, PartialEq, Eq)]
#[cfg_attr(feature = "reflect", derive(facet::Facet))]
#[cfg_attr(feature = "reflect", repr(C))]
pub enum ResolutionScope {
    /// In this module.
    Module(Entry<ModuleDef>),
    /// In another module of this assembly.
    ModuleRef(Entry<ModuleRef>),
    /// In another assembly.
    AssemblyRef(Entry<AssemblyRef>),
    /// Nested inside another referenced type.
    TypeRef(Entry<TypeRef>),
}

/// A reference to a type defined in another assembly or module (II.22.38).
#[derive(Debug, Clone, Default)]
#[cfg_attr(feature = "reflect", derive(facet::Facet))]
pub struct TypeRef {
    /// `None` means the type is found through the `ExportedType` table.
    pub scope: Option<ResolutionScope>,
    /// Type name, e.g. ``List`1``.
    pub name: String,
    /// Namespace; empty for nested types.
    pub namespace: String,
    /// Attributes applied to this reference.
    pub custom_attributes: Vec<CustomAttribute>,
}

impl TypeRef {
    /// A reference to `namespace.name` in `scope`.
    pub fn new(
        scope: ResolutionScope,
        namespace: impl Into<String>,
        name: impl Into<String>,
    ) -> Self {
        Self {
            scope: Some(scope),
            name: name.into(),
            namespace: namespace.into(),
            custom_attributes: Vec::new(),
        }
    }

    /// `Namespace.Name`, or `Outer/Inner` for nested types.
    pub fn full_name(&self) -> String {
        match &self.scope {
            Some(ResolutionScope::TypeRef(parent)) => {
                format!("{}/{}", parent.get().full_name(), self.name)
            }
            _ if self.namespace.is_empty() => self.name.clone(),
            _ => format!("{}.{}", self.namespace, self.name),
        }
    }

    /// Whether this references `ty`, by namespace and name.
    pub fn full_name_is(&self, ty: impl TypeName) -> bool {
        let (namespace, name) = ty.type_name();
        self.namespace.as_str() == &*namespace && self.name.as_str() == &*name
    }

    /// Whether the type comes from the core library (see [`AssemblyRef::is_corlib`]).
    pub fn is_corlib(&self) -> bool {
        matches!(&self.scope, Some(ResolutionScope::AssemblyRef(r)) if r.get().is_corlib())
    }

    /// The matching [`WellKnown`] type, if this is a core library type hao knows about.
    pub fn well_known(&self) -> Option<WellKnown> {
        if self.is_corlib() {
            WellKnown::from_full_name(&self.namespace, &self.name)
        } else {
            None
        }
    }

    /// Finds the matching [`TypeDef`] in the referenced module, if it was loaded.
    pub fn resolve(&self) -> Option<Entry<TypeDef>> {
        let module: Shared<Module> = match &self.scope {
            Some(ResolutionScope::AssemblyRef(asm)) => asm.get().resolved.clone()?,
            Some(ResolutionScope::TypeRef(parent)) => {
                let parent = parent.get().resolve()?;
                let parent = parent.get();
                return parent
                    .nested_types
                    .iter()
                    .find(|t| t.get().name == self.name)
                    .cloned();
            }
            _ => return None,
        };
        module.resolve_type(&self.namespace, &self.name)
    }
}

impl EntryName for TypeRef {
    fn entry_name(&self) -> String {
        self.full_name()
    }
}

/// A constructed type used as a token, e.g. `List<int>` or `int[]` (II.22.39).
#[derive(Debug, Clone, Default)]
#[cfg_attr(feature = "reflect", derive(facet::Facet))]
pub struct TypeSpec {
    /// The type's signature.
    pub signature: TypeSig,
    /// Attributes applied to the type spec.
    pub custom_attributes: Vec<CustomAttribute>,
}

impl EntryName for TypeSpec {
    fn entry_name(&self) -> String {
        format!("{:?}", self.signature)
    }
}

/// The type (or module, or method) a [`MemberRef`] belongs to.
#[derive(Debug, Clone, PartialEq, Eq)]
#[cfg_attr(feature = "reflect", derive(facet::Facet))]
#[cfg_attr(feature = "reflect", repr(C))]
pub enum MemberRefParent {
    /// A type defined in this module.
    TypeDef(Entry<TypeDef>),
    /// A type from another assembly or module.
    TypeRef(Entry<TypeRef>),
    /// A global member of another module.
    ModuleRef(Entry<ModuleRef>),
    /// A vararg call site of a method defined here.
    Method(Entry<Method>),
    /// A constructed type, e.g. a member of `List<int>`.
    TypeSpec(Entry<TypeSpec>),
}

impl MemberRefParent {
    /// The parent as a type token; `None` for module and method parents.
    pub fn as_type(&self) -> Option<TypeDefOrRef> {
        match self {
            Self::TypeDef(t) => Some(TypeDefOrRef::TypeDef(t.clone())),
            Self::TypeRef(t) => Some(TypeDefOrRef::TypeRef(t.clone())),
            Self::TypeSpec(t) => Some(TypeDefOrRef::TypeSpec(t.clone())),
            _ => None,
        }
    }
}

impl Default for MemberRefParent {
    fn default() -> Self {
        Self::TypeRef(Entry::new(TypeRef::default()))
    }
}

/// A reference to a field or method, usually in another assembly.
#[derive(Debug, Clone, Default)]
#[cfg_attr(feature = "reflect", derive(facet::Facet))]
pub struct MemberRef {
    /// The type declaring the member.
    pub parent: MemberRefParent,
    /// Member name, e.g. `WriteLine` or `.ctor`.
    pub name: String,
    /// Method or field signature, which picks the overload.
    pub signature: MemberRefSig,
    /// Attributes applied to this reference.
    pub custom_attributes: Vec<CustomAttribute>,
}

impl EntryName for MemberRef {
    fn entry_name(&self) -> String {
        let parent = self
            .parent
            .as_type()
            .map(|t| t.full_name())
            .unwrap_or_default();
        format!("{}::{}", parent, self.name)
    }
}

/// A method token: one defined here or one referenced from elsewhere.
#[derive(Debug, Clone, PartialEq, Eq)]
#[cfg_attr(feature = "reflect", derive(facet::Facet))]
#[cfg_attr(feature = "reflect", repr(C))]
pub enum MethodDefOrRef {
    /// A method defined in this module.
    Method(Entry<Method>),
    /// A method of another type, by reference.
    MemberRef(Entry<MemberRef>),
}

impl MethodDefOrRef {
    /// The method's name.
    pub fn name(&self) -> String {
        match self {
            Self::Method(m) => m.get().name.clone(),
            Self::MemberRef(m) => m.get().name.clone(),
        }
    }
}

impl Default for MethodDefOrRef {
    fn default() -> Self {
        Self::MemberRef(Entry::new(MemberRef::default()))
    }
}

/// An instantiation of a generic method.
#[derive(Debug, Clone, Default)]
#[cfg_attr(feature = "reflect", derive(facet::Facet))]
pub struct MethodSpec {
    /// The generic method being instantiated.
    pub method: MethodDefOrRef,
    /// The type arguments, in order.
    pub instantiation: Vec<TypeSig>,
    /// Attributes applied to the method spec.
    pub custom_attributes: Vec<CustomAttribute>,
}

impl EntryName for MethodSpec {
    fn entry_name(&self) -> String {
        self.method.name()
    }
}

/// A reference to another module by name (II.22.31): a native library used by
/// P/Invoke, or another module of this assembly.
#[derive(Debug, Clone, Default)]
#[cfg_attr(feature = "reflect", derive(facet::Facet))]
pub struct ModuleRef {
    /// File name, e.g. `kernel32.dll` or `user32`.
    pub name: String,
    /// Attributes applied to this reference.
    pub custom_attributes: Vec<CustomAttribute>,
}

impl EntryName for ModuleRef {
    fn entry_name(&self) -> String {
        self.name.clone()
    }
}