Abstract services to serialize Nit objects to different formats

This module declares the serialize annotation to mark Nit classes as serializable. For an introduction to this service, refer to the documentation of the serialization group. This documentation provides more technical information on interesting entitie of this module.

Interesting entities for end users of serializable classes:

  • Serialize an instance subclass of Serializable with either Serializer::serializable and Serializable::serialize.
  • Deserialize an object using Deserializer::deserialize. The object type must the be checked with an assert or otherwise.

Interesting entities to create custom serializable classes:

  • Subclass Serializable to declare a class as serializable and to customize the serialization and deserialization behavior.
  • Redefine Serializable::core_serialize_to to customize the serialization of the receiver class.
  • Redefine Deserializer::deserialize_class to customize the deserialization of a specific class by name.

Interesting entities for serialization format:

Introduced classes

abstract class AttributeError

serialization :: AttributeError

Deserialization error related to an attribute of receiver
class AttributeMissingError

serialization :: AttributeMissingError

Missing attribute at deserialization
class AttributeTypeError

serialization :: AttributeTypeError

Invalid dynamic type for a deserialized attribute
abstract class Deserializer

serialization :: Deserializer

Abstract deserialization service
interface DirectSerializable

serialization :: DirectSerializable

Instances of this class are not delayed and instead serialized immediately
interface Serializable

serialization :: Serializable

Instances of this class can be passed to Serializer::serialize
interface Serializer

serialization :: Serializer

Abstract serialization service to be sub-classed by specialized services.

Redefined classes

redef enum Bool

serialization :: serialization_core $ Bool

Native Booleans.
redef enum Byte

serialization :: serialization_core $ Byte

Native bytes.
redef extern class CString

serialization :: serialization_core $ CString

C string char *
redef enum Char

serialization :: serialization_core $ Char

Native characters.
redef class Couple[F: nullable Object, S: nullable Object]

serialization :: serialization_core $ Couple

Two objects in a simple structure.
redef class Error

serialization :: serialization_core $ Error

Standard class for error messages
redef enum Float

serialization :: serialization_core $ Float

Native floating point numbers.
redef enum Int

serialization :: serialization_core $ Int

Native integer numbers.
redef interface Map[K: nullable Object, V: nullable Object]

serialization :: serialization_core $ Map

Maps are associative collections: key -> item.
redef class MinHeap[E: Object]

serialization :: serialization_core $ MinHeap

A min-heap implemented over an array
redef class Ref[E: nullable Object]

serialization :: serialization_core $ Ref

A collection that contains only one item.
redef interface SimpleCollection[E: nullable Object]

serialization :: serialization_core $ SimpleCollection

Items can be added to these collections.
redef abstract class Text

serialization :: serialization_core $ Text

High-level abstraction for all text representations

All class definitions

abstract class AttributeError

serialization $ AttributeError

Deserialization error related to an attribute of receiver
class AttributeMissingError

serialization $ AttributeMissingError

Missing attribute at deserialization
class AttributeTypeError

serialization $ AttributeTypeError

Invalid dynamic type for a deserialized attribute
redef enum Bool

serialization :: serialization_core $ Bool

Native Booleans.
redef enum Byte

serialization :: serialization_core $ Byte

Native bytes.
redef extern class CString

serialization :: serialization_core $ CString

C string char *
redef enum Char

serialization :: serialization_core $ Char

Native characters.
redef class Couple[F: nullable Object, S: nullable Object]

serialization :: serialization_core $ Couple

Two objects in a simple structure.
abstract class Deserializer

serialization $ Deserializer

Abstract deserialization service
interface DirectSerializable

serialization $ DirectSerializable

Instances of this class are not delayed and instead serialized immediately
redef class Error

serialization :: serialization_core $ Error

Standard class for error messages
redef enum Float

serialization :: serialization_core $ Float

Native floating point numbers.
redef enum Int

serialization :: serialization_core $ Int

Native integer numbers.
redef interface Map[K: nullable Object, V: nullable Object]

serialization :: serialization_core $ Map

Maps are associative collections: key -> item.
redef class MinHeap[E: Object]

serialization :: serialization_core $ MinHeap

