Skip to main content

IntrospectCustomType

Derive Macro IntrospectCustomType 

Source
#[derive(IntrospectCustomType)]
{
    // Attributes available to this derive:
    #[zlink]
}
Expand description

Derives Type for structs and enums, generating named custom type definitions.

Requires the introspection feature to be enabled.

This macro generates implementations of the CustomType trait, which provides named custom type definitions suitable for IDL generation. It also generates a Type implementation and therefore is mutually exclusive to zlink::introspect::Type derive macro.

§Structs

For structs, this macro generates a custom::Type::Object containing the struct name and all fields with their names and types.

§Enums

For enums, this macro only supports unit variants and generates a custom::Type::Enum containing the enum name and all variant names.

§Supported Attributes

The following attributes can be used to customize the behavior of this derive macro:

  • #[zlink(crate = "path")] - Specifies the crate path to use for zlink types. Defaults to ::zlink.

§Examples

§Named Structs

use zlink::introspect::{CustomType, Type};
use zlink::idl;

#[derive(CustomType)]
struct Point {
    x: f64,
    y: f64,
}

// Access the generated custom type information
match Point::CUSTOM_TYPE {
    idl::CustomType::Object(obj) => {
        assert_eq!(obj.name(), "Point");
        let fields: Vec<_> = obj.fields().collect();
        assert_eq!(fields.len(), 2);
        assert_eq!(fields[0].name(), "x");
        assert_eq!(fields[1].name(), "y");
    }
    _ => panic!("Expected custom object type"),
}

match Point::TYPE {
    idl::Type::Custom(name) => {
        assert_eq!(*name, "Point");
    }
    _ => panic!("Expected custom type"),
}

§Unit Enums

#[derive(CustomType)]
enum Status {
    Active,
    Inactive,
    Pending,
}

// Access the generated custom enum type information
match Status::CUSTOM_TYPE {
    idl::CustomType::Enum(enm) => {
        assert_eq!(enm.name(), "Status");
        let variants: Vec<_> = enm.variants().collect();
        assert_eq!(variants.len(), 3);
        assert_eq!(variants[0].name(), "Active");
        assert_eq!(variants[1].name(), "Inactive");
        assert_eq!(variants[2].name(), "Pending");
    }
    _ => panic!("Expected custom enum type"),
}

match Status::TYPE {
    idl::Type::Custom(name) => {
        assert_eq!(*name, "Status");
    }
    _ => panic!("Expected custom type"),
}