Refine Serializable::inspect to show more useful information

Redefined classes

redef enum Bool

serialization :: inspect $ Bool

Native Booleans.
redef enum Byte

serialization :: inspect $ Byte

Native bytes.
redef extern class CString

serialization :: inspect $ CString

C string char *
redef enum Char

serialization :: inspect $ Char

Native characters.
redef interface Collection[E: nullable Object]

serialization :: inspect $ Collection

The root of the collection hierarchy.
redef enum Float

serialization :: inspect $ Float

Native floating point numbers.
redef enum Int

serialization :: inspect $ Int

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

serialization :: inspect $ Map

Maps are associative collections: key -> item.
redef interface Serializable

serialization :: inspect $ Serializable

Instances of this class can be passed to Serializer::serialize
redef interface SimpleCollection[E: nullable Object]

serialization :: inspect $ SimpleCollection

Items can be added to these collections.
redef class Sys

serialization :: inspect $ Sys

The main class of the program.
redef abstract class Text

serialization :: inspect $ Text

High-level abstraction for all text representations

All class definitions

redef enum Bool

serialization :: inspect $ Bool

Native Booleans.
redef enum Byte

serialization :: inspect $ Byte

Native bytes.
redef extern class CString

serialization :: inspect $ CString

C string char *
redef enum Char

serialization :: inspect $ Char

Native characters.
redef interface Collection[E: nullable Object]

serialization :: inspect $ Collection

The root of the collection hierarchy.
redef enum Float

serialization :: inspect $ Float

Native floating point numbers.
redef enum Int

serialization :: inspect $ Int

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

serialization :: inspect $ Map

Maps are associative collections: key -> item.
redef interface Serializable

serialization :: inspect $ Serializable

Instances of this class can be passed to Serializer::serialize
redef interface SimpleCollection[E: nullable Object]

serialization :: inspect $ SimpleCollection

Items can be added to these collections.
redef class Sys

serialization :: inspect $ Sys

The main class of the program.
redef abstract class Text

serialization :: inspect $ Text

High-level abstraction for all text representations
package_diagram serialization::inspect inspect serialization::caching caching serialization::inspect->serialization::caching serialization::engine_tools engine_tools serialization::caching->serialization::engine_tools ...serialization::engine_tools ... ...serialization::engine_tools->serialization::engine_tools serialization::serialization serialization serialization::serialization->serialization::inspect serialization::serialization... ... serialization::serialization...->serialization::serialization

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 engine_tools

serialization :: engine_tools

Advanced services for serialization engines
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 meta

meta :: meta

Simple user-defined meta-level to manipulate types of instances as object.
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 serialization_core

serialization :: serialization_core

Abstract services to serialize Nit objects to different formats
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 caching

serialization :: caching

Services for caching serialization engines

Children

module serialization

serialization :: serialization

General serialization services

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 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 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 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

android :: data_store

Implements app::data_store using shared_preferences
module data_store

app :: data_store

Key/value storage services
module data_store

linux :: data_store

app::data_store implementation on GNU/Linux
module data_store

ios :: data_store

Implements app::data_store using NSUserDefaults
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

json :: error

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

neo4j :: error

Errors thrown by the neo4j library.
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 ext

msgpack :: ext

Application specific MessagePack extension MsgPackExt
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

ios :: http_request

Implementation of app::http_request for iOS
module http_request

app :: http_request

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

linux :: http_request

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

nitcorn :: http_request

Provides the HttpRequest class and services to create it
module http_request

android :: http_request

Android implementation of app:http_request
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 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_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 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 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 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
# Refine `Serializable::inspect` to show more useful information
module inspect

import serialization_core
private import caching

private fun inspect_testing: Bool do return "NIT_TESTING".environ == "true"

# Serialization engine writing the object attributes to strings
private class InspectSerializer
	super CachingSerializer

	# Target writing stream
	var stream: Writer

	redef var current_object = null

	var first_object: nullable Object = null

	redef fun serialize(object)
	do
		if object == null then
			stream.write "null"
		else
			if current_object == null then
				first_object = object
			end

			var last_object = current_object
			current_object = object
			object.accept_inspect_serializer self
			current_object = last_object
		end
	end

	var first_attribute_serialized = false

	redef fun serialize_attribute(name, value)
	do
		if first_attribute_serialized then
			stream.write ", "
		else
			stream.write " "
			first_attribute_serialized = true
		end

		stream.write name
		stream.write ":"

		super
	end

	redef fun serialize_reference(object)
	do
		if cache.has_object(object) then
			# Cycle
			var id = object.object_id
			if inspect_testing then id = cache.id_for(object)

			stream.write "<"
			stream.write object.class_name
			stream.write "#"
			stream.write id.to_s
			stream.write ">"
		else if object != first_object and (not object isa DirectSerializable) then
			# Another object, print class and id only
			var id = object.object_id
			if inspect_testing then id = cache.new_id_for(object)

			stream.write "<"
			stream.write object.class_name
			stream.write "#"
			stream.write id.to_s
			stream.write ">"
		else
			# Main object
			serialize object
		end
	end
end

