Skip to content

Runtime Type Information

IsaacShelton edited this page Mar 21, 2022 · 1 revision

Runtime Type Information

Unless runtime type information is disabled, type information for every type in the program is available at runtime.

This is very powerful, since it allows us to operate on arbitrary data structures.

Intrinsic Type Information

When runtime type information isn't disabled, there will be three global pseudo-variables.

Name Type Description
__types__ **AnyType Primitive array containing every type
__types_length__ usize Number of types in __types__
__types_kinds__ **ubyte Primitive array containing the name of each type kind

Obtaining Typeinfo

The specific *AnyType for a type can be obtained with typeinfo.

float_ty *AnyType = typeinfo float

The typeinfo expression will always return the same pointer when given the same type, and therefore *AnyType values can be compared by comparing their pointers.

if ty == typeinfo String {
    print(value)
}

Usage Example

The following is an example of loading textures based on struct field names:

struct GlobalTextures (
    floor,
    wall,
    player,
    enemy Texture
) {
    func load {
        assetsFolder String = "assets/"
        ty *AnyStructType = typeinfo GlobalTextures as *AnyStructType
        
        repeat ty.length {
            unless ty.members[idx] == typeinfo Texture, continue
            
            name String = stringConstant(ty.member_names[idx])
            location *Texture = cast *Texture (this + ty.offsets[idx])
            
            location.load(assetsFolder + name + ".png")
        }
    }
}

Disabling Runtime Type Information

Runtime type information isn't always worth the increased executable size. In these cases, runtime type information can be disabled using either:

  • --no-typeinfo command line option
  • pragma no_typeinfo pragma directive
Clone this wiki locally