Type

Struct Type 

Source
pub struct Type(/* private fields */);
Expand description

A type in the Gruel type system.

After Phase 4.1 of ADR-0024, Type is a newtype wrapping a u32 index. This enables O(1) type equality via u32 comparison.

§Encoding

The u32 value uses a tag-based encoding:

  • Primitives (0-18): I8=0, I16=1, I32=2, I64=3, U8=4, U16=5, U32=6, U64=7, Isize=8, Usize=9, F16=10, F32=11, F64=12, Bool=13, Unit=14, Error=15, Never=16, ComptimeType=17, ComptimeStr=18, ComptimeInt=19
  • Composites: low byte is tag (TAG_STRUCT, TAG_ENUM, TAG_ARRAY, TAG_MODULE), high 24 bits are the ID

§Usage

Use the associated constants for primitive types:

let ty = Type::I32;

Use constructor methods for composite types:

let ty = Type::new_struct(struct_id);

Use kind() for pattern matching:

match ty.kind() {
    TypeKind::I32 => { /* ... */ }
    TypeKind::Struct(id) => { /* ... */ }
    _ => { /* ... */ }
}

Implementations§

Source§

impl Type

Source

pub const I8: Type

8-bit signed integer

Source

pub const I16: Type

16-bit signed integer

Source

pub const I32: Type

32-bit signed integer

Source

pub const I64: Type

64-bit signed integer

Source

pub const U8: Type

8-bit unsigned integer

Source

pub const U16: Type

16-bit unsigned integer

Source

pub const U32: Type

32-bit unsigned integer

Source

pub const U64: Type

64-bit unsigned integer

Source

pub const ISIZE: Type

Pointer-sized signed integer

Source

pub const USIZE: Type

Pointer-sized unsigned integer

Source

pub const F16: Type

IEEE 754 binary16 (half-precision float)

Source

pub const F32: Type

IEEE 754 binary32 (single-precision float)

Source

pub const F64: Type

IEEE 754 binary64 (double-precision float)

Source

pub const BOOL: Type

Boolean

Source

pub const UNIT: Type

The unit type (for functions that don’t return a value)

Source

pub const ERROR: Type

An error type (used during type checking to continue after errors)

Source

pub const NEVER: Type

The never type - represents computations that don’t return

Source

pub const COMPTIME_TYPE: Type

The comptime type - the type of types themselves

Source

pub const COMPTIME_STR: Type

The comptime string type - compile-time only string values

Source

pub const COMPTIME_INT: Type

The comptime integer type - compile-time only integer values

Source§

impl Type

Source

pub const fn new_struct(id: StructId) -> Type

Create a struct type from a StructId.

Source

pub const fn new_enum(id: EnumId) -> Type

Create an enum type from an EnumId.

Source

pub const fn new_array(id: ArrayTypeId) -> Type

Create an array type from an ArrayTypeId.

Source

pub const fn new_ptr_const(id: PtrConstTypeId) -> Type

Create a raw const pointer type from a PtrConstTypeId.

Source

pub const fn new_ptr_mut(id: PtrMutTypeId) -> Type

Create a raw mut pointer type from a PtrMutTypeId.

Source

pub const fn new_module(id: ModuleId) -> Type

Create a module type from a ModuleId.

Source§

impl Type

Source

pub fn kind(&self) -> TypeKind

Get the kind of this type for pattern matching.

This method decodes the u32 representation back to a TypeKind for pattern matching. Primitive types (0-12) decode directly; composite types decode the tag and ID.

§Panics

Panics if the Type has an invalid encoding. This should never happen with Types created through the normal API. If you’re working with potentially corrupt data, use try_kind instead.

§Example
match ty.kind() {
    TypeKind::I32 | TypeKind::I64 => { /* handle integers */ }
    TypeKind::Struct(id) => { /* handle struct */ }
    _ => { /* other types */ }
}
Source

pub fn try_kind(&self) -> Option<TypeKind>

Try to get the kind of this type, returning None if the encoding is invalid.

This is the non-panicking version of kind. Use this when working with potentially corrupt data or for defensive programming.

§Example
if let Some(kind) = ty.try_kind() {
    match kind {
        TypeKind::I32 => { /* ... */ }
        _ => { /* ... */ }
    }
} else {
    eprintln!("corrupt type data");
}
Source

