libyay 1.0.0__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.
libyay/__init__.py ADDED
@@ -0,0 +1,12 @@
1
+ """
2
+ YAY - Yet Another YAML
3
+
4
+ A Python parser and serializer for the YAY data format.
5
+ """
6
+
7
+ from .parser import load, loads
8
+ from .dumper import dump, dumps
9
+ from .errors import YayError, YaySyntaxError
10
+
11
+ __all__ = ["load", "loads", "dump", "dumps", "YayError", "YaySyntaxError"]
12
+ __version__ = "1.0.0"
libyay/dumper.py ADDED
@@ -0,0 +1,180 @@
1
+ """
2
+ YAY dumper - serializes Python objects to YAY format.
3
+ """
4
+
5
+ import math
6
+ import re
7
+ from typing import Any, TextIO
8
+
9
+
10
+ def _is_simple_key(key: str) -> bool:
11
+ """Check if a key can be written without quotes."""
12
+ if not key:
13
+ return False
14
+ if not (key[0].isalpha() or key[0] == "_"):
15
+ return False
16
+ return all(c.isalnum() or c == "_" for c in key)
17
+
18
+
19
+ def _needs_double_quote(s: str) -> bool:
20
+ """Check if string needs double quotes (has escapes)."""
21
+ for ch in s:
22
+ if ch in "\n\r\t\b\f\\":
23
+ return True
24
+ if ord(ch) < 0x20:
25
+ return True
26
+ return False
27
+
28
+
29
+ def _escape_double_quoted(s: str) -> str:
30
+ """Escape a string for double-quoted output."""
31
+ result = []
32
+ for ch in s:
33
+ if ch == '"':
34
+ result.append('\\"')
35
+ elif ch == "\\":
36
+ result.append("\\\\")
37
+ elif ch == "\n":
38
+ result.append("\\n")
39
+ elif ch == "\r":
40
+ result.append("\\r")
41
+ elif ch == "\t":
42
+ result.append("\\t")
43
+ elif ch == "\b":
44
+ result.append("\\b")
45
+ elif ch == "\f":
46
+ result.append("\\f")
47
+ elif ord(ch) < 0x20:
48
+ result.append(f"\\u{ord(ch):04x}")
49
+ else:
50
+ result.append(ch)
51
+ return "".join(result)
52
+
53
+
54
+ def _escape_single_quoted(s: str) -> str:
55
+ """Escape a string for single-quoted output."""
56
+ return s.replace("'", "''")
57
+
58
+
59
+ def _format_value(value: Any, indent: int = 0, inline: bool = False) -> str:
60
+ """Format a value as YAY."""
61
+ prefix = " " * indent
62
+
63
+ if value is None:
64
+ return "null"
65
+
66
+ if isinstance(value, bool):
67
+ return "true" if value else "false"
68
+
69
+ if isinstance(value, int):
70
+ return str(value)
71
+
72
+ if isinstance(value, float):
73
+ if math.isnan(value):
74
+ return "nan"
75
+ if math.isinf(value):
76
+ return "-infinity" if value < 0 else "infinity"
77
+ # Format float to preserve distinction from int
78
+ s = repr(value)
79
+ # Ensure there's a decimal point
80
+ if "." not in s and "e" not in s and "E" not in s:
81
+ s += ".0"
82
+ return s
83
+
84
+ if isinstance(value, str):
85
+ if _needs_double_quote(value):
86
+ return f'"{_escape_double_quoted(value)}"'
87
+ else:
88
+ # Prefer single quotes for simple strings
89
+ if "'" in value and '"' not in value:
90
+ return f'"{value}"'
91
+ return f"'{_escape_single_quoted(value)}'"
92
+
93
+ if isinstance(value, bytes):
94
+ return f"<{value.hex()}>"
95
+
96
+ if isinstance(value, list):
97
+ if inline or not value:
98
+ # Inline array
99
+ items = [_format_value(item, 0, inline=True) for item in value]
100
+ return "[" + ", ".join(items) + "]"
101
+ else:
102
+ # Block array
103
+ lines = []
104
+ for item in value:
105
+ if isinstance(item, (dict, list)) and item:
106
+ # Complex nested item
107
+ item_str = _format_value(item, indent + 1, inline=False)
108
+ if isinstance(item, list):
109
+ # Nested list - format inline or as nested block
110
+ lines.append(f"{prefix}- {_format_value(item, 0, inline=True)}")
111
+ else:
112
+ # Nested object
113
+ lines.append(f"{prefix}-")
114
+ for line in item_str.split("\n"):
115
+ if line.strip():
116
+ lines.append(f"{prefix} {line}")
117
+ else:
118
+ item_str = _format_value(item, 0, inline=True)
119
+ lines.append(f"{prefix}- {item_str}")
120
+ return "\n".join(lines)
121
+
122
+ if isinstance(value, dict):
123
+ if inline or not value:
124
+ # Inline object
125
+ items = []
126
+ for k, v in value.items():
127
+ key_str = k if _is_simple_key(k) else f"'{_escape_single_quoted(k)}'"
128
+ val_str = _format_value(v, 0, inline=True)
129
+ items.append(f"{key_str}: {val_str}")
130
+ return "{" + ", ".join(items) + "}"
131
+ else:
132
+ # Block object
133
+ lines = []
134
+ for k, v in value.items():
135
+ key_str = k if _is_simple_key(k) else f"'{_escape_single_quoted(k)}'"
136
+
137
+ if isinstance(v, dict) and v:
138
+ # Nested object
139
+ lines.append(f"{prefix}{key_str}:")
140
+ nested = _format_value(v, indent + 1, inline=False)
141
+ lines.append(nested)
142
+ elif isinstance(v, list) and v:
143
+ # Nested array
144
+ lines.append(f"{prefix}{key_str}:")
145
+ nested = _format_value(v, indent + 1, inline=False)
146
+ lines.append(nested)
147
+ else:
148
+ # Inline value
149
+ val_str = _format_value(v, 0, inline=True)
150
+ lines.append(f"{prefix}{key_str}: {val_str}")
151
+ return "\n".join(lines)
152
+
153
+ raise TypeError(f"Cannot serialize type {type(value).__name__} to YAY")
154
+
155
+
156
+ def dumps(obj: Any, *, indent: bool = True) -> str:
157
+ """
158
+ Serialize Python objects to a YAY string.
159
+
160
+ Args:
161
+ obj: The Python object to serialize
162
+ indent: If True (default), use block format for arrays/objects.
163
+ If False, use inline format.
164
+
165
+ Returns:
166
+ YAY-formatted string
167
+ """
168
+ return _format_value(obj, 0, inline=not indent)
169
+
170
+
171
+ def dump(obj: Any, fp: TextIO, *, indent: bool = True) -> None:
172
+ """
173
+ Serialize Python objects to a YAY file.
174
+
175
+ Args:
176
+ obj: The Python object to serialize
177
+ fp: File-like object to write to
178
+ indent: If True (default), use block format for arrays/objects.
179
+ """
180
+ fp.write(dumps(obj, indent=indent))
libyay/errors.py ADDED
@@ -0,0 +1,22 @@
1
+ """
2
+ YAY error types.
3
+ """
4
+
5
+
6
+ class YayError(Exception):
7
+ """Base exception for YAY parsing/serialization errors."""
8
+
9
+ def __init__(self, message: str, line: int | None = None, col: int | None = None):
10
+ self.line = line
11
+ self.col = col
12
+ if line is not None and col is not None:
13
+ message = f"{message} (line {line}, col {col})"
14
+ elif line is not None:
15
+ message = f"{message} (line {line})"
16
+ super().__init__(message)
17
+
18
+
19
+ class YaySyntaxError(YayError):
20
+ """Syntax error in YAY input."""
21
+
22
+ pass