A min-heap implemented over an array
redef class Ref[E: nullable Object]

serialization :: serialization_core $ Ref

A collection that contains only one item.
interface Serializable

serialization $ Serializable

Instances of this class can be passed to Serializer::serialize
interface Serializer

serialization $ Serializer

Abstract serialization service to be sub-classed by specialized services.
redef interface SimpleCollection[E: nullable Object]

serialization :: serialization_core $ SimpleCollection

Items can be added to these collections.
redef abstract class Text

serialization :: serialization_core $ Text

High-level abstraction for all text representations
package_diagram serialization::serialization_core serialization_core meta meta serialization::serialization_core->meta core core meta->core ...core ... ...core->core serialization::engine_tools engine_tools serialization::engine_tools->serialization::serialization_core poset::poset poset poset::poset->serialization::serialization_core serialization::caching caching serialization::caching->serialization::engine_tools serialization::caching... ... serialization::caching...->serialization::caching serialization::safe safe serialization::safe->poset::poset more_collections::more_collections more_collections more_collections::more_collections->poset::poset counter::counter counter counter::counter->poset::poset fca::fca fca fca::fca->poset::poset serialization::safe... ... serialization::safe...->serialization::safe more_collections::more_collections... ... more_collections::more_collections...->more_collections::more_collections counter::counter... ... counter::counter...->counter::counter fca::fca... ... fca::fca...->fca::fca

Ancestors

module abstract_collection

core :: abstract_collection

Abstract collection classes and services.
module abstract_text

core :: abstract_text

Abstract class for manipulation of sequences of characters
module array

core :: array

This module introduces the standard array structure.
module bitset

core :: bitset

Services to handle BitSet
module bytes

core :: bytes

Services for byte streams and arrays
module circular_array

core :: circular_array

Efficient data structure to access both end of the sequence.
module codec_base

core :: codec_base

Base for codecs to use with streams
module codecs

core :: codecs

Group module for all codec-related manipulations
module collection

core :: collection

This module define several collection classes.
module core

core :: core

Standard classes and methods used by default by Nit programs and libraries.
module environ

core :: environ

Access to the environment variables of the process
module error

core :: error

Standard error-management infrastructure.
module exec

core :: exec

Invocation and management of operating system sub-processes.
module file

core :: file

File manipulations (create, read, write, etc.)
module fixed_ints

core :: fixed_ints

Basic integers of fixed-precision
module fixed_ints_text

core :: fixed_ints_text

Text services to complement fixed_ints
module flat

core :: flat

All the array-based text representations
module gc

core :: gc

Access to the Nit internal garbage collection mechanism
module hash_collection

core :: hash_collection

Introduce HashMap and HashSet.
module iso8859_1

core :: iso8859_1

Codec for ISO8859-1 I/O
module kernel

core :: kernel

Most basic classes and methods.
module list

core :: list

This module handle double linked lists
module math

core :: math

Mathematical operations
module native

core :: native

Native structures for text and bytes
module numeric

core :: numeric

Advanced services for Numeric types
module protocol

core :: protocol

module queue

core :: queue

Queuing data structures and wrappers
module range

core :: range

Module for range of discrete objects.
module re

core :: re

Regular expression support for all services based on Pattern
module ropes

core :: ropes

Tree-based representation of a String.
module sorter

core :: sorter

This module contains classes used to compare things and sorts arrays.
module stream

core :: stream

Input and output streams of characters
module text

core :: text

All the classes and methods related to the manipulation of text entities
module time

core :: time

Management of time and dates
module union_find

core :: union_find

union–find algorithm using an efficient disjoint-set data structure
module utf8

core :: utf8

Codec for UTF-8 I/O

Parents

module meta

meta :: meta

Simple user-defined meta-level to manipulate types of instances as object.

Children

module engine_tools

serialization :: engine_tools

Advanced services for serialization engines
module poset

poset :: poset

Pre order sets and partial order set (ie hierarchies)

Descendants

module a_star

a_star :: a_star

A* pathfinding in graphs
module a_star-m

a_star-m

module android19

gamnit :: android19

Variation using features from Android API 19
module angles

geometry :: angles