pub fn name(&self) -> &'static str

Get a human-readable name for this type. Note: For struct and array types, this returns a placeholder. Use type_name_with_structs for proper struct/array names.

Source

pub fn safe_name_with_pool(&self, pool: Option<&TypeInternPool>) -> String

Get a human-readable type name, safely handling anonymous structs and missing definitions.

Unlike name(), this method can access the type pool to get actual struct/enum names instead of returning generic placeholders like "<struct>".

This is primarily used for error messages where we want to show meaningful type names even if the type pool lookup fails (returns safe fallback in that case).

§Safety

This method is safe even if the struct/enum ID is invalid or the pool is None. It will return a fallback string like "<struct#123>" in those cases.

Source

pub fn is_integer(&self) -> bool

Check if this type is an integer type. Optimized: checks tag range directly (0-9 are integer types: i8..u64, isize/usize).

Source

pub fn is_error(&self) -> bool

Check if this is an error type.

Source

pub fn is_never(&self) -> bool

Check if this is the never type.

Source

pub fn is_comptime_type(&self) -> bool

Check if this is the comptime type (the type of types).

Source

pub fn is_comptime_str(&self) -> bool

Check if this is the comptime string type.

Source

pub fn is_comptime_int(&self) -> bool

Check if this is the comptime integer type.

Source

pub fn is_struct(&self) -> bool

Check if this is a struct type.

Source

pub fn as_struct(&self) -> Option<StructId>

Get the struct ID if this is a struct type.

Source

pub fn is_array(&self) -> bool

Check if this is an array type.

Source

pub fn as_array(&self) -> Option<ArrayTypeId>

Get the array type ID if this is an array type.

Source

pub fn is_enum(&self) -> bool

Check if this is an enum type.

Source

pub fn as_enum(&self) -> Option<EnumId>

Get the enum ID if this is an enum type.

Source

pub fn is_module(&self) -> bool

Check if this is a module type.

Source

pub fn as_module(&self) -> Option<ModuleId>

Get the module ID if this is a module type.

Source

pub fn is_ptr_const(&self) -> bool

Check if this is a raw const pointer type.

Source

pub fn as_ptr_const(&self) -> Option<PtrConstTypeId>

Get the pointer type ID if this is a ptr const type.

Source

pub fn is_ptr_mut(&self) -> bool

Check if this is a raw mut pointer type.

Source

pub fn as_ptr_mut(&self) -> Option<PtrMutTypeId>

Get the pointer type ID if this is a ptr mut type.

Source

pub fn is_ptr(&self) -> bool

Check if this is any raw pointer type (ptr const or ptr mut).

Source

pub fn is_signed(&self) -> bool

Check if this is a signed integer type. Signed integers: I8=0, I16=1, I32=2, I64=3, Isize=8.

Source

pub fn is_float(&self) -> bool

Check if this is a floating-point type. Float types: F16=10, F32=11, F64=12.

Source

pub fn is_numeric(&self) -> bool

Check if this is a numeric type (integer or float).

Source

pub fn is_copy(&self) -> bool

Check if this is a Copy type (can be implicitly duplicated).

Copy types are:

  • All integer types (i8-i64, u8-u64)
  • Boolean
  • Unit
  • Enum types
  • Never type and Error type (for convenience in error recovery)

Non-Copy types (move types) are:

  • Struct types (unless marked @copy, checked via StructDef.is_copy)
  • Array types (unless element type is Copy, checked via Sema.is_type_copy)

Note: This method can’t check struct’s is_copy attribute or array element types since it doesn’t have access to StructDefs or array type information. Use Sema.is_type_copy() for full checking.

Source

pub fn is_copy_in_pool(&self, type_pool: &TypeInternPool) -> bool

Check if this type is Copy, with access to TypeInternPool for struct checking.

This is used during anonymous struct creation to determine if the new struct should be Copy based on its field types.

Source

pub fn is_64_bit(&self) -> bool

Check if this is a 64-bit type (uses 64-bit operations). Optimized: checks for I64 (3) or U64 (7).

Source

pub fn is_pointer_sized(&self) -> bool

Check if this is a pointer-sized type (isize or usize). Checks for Isize (8) or Usize (9).

