reflection | Modular

Mojo package

Compile-time reflection utilities for introspecting Mojo types and functions.

This module provides compile-time reflection capabilities including:

  • Type name introspection (get_type_name)
  • Function name and linkage introspection (get_function_name, get_linkage_name)
  • Type checking (is_struct_type)
  • Struct field reflection (struct_field_count, struct_field_names, struct_field_types)
  • Field lookup by name (struct_field_index_by_name, struct_field_type_by_name)
  • Field offset calculation (offset_of)
  • Source location introspection (source_location, call_location)
  • Base type reflection (get_base_type_name)

Example:

from reflection import struct_field_count, struct_field_names

struct Point:
    var x: Int
    var y: Float64

fn print_fields[T: AnyType]():
    comptime names = struct_field_names[T]()
    comptime for i in range(struct_field_count[T]()):
        print(names[i])

fn main():
    print_fields[Point]()  # Prints: x, y

Modules

  • location: Implements utilities to capture and represent source code location.
  • struct_fields: Provides struct field reflection and introspection utilities.
  • traits: Compile-time meta functions for checking trait conformance across variadic type lists.
  • type_info: Provides type and function name introspection utilities.