Angle related service using Float to represent an angle in radians
module api

github :: api

Nit object oriented interface to Github api.
module array_debug

array_debug :: array_debug

Exposes functions to help profile or debug Arrays.
module at_boot

android :: at_boot

Import this module to launch Service at device boot
module bmfont

gamnit :: bmfont

Parse Angel Code BMFont format and draw text
module boxes

geometry :: boxes

Provides interfaces and classes to represent basic geometry needs.
module bucketed_game

bucketed_game :: bucketed_game

Game framework with an emphasis on efficient event coordination
module bundle

android :: bundle

A mapping class of String to various value types used by the
module cache

github :: cache

Enable caching on Github API accesses.
module caching

serialization :: caching

Services for caching serialization engines
module camera_control

gamnit :: camera_control

Simple camera control for user, as the method accept_scroll_and_zoom
module camera_control_android

gamnit :: camera_control_android

Two fingers camera manipulation, pinch to zoom and slide to scroll
module camera_control_linux

gamnit :: camera_control_linux

Mouse wheel and middle mouse button to control camera
module cameras

gamnit :: cameras

Camera services producing Model-View-Projection matrices
module cameras_cache

gamnit :: cameras_cache

Cache the Matrix produced by Camera::mvp_matrix
module cardboard

gamnit :: cardboard

Update the orientation of world_camera at each frame using the head position given by android::cardboard
module checker

dom :: checker

Simple XML validity checker using the dom module
module client

gamnit :: client

Client-side network services for games and such
module common

gamnit :: common

Services common to the client and server modules
module commonmark_gen

markdown2 :: commonmark_gen

Generate Nitunit tests from commonmark specification.
module counter

counter :: counter

Simple numerical statistical analysis and presentation
module curl_json

neo4j :: curl_json

cURL requests compatible with the JSON REST APIs.
module curl_rest

curl :: curl_rest

module custom_serialization

serialization :: custom_serialization

Example of an ad hoc serializer that is tailored to transform business specific objects into customized representation.
module data_store

ios :: data_store

Implements app::data_store using NSUserDefaults
module data_store

android :: data_store

Implements app::data_store using shared_preferences
module data_store

linux :: data_store

app::data_store implementation on GNU/Linux
module data_store

app :: data_store

Key/value storage services
module depth

gamnit :: depth

Framework for 3D games in Nit
module depth_core

gamnit :: depth_core

Base entities of the depth 3D game framework
module dom

dom :: dom

Easy XML DOM parser
module dynamic

json :: dynamic

Dynamic interface to read values from JSON strings
module dynamic_resolution

gamnit :: dynamic_resolution

Virtual screen with a resolution independent from the real screen
module error

neo4j :: error

Errors thrown by the neo4j library.
module error

json :: error

Intro JsonParseError which is exposed by all JSON reading APIs
module events

github :: events

Events are emitted by Github Hooks.
module example_angular

popcorn :: example_angular

This is an example of how to use angular.js with popcorn
module example_vsm

vsm :: example_vsm

Example using a FileIndex
module ext

msgpack :: ext

Application specific MessagePack extension MsgPackExt
module fca

fca :: fca

Formal Concept Analysis
module file_server

nitcorn :: file_server

Provides the FileServer action, which is a standard and minimal file server
module flat

gamnit :: flat

Simple API for 2D games, built around Sprite and App::update
module flat_core

gamnit :: flat_core

Core services for the flat API for 2D games
module font

gamnit :: font

Abstract font drawing services, implemented by bmfont and tileset
module gamnit

gamnit :: gamnit

Game and multimedia framework for Nit
module gamnit_android

gamnit :: gamnit_android

Support services for Gamnit on Android
module gamnit_ios

gamnit :: gamnit_ios

Support services for gamnit on iOS
module gamnit_linux

gamnit :: gamnit_linux

Support services for Gamnit on GNU/Linux
module geometry

geometry :: geometry

Provides interfaces and classes to represent basic geometry needs.
module github

github :: github

Nit wrapper for Github API
module graph

neo4j :: graph

Provides an interface for services on a Neo4j graphs.
module hooks

github :: hooks

