Commit aceb5bda authored by Eckhart Arnold's avatar Eckhart Arnold

- syntaxtree.py: general json serialization complete (but untested)

parent 7aa81606
......@@ -37,11 +37,12 @@ the string representations of the error objects. For example::
import bisect
from typing import Iterable, Iterator, Union, Dict, Tuple, List
from DHParser.preprocess import SourceMapFunc
from DHParser.stringview import StringView
from DHParser.toolkit import typing
from typing import Iterable, Iterator, Union, Dict, Tuple, List
from DHParser.toolkit import JSONSerializable, gen_id
__all__ = ('ErrorCode',
'Error',
......@@ -58,8 +59,8 @@ class ErrorCode(int):
pass
class Error:
__slots__ = ['message', 'code', '_pos', 'orig_pos', 'line', 'column']
class Error(JSONSerializable):
__slots__ = ['message', 'code', '_pos', 'orig_pos', 'line', 'column', '_id']
# error levels
......@@ -111,6 +112,15 @@ class Error:
return 'Error("%s", %s, %i, %i, %i, %i)' \
% (self.message, repr(self.code), self.pos, self.orig_pos, self.line, self.column)
@property
def id(self) -> int:
"""Returns the unique id of the Error."""
try:
return self._id
except AttributeError:
self._id = gen_id()
return self._id
@property
def pos(self):
return self._pos
......@@ -137,7 +147,8 @@ class Error:
"""Serialize Error object as json-object."""
return { '__class__': 'DHParser.Error',
'data': [self.message, self._pos, self.code, self.orig_pos,
self.line, self.column] }
self.line, self.column],
'id': self.id }
@staticmethod
def from_json_obj(json_obj: Dict) -> 'Error':
......@@ -147,7 +158,9 @@ class Error:
if json_obj.get('__class__', '') != 'DHParser.Error':
raise ValueError('JSON object: ' + str(json_obj) +
' does not represent an Error object.')
return Error(*json_obj['data'])
err = Error(*json_obj['data'])
err._id = json_obj['id']
return err
def is_warning(code: int) -> bool:
......
......@@ -50,7 +50,7 @@ import sys
import time
from typing import Callable, Coroutine, Optional, Union, Dict, List, Tuple, Sequence, Set, cast
from DHParser.syntaxtree import Node_JSONEncoder
from DHParser.syntaxtree import DHParser_JSONEncoder
from DHParser.toolkit import get_config_value, re
__all__ = ('RPC_Table',
......@@ -319,7 +319,7 @@ class Server:
if rpc_error is None:
json_result = {"jsonrpc": "2.0", "result": result, "id": json_id}
writer.write(json.dumps(json_result, cls=Node_JSONEncoder).encode())
writer.write(json.dumps(json_result, cls=DHParser_JSONEncoder).encode())
else:
writer.write(('{"jsonrpc": "2.0", "error": {"code": %i, "message": "%s"}, "id": %s}'
% (rpc_error[0], rpc_error[1], json_id)).encode())
......
This diff is collapsed.
......@@ -70,7 +70,9 @@ __all__ = ('typing',
'sane_parser_name',
'GLOBALS',
'get_config_value',
'set_config_value')
'set_config_value',
'gen_id',
'JSONSerializable')
#######################################################################
......@@ -116,6 +118,18 @@ def set_config_value(key: Hashable, value: Any):
GLOBALS.config[key] = value
global_id_counter = multiprocessing.Value('Q', 0)
def gen_id() -> int:
"""Generates a unique id."""
global global_id_counter
with global_id_counter.get_lock():
next_id = global_id_counter.value + 1
global_id_counter.value = next_id
return next_id
#######################################################################
#
# miscellaneous (generic)
......@@ -458,3 +472,27 @@ except AttributeError:
pass
#######################################################################
#
# Serialization
#
#######################################################################
class JSONSerializable:
"""
JSONSerializable is an Interface for objects that can be serialized
as json-objects.
"""
def to_json_obj(self) -> Dict:
"""Serialize object as json-object."""
raise NotImplementedError
@staticmethod
def from_json_obj(json_obj: Dict) -> 'JSONSerializable':
"""Convert a json object representing a JSONSerializable back into
an JSONSerializable-object. Raises a ValueError, if json_obj does
not represent an instance of the (sub-)class from which this method
has been called."""
raise NotImplementedError
Markdown is supported
0% or
You are about to add 0 people to the discussion. Proceed with caution.
Finish editing this message first!
Please register or to comment