Skip to content

Auto conversion on instance creation and assign - #478

Open
joente wants to merge 8 commits into
mainfrom
auto-convert
Open

joente wants to merge 8 commits into
mainfrom
auto-convert

Conversation

@joente

@joente joente commented Nov 20, 2026 •

Copy link
Copy Markdown
Member

This pull request introduces automatic (implicit) conversion of compatible values into target property types during instance initialization from an existing object (Type(thing)) and when using .assign().

Motivation

When initializing nested types from external input (such as JSON or MessagePack payloads), callers previously had to manually map and cast every nested type, enum, set, or error:

set_enum('Status', {
    Pending: 0,
    Complete: 1,
});
set_type('Task', {
    id: '#',
    name: 'str',
    status: 'Status',
    err: 'error?',
});
set_type('User', {
    id: '#',
    name: 'str',
    email: 'email',
});
set_type('Job', {
    id: '#',
    title: 'str',
    user: '&User',
    tasks: '&{Task}',
});

.users = [
    User{name: 'Iris', email: 'iris@example.com'},
];
.jobs = [];

Previously, creating a Job from raw input required explicit boilerplate:

new_procedure('add_job', |object| {
    job = Job{
        title: object.title,
        user: User(object.user),
        tasks: set(object.tasks.map(|t| Task{
            name: t.name,
            status: Status(t.status),
            err: t.err ? err(t.err) : nil,
        })),
    };
    .jobs.push(job);
    job.wrap();
});

With automatic conversion, the same procedure simplifies to:

new_procedure('add_job', |object| {
    job = Job(object);
    .jobs.push(job);
    job.wrap();
});

Scope: When Auto-Conversion Applies

Auto-conversion only occurs when:

  1. Initializing a type from an existing object: Type(thing)
  2. Updating an instance via .assign(...)

Direct literal instantiation (Type{...}) and standard property assignments (instance.prop = val) remain strictly typed and will still raise a type mismatch error:

Task({name: 'Build', status: 0});  // OK (auto-converted)
Task{name: 'Build', status: 0};   // Error: mismatch in type `Task`; type `int` is invalid for property `status` with definition `Status`

This keeps explicit syntax strict where types are written directly in code, while removing friction when ingesting serialized payloads.

Supported Conversions

int

  • Accepted: float (exact whole numbers only)
  • Why: Some serialization formats and languages (e.g., JavaScript/JSON) do not distinguish between integers and floats. Unlike explicit int(f) (which truncates toward zero), auto-conversion rejects floats with a non-zero fractional part to prevent silent data loss. Other types (such as bool) are not converted.
set_type('Int', {v: 'int'});
Int({v: 3.0});  // OK -> 3
Int({v: 3.1});  // Error: mismatch in type `Int`; conversion error for property `v`: cannot convert float with fractional part to integer

float

  • Accepted: int
  • Why: Serialized formats often encode whole-number floats without a decimal point (e.g., 6 instead of 6.0).

regex

  • Accepted: str formatted as "/expression/flags"
  • Why: Formats like JSON and MessagePack have no native regex type.

error

  • Accepted: str like "integer overflow"
  • Why: Formats like JSON and MessagePack have no native error type.

closure

  • Accepted: str formatted as "|args| body"
  • Why: Formats like JSON and MessagePack have no native closure type.

uuid

  • Accepted: str (standard UUID format) or bytes (16-byte raw UUID)
  • Why: JSON serializes UUIDs as strings, while binary formats like MessagePack can encode them as 16-byte binary values (bytes).
set_type('Item', {v: 'uuid'});

Item({v: '550e8400-e29b-41d4-a716-446655440000'});  // OK (from str)
Item({v: base64_decode('VQ6EAOKbQdSnFkRmVUQAAA==')});  // OK (from 16-byte bytes)

enum

  • Accepted: str (matching a member name) or the underlying enum member value type (e.g., int, float, str, bytes, or thing). When a str is provided, member names are checked first, followed by member values.
  • Why: Serialized formats like JSON and MessagePack represent enums as raw strings or numbers rather than typed enum instances.
set_enum('Status', {
    Pending: 0,
    Complete: 1,
});
set_type('Task', {v: 'Status'});

Task({v: 'Pending'});  // OK -> Status{Pending} (matched by name)
Task({v: 1});          // OK -> Status{Complete} (matched by value)

thing (Typed Things & Instances)

  • Accepted:
    • Plain thing ({...}): Converted recursively into the target typed thing (thing<...>) or type instance.
    • Instance ID (int): Resolved to the existing instance in the collection, if it exists.
set_type('TypedThing', {v: '&thing<Status>'});
TypedThing({v: {a: 0, b: 1}}).wrap();  // OK

Job({user: 99});  // Error: mismatch in type `Job`; conversion error for property `user`: collection `stuff` has no `thing` with id 99

set

  • Accepted: array ([...]), with elements converted to the target set definition type.
  • Why: Serialized formats like JSON do not have a native set type.
Job({tasks: [{name: 'Deploy', status: 1}]}).wrap();

array

  • Accepted: array ([...]), with elements converted recursively to the target item type.
set_type('ArrInt', {v: '[int]'});
ArrInt({v: [2.0, 6.0]});  // OK -> [2, 6]

datetime

  • Accepted: str (ISO 8601 format)
  • Why: datetime serializes to an ISO string; accepting the string back makes round-trip serialization seamless.
set_type('Datetime', {v: 'datetime'});
Datetime({v: "2026-11-20T22:32:28Z"});

timeval

  • Accepted: int and float (UNIX timestamps)
  • Why: timeval serializes to a numeric UNIX timestamp; accepting int/float enables seamless round-trip deserialization.
set_type('Timeval', {v: 'timeval'});
Timeval({v: 1795214029});

Type of change

  • New feature (non-breaking change which adds functionality)

How Has This Been Tested?

  • Test auto conversion

Checklist:

  • My code follows the style guidelines of this project
  • I have performed a self-review of my own code
  • I have commented my code, particularly in hard-to-understand areas
  • I have made corresponding changes to the documentation
  • New and existing unit tests pass locally with my changes

@joente joente self-assigned this Nov 20, 2026
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Labels

None yet

Projects

None yet

Development

Successfully merging this pull request may close these issues.

1 participant