Source

pub fn can_coerce_to(&self, target: &Type) -> bool

Check if this type can coerce to the target type.

Coercion rules:

  • Never can coerce to any type (it represents divergent control flow)
  • Error can coerce to any type (for error recovery during type checking)
  • Otherwise, types must be equal
Source

pub fn is_unsigned(&self) -> bool

Check if this is an unsigned integer type. Unsigned integers: U8=4, U16=5, U32=6, U64=7, Usize=9.

Source

pub fn literal_fits(&self, value: u64) -> bool

Check if a u64 value fits within the range of this integer type.

For signed types, only the positive range is checked (0 to max positive). Negation is handled separately to allow values like -128 for i8.

Returns true if the value fits, false otherwise. For non-integer types, returns false.

Source

pub fn negated_literal_fits(&self, value: u64) -> bool

Check if a u64 value can be negated to fit within the range of this signed integer type.

This is used to allow literals like 2147483648 when negated to -2147483648 (i32::MIN). Returns true if the negated value fits, false otherwise.

Source

pub fn as_u32(&self) -> u32

Encode this type as a u32 for storage in extra arrays.

Since Type is now a u32 newtype, this simply returns the inner value.

Source

pub fn from_u32(v: u32) -> Type

Decode a type from a u32 value.

Since Type is now a u32 newtype, this simply wraps the value. Note: This does not validate the encoding - use with values from as_u32().

§Safety (not unsafe, but correctness)

This method trusts that the input is a valid encoding. For untrusted data, use try_from_u32 which validates the encoding.

Source

pub fn try_from_u32(v: u32) -> Option<Type>

Try to decode a type from a u32 value, returning None if invalid.

This validates that the encoding represents a valid type before returning. Use this when reading potentially corrupt data (e.g., deserialization, memory-mapped files, or debugging).

§Example
if let Some(ty) = Type::try_from_u32(encoded) {
    // Safe to use ty.kind()
} else {
    // Handle invalid encoding
}
Source

pub fn is_valid_encoding(v: u32) -> bool

Check if a u32 value is a valid Type encoding.

Returns true if the value represents a valid primitive or composite type.

Source

pub fn is_valid(&self) -> bool

Check if this Type has a valid encoding.

This is useful for debugging and assertions.

Trait Implementations§

Source§

impl Clone for Type

Source§

fn clone(&self) -> Type

Returns a duplicate of the value. Read more
1.0.0 · Source§

fn clone_from(&mut self, source: &Self)

Performs copy-assignment from source. Read more
Source§

impl Debug for Type

Source§

