jk-jsonmodel 0.2024.3.13__py3-none-any.whl

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
@@ -0,0 +1,89 @@
1
+
2
+
3
+
4
+ import typing
5
+
6
+
7
+
8
+
9
+ class AbstractConstraint(object):
10
+
11
+ ################################################################################################################################
12
+ ## Constructor
13
+ ################################################################################################################################
14
+
15
+ ################################################################################################################################
16
+ ## Public Properties
17
+ ################################################################################################################################
18
+
19
+ ################################################################################################################################
20
+ ## Helper Methods
21
+ ################################################################################################################################
22
+
23
+ ################################################################################################################################
24
+ ## Public Methods
25
+ ################################################################################################################################
26
+
27
+ def __call__(self, value) -> typing.Union[str,None]:
28
+ raise NotImplementedError()
29
+ #
30
+
31
+ #
32
+
33
+
34
+
35
+
36
+ class _ConstraintSequence(AbstractConstraint):
37
+
38
+ ################################################################################################################################
39
+ ## Constructor
40
+ ################################################################################################################################
41
+
42
+ def __init__(self, sequence:typing.List[AbstractConstraint]) -> None:
43
+ self.__sequence = sequence
44
+ #
45
+
46
+ ################################################################################################################################
47
+ ## Public Properties
48
+ ################################################################################################################################
49
+
50
+ ################################################################################################################################
51
+ ## Helper Methods
52
+ ################################################################################################################################
53
+
54
+ ################################################################################################################################
55
+ ## Public Methods
56
+ ################################################################################################################################
57
+
58
+ def __call__(self, value) -> typing.Union[str,None]:
59
+ for c in self.__sequence:
60
+ s = c(value)
61
+ if s:
62
+ return s
63
+ return None
64
+ #
65
+
66
+ #
67
+
68
+
69
+
70
+ def _packConstraints(constraints:typing.Tuple[AbstractConstraint]) -> typing.Union[AbstractConstraint,None]:
71
+ assert isinstance(constraints, tuple)
72
+
73
+ if len(constraints) == 0:
74
+ return None
75
+
76
+ if len(constraints) == 1:
77
+ if not isinstance(constraints[0], AbstractConstraint):
78
+ raise Exception("Not a constraint: " + str(constraints[0]))
79
+ return constraints[0]
80
+
81
+ ret = []
82
+ for i, c in enumerate(constraints):
83
+ if not isinstance(c, AbstractConstraint):
84
+ raise Exception("Not a constraint at index {}: {}".format(i, str(c)))
85
+ ret.append(c)
86
+ return _ConstraintSequence(ret)
87
+ #
88
+
89
+
@@ -0,0 +1,29 @@
1
+
2
+
3
+ import typing
4
+
5
+
6
+
7
+
8
+ class JMLocation(typing.NamedTuple):
9
+ sourceID: typing.Union[str,None]
10
+ lineNo: int
11
+ charPos: int
12
+ jsonPath: str
13
+
14
+ @classmethod
15
+ def instantiate(cls, sourceID:typing.Union[str,None], lineNo:int, charPos:int, jsonPath:str):
16
+ if jsonPath.startswith("."):
17
+ jsonPath = jsonPath[1:]
18
+ return cls(sourceID, lineNo, charPos, jsonPath)
19
+ #
20
+
21
+ def __str__(self) -> str:
22
+ if self.sourceID:
23
+ return "{}:{}:{}".format(self.sourceID, self.lineNo + 1, self.charPos + 1)
24
+ else:
25
+ return "{}:{}".format(self.lineNo + 1, self.charPos + 1)
26
+ #
27
+
28
+ #
29
+
@@ -0,0 +1,172 @@
1
+
2
+
3
+ import os
4
+ import typing
5
+
6
+ import jk_typing
7
+ import jk_utils
8
+ import jk_logging
9
+ import jk_json
10
+ import jk_prettyprintobj
11
+
12
+ from .JMLocation import JMLocation
13
+ from .AbstractConstraint import AbstractConstraint
14
+ from .jclasses import AbstractJMElement, JMDict, JMValue, JMList
15
+ from . import constraints
16
+
17
+
18
+
19
+
20
+
21
+
22
+
23
+
24
+ class JMRetriever(object):
25
+
26
+ ################################################################################################################################
27
+ ## Constants
28
+ ################################################################################################################################
29
+
30
+ ################################################################################################################################
31
+ ## Constructor
32
+ ################################################################################################################################
33
+
34
+ ################################################################################################################################
35
+ ## Public Properties
36
+ ################################################################################################################################
37
+
38
+ ################################################################################################################################
39
+ ## Helper Methods
40
+ ################################################################################################################################
41
+
42
+ ################################################################################################################################
43
+ ## Public Methods
44
+ ################################################################################################################################
45
+
46
+ ################################################################################################################################
47
+ ## Public Static Methods
48
+ ################################################################################################################################
49
+
50
+ @staticmethod
51
+ def getValueE(jmData:JMDict, *keySequence:str, refPath:str = None) -> JMValue:
52
+ assert isinstance(jmData, JMDict)
53
+
54
+ if refPath is not None:
55
+ assert isinstance(refPath, str)
56
+ if keySequence:
57
+ raise Exception("Either specify a key sequence or a reference path!")
58
+ keySequence = refPath.split(".")
59
+
60
+ for i in range(0, len(keySequence) - 1):
61
+ key = keySequence[i]
62
+ assert isinstance(key, str)
63
+ if not key or (" " in key):
64
+ if refPath is not None:
65
+ raise Exception("Invalid reference path specified: " + repr(refPath))
66
+ else:
67
+ raise Exception("Invalid key specified: " + repr(key))
68
+ jmData = jmData.getDictE(key)
69
+
70
+ key = keySequence[-1]
71
+ if not key or (" " in key):
72
+ if refPath is not None:
73
+ raise Exception("Invalid reference path specified: " + repr(refPath))
74
+ else:
75
+ raise Exception("Invalid key specified: " + repr(key))
76
+ return jmData.getValueE(key)
77
+ #
78
+
79
+ @staticmethod
80
+ def getValueN(jmData:JMDict, *keySequence:str, refPath:str = None) -> typing.Union[JMValue,None]:
81
+ assert isinstance(jmData, JMDict)
82
+
83
+ if refPath is not None:
84
+ assert isinstance(refPath, str)
85
+ if keySequence:
86
+ raise Exception("Either specify a key sequence or a reference path!")
87
+ keySequence = refPath.split(".")
88
+
89
+ for i in range(0, len(keySequence) - 1):
90
+ key = keySequence[i]
91
+ assert isinstance(key, str)
92
+ if not key or (" " in key):
93
+ if refPath is not None:
94
+ raise Exception("Invalid reference path specified: " + repr(refPath))
95
+ else:
96
+ raise Exception("Invalid key specified: " + repr(key))
97
+ jmData = jmData.getDictN(key)
98
+ if jmData is None:
99
+ return None
100
+
101
+ key = keySequence[-1]
102
+ if not key or (" " in key):
103
+ if refPath is not None:
104
+ raise Exception("Invalid reference path specified: " + repr(refPath))
105
+ else:
106
+ raise Exception("Invalid key specified: " + repr(key))
107
+ return jmData.getValueN(key)
108
+ #
109
+
110
+ # --------------------------------------------------------------------------------------------------------------------------------
111
+
112
+ @staticmethod
113
+ def getStrE(jmData:JMDict, *keySequence:str, refPath:str = None) -> str:
114
+ v = JMRetriever.getValueE(jmData, *keySequence, refPath=refPath)
115
+ return v.vStrE()
116
+ #
117
+
118
+ @staticmethod
119
+ def getStrN(jmData:JMDict, *keySequence:str, refPath:str = None) -> typing.Union[str,None]:
120
+ v = JMRetriever.getValueN(jmData, *keySequence, refPath=refPath)
121
+ if v is None:
122
+ return None
123
+ return v.vStrN()
124
+ #
125
+
126
+ @staticmethod
127
+ def getIntE(jmData:JMDict, *keySequence:str, refPath:str = None) -> int:
128
+ v = JMRetriever.getValueE(jmData, *keySequence, refPath=refPath)
129
+ return v.vIntE()
130
+ #
131
+
132
+ @staticmethod
133
+ def getIntN(jmData:JMDict, *keySequence:str, refPath:str = None) -> typing.Union[int,None]:
134
+ v = JMRetriever.getValueN(jmData, *keySequence, refPath=refPath)
135
+ if v is None:
136
+ return None
137
+ return v.vIntN()
138
+ #
139
+
140
+ @staticmethod
141
+ def getFloatE(jmData:JMDict, *keySequence:str, refPath:str = None) -> float:
142
+ v = JMRetriever.getValueE(jmData, *keySequence, refPath=refPath)
143
+ return v.vFloatE()
144
+ #
145
+
146
+ @staticmethod
147
+ def getFloatN(jmData:JMDict, *keySequence:str, refPath:str = None) -> typing.Union[float,None]:
148
+ v = JMRetriever.getValueN(jmData, *keySequence, refPath=refPath)
149
+ if v is None:
150
+ return None
151
+ return v.vFloatN()
152
+ #
153
+
154
+ @staticmethod
155
+ def getBoolE(jmData:JMDict, *keySequence:str, refPath:str = None) -> bool:
156
+ v = JMRetriever.getValueE(jmData, *keySequence, refPath=refPath)
157
+ return v.vBoolE()
158
+ #
159
+
160
+ @staticmethod
161
+ def getBoolN(jmData:JMDict, *keySequence:str, refPath:str = None) -> typing.Union[bool,None]:
162
+ v = JMRetriever.getValueN(jmData, *keySequence, refPath=refPath)
163
+ if v is None:
164
+ return None
165
+ return v.vBoolN()
166
+ #
167
+
168
+ #
169
+
170
+
171
+
172
+
@@ -0,0 +1,276 @@
1
+
2
+
3
+ import typing
4
+ import math
5
+
6
+ import jk_json
7
+
8
+
9
+
10
+ from .JMLocation import JMLocation
11
+ from .jclasses import JMDict, JMValue, JMList, _JMProperty
12
+
13
+
14
+
15
+
16
+
17
+
18
+
19
+ class JsonParserRelaxedModel(jk_json.ParserBase):
20
+
21
+ ################################################################################################################################
22
+ ## Constructor
23
+ ################################################################################################################################
24
+
25
+ def __init__(self):
26
+ pass
27
+ #
28
+
29
+ ################################################################################################################################
30
+ ## Public Properties
31
+ ################################################################################################################################
32
+
33
+ ################################################################################################################################
34
+ ## Helper Methods
35
+ ################################################################################################################################
36
+
37
+ # @jk_json.debugDecorator
38
+ def _tryEat_S(self, ctx:jk_json.ParsingContext, ts:jk_json.TokenStream) -> typing.Tuple[bool,typing.Union[JMDict,JMList,None]]:
39
+ # loc = ts.location
40
+
41
+ n = ts.skipAll("eol", None)
42
+ hrPath:typing.List[str] = [ "" ]
43
+
44
+ bSuccess, parsedData = self._tryEat_JOBJECT(ctx, hrPath, ts)
45
+ if not bSuccess:
46
+ bSuccess, parsedData = self._tryEat_JARRAY(ctx, hrPath, ts)
47
+ if not bSuccess:
48
+ raise jk_json.ParserErrorException(ts.location, "Syntax error: Expecting valid JSON value element")
49
+
50
+ n = ts.skipAll("eol", None)
51
+
52
+ #if not ts.isEOS:
53
+ # raise ParserErrorException(ts.location, "Syntax error")
54
+
55
+ return (True, parsedData)
56
+ #
57
+
58
+ # @jk_json.debugDecorator
59
+ def _tryEat_JANYVALUE(self, ctx:jk_json.ParsingContext, hrPath:typing.List[str], ts:jk_json.TokenStream) -> typing.Tuple[bool,typing.Union[JMDict,JMList,JMValue,None]]:
60
+ # loc = ts.location
61
+
62
+ t1 = ts.peek()
63
+ _loc = JMLocation.instantiate(t1.sourceID, t1.lineNo, t1.charPos, "".join(hrPath))
64
+
65
+ if t1.type == "w":
66
+ if t1.text == "null":
67
+ ts.skip()
68
+ return (True, JMValue(_loc, None))
69
+ if t1.text == "true":
70
+ ts.skip()
71
+ return (True, JMValue(_loc, True))
72
+ if t1.text == "false":
73
+ ts.skip()
74
+ return (True, JMValue(_loc, False))
75
+ if t1.text == "Infinity":
76
+ ts.skip()
77
+ return (True, JMValue(_loc, math.inf))
78
+ if t1.text == "NaN":
79
+ ts.skip()
80
+ return (True, JMValue(_loc, math.nan))
81
+ raise jk_json.ParserErrorException(ts.location, "Syntax error: Expecting valid JSON value element")
82
+ if t1.type == "s":
83
+ ts.skip()
84
+ return (True, JMValue(_loc, t1.text))
85
+ if t1.type == "i":
86
+ ts.skip()
87
+ return (True, JMValue(_loc, int(t1.text)))
88
+ if t1.type == "f":
89
+ ts.skip()
90
+ return (True, JMValue(_loc, float(t1.text)))
91
+
92
+ bSuccess, parsedData = self._tryEat_JARRAY(ctx, hrPath, ts)
93
+ if bSuccess:
94
+ return (True, parsedData)
95
+
96
+ bSuccess, parsedData = self._tryEat_JOBJECT(ctx, hrPath, ts)
97
+ if bSuccess:
98
+ return (True, parsedData)
99
+
100
+ if (t1.type == "d") and (t1.text == "-"):
101
+ m = ts.mark()
102
+ ts.skip()
103
+ t2 = ts.peek()
104
+ if (t2.type == "w") and (t2.text == "Infinity"):
105
+ ts.skip()
106
+ return (True, float("-inf"))
107
+ m.resetToMark()
108
+
109
+ return (False, None)
110
+ #
111
+
112
+ # @jk_json.debugDecorator
113
+ def _tryEat_JARRAY(self, ctx:jk_json.ParsingContext, hrPath:typing.List[str], ts:jk_json.TokenStream) -> typing.Tuple[bool,typing.Union[JMList,None]]:
114
+ # loc = ts.location
115
+
116
+ t1 = ts.peek()
117
+ if (t1.type != "d") or (t1.text != "["):
118
+ return (False, None)
119
+ ts.skip()
120
+
121
+ bSuccess, _parsedData = self._tryEat_JVALUE_LIST(ctx, hrPath, ts)
122
+ _loc = JMLocation.instantiate(t1.sourceID, t1.lineNo, t1.charPos, "".join(hrPath))
123
+ if bSuccess:
124
+ parsedData = JMList(_loc, _parsedData)
125
+ else:
126
+ parsedData = JMList(_loc, [])
127
+
128
+ t1 = ts.peek()
129
+ if (t1.type != "d") or (t1.text != "]"):
130
+ raise jk_json.ParserErrorException(ts.location, "Syntax error: Expecting JSON array elements or ']'")
131
+ ts.skip()
132
+
133
+ return (True, parsedData)
134
+ #
135
+
136
+ # @jk_json.debugDecorator
137
+ def _tryEat_JVALUE_LIST(self, ctx:jk_json.ParsingContext, hrPath:typing.List[str], ts:jk_json.TokenStream) -> typing.Tuple[bool,typing.Union[list,None]]:
138
+ # loc = ts.location
139
+
140
+ retData = []
141
+
142
+ _index = 0
143
+ hrPath.append("[{}]".format(_index))
144
+ bSuccess, parsedData = self._tryEat_JANYVALUE(ctx, hrPath, ts)
145
+ hrPath.pop()
146
+ if not bSuccess:
147
+ return (False, None)
148
+ retData.append(parsedData)
149
+ _index += 1
150
+
151
+ while True:
152
+ t1 = ts.peek()
153
+ if (t1.type != "d") or (t1.text != ","):
154
+ return (True, retData)
155
+ ts.skip()
156
+
157
+ hrPath.append("[{}]".format(_index))
158
+ bSuccess, parsedData = self._tryEat_JANYVALUE(ctx, hrPath, ts)
159
+ hrPath.pop()
160
+ if not bSuccess:
161
+ return (True, retData)
162
+ retData.append(parsedData)
163
+ _index += 1
164
+ #
165
+
166
+ # @jk_json.debugDecorator
167
+ def _tryEat_JOBJECT(self, ctx:jk_json.ParsingContext, hrPath:typing.List[str], ts:jk_json.TokenStream) -> typing.Tuple[bool,typing.Union[JMDict,None]]:
168
+ # loc = ts.location
169
+
170
+ t1 = ts.peek()
171
+ if (t1.type != "d") or (t1.text != "{"):
172
+ return (False, None)
173
+ ts.skip()
174
+
175
+ hrPath.append(".")
176
+ bSuccess, _parsedData = self._tryEat_JPROPERTY_LIST(ctx, hrPath, ts)
177
+ hrPath.pop()
178
+ _loc = JMLocation.instantiate(t1.sourceID, t1.lineNo, t1.charPos, "".join(hrPath))
179
+ if bSuccess:
180
+ parsedData = JMDict(_loc, _parsedData)
181
+ else:
182
+ parsedData = JMDict(_loc, {})
183
+
184
+ t1 = ts.peek()
185
+ if (t1.type != "d") or (t1.text != "}"):
186
+ raise jk_json.ParserErrorException(ts.location, "Syntax error: Expecting JSON property or '}'")
187
+ ts.skip()
188
+
189
+ return (True, parsedData)
190
+ #
191
+
192
+ # @jk_json.debugDecorator
193
+ def _tryEat_JPROPERTY_LIST(self, ctx:jk_json.ParsingContext, hrPath:typing.List[str], ts:jk_json.TokenStream) -> typing.Tuple[bool,typing.Union[dict,None]]:
194
+ # loc = ts.location
195
+
196
+ retData = {}
197
+ bSuccess, parsedData = self._tryEat_JPROPERTY(ctx, hrPath, ts)
198
+ if not bSuccess:
199
+ return (False, None)
200
+
201
+ assert isinstance(parsedData, _JMProperty)
202
+ retData[parsedData._key] = parsedData
203
+
204
+ while True:
205
+ t1 = ts.peek()
206
+ if (t1.type != "d") or (t1.text != ","):
207
+ return (True, retData)
208
+ ts.skip()
209
+
210
+ bSuccess, parsedData = self._tryEat_JPROPERTY(ctx, hrPath, ts)
211
+ if not bSuccess:
212
+ return (True, retData)
213
+
214
+ assert isinstance(parsedData, _JMProperty)
215
+ if parsedData._key in retData:
216
+ if not ctx.allowDuplicatePropertyNames:
217
+ raise jk_json.ParserErrorException(ts.location, "Syntax error: Duplicate property key detected: " + repr(parsedData._key))
218
+ retData[parsedData._key] = parsedData
219
+ #
220
+
221
+ # @jk_json.debugDecorator
222
+ def _tryEat_JPROPERTY(self, ctx:jk_json.ParsingContext, hrPath:typing.List[str], ts:jk_json.TokenStream) -> typing.Tuple[bool,typing.Union[_JMProperty,None]]:
223
+ # loc = ts.location
224
+
225
+ t1 = ts.peek()
226
+ if t1.type != "s":
227
+ return (False, None)
228
+ ts.skip()
229
+
230
+ t2 = ts.peek()
231
+ if (t2.type != "d") or (t2.text != ":"):
232
+ raise jk_json.ParserErrorException(ts.location, "Syntax error: Expecting ':' followed by a property value!")
233
+ ts.skip()
234
+
235
+ hrPath.append(t1.text)
236
+ bSuccess, parsedData = self._tryEat_JANYVALUE(ctx, hrPath, ts)
237
+ if bSuccess:
238
+ _loc = JMLocation.instantiate(t1.sourceID, t1.lineNo, t1.charPos, "".join(hrPath))
239
+ hrPath.pop()
240
+ return (True, _JMProperty(_loc, t1.text, parsedData))
241
+ else:
242
+ hrPath.pop()
243
+
244
+ raise jk_json.ParserErrorException(ts.location, "Syntax error: Expecting a valid JSON value!")
245
+ #
246
+
247
+ ################################################################################################################################
248
+ ## Public Methods
249
+ ################################################################################################################################
250
+
251
+ #
252
+ # Parse the tokens. Construct an abstract syntax tree from the tokens provided by the tokenizer.
253
+ #
254
+ # @param Tokenizer tokenizer The tokenizer that provides the tokens.
255
+ #
256
+ def parse(self, tokenizer, bDebugging:bool = False, allowDuplicatePropertyNames:bool = False) -> typing.Union[JMDict,JMList,None]:
257
+ if isinstance(tokenizer, jk_json.TokenStream):
258
+ ts = tokenizer
259
+ else:
260
+ ts = jk_json.TokenStream(tokenizer)
261
+
262
+ ctx = jk_json.ParsingContext(bDebugging, allowDuplicatePropertyNames)
263
+ bSuccess, data = self._tryEat_S(ctx, ts)
264
+ if bSuccess:
265
+ return data
266
+ else:
267
+ raise Exception()
268
+ #
269
+
270
+ #
271
+
272
+
273
+
274
+
275
+
276
+