Github hook event listening with nitcorn.
module htcpcp_server

nitcorn :: htcpcp_server

A server that implements HTCPCP. At the moment there are no additions.
module http_errors

nitcorn :: http_errors

Offers ErrorTemplate to display error pages
module http_request

app :: http_request

HTTP request services: AsyncHttpRequest and Text::http_get
module http_request

nitcorn :: http_request

Provides the HttpRequest class and services to create it
module http_request

linux :: http_request

Implementation of app::http_request using GDK and Curl
module http_request

android :: http_request

Android implementation of app:http_request
module http_request

ios :: http_request

Implementation of app::http_request for iOS
module http_request_example

app :: http_request_example

Example for the app::http_request main service AsyncHttpRequest
module http_response

nitcorn :: http_response

Provides the HttpResponse class and http_status_codes
module input_ios

gamnit :: input_ios

Gamnit event support for iOS
module inspect

serialization :: inspect

Refine Serializable::inspect to show more useful information
module intent

android :: intent

Services allowing to launch activities and start/stop services using
module intent_api10

android :: intent_api10

Services allowing to launch activities and start/stop services using
module intent_api11

android :: intent_api11

Refines intent module to add API 11 services
module intent_api12

android :: intent_api12

Refines intent module to add API 12 services
module intent_api14

android :: intent_api14

Refines intent module to add API 14 services
module intent_api15

android :: intent_api15

Refines intent module to add API 15 services
module intent_api16

android :: intent_api16

Refines intent module to add API 16 services
module intent_api17

android :: intent_api17

Refines intent module to add API 17 services
module intent_api18

android :: intent_api18

Refines intent module to add API 18 services
module intent_api19

android :: intent_api19

Refines intent module to add API 19 services
module json

json :: json

Read and write JSON formatted text using the standard serialization services
module json_graph_store

neo4j :: json_graph_store

Provides JSON as a mean to store graphs.
module keys

gamnit :: keys

Simple service keeping track of which keys are currently pressed
module limit_fps

gamnit :: limit_fps

Frame-rate control for applications
module loader

github :: loader

module log

nitcorn :: log

Services inserting a timestamp in all prints and to log each requests
module model_dimensions

gamnit :: model_dimensions

Dimensions related services for Model and Mesh
module model_parser_base

gamnit :: model_parser_base

Services to parse models from a text description
module mongodb

mongodb :: mongodb

MongoDB Nit Driver.
module more_collections

more_collections :: more_collections

Highly specific, but useful, collections-related classes.
module more_lights

gamnit :: more_lights

More implementations of Light
module more_materials

gamnit :: more_materials

Various material implementations
module more_meshes

gamnit :: more_meshes

More simple geometric meshes
module more_models

gamnit :: more_models

Services to load models from the assets folder
module mpi

mpi :: mpi

Implementation of the Message Passing Interface protocol by wrapping OpenMPI
module msgpack

msgpack :: msgpack

MessagePack, an efficient binary serialization format
module msgpack_to_json

msgpack :: msgpack_to_json

Convert MessagePack format to JSON
module mtl

gamnit :: mtl

Services to parse .mtl material files
module native_ui

android :: native_ui

Native services from the android.view and android.widget namespaces
module neo4j

neo4j :: neo4j

Neo4j connector through its JSON REST API using curl.
module network

gamnit :: network

Easy client/server logic for games and simple distributed applications
module nit_activity

android :: nit_activity

Core implementation of app.nit on Android using a custom Java entry point
module nitcc_runtime

nitcc_runtime :: nitcc_runtime

Runtime library required by parsers and lexers generated by nitcc
module nitcorn

nitcorn :: nitcorn

The nitcorn Web server framework creates server-side Web apps in Nit
module nitcorn_hello_world

nitcorn :: nitcorn_hello_world

Hello World Web server example
module nitcorn_reverse_proxy

nitcorn :: nitcorn_reverse_proxy

Minimal example using a ProxyAction
module nlp

nlp :: nlp

Natural Language Processor based on the StanfordNLP core.
module nlp_index

nlp :: nlp_index

Example showing how to use a NLPFileIndex.
module noise

noise :: noise