fn fmt(&self, f: &mut Formatter<'_>) -> Result<(), Error>

Formats the value using the given formatter. Read more
Source§

impl Default for Type

Source§

fn default() -> Type

Returns the “default value” for a type. Read more
Source§

impl Display for Type

Source§

fn fmt(&self, f: &mut Formatter<'_>) -> Result<(), Error>

Formats the value using the given formatter. Read more
Source§

impl Hash for Type

Source§

fn hash<__H>(&self, state: &mut __H)
where __H: Hasher,

Feeds this value into the given Hasher. Read more
1.3.0 · Source§

fn hash_slice<H>(data: &[Self], state: &mut H)
where H: Hasher, Self: Sized,

Feeds a slice of this type into the given Hasher. Read more
Source§

impl PartialEq for Type

Source§

fn eq(&self, other: &Type) -> bool

Tests for self and other values to be equal, and is used by ==.
1.0.0 · Source§

fn ne(&self, other: &Rhs) -> bool

Tests for !=. The default implementation is almost always sufficient, and should not be overridden without very good reason.
Source§

impl Copy for Type

Source§

impl Eq for Type

Source§

impl StructuralPartialEq for Type

Auto Trait Implementations§

§

impl Freeze for Type

§

impl RefUnwindSafe for Type

§

impl Send for Type

§

impl Sync for Type

§

impl Unpin for Type

§

impl UnwindSafe for Type

Blanket Implementations§

Source§

impl<T> Any for T
where T: 'static + ?Sized,

Source§

fn type_id(&self) -> TypeId

Gets the TypeId of self. Read more
Source§

impl<T> Borrow<T> for T
where T: ?Sized,

Source§

fn borrow(&self) -> &T

Immutably borrows from an owned value. Read more
Source§

impl<T> BorrowMut<T> for T
where T: ?Sized,

Source§

fn borrow_mut(&mut self) -> &mut T

Mutably borrows from an owned value. Read more
Source§

impl<T> CloneToUninit for T
where T: Clone,

Source§

unsafe fn clone_to_uninit(&self, dest: *mut u8)

🔬This is a nightly-only experimental API. (clone_to_uninit)
Performs copy-assignment from self to dest. Read more
§

impl<Q, K> Equivalent<K> for Q
where Q: Eq + ?Sized, K: Borrow<Q> + ?Sized,

§

fn equivalent(&self, key: &K) -> bool

Checks if this value is equivalent to the given key. Read more
§

impl<Q, K> Equivalent<K> for Q
where Q: Eq + ?Sized, K: Borrow<Q> + ?Sized,

§

fn equivalent(&self, key: &K) -> bool

Compare self to key and return true if they are equal.
Source§

impl<T> From<T> for T

Source§

fn from(t: T) -> T

Returns the argument unchanged.

§

impl<T> Instrument for T

§

fn instrument(self, span: Span) -> Instrumented<Self>

Instruments this type with the provided [Span], returning an Instrumented wrapper. Read more
§

fn in_current_span(self) -> Instrumented<Self>

Instruments this type with the current Span, returning an Instrumented wrapper. Read more
Source§

impl<T, U> Into<U> for T
where U: From<T>,

Source§

fn into(self) -> U

Calls U::from(self).

That is, this conversion is whatever the implementation of From<T> for U chooses to do.

§

impl<'src, T> IntoMaybe<'src, T> for T
where T: 'src,

§

type Proj<U: 'src> = U

§

fn map_maybe<R>( self, _f: impl FnOnce(&'src T) -> &'src R, g: impl FnOnce(T) -> R, ) -> <T as IntoMaybe<'src, T>>::Proj<R>
where R: 'src,

§

impl<'p, T> Seq<'p, T> for T
where T: Clone,

§

type Item<'a> = &'a T where T: 'a

The item yielded by the iterator.
§

type Iter<'a> = Once<&'a T> where T: 'a

An iterator over the items within this container, by reference.
§

fn seq_iter(&self) -> <T as Seq<'p, T>>::Iter<'_>

Iterate over the elements of the container.
§

fn contains(&self, val: &T) -> bool
where T: PartialEq,

Check whether an item is contained within this sequence.
§

fn to_maybe_ref<'b>(item: <T as Seq<'p, T>>::Item<'b>) -> Maybe<T, &'p T>
where 'p: 'b,

Convert an item of the sequence into a [MaybeRef].
Source§

impl<T> ToOwned for T
where T: Clone,

Source§

type Owned = T

The resulting type after obtaining ownership.
Source§

fn to_owned(&self) -> T

Creates owned data from borrowed data, usually by cloning. Read more
Source§

fn clone_into(&self, target: &mut T)

Uses borrowed data to replace owned data, usually by cloning. Read more
Source§

impl<T> ToString for T
where T: Display + ?Sized,

Source§

fn to_string(&self) -> String

Converts the given value to a String. Read more
Source§

impl<T, U> TryFrom<U> for T
where U: Into<T>,

Source§

type Error = Infallible

The type returned in the event of a conversion error.
Source§

fn try_from(value: U) -> Result<T, <T as TryFrom<U>>::Error>

Performs the conversion.
Source§

impl<T, U> TryInto<U> for T
where U: TryFrom<T>,

Source§

type Error = <U as TryFrom<T>>::Error

The type returned in the event of a conversion error.
Source§

fn try_into(self) -> Result<U, <U as TryFrom<T>>::Error>

Performs the conversion.
§

impl<T> WithSubscriber for T

§

fn with_subscriber<S>(self, subscriber: S) -> WithDispatch<Self>
where S: Into<Dispatch>,

Attaches the provided Subscriber to this type, returning a [WithDispatch] wrapper. Read more
§

fn with_current_subscriber(self) -> WithDispatch<Self>

Attaches the current default Subscriber to this type, returning a [WithDispatch] wrapper. Read more
§

impl<T> OrderedSeq<'_, T> for T
where T: Clone,