Module

serialization

AST serialization — JSON round-trip for Patitas AST nodes.

Converts typed AST nodes to/from JSON-compatible dicts. Useful for:

  • Caching parsed ASTs to disk (Bengal incremental builds)
  • Sending AST diffs over the wire (Purr SSE)
  • Debugging and inspection

All output is deterministic (sorted keys) for cache-key stability.

Example:

from patitas import parse
from patitas.serialization import to_json, from_json

doc = parse("# Hello **World**")
json_str = to_json(doc)
restored = from_json(json_str)
assert doc == restored

Thread Safety:

All functions are pure — safe to call from any thread.

Functions

to_dict 1 dict[str, Any]
Convert an AST node to a JSON-compatible dict. Includes a ``_type`` discrimina…
def to_dict(node: Node) -> dict[str, Any]

Convert an AST node to a JSON-compatible dict.

Includes a_typediscriminator field for deserialization. Recursively serializes child nodes and SourceLocation objects.

Parameters
Name Type Description
node Node

Any Patitas AST node.

Returns
dict[str, Any]
_serialize_value 2 Any
Serialize a single field value.
def _serialize_value(value: Any, field_name: str = '') -> Any
Parameters
Name Type Description
value Any
field_name str Default:''
Returns
Any
from_dict 1 Node
Reconstruct a typed AST node from a dict. Uses the ``_type`` discriminator to …
def from_dict(data: dict[str, Any]) -> Node

Reconstruct a typed AST node from a dict.

Uses the_typediscriminator to determine the node class. Recursively deserializes child nodes and SourceLocation objects.

Parameters
Name Type Description
data dict[str, Any]

Dict with_typeand node fields (as produced by to_dict).

Returns
Node
_deserialize_value 2 Any
Deserialize a single field value.
def _deserialize_value(value: Any, field_name: str = '') -> Any
Parameters
Name Type Description
value Any
field_name str Default:''
Returns
Any
to_json 2 str
Serialize a Document AST to a JSON string. Output is deterministic (sorted key…
def to_json(doc: Document, *, indent: int | None = None) -> str

Serialize a Document AST to a JSON string.

Output is deterministic (sorted keys) for cache-key stability.

Parameters
Name Type Description
doc Document

Document to serialize.

indent int | None

JSON indentation level (None for compact).

Default:None
Returns
str
from_json 1 Document
Deserialize a Document AST from a JSON string.
def from_json(data: str) -> Document
Parameters
Name Type Description
data str

JSON string (as produced by to_json).

Returns
Document