Noise generators PerlinNoise and InterpolatedNoise
module obj

gamnit :: obj

Services to parse .obj geometry files
module parser

dom :: parser

XML DOM-parsing facilities
module parser_base

parser_base :: parser_base

Simple base for hand-made parsers of all kinds
module particles

gamnit :: particles

Particle effects
module points_and_lines

geometry :: points_and_lines

Interfaces and classes to represent basic geometry needs.
module polygon

geometry :: polygon

Convex Polygons manipulations
module pop_auth

popcorn :: pop_auth

Authentification handlers.
module pop_handlers

popcorn :: pop_handlers

Route handlers.
module pop_json

popcorn :: pop_json

Introduce useful services for JSON REST API handlers.
module pop_repos

popcorn :: pop_repos

Repositories for data management.
module pop_routes

popcorn :: pop_routes

Internal routes representation.
module pop_sessions

popcorn :: pop_sessions

Session handlers
module pop_tasks

popcorn :: pop_tasks

Popcorn threaded tasks
module pop_templates

popcorn :: pop_templates

Template rendering for popcorn
module pop_tests

popcorn :: pop_tests

Popcorn testing services
module pop_validation

popcorn :: pop_validation

Quick and easy validation framework for Json inputs
module popcorn

popcorn :: popcorn

Application server abstraction on top of nitcorn.
module programs

gamnit :: programs

Services for graphical programs with shaders, attributes and uniforms
module proxy

nitcorn :: proxy

Provides the ProxyAction action, which redirects requests to another interface
module pthreads

nitcorn :: pthreads

Activate the use of pthreads with nitcorn
module quadtree

geometry :: quadtree

QuadTree API mostly used for 2 dimensional collision detection
module queries

mongodb :: queries

Mongo queries framework
module reactor

nitcorn :: reactor

Core of the nitcorn project, provides HttpFactory and Action
module read

msgpack :: read

Low-level read MessagePack format from Reader streams
module restful

nitcorn :: restful

Support module for the nitrestful tool and the restful annotation
module restful_annot

nitcorn :: restful_annot

Example for the restful annotation documented at lib/nitcorn/restful.nit
module safe

serialization :: safe

Services for safer deserialization engines
module selection

gamnit :: selection

Select Actor from a screen coordinate
module sensors

android :: sensors

Access Android sensors
module sequential_id

neo4j :: sequential_id

Provides a sequential identification scheme for Neo4j nodes.
module serialization

serialization :: serialization

General serialization services
module serialization_read

json :: serialization_read

Services to read JSON: deserialize_json and JsonDeserializer
module serialization_read

msgpack :: serialization_read

Deserialize full Nit objects from MessagePack format
module serialization_write

msgpack :: serialization_write

Serialize full Nit objects to MessagePack format
module serialization_write

json :: serialization_write

Services to write Nit objects to JSON strings: serialize_to_json and JsonSerializer
module server

gamnit :: server

Server-side network services for games and such
module service

android :: service

Android service support for app.nit centered around the class Service
module sessions

nitcorn :: sessions

Automated session management
module sexp

sexp :: sexp

S-Expression parsing facilities
module shadow

gamnit :: shadow

Shadow mapping using a depth texture
module shared_preferences

android :: shared_preferences

Services allowing to save and load datas to internal android device
module shared_preferences_api10

android :: shared_preferences_api10

Services to save/load data using android.content.SharedPreferences for the android platform
module shared_preferences_api11

android :: shared_preferences_api11

Refines shared_preferences module to add API 11 services
module signal_handler

nitcorn :: signal_handler

Handle SIGINT and SIGTERM to close the server after all active events
module simple_file_server

nitcorn :: simple_file_server

Basic file server on port 80 by default, may require root to execute
module stanford

nlp :: stanford

Natural Language Processor based on the StanfordNLP core.
module static

json :: static

Static interface to read Nit objects from JSON strings
module stereoscopic_view

gamnit :: stereoscopic_view

Refine EulerCamera and App::frame_core_draw to get a stereoscopic view
module store

json :: store

Store and load json data.
module text_stat

text_stat :: text_stat