redef class Serializable

	# Improve the default inspection reading serializable attributes
	#
	# Simple immutable data are inspected as they would be written in Nit code.
	#
	# ~~~
	# assert 123.inspect == "123"
	# assert 1.5.inspect == "1.5"
	# assert 0xa1u8.inspect == "0xa1u8"
	# assert 'c'.inspect == "'c'"
	# assert "asdf\n".inspect == "\"asdf\\n\""
	# ~~~
	#
	# Inspections of mutable serializable objects show their dynamic type,
	# their `object_id` and their first level attributes. When testing,
	# the `object_id` is replaced by an id unique to each call to `inspect`.
	#
	# ~~~
	# class MyClass
	#     serialize
	#
	#     var i: Int
	#     var o: nullable Object
	# end
	#
	# var class_with_null = new MyClass(123)
	# assert class_with_null.to_s == class_with_null.inspect
	# assert class_with_null.to_s == "<MyClass#0 i:123, o:null>"
	#
	# var class_with_other = new MyClass(456, class_with_null)
	# assert class_with_other.to_s == "<MyClass#0 i:456, o:<MyClass#1>>"
	#
	# var class_with_cycle = new MyClass(789)
	# class_with_cycle.o = class_with_cycle
	# assert class_with_cycle.to_s == "<MyClass#0 i:789, o:<MyClass#0>>"
	# ~~~
	#
	# Items of collections are flattened and appended to the output.
	#
	# ~~~
	# assert [1, 2, 3].inspect == "<Array[Int]#0 [1, 2, 3]>"
	#
	# var set = new HashSet[Object].from([1, 1.5, "two": Object])
	# assert set.inspect == """<HashSet[Object]#0 [1, 1.5, "two"]>"""
	#
	# var map = new Map[Int, String]
	# map[1] = "one"
	# map[2] = "two"
	# assert map.inspect == """<HashMap[Int, String]#0 {1:"one", 2:"two"}>"""
	# ~~~
	#
	# Inspections producing over 80 characters are cut short.
	#
	# ~~~
	# var long_class = new MyClass(123456789, "Some " + "very "*8 + "long string")
	# assert long_class.to_s == "<MyClass#0 i:123456789, o:\"Some very very very very very very very very long s…>"
	# ~~~
	redef fun inspect
	do
		var stream = new StringWriter
		var serializer = new InspectSerializer(stream)
		serializer.serialize self
		stream.close
		var str = stream.to_s

		# Cut long inspects
		var max_length = 80
		if str.length > max_length then
			str = str.substring(0, max_length-2) + "…>"
		end

		return str
	end

	private fun accept_inspect_serializer(v: InspectSerializer)
	do
		v.stream.write "<"

		v.stream.write class_name
		v.stream.write "#"

		var id = object_id
		if inspect_testing then id = v.cache.new_id_for(self)
		v.stream.write id.to_s

		accept_inspect_serializer_core v

		v.stream.write ">"
	end

	private fun accept_inspect_serializer_core(v: InspectSerializer)
	do v.serialize_core(self)
end

redef class Int
	redef fun accept_inspect_serializer(v) do v.stream.write to_s
end

redef class Float
	redef fun accept_inspect_serializer(v) do v.stream.write to_s
end

redef class Bool
	redef fun accept_inspect_serializer(v) do v.stream.write to_s
end

redef class Char
	redef fun accept_inspect_serializer(v)
	do
		v.stream.write "'"
		v.stream.write to_s.escape_to_nit
		v.stream.write "'"
	end
end

redef class Byte
	redef fun accept_inspect_serializer(v)
	do
		v.stream.write to_s
		v.stream.write "u8"
	end
end

redef class CString
	redef fun accept_inspect_serializer_core(v)
	do
		v.stream.write " \""
		v.stream.write to_s.escape_to_nit
		v.stream.write_char '"'
	end
end

redef class Text

	redef fun accept_inspect_serializer(v)
	do
		v.stream.write "\""
		v.stream.write escape_to_nit
		v.stream.write "\""
	end
end

redef class Collection[E]
	private fun serialize_as_inspect(v: InspectSerializer)
	do
		v.stream.write "["
		var is_first = true
		for e in self do
			if is_first then
				is_first = false
			else
				v.stream.write ", "
			end

			if not v.try_to_serialize(e) then
				assert e != null
				v.stream.write e.inspect
			end
		end
		v.stream.write "]"
	end
end

redef class SimpleCollection[E]
	redef fun accept_inspect_serializer_core(v)
	do
		v.stream.write " "
		serialize_as_inspect v
	end
end

redef class Map[K, V]
	redef fun accept_inspect_serializer_core(v)
	do
		v.stream.write " \{"

		var first = true
		for key, val in self do
			if not first then
				v.stream.write ", "
			else first = false

			if not v.try_to_serialize(key) then
				assert key != null
				v.stream.write key.inspect
			end

			v.stream.write ":"

			if not v.try_to_serialize(val) then
				assert val != null
				v.stream.write val.inspect
			end
		end

		v.stream.write "\}"
	end
end
lib/serialization/inspect.nit:15,1--294,3