Commit 18fd3335 authored by Eckhart Arnold's avatar Eckhart Arnold

- simplified json generation

parent 0500646e
......@@ -88,20 +88,17 @@ CONFIG_PRESET['max_parser_dropouts'] = 3
# 'json' - output in JSON-format. This is probably the least
# readable representation, but useful for serialization, for
# example, to return syntax trees from remote procedure calls.
# 'simple-json' - a more readable JSON-format
# Default values: "compact" for concrete syntax trees and "XML" for abstract
# syntax trees and "S-expression" for any other kind of tree.
XML_SERIALIZATION = "XML"
SXPRESSION_SERIALIZATION = "S-expression"
COMPACT_SERIALIZATION = "compact"
JSON_SERIALIZATION = "json"
SIMPLE_JSON_SERIALIZATION = "simple-json"
SERIALIZATIONS = frozenset({XML_SERIALIZATION,
SXPRESSION_SERIALIZATION,
COMPACT_SERIALIZATION,
JSON_SERIALIZATION,
SIMPLE_JSON_SERIALIZATION})
JSON_SERIALIZATION})
CONFIG_PRESET['cst_serialization'] = COMPACT_SERIALIZATION
CONFIG_PRESET['ast_serialization'] = XML_SERIALIZATION
......
......@@ -41,7 +41,6 @@ from typing import Iterable, Iterator, Union, Dict, Tuple, List
from DHParser.preprocess import SourceMapFunc
from DHParser.stringview import StringView
from DHParser.toolkit import JSONSerializable, gen_id
__all__ = ('ErrorCode',
......@@ -59,8 +58,8 @@ class ErrorCode(int):
pass
class Error(JSONSerializable):
__slots__ = ['message', 'code', '_pos', 'orig_pos', 'line', 'column', '_id']
class Error:
__slots__ = ['message', 'code', '_pos', 'orig_pos', 'line', 'column']
# error levels
......@@ -112,15 +111,6 @@ class Error(JSONSerializable):
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
......@@ -143,25 +133,6 @@ class Error(JSONSerializable):
stop = document.find('\n', self.pos)
return document[start:stop] + '\n' + ' ' * (self.pos - start) + '^\n'
def to_json_obj(self) -> Dict:
"""Serialize Error object as json-object."""
return { '__class__': 'DHParser.Error',
'data': [self.message, self._pos, self.code, self.orig_pos,
self.line, self.column],
'id': self.id }
@staticmethod
def from_json_obj(json_obj: Dict) -> 'Error':
"""Convert a json object representing an Error object back into an
Error object. Raises a ValueError, if json_obj does not represent
an Error object"""
if json_obj.get('__class__', '') != 'DHParser.Error':
raise ValueError('JSON object: ' + str(json_obj) +
' does not represent an Error object.')
err = Error(*json_obj['data'])
err._id = json_obj['id']
return err
def is_warning(code: int) -> bool:
"""Returns True, if error is merely a warning."""
......
This diff is collapsed.
......@@ -70,9 +70,7 @@ __all__ = ('typing',
'sane_parser_name',
'GLOBALS',
'get_config_value',
'set_config_value',
'gen_id',
'JSONSerializable')
'set_config_value')
#######################################################################
......@@ -118,16 +116,16 @@ 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
# 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
#######################################################################
......@@ -471,28 +469,3 @@ except AttributeError:
# somebody has already taken care of this !?
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
......@@ -83,7 +83,7 @@ class TestParseJSON:
json_obj_tree = self.tree.to_json_obj()
# print(json.dumps(json_obj_tree, ensure_ascii=False, indent=2))
tree_copy = Node.from_json_obj(json_obj_tree)
assert tree_copy.equals(self.tree)
assert tree_copy.equals(self.tree), tree_copy.as_sxpr()
def test_json_rountrip(self):
s = self.tree.as_json(indent=None, ensure_ascii=True)
......
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