curly-message 1.0.0rc0__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,61 @@
1
+ """The Curly Message Format, version 3 (``curly-message-3``)."""
2
+
3
+ from ._cst import cst
4
+ from ._modifiers import levels
5
+ from ._resolve import create_parser
6
+ from ._types import (
7
+ MAX_CONVERSION_NODES,
8
+ MAX_NESTING,
9
+ MAX_OUTPUT_LENGTH,
10
+ MAX_READ_LENGTH,
11
+ MAX_REENTRY,
12
+ UNDEFINED,
13
+ CstEscape,
14
+ CstMessage,
15
+ CstName,
16
+ CstNode,
17
+ CstOptionValue,
18
+ CstPlaceholder,
19
+ CstPunctuation,
20
+ CstSpace,
21
+ CstText,
22
+ Modifier,
23
+ ModifierInput,
24
+ Option,
25
+ Parser,
26
+ ReentryLimitError,
27
+ Report,
28
+ ReportCode,
29
+ ReportOrigin,
30
+ Undefined,
31
+ )
32
+
33
+ __all__ = [
34
+ "MAX_CONVERSION_NODES",
35
+ "MAX_NESTING",
36
+ "MAX_OUTPUT_LENGTH",
37
+ "MAX_READ_LENGTH",
38
+ "MAX_REENTRY",
39
+ "UNDEFINED",
40
+ "CstEscape",
41
+ "CstMessage",
42
+ "CstName",
43
+ "CstNode",
44
+ "CstOptionValue",
45
+ "CstPlaceholder",
46
+ "CstPunctuation",
47
+ "CstSpace",
48
+ "CstText",
49
+ "Modifier",
50
+ "ModifierInput",
51
+ "Option",
52
+ "Parser",
53
+ "ReentryLimitError",
54
+ "Report",
55
+ "ReportCode",
56
+ "ReportOrigin",
57
+ "Undefined",
58
+ "create_parser",
59
+ "cst",
60
+ "levels",
61
+ ]
@@ -0,0 +1,315 @@
1
+ """The value model of section 4: what a host value is as text.
2
+
3
+ Everything the format carries is text. A plain ``dict`` and a plain ``list``
4
+ become JSON, so a host-defined modifier can read them back, and every other
5
+ value becomes what ``str`` makes of it.
6
+ """
7
+
8
+ from __future__ import annotations
9
+
10
+ import json.encoder
11
+ import math
12
+ from collections.abc import Iterator
13
+ from typing import Any, Final, cast
14
+
15
+ from ._types import MAX_CONVERSION_NODES, UNDEFINED
16
+ from ._utils import MISSING, WHITESPACE_CHARS
17
+
18
+ Conversions = dict[int, tuple[object, str | None]]
19
+ """What each value a resolution read came out as, by identity.
20
+
21
+ The record holds the value itself beside its text, so an identity cannot be
22
+ reused by another value while the resolution that recorded it runs.
23
+ """
24
+
25
+ WrapperParts = tuple[object, object, object]
26
+ """A wrapper's own ``value``, ``default`` and ``props``, each ``MISSING`` where it holds none."""
27
+
28
+ Wrappers = dict[int, tuple[object, WrapperParts | None]]
29
+ """Which entries a resolution asked about are wrappers, by identity."""
30
+
31
+ _encode: Final = json.encoder.encode_basestring
32
+
33
+ _END: Final = object()
34
+
35
+ MAX_CONVERSION_LENGTH: Final = 10_000_000
36
+ """Code points one serialization may write before it is abandoned.
37
+
38
+ The node limit bounds what a serialization visits and not what it writes: a
39
+ list naming one long string a thousand times visits a thousand and one nodes.
40
+ This bound is a hundred code points for each node the limit allows, where
41
+ JavaScript's serialization gives up at its engine's longest string.
42
+ """
43
+
44
+
45
+ _REMEMBERED_LENGTH: Final = 64
46
+ """The longest string encoded where it is met: one looked up costs about what encoding it does."""
47
+
48
+ _REMEMBERED_BITS: Final = 256
49
+ """The widest integer written where it is met, as for a string."""
50
+
51
+
52
+ class _UnserializableError(ValueError):
53
+ pass
54
+
55
+
56
+ def _key(key: object) -> str:
57
+ """A member's name as ``json`` spells it, which coerces a scalar and refuses the rest."""
58
+ if issubclass(type(key), str):
59
+ return _encode(str.__str__(key))
60
+ if issubclass(type(key), float):
61
+ return _encode(_float(key)) # type: ignore[arg-type]
62
+ if key is True:
63
+ return '"true"'
64
+ if key is False:
65
+ return '"false"'
66
+ if key is None:
67
+ return '"null"'
68
+ if issubclass(type(key), int):
69
+ return _encode(int.__repr__(key))
70
+ raise _UnserializableError("a key json cannot name")
71
+
72
+
73
+ def _float(value: float) -> str:
74
+ if not math.isfinite(value):
75
+ raise _UnserializableError("JSON holds no such number")
76
+ return float.__repr__(value)
77
+
78
+
79
+ def _serialize(root: object) -> str:
80
+ """``json.dumps(root, ensure_ascii=False, separators=(",", ":"), allow_nan=False)``.
81
+
82
+ Written out rather than called for two reasons: ``json`` cannot count the
83
+ nodes it visits, and its encoder recurses, so a value nested deep raises
84
+ ``RecursionError`` instead of serializing. Containers are read through
85
+ their base types' own storage, so no override runs. ``UNDEFINED`` is
86
+ ECMAScript's undefined, which ``json`` cannot describe: a member holding
87
+ it is left out of its object, key and all, and an element holding it is
88
+ written ``null``. Every value visited, the root and each member at each
89
+ time it is reached, a member left out among them, spends a node
90
+ (section 13), and every code point written spends a place of
91
+ ``MAX_CONVERSION_LENGTH``. A long string or a wide integer met again is
92
+ written from its first encoding rather than encoded again, so a leaf named
93
+ many times costs its encoding once.
94
+ """
95
+ parts: list[str] = []
96
+ room = MAX_CONVERSION_LENGTH
97
+ # By identity, beside the value itself, as a resolution records its
98
+ # conversions.
99
+ encoded: dict[int, tuple[object, str]] = {}
100
+ ancestors: set[int] = set()
101
+ # Each open container: its members still to write, whether it is an
102
+ # object, its identity, and whether it has written a member yet.
103
+ frames: list[list[Any]] = []
104
+ budget = MAX_CONVERSION_NODES
105
+ value = root
106
+ while True:
107
+ budget -= 1
108
+ if budget < 0:
109
+ raise _UnserializableError("the value visits more nodes than a conversion may")
110
+ kind = type(value)
111
+ piece: str | None = None
112
+ if issubclass(kind, str):
113
+ if str.__len__(value) <= _REMEMBERED_LENGTH: # type: ignore[arg-type]
114
+ piece = _encode(str.__str__(value))
115
+ else:
116
+ known = encoded.get(id(value))
117
+ if known is not None:
118
+ piece = known[1]
119
+ else:
120
+ # The encoding is never shorter than the text and its
121
+ # quotes, so a text with no room is not encoded at all.
122
+ if str.__len__(value) + 2 > room: # type: ignore[arg-type]
123
+ raise _UnserializableError("the value writes more than a conversion may")
124
+ piece = _encode(str.__str__(value))
125
+ encoded[id(value)] = (value, piece)
126
+ elif value is True:
127
+ piece = "true"
128
+ elif value is False:
129
+ piece = "false"
130
+ elif issubclass(kind, int):
131
+ if int.bit_length(value) <= _REMEMBERED_BITS: # type: ignore[arg-type]
132
+ piece = int.__repr__(value)
133
+ else:
134
+ known = encoded.get(id(value))
135
+ if known is not None:
136
+ piece = known[1]
137
+ else:
138
+ piece = int.__repr__(value)
139
+ encoded[id(value)] = (value, piece)
140
+ elif value is None or (value is UNDEFINED and frames):
141
+ piece = "null"
142
+ elif issubclass(kind, float):
143
+ piece = _float(value) # type: ignore[arg-type]
144
+ if piece is not None:
145
+ room -= len(piece)
146
+ parts.append(piece)
147
+ elif issubclass(kind, (list, tuple, dict)):
148
+ identity = id(value)
149
+ if identity in ancestors:
150
+ raise _UnserializableError("the value holds itself")
151
+ ancestors.add(identity)
152
+ members: Iterator[Any]
153
+ if issubclass(kind, dict):
154
+ members = iter(dict.items(value)) # type: ignore[arg-type]
155
+ parts.append("{")
156
+ room -= 1
157
+ else:
158
+ members = (
159
+ list.__iter__(value) # type: ignore[arg-type]
160
+ if issubclass(kind, list)
161
+ else tuple.__iter__(value) # type: ignore[arg-type]
162
+ )
163
+ parts.append("[")
164
+ room -= 1
165
+ frames.append([members, issubclass(kind, dict), identity, False])
166
+ else:
167
+ raise _UnserializableError("a value json cannot describe")
168
+ while frames:
169
+ if room < 0:
170
+ raise _UnserializableError("the value writes more than a conversion may")
171
+ frame = frames[-1]
172
+ member = next(frame[0], _END)
173
+ if member is _END:
174
+ frames.pop()
175
+ ancestors.discard(frame[2])
176
+ parts.append("}" if frame[1] else "]")
177
+ room -= 1
178
+ continue
179
+ if frame[1]:
180
+ name, value = cast(tuple[object, object], member)
181
+ if value is UNDEFINED:
182
+ budget -= 1
183
+ if budget < 0:
184
+ raise _UnserializableError(
185
+ "the value visits more nodes than a conversion may"
186
+ )
187
+ continue
188
+ if frame[3]:
189
+ parts.append(",")
190
+ room -= 1
191
+ frame[3] = True
192
+ # A name writes at least itself, its quotes and its colon.
193
+ if issubclass(type(name), str) and str.__len__(name) + 3 > room: # type: ignore[arg-type]
194
+ raise _UnserializableError("the value writes more than a conversion may")
195
+ key = _key(name)
196
+ parts.append(key)
197
+ parts.append(":")
198
+ room -= len(key) + 1
199
+ else:
200
+ if frame[3]:
201
+ parts.append(",")
202
+ room -= 1
203
+ frame[3] = True
204
+ value = member
205
+ break
206
+ else:
207
+ if room < 0:
208
+ raise _UnserializableError("the value writes more than a conversion may")
209
+ return "".join(parts)
210
+
211
+
212
+ def serialize(value: object) -> str | None:
213
+ """A plain value's JSON, or ``None`` where no serialization describes it."""
214
+ try:
215
+ return _serialize(value)
216
+ except Exception:
217
+ return None
218
+
219
+
220
+ def _string(value: object) -> str | None:
221
+ """The host's ordinary string conversion, or ``None`` where it raises."""
222
+ try:
223
+ converted = str(value)
224
+ except Exception:
225
+ return None
226
+ # `str` hands back a subclass where `__str__` answers one, and the text is
227
+ # what the format carries rather than the type it came in.
228
+ return converted if type(converted) is str else str.__str__(converted)
229
+
230
+
231
+ def text(value: object, conversions: Conversions) -> str | None:
232
+ """The text a value resolves to, or ``None``: no value, or one no conversion describes.
233
+
234
+ A conversion that runs host code, or costs a walk, is recorded for the
235
+ resolution, so a value is converted once however many placeholders read it
236
+ and every later read answers with the first answer (section 13). A
237
+ built-in scalar runs no host code and answers the same every time, so it is
238
+ not recorded.
239
+ """
240
+ if value is UNDEFINED or value is MISSING:
241
+ return None
242
+ kind = type(value)
243
+ if kind is str:
244
+ return value # type: ignore[return-value]
245
+ if kind is int:
246
+ try:
247
+ return str(value)
248
+ except ValueError:
249
+ # Past the host's limit on the digits it converts.
250
+ return None
251
+ if kind is float or kind is bool or value is None:
252
+ return str(value)
253
+ identity = id(value)
254
+ known = conversions.get(identity)
255
+ if known is not None:
256
+ return known[1]
257
+ converted = serialize(value) if kind is dict or kind is list else _string(value)
258
+ conversions[identity] = (value, converted)
259
+ return converted
260
+
261
+
262
+ def wrapper_parts(entry: object, wrappers: Wrappers) -> WrapperParts | None:
263
+ """An entry's own ``value``, ``default`` and ``props`` where it is a wrapper (section 4.1).
264
+
265
+ A wrapper is a plain ``dict`` whose every own key names one of those three,
266
+ and which holds at least one. A key that is not a ``str`` names none of
267
+ them, so a ``dict`` holding one is a value. Enumerating costs what the
268
+ entry holds, so the verdict is recorded for the resolution the way a
269
+ conversion is.
270
+ """
271
+ if type(entry) is not dict:
272
+ return None
273
+ identity = id(entry)
274
+ known = wrappers.get(identity)
275
+ if known is not None:
276
+ return known[1]
277
+ parts: list[object] = [MISSING, MISSING, MISSING]
278
+ named = False
279
+ verdict: WrapperParts | None = None
280
+ for key, member in dict.items(entry):
281
+ slot = _WRAPPED.get(str.__str__(key)) if issubclass(type(key), str) else None
282
+ if slot is None:
283
+ named = False
284
+ break
285
+ if parts[slot] is MISSING:
286
+ parts[slot] = member
287
+ named = True
288
+ if named:
289
+ verdict = (parts[0], parts[1], parts[2])
290
+ wrappers[identity] = (entry, verdict)
291
+ return verdict
292
+
293
+
294
+ _WRAPPED: Final = {"value": 0, "default": 1, "props": 2}
295
+
296
+
297
+ def to_number(value: str) -> float | None:
298
+ """The host's ordinary numeric conversion of text, or ``None`` where it yields no number.
299
+
300
+ The format's whitespace class is stripped first, since it is not part of a
301
+ number and ``float`` strips only its own. What ``float`` would skip beyond
302
+ the class, ``U+0085`` among it, is part of the text, so text that begins
303
+ or ends with it is no number; every code point ``float`` skips is one
304
+ ``str.isspace`` holds.
305
+ NaN is no number: left in, it compares false to everything, and an
306
+ ordering would freeze around it.
307
+ """
308
+ text = value.strip(WHITESPACE_CHARS)
309
+ try:
310
+ number = float(text)
311
+ except ValueError:
312
+ return None
313
+ if math.isnan(number) or text[0].isspace() or text[-1].isspace():
314
+ return None
315
+ return number
curly_message/_cst.py ADDED
@@ -0,0 +1,167 @@
1
+ """``cst``: the tree a message is described by (CST.md)."""
2
+
3
+ from __future__ import annotations
4
+
5
+ from typing import Literal, cast
6
+
7
+ from ._types import (
8
+ CstEscape,
9
+ CstMessage,
10
+ CstName,
11
+ CstOptionValue,
12
+ CstPlaceholder,
13
+ CstPunctuation,
14
+ CstSpace,
15
+ CstText,
16
+ )
17
+ from ._utils import Scanner, cancels, separated, trimmed, unesc
18
+
19
+ _Contents = list[CstText | CstEscape | CstPlaceholder]
20
+
21
+ # The option values described but not yet filled, each with the range it is
22
+ # filled from. Nesting is not otherwise limited (section 6, note 10), so a value
23
+ # is filled off this stack rather than by a call per level.
24
+ _Pending = list[tuple[_Contents, int, int]]
25
+
26
+
27
+ def _spelled(message: str, from_: int, to: int) -> list[CstText | CstEscape]:
28
+ """Text with every escape sequence in it marked.
29
+
30
+ Section 7's rule is uniform over the message, so the same reading serves a
31
+ message, a name and an option value. A backslash with nothing left to
32
+ consume denotes itself and is text.
33
+ """
34
+ nodes: list[CstText | CstEscape] = []
35
+ start = from_
36
+ index = message.find("\\", from_, to)
37
+ while 0 <= index < to - 1:
38
+ if index > start:
39
+ nodes.append({"type": "text", "start": start, "end": index})
40
+ end = index + 2
41
+ nodes.append(
42
+ {"type": "escape", "start": index, "end": end, "cancels": cancels(message[index + 1])}
43
+ )
44
+ start = end
45
+ index = message.find("\\", end, to)
46
+ if to > start:
47
+ nodes.append({"type": "text", "start": start, "end": to})
48
+ return nodes
49
+
50
+
51
+ def _space(from_: int, to: int) -> CstSpace:
52
+ return {"type": "space", "start": from_, "end": to}
53
+
54
+
55
+ def _separator(at: int) -> CstPunctuation:
56
+ return {"type": "separator", "start": at, "end": at + 1}
57
+
58
+
59
+ _Parts = list[CstPunctuation | CstSpace | CstName | CstOptionValue]
60
+
61
+
62
+ def _named(
63
+ message: str,
64
+ kind: Literal["key", "modifier", "option-key"],
65
+ from_: int,
66
+ to: int,
67
+ nodes: _Parts,
68
+ ) -> None:
69
+ """A name and the padding it is read without, which are nodes of their own."""
70
+ start, end = trimmed(message, from_, to)
71
+ if start > from_:
72
+ nodes.append(_space(from_, start))
73
+ nodes.append(
74
+ {
75
+ "type": kind,
76
+ "start": start,
77
+ "end": end,
78
+ "name": unesc(message[start:end]),
79
+ "nodes": _spelled(message, start, end),
80
+ }
81
+ )
82
+ if to > end:
83
+ nodes.append(_space(end, to))
84
+
85
+
86
+ def _valued(
87
+ message: str,
88
+ from_: int,
89
+ to: int,
90
+ nodes: _Parts,
91
+ pending: _Pending,
92
+ ) -> None:
93
+ """An option value and its padding; what it holds is left on ``pending``."""
94
+ start, end = trimmed(message, from_, to)
95
+ contents: _Contents = []
96
+ pending.append((contents, start, end))
97
+ if start > from_:
98
+ nodes.append(_space(from_, start))
99
+ nodes.append({"type": "option-value", "start": start, "end": end, "nodes": contents})
100
+ if to > end:
101
+ nodes.append(_space(end, to))
102
+
103
+
104
+ def _placeholder(
105
+ message: str, scan: Scanner, open_: int, close: int, pending: _Pending
106
+ ) -> CstPlaceholder:
107
+ nodes: _Parts = [{"type": "open", "start": open_, "end": open_ + 2}]
108
+ # A `;` a nested placeholder encloses divides that placeholder and not this
109
+ # one (section 6, note 5).
110
+ declaration, *options = separated(message, open_ + 2, close - 2, ";", scan)
111
+ # The selector's colon is the first one no escape claims; a later colon is
112
+ # part of the modifier name (note 3).
113
+ key, *modifier = separated(message, declaration[0], declaration[1], ":")
114
+ _named(message, "key", key[0], key[1], nodes)
115
+ if modifier:
116
+ nodes.append(_separator(key[1]))
117
+ _named(message, "modifier", key[1] + 1, declaration[1], nodes)
118
+ for from_, to in options:
119
+ # The `;` that opened this segment sits immediately before it.
120
+ nodes.append(_separator(from_ - 1))
121
+ option_key, *value = separated(message, from_, to, ":", scan)
122
+ _named(message, "option-key", option_key[0], option_key[1], nodes)
123
+ # A segment stating no value stands for its own key (section 9.4), so
124
+ # there is no value to describe.
125
+ if value:
126
+ nodes.append(_separator(option_key[1]))
127
+ _valued(message, option_key[1] + 1, to, nodes, pending)
128
+ nodes.append({"type": "close", "start": close - 2, "end": close})
129
+ return {"type": "placeholder", "start": open_, "end": close, "nodes": nodes}
130
+
131
+
132
+ def _contents(
133
+ message: str, scan: Scanner, nodes: _Contents, from_: int, to: int, *, pending: _Pending
134
+ ) -> None:
135
+ """What a range of the message holds: its text, its escapes and its placeholders."""
136
+ at = from_
137
+ found = scan.next(at, to)
138
+ while found is not None:
139
+ open_, close = found
140
+ nodes.extend(_spelled(message, at, open_))
141
+ nodes.append(_placeholder(message, scan, open_, close, pending))
142
+ at = close
143
+ found = scan.next(at, to)
144
+ nodes.extend(_spelled(message, at, to))
145
+
146
+
147
+ def cst(message: object) -> CstMessage:
148
+ """Describe a message: its placeholders, what each is made of, and every escape.
149
+
150
+ Spans count code points. The placeholders are the ones resolution finds,
151
+ because the same scanner finds them; a construct that derives nothing is
152
+ text. A message that is not a ``str`` has no characters to describe and
153
+ carries no parts. Like the rest of the tree, the answer is plain dicts and
154
+ lists, so ``json.dumps(cst(message))`` is the interchange encoding of
155
+ CST.md, section 8.
156
+ """
157
+ if not issubclass(type(message), str):
158
+ return {"type": "message", "start": 0, "end": 0, "nodes": []}
159
+ # A subclass is read through `str`'s own storage, so no override runs.
160
+ text = str.__str__(cast(str, message))
161
+ scan = Scanner(text)
162
+ nodes: _Contents = []
163
+ pending: _Pending = [(nodes, 0, len(text))]
164
+ while pending:
165
+ into, from_, to = pending.pop()
166
+ _contents(text, scan, into, from_, to, pending=pending)
167
+ return {"type": "message", "start": 0, "end": len(text), "nodes": nodes}