Injects stat-calculating functionalities to Text and its variants
module texture_atlas_parser

gamnit :: texture_atlas_parser

Tool to parse XML texture atlas and generated Nit code to access subtextures
module tileset

gamnit :: tileset

Support for TileSet, TileSetFont and drawing text with TextSprites
module ui

android :: ui

Views and services to use the Android native user interface
module ui

linux :: ui

Implementation of the app.nit UI module for GNU/Linux
module ui_example

app :: ui_example

User interface example using app::ui
module ui_test

android :: ui_test

Test for app.nit's UI services
module vararg_routes

nitcorn :: vararg_routes

Routes with parameters.
module virtual_gamepad

gamnit :: virtual_gamepad

Virtual gamepad mapped to keyboard keys for quick and dirty mobile support
module vr

gamnit :: vr

VR support for gamnit depth, for Android only
module vsm

vsm :: vsm

Vector Space Model
module wallet

github :: wallet

Github OAuth tokens management
module wifi

android :: wifi

Simple wrapper of the Android WiFi services
module xml_entities

dom :: xml_entities

Basic blocks for DOM-XML representation
# Abstract services to serialize Nit objects to different formats
#
# This module declares the `serialize` annotation to mark Nit classes as serializable.
# For an introduction to this service, refer to the documentation of the `serialization` group.
# This documentation provides more technical information on interesting entitie of this module.
#
# Interesting entities for end users of serializable classes:
#
# * Serialize an instance subclass of `Serializable` with either
#   `Serializer::serializable` and `Serializable::serialize`.
# * Deserialize an object using `Deserializer::deserialize`.
#   The object type must the be checked with an `assert` or otherwise.
#
# Interesting entities to create custom serializable classes:
#
# * Subclass `Serializable` to declare a class as serializable and to customize
#   the serialization and deserialization behavior.
# * Redefine `Serializable::core_serialize_to` to customize the serialization
#   of the receiver class.
# * Redefine `Deserializer::deserialize_class` to customize the deserialization
#   of a specific class by name.
#
# Interesting entities for serialization format:
#
# * Subclass `Serializer` and `Deserializer` with custom serices.
# * In `Serializer`, `serialize` and `serialize_reference` must be redefined.
# * In `Deserializer`; `deserialize`, `deserialize_attribute and
#   `notify_of_creation` must be redefined.
module serialization_core is
	new_annotation auto_serializable
	new_annotation serialize
	new_annotation noserialize
	new_annotation serialize_as
end

intrude import core::queue
import meta

# Abstract serialization service to be sub-classed by specialized services.
interface Serializer
	# Entry point method of this service, serialize the `object`
	#
	# This method, and refinements, should handle `null` and probably
	# use double dispatch to customize the bahavior per serializable objects.
	fun serialize(object: nullable Serializable) is abstract

	# The object currently serialized by `serialized`
	#
	# Can be used by a custom serializer to add domain-specific serialization behavior.
	protected fun current_object: nullable Object is abstract

	# Serialize an object, with full serialization or a simple reference
	protected fun serialize_reference(object: Serializable) is abstract

	# Serialize an attribute to compose a serializable object
	#
	# This method should be called from `Serializable::core_serialize_to`.
	fun serialize_attribute(name: String, value: nullable Object)
	do
		if not try_to_serialize(value) then
			assert value != null # null would have been serialized
			warn("argument {name} of type {value.class_name} is not serializable.")
		end
	end

	# Serialize `value` is possible, i.e. it is `Serializable` or `null`
	fun try_to_serialize(value: nullable Object): Bool
	do
		if value isa Serializable then
			value.serialize_to_or_delay(self)
		else if value == null then
			serialize value
		else return false
		return true
	end

	# The method is called when a standard `value` is serialized
	#
	# The default behavior is to call `value.core_serialize_to(self)` but it
	# can be redefined by a custom serializer to add domain-specific serialization behavior.
	fun serialize_core(value: Serializable)
	do
		value.core_serialize_to(self)
	end

	# Warn of problems and potential errors (such as if an attribute
	# is not serializable)
	fun warn(msg: String) do print "Serialization warning: {msg}"
end

