CrucibleIR.Serialization (CrucibleIR v0.3.0)

View Source

JSON serialization and deserialization for IR structs.

This module provides functions to convert CrucibleIR structs to and from JSON, enabling persistence, transport, and interoperability with other systems.

Functions

Contract Notes

  • This module is the canonical JSON round-trip layer for CrucibleIR.
  • Fields like options and StageDef.options are treated as opaque maps and are not coerced or validated.
  • For stable round-trip behavior, ensure map keys are JSON-friendly (strings).

Examples

iex> alias CrucibleIR.BackendRef
iex> backend = %BackendRef{id: :gpt4}
iex> json = CrucibleIR.Serialization.to_json(backend)
iex> is_binary(json)
true

iex> alias CrucibleIR.BackendRef
iex> json = ~s({"id":"gpt4","profile":"default"})
iex> {:ok, backend} = CrucibleIR.Serialization.from_json(json, BackendRef)
iex> backend.id
:gpt4

Summary

Functions

Decodes a JSON string to a struct of the given type.

Converts a plain map to a struct of the given type.

Encodes a struct to a JSON string.

Functions

from_json(json, type)

@spec from_json(String.t(), module()) :: {:ok, struct()} | {:error, term()}

Decodes a JSON string to a struct of the given type.

Parameters

  • json - JSON string to decode
  • type - The module name of the target struct type

Returns

  • {:ok, struct} - Successfully decoded struct
  • {:error, reason} - Decoding failed

Examples

iex> alias CrucibleIR.BackendRef
iex> json = ~s({"id":"gpt4","profile":"default"})
iex> {:ok, backend} = CrucibleIR.Serialization.from_json(json, BackendRef)
iex> backend.id
:gpt4

from_map(map, arg)

@spec from_map(map(), module()) :: {:ok, struct()} | {:error, term()}

Converts a plain map to a struct of the given type.

Handles conversion of string keys to atoms and nested struct construction.

Parameters

  • map - Map with string or atom keys
  • type - The module name of the target struct type

Returns

  • {:ok, struct} - Successfully converted struct
  • {:error, reason} - Conversion failed

Examples

iex> alias CrucibleIR.BackendRef
iex> map = %{"id" => "gpt4", "profile" => "default"}
iex> {:ok, backend} = CrucibleIR.Serialization.from_map(map, BackendRef)
iex> backend.id
:gpt4

to_json(struct)

@spec to_json(struct()) :: String.t()

Encodes a struct to a JSON string.

Parameters

  • struct - Any CrucibleIR struct with @derive Jason.Encoder

Returns

  • JSON string representation

Examples

iex> alias CrucibleIR.BackendRef
iex> backend = %BackendRef{id: :gpt4}
iex> json = CrucibleIR.Serialization.to_json(backend)
iex> is_binary(json)
true