# Abstract deserialization service
#
# The main service is `deserialize`.
abstract class Deserializer
	# Deserialize and return an object, storing errors in the attribute `errors`
	#
	# If a `static_type` is given, only subtypes of the `static_type` are accepted.
	#
	# This method behavior varies according to the implementation engines.
	fun deserialize(static_type: nullable String): nullable Object is abstract

	# Deserialize the attribute with `name` from the object open for deserialization
	#
	# The `static_type` restricts what kind of object can be deserialized.
	#
	# Return the deserialized value or null on error, and set
	# `deserialize_attribute_missing` to whether the attribute was missing.
	#
	# Internal method to be implemented by the engines.
	fun deserialize_attribute(name: String, static_type: nullable String): nullable Object is abstract

	# Was the attribute queried by the last call to `deserialize_attribute` missing?
	var deserialize_attribute_missing = false

	# Register a newly allocated object (even if not completely built)
	#
	# Internal method called by objects in creation, to be implemented by the engines.
	fun notify_of_creation(new_object: Object) is abstract

	# Deserialize the next available object as an instance of `class_name`
	#
	# Return the deserialized object on success and
	# record in `errors` if `class_name` is unknown.
	#
	# This method should be redefined for each custom subclass of `Serializable`.
	# All refinement should look for a precise `class_name` and call super
	# on unsupported classes.
	protected fun deserialize_class(class_name: Text): nullable Object do
		if class_name == "Error" then return new Error.from_deserializer(self)
		return deserialize_class_intern(class_name)
	end

	# Generated service to deserialize the next available object as an instance of `class_name`
	#
	# Refinements to this method will be generated by the serialization phase.
	# To avoid conflicts, there should not be any other refinements to this method.
	# You can instead use `deserialize_class`.
	protected fun deserialize_class_intern(class_name: Text): nullable Object do
		errors.add new Error("Deserialization Error: Doesn't know how to deserialize class \"{class_name}\"")
		return null
	end

	# Should `self` keep trying to deserialize an object after an error?
	#
	# This behavior takes effect after each attribute deserialization with
	# errors such as a missing attribute or the value is of the wrong type.
	# If `keep_going`, the attribute will be skipped but the engine will
	# deserialize the next attribute.
	# If `not keep_going`, the engine stops deserializing right away.
	#
	# When at `true`, this may cause the accumulation of a lot of entries in `errors`.
	#
	# Default at `true`.
	var keep_going: nullable Bool = null is writable

	# Errors encountered in the last call to `deserialize`
	var errors = new Array[Error]
end

# Deserialization error related to an attribute of `receiver`
abstract class AttributeError
	super Error

	# Parent object of the problematic attribute
	var receiver: Object

	# Name of the problematic attribute in `receiver`
	var attribute_name: String
end

# Invalid dynamic type for a deserialized attribute
class AttributeTypeError
	super AttributeError

	autoinit receiver, attribute_name, attribute, expected_type

	# Deserialized object that isn't of the `expected_type`
	var attribute: nullable Object

	# Name of the type expected for `attribute`
	var expected_type: String

	redef var message is lazy do
		var attribute = attribute
		var found_type = if attribute != null then attribute.class_name else "null"

		return "Deserialization Error: {
		}Wrong type on `{receiver.class_name}::{attribute_name}` expected `{expected_type}`, got `{found_type}`"
	end
end

# Missing attribute at deserialization
class AttributeMissingError
	super AttributeError

	autoinit receiver, attribute_name

	redef var message is lazy do
		return "Deserialization Error: Missing attribute `{receiver.class_name}::{attribute_name}`"
	end
end

# Instances of this class can be passed to `Serializer::serialize`
interface Serializable
	# Serialize `self` to `serializer`
	#
	# This is a shortcut to `Serializer::serialize`.
	fun serialize_to(serializer: Serializer) do serializer.serialize(self)

	# Actual serialization of `self` to `serializer`
	#
	# This writes the full data of `self` to `serializer`.
	#
	# This method can be redefined in sub classes and refinements.
	# It should use `Serializer::serialize_attribute` to to register real or
	# logical attributes.
	#
	# Any refinement should have its equivalent refinement of
	# `Deserializer::deserialize_class` to support this custom deserialization.
	fun core_serialize_to(serializer: Serializer) do end

	# Accept references or force direct serialization (using `serialize_to`)
	#
	# The subclass change the default behavior, which will accept references,
	# to force to always serialize copies of `self`.
	private fun serialize_to_or_delay(v: Serializer) do v.serialize_reference(self)

	# Create an instance of this class from the `deserializer`
	#
	# This constructor is refined by subclasses to correctly build their instances.
	init from_deserializer(deserializer: Deserializer) is nosuper do end
end

# Instances of this class are not delayed and instead serialized immediately
# This applies mainly to `universal` types
interface DirectSerializable
	super Serializable

	redef fun serialize_to_or_delay(v) do serialize_to(v)
end

redef class Bool super DirectSerializable end
redef class Char super DirectSerializable end
redef class Byte super DirectSerializable end
redef class Int super DirectSerializable end
redef class Float super DirectSerializable end
redef class CString super DirectSerializable end
redef class Text super DirectSerializable end
redef class SimpleCollection[E] super Serializable end
redef class Map[K, V] super Serializable end

redef class Couple[F, S]
	super Serializable

	redef init from_deserializer(v)
	do
		v.notify_of_creation self
		var first = v.deserialize_attribute("first")
		var second = v.deserialize_attribute("second")
		init(first, second)
	end

	redef fun core_serialize_to(v)
	do
		v.serialize_attribute("first", first)
		v.serialize_attribute("second", second)
	end
end

redef class Ref[E]
	super Serializable

	redef init from_deserializer(v)
	do
		v.notify_of_creation self
		var item = v.deserialize_attribute("item")
		init item
	end

	redef fun core_serialize_to(v)
	do
		v.serialize_attribute("item", first)
	end
end

redef class Error
	super Serializable

	redef init from_deserializer(v)
	do
		v.notify_of_creation self

		var message = v.deserialize_attribute("message")
		if not message isa String then message = ""
		init message

		var cause = v.deserialize_attribute("cause")
		if cause isa nullable Error then self.cause = cause
	end

	redef fun core_serialize_to(v)
	do
		v.serialize_attribute("message", message)
		v.serialize_attribute("cause", cause)
	end
end

# ---
# core::queue classes

redef abstract class ProxyQueue[E]

	redef init from_deserializer(v)
	do
		v.notify_of_creation self

		var seq = v.deserialize_attribute("seq", (new GetName[Sequence[E]]).to_s)
		if not seq isa Sequence[E] then seq = new Array[E]
		if v.deserialize_attribute_missing then
			v.errors.add new AttributeMissingError(self, "seq")
		end

		init seq
	end

	redef fun core_serialize_to(v) do v.serialize_attribute("seq", seq)
end

redef class RandQueue[E]

	redef init from_deserializer(v)
	do
		v.notify_of_creation self

		var seq = v.deserialize_attribute("seq", (new GetName[SimpleCollection[E]]).to_s)
		if not seq isa SimpleCollection[E] then seq = new Array[E]
		if v.deserialize_attribute_missing then
			v.errors.add new AttributeMissingError(self, "seq")
		end

		init seq
	end

	redef fun core_serialize_to(v) do v.serialize_attribute("seq", seq)
end

redef class MinHeap[E]

	redef init from_deserializer(v)
	do
		v.notify_of_creation self

		var items = v.deserialize_attribute("items", (new GetName[SimpleCollection[E]]).to_s)
		if not items isa Array[E] then items = new Array[E]
		if v.deserialize_attribute_missing then
			v.errors.add new AttributeMissingError(self, "items")
		end

		var comparator = v.deserialize_attribute("comparator", "Comparator")
		if not comparator isa Comparator then comparator = default_comparator
		if v.deserialize_attribute_missing then
			v.errors.add new AttributeMissingError(self, "comparator")
		end

		init comparator
		self.items.add_all items
	end

	redef fun core_serialize_to(v)
	do
		v.serialize_attribute("items", items)
		v.serialize_attribute("comparator", comparator)
	end
end
lib/serialization/serialization_core.nit:17,1--390,3