codecin 7.22.10__py3-none-win_amd64.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.
- codecin/__init__.py +27 -0
- codecin/aot.py +1057 -0
- codecin/assembler.py +619 -0
- codecin/cbackend.py +3024 -0
- codecin/cin.py +4265 -0
- codecin/cli.py +670 -0
- codecin/codecin_native.dll +0 -0
- codecin/config.py +50 -0
- codecin/console.py +183 -0
- codecin/cpu.py +312 -0
- codecin/crom.py +449 -0
- codecin/cvm.py +708 -0
- codecin/disasm.py +149 -0
- codecin/environment.py +176 -0
- codecin/errors.py +54 -0
- codecin/isa.py +560 -0
- codecin/lib/array/pic.toml +10 -0
- codecin/lib/array/src/array.cin +103 -0
- codecin/lib/bigint/pic.toml +10 -0
- codecin/lib/bigint/src/bigint.cin +589 -0
- codecin/lib/bits/pic.toml +10 -0
- codecin/lib/bits/src/bits.cin +143 -0
- codecin/lib/bitset/pic.toml +10 -0
- codecin/lib/bitset/src/bitset.cin +374 -0
- codecin/lib/codec/pic.toml +10 -0
- codecin/lib/codec/src/codec.cin +563 -0
- codecin/lib/combin/pic.toml +10 -0
- codecin/lib/combin/src/combin.cin +414 -0
- codecin/lib/conv/pic.toml +10 -0
- codecin/lib/conv/src/conv.cin +151 -0
- codecin/lib/cppstd/pic.toml +10 -0
- codecin/lib/cppstd/src/cppstd.cin +418 -0
- codecin/lib/cstd/pic.toml +10 -0
- codecin/lib/cstd/src/cstd.cin +424 -0
- codecin/lib/csv/pic.toml +10 -0
- codecin/lib/csv/src/csv.cin +405 -0
- codecin/lib/dp/pic.toml +10 -0
- codecin/lib/dp/src/dp.cin +325 -0
- codecin/lib/ffi/pic.toml +10 -0
- codecin/lib/ffi/src/ffi.cin +163 -0
- codecin/lib/fmt/pic.toml +10 -0
- codecin/lib/fmt/src/fmt.cin +325 -0
- codecin/lib/frac/pic.toml +10 -0
- codecin/lib/frac/src/frac.cin +252 -0
- codecin/lib/gostd/pic.toml +10 -0
- codecin/lib/gostd/src/gostd.cin +415 -0
- codecin/lib/graph/pic.toml +10 -0
- codecin/lib/graph/src/graph.cin +367 -0
- codecin/lib/gui/pic.toml +10 -0
- codecin/lib/gui/src/gui.cin +218 -0
- codecin/lib/hash/pic.toml +10 -0
- codecin/lib/hash/src/hash.cin +67 -0
- codecin/lib/heap/pic.toml +10 -0
- codecin/lib/heap/src/heap.cin +199 -0
- codecin/lib/io/pic.toml +10 -0
- codecin/lib/io/src/io.cin +141 -0
- codecin/lib/json/pic.toml +10 -0
- codecin/lib/json/src/json.cin +84 -0
- codecin/lib/key/pic.toml +10 -0
- codecin/lib/key/src/key.cin +78 -0
- codecin/lib/math/pic.toml +10 -0
- codecin/lib/math/src/math.cin +50 -0
- codecin/lib/matrix/pic.toml +10 -0
- codecin/lib/matrix/src/matrix.cin +155 -0
- codecin/lib/net/pic.toml +10 -0
- codecin/lib/net/src/net.cin +171 -0
- codecin/lib/path/pic.toml +10 -0
- codecin/lib/path/src/path.cin +372 -0
- codecin/lib/queue/pic.toml +10 -0
- codecin/lib/queue/src/queue.cin +112 -0
- codecin/lib/rand/pic.toml +10 -0
- codecin/lib/rand/src/rand.cin +46 -0
- codecin/lib/set/pic.toml +10 -0
- codecin/lib/set/src/set.cin +269 -0
- codecin/lib/sort/pic.toml +10 -0
- codecin/lib/sort/src/sort.cin +93 -0
- codecin/lib/stat/pic.toml +10 -0
- codecin/lib/stat/src/stat.cin +138 -0
- codecin/lib/str/pic.toml +10 -0
- codecin/lib/str/src/str.cin +54 -0
- codecin/lib/termux/pic.toml +10 -0
- codecin/lib/termux/src/termux.cin +118 -0
- codecin/lib/test/pic.toml +10 -0
- codecin/lib/test/src/test.cin +74 -0
- codecin/lib/text/pic.toml +10 -0
- codecin/lib/text/src/text.cin +323 -0
- codecin/lib/time/pic.toml +10 -0
- codecin/lib/time/src/time.cin +54 -0
- codecin/lib/token/pic.toml +10 -0
- codecin/lib/token/src/token.cin +183 -0
- codecin/lib/tree/pic.toml +10 -0
- codecin/lib/tree/src/tree.cin +256 -0
- codecin/lib/unionfind/pic.toml +10 -0
- codecin/lib/unionfind/src/unionfind.cin +115 -0
- codecin/lib/validate/pic.toml +10 -0
- codecin/lib/validate/src/validate.cin +148 -0
- codecin/lib/vec/pic.toml +10 -0
- codecin/lib/vec/src/vec.cin +88 -0
- codecin/logger.py +145 -0
- codecin/memory.py +306 -0
- codecin/mkn.py +916 -0
- codecin/native/aot/aot.go +114 -0
- codecin/native/aot/stub_main.go.txt +23 -0
- codecin/native/build.ps1 +33 -0
- codecin/native/build.sh +48 -0
- codecin/native/cmd/cincc/main.go +66 -0
- codecin/native/compiler/codegen.go +2238 -0
- codecin/native/compiler/compile_test.go +1069 -0
- codecin/native/compiler/parser.go +1331 -0
- codecin/native/compiler/syscalls.go +166 -0
- codecin/native/compiler/tokenizer.go +394 -0
- codecin/native/compiler/types.go +217 -0
- codecin/native/engine/args.go +37 -0
- codecin/native/engine/audio.go +402 -0
- codecin/native/engine/audio_other.go +105 -0
- codecin/native/engine/audio_test.go +279 -0
- codecin/native/engine/audio_windows.go +190 -0
- codecin/native/engine/canvas.go +271 -0
- codecin/native/engine/console_other.go +9 -0
- codecin/native/engine/console_windows.go +43 -0
- codecin/native/engine/crom.go +86 -0
- codecin/native/engine/encode.go +93 -0
- codecin/native/engine/engine_test.go +198 -0
- codecin/native/engine/ffi_nocgo.go +20 -0
- codecin/native/engine/ffi_registry.go +69 -0
- codecin/native/engine/ffi_unix.go +109 -0
- codecin/native/engine/ffi_windows.go +117 -0
- codecin/native/engine/gui.go +209 -0
- codecin/native/engine/gui_stub.go +13 -0
- codecin/native/engine/gui_test.go +148 -0
- codecin/native/engine/gui_windows.go +604 -0
- codecin/native/engine/gui_x11.go +723 -0
- codecin/native/engine/host_test.go +139 -0
- codecin/native/engine/hostcrypto.go +30 -0
- codecin/native/engine/hostdesktop.go +173 -0
- codecin/native/engine/hostnet.go +127 -0
- codecin/native/engine/isa_gen.go +689 -0
- codecin/native/engine/keyboard.go +432 -0
- codecin/native/engine/keyboard_other.go +94 -0
- codecin/native/engine/keyboard_stub.go +17 -0
- codecin/native/engine/keyboard_termios_darwin.go +9 -0
- codecin/native/engine/keyboard_termios_linux.go +9 -0
- codecin/native/engine/keyboard_test.go +246 -0
- codecin/native/engine/keyboard_windows.go +208 -0
- codecin/native/engine/keyboard_windows_test.go +123 -0
- codecin/native/engine/lineedit.go +262 -0
- codecin/native/engine/lineedit_test.go +105 -0
- codecin/native/engine/lineint_unix.go +17 -0
- codecin/native/engine/lineint_windows.go +19 -0
- codecin/native/engine/mem_other.go +37 -0
- codecin/native/engine/mem_windows.go +33 -0
- codecin/native/engine/native.go +640 -0
- codecin/native/engine/netsock.go +321 -0
- codecin/native/engine/ops_ext.go +515 -0
- codecin/native/engine/stdin.go +72 -0
- codecin/native/engine/stdin_other.go +9 -0
- codecin/native/engine/stdin_windows.go +60 -0
- codecin/native/engine/system.go +313 -0
- codecin/native/engine/termux.go +180 -0
- codecin/native/engine/version_gen.go +7 -0
- codecin/native/engine/vkb_darwin.go +62 -0
- codecin/native/engine/vkb_linux.go +95 -0
- codecin/native/engine/vkb_stub.go +11 -0
- codecin/native/engine/vm.go +1677 -0
- codecin/native/go.mod +3 -0
- codecin/native/ir/ir.go +48 -0
- codecin/native/main.go +448 -0
- codecin/native/mc/aarch64.go +165 -0
- codecin/native/mc/aarch64_test.go +30 -0
- codecin/native/mc/elf.go +88 -0
- codecin/native/mc/print_test.go +52 -0
- codecin/native/mc/x86_64.go +1262 -0
- codecin/native/mc/x86_64_test.go +102 -0
- codecin/native.py +432 -0
- codecin/native_codegen.py +987 -0
- codecin/nativegen.py +786 -0
- codecin/object.py +539 -0
- codecin/optimizer.py +236 -0
- codecin/packaging/__init__.py +46 -0
- codecin/packaging/archive.py +177 -0
- codecin/packaging/model.py +519 -0
- codecin/packaging/spec.py +193 -0
- codecin/packaging/store.py +372 -0
- codecin/packaging/toml.py +541 -0
- codecin/packaging/vcs.py +215 -0
- codecin/pic.py +1917 -0
- codecin/pic_api.py +374 -0
- codecin/pic_login.py +519 -0
- codecin/pic_registry.py +515 -0
- codecin/registers.py +130 -0
- codecin/sdgcc.py +493 -0
- codecin/stats.py +230 -0
- codecin/stdlib.py +138 -0
- codecin/toolchain.py +396 -0
- codecin/toolkit.py +26 -0
- codecin/version.py +260 -0
- codecin-7.22.10.dist-info/METADATA +1077 -0
- codecin-7.22.10.dist-info/RECORD +202 -0
- codecin-7.22.10.dist-info/WHEEL +5 -0
- codecin-7.22.10.dist-info/entry_points.txt +5 -0
- codecin-7.22.10.dist-info/licenses/LICENSE +7 -0
- codecin-7.22.10.dist-info/top_level.txt +1 -0
|
@@ -0,0 +1,541 @@
|
|
|
1
|
+
"""最小 TOML 读写器 (零依赖, 覆盖工具链所需的 TOML 子集)。
|
|
2
|
+
|
|
3
|
+
为什么不用 ``tomllib``: 项目 ``requires-python >= 3.8``, 而 ``tomllib`` 从
|
|
4
|
+
Python 3.11 才进入标准库。本模块提供**够用的**子集:
|
|
5
|
+
|
|
6
|
+
* ``[table]`` / ``[a.b]`` / ``[[array-of-tables]]``;
|
|
7
|
+
* 基本字符串、字面量字符串、多行字符串 (``\"\"\"`` / ``'''``);
|
|
8
|
+
* 整数 (含 0x/0o/0b 与下划线)、浮点、布尔、数组、内联表;
|
|
9
|
+
* 注释与行尾注释、点号键、带引号的键。
|
|
10
|
+
|
|
11
|
+
不支持的 TOML 特性 (日期时间会按 ISO 字符串保留) 在写入时不会被生成。
|
|
12
|
+
对外只暴露 :func:`loads` / :func:`dumps` 与 :class:`TomlError`。
|
|
13
|
+
"""
|
|
14
|
+
|
|
15
|
+
import json
|
|
16
|
+
import re
|
|
17
|
+
from datetime import date, datetime
|
|
18
|
+
from typing import Any, Dict, List, Optional, Tuple
|
|
19
|
+
|
|
20
|
+
__all__ = ['TomlError', 'loads', 'dumps']
|
|
21
|
+
|
|
22
|
+
|
|
23
|
+
class TomlError(ValueError):
|
|
24
|
+
"""TOML 语法错误 (带行号提示)。"""
|
|
25
|
+
|
|
26
|
+
|
|
27
|
+
_BARE_KEY_RE = re.compile(r'^[A-Za-z0-9_-]+$')
|
|
28
|
+
_NUMBER_RE = re.compile(
|
|
29
|
+
r'^[+-]?(?:0[xX][0-9A-Fa-f_]+|0[oO][0-7_]+|0[bB][01_]+'
|
|
30
|
+
r'|\d[\d_]*(?:\.\d[\d_]*)?(?:[eE][+-]?\d[\d_]*)?)$')
|
|
31
|
+
_DATE_RE = re.compile(r'^\d{4}-\d{2}-\d{2}(?:[Tt ].*)?$')
|
|
32
|
+
_ESCAPES = {
|
|
33
|
+
'b': '\b', 't': '\t', 'n': '\n', 'f': '\f', 'r': '\r',
|
|
34
|
+
'"': '"', '\\': '\\', '/': '/',
|
|
35
|
+
}
|
|
36
|
+
|
|
37
|
+
|
|
38
|
+
def _line_of(text: str, pos: int) -> int:
|
|
39
|
+
return text.count('\n', 0, pos) + 1
|
|
40
|
+
|
|
41
|
+
|
|
42
|
+
def _logical_statements(text: str) -> List[Tuple[str, int]]:
|
|
43
|
+
"""把源码切成逻辑语句 (表头 / 键值), 去掉注释并保留行号。"""
|
|
44
|
+
if text.startswith('\ufeff'):
|
|
45
|
+
text = text[1:]
|
|
46
|
+
out: List[Tuple[str, int]] = []
|
|
47
|
+
buf: List[str] = []
|
|
48
|
+
start_line = 1
|
|
49
|
+
line = 1
|
|
50
|
+
quote: Optional[str] = None
|
|
51
|
+
depth = 0
|
|
52
|
+
i, n = 0, len(text)
|
|
53
|
+
while i < n:
|
|
54
|
+
ch = text[i]
|
|
55
|
+
if quote:
|
|
56
|
+
if quote == '"' and ch == '\\':
|
|
57
|
+
buf.append(ch)
|
|
58
|
+
i += 1
|
|
59
|
+
if i < n:
|
|
60
|
+
buf.append(text[i])
|
|
61
|
+
if text[i] == '\n':
|
|
62
|
+
line += 1
|
|
63
|
+
i += 1
|
|
64
|
+
continue
|
|
65
|
+
if text.startswith(quote, i):
|
|
66
|
+
buf.append(quote)
|
|
67
|
+
i += len(quote)
|
|
68
|
+
quote = None
|
|
69
|
+
continue
|
|
70
|
+
buf.append(ch)
|
|
71
|
+
if ch == '\n':
|
|
72
|
+
line += 1
|
|
73
|
+
i += 1
|
|
74
|
+
continue
|
|
75
|
+
|
|
76
|
+
if ch == '#':
|
|
77
|
+
while i < n and text[i] not in '\r\n':
|
|
78
|
+
i += 1
|
|
79
|
+
continue
|
|
80
|
+
if ch in ('"', "'"):
|
|
81
|
+
triple = ch * 3
|
|
82
|
+
if text.startswith(triple, i):
|
|
83
|
+
quote = triple
|
|
84
|
+
buf.append(triple)
|
|
85
|
+
i += 3
|
|
86
|
+
continue
|
|
87
|
+
quote = ch
|
|
88
|
+
buf.append(ch)
|
|
89
|
+
i += 1
|
|
90
|
+
continue
|
|
91
|
+
if ch in '[{':
|
|
92
|
+
depth += 1
|
|
93
|
+
elif ch in ']}':
|
|
94
|
+
depth = max(0, depth - 1)
|
|
95
|
+
if ch in '\r\n':
|
|
96
|
+
if ch == '\r' and i + 1 < n and text[i + 1] == '\n':
|
|
97
|
+
i += 1
|
|
98
|
+
raw = ''.join(buf).strip()
|
|
99
|
+
if depth == 0 and raw:
|
|
100
|
+
out.append((raw, start_line))
|
|
101
|
+
buf = []
|
|
102
|
+
start_line = line + 1
|
|
103
|
+
else:
|
|
104
|
+
buf.append('\n')
|
|
105
|
+
line += 1
|
|
106
|
+
i += 1
|
|
107
|
+
continue
|
|
108
|
+
if not buf:
|
|
109
|
+
start_line = line
|
|
110
|
+
buf.append(ch)
|
|
111
|
+
i += 1
|
|
112
|
+
if quote:
|
|
113
|
+
raise TomlError(f'未闭合的字符串 (从第 {start_line} 行开始)')
|
|
114
|
+
raw = ''.join(buf).strip()
|
|
115
|
+
if raw:
|
|
116
|
+
out.append((raw, start_line))
|
|
117
|
+
return out
|
|
118
|
+
|
|
119
|
+
|
|
120
|
+
def _split_key_path(text: str, line: int) -> List[str]:
|
|
121
|
+
"""解析 ``a.b."c d"`` 形式的键路径。"""
|
|
122
|
+
parts: List[str] = []
|
|
123
|
+
buf: List[str] = []
|
|
124
|
+
quote: Optional[str] = None
|
|
125
|
+
i = 0
|
|
126
|
+
while i < len(text):
|
|
127
|
+
ch = text[i]
|
|
128
|
+
if quote:
|
|
129
|
+
if ch == quote:
|
|
130
|
+
quote = None
|
|
131
|
+
else:
|
|
132
|
+
buf.append(ch)
|
|
133
|
+
i += 1
|
|
134
|
+
continue
|
|
135
|
+
if ch in ('"', "'"):
|
|
136
|
+
quote = ch
|
|
137
|
+
i += 1
|
|
138
|
+
continue
|
|
139
|
+
if ch == '.':
|
|
140
|
+
part = ''.join(buf).strip()
|
|
141
|
+
if not part:
|
|
142
|
+
raise TomlError(f'第 {line} 行: 空键')
|
|
143
|
+
parts.append(part)
|
|
144
|
+
buf = []
|
|
145
|
+
i += 1
|
|
146
|
+
continue
|
|
147
|
+
buf.append(ch)
|
|
148
|
+
i += 1
|
|
149
|
+
part = ''.join(buf).strip()
|
|
150
|
+
if not part:
|
|
151
|
+
raise TomlError(f'第 {line} 行: 空键')
|
|
152
|
+
parts.append(part)
|
|
153
|
+
return parts
|
|
154
|
+
|
|
155
|
+
|
|
156
|
+
def _find_equals(text: str, line: int) -> int:
|
|
157
|
+
quote: Optional[str] = None
|
|
158
|
+
i = 0
|
|
159
|
+
while i < len(text):
|
|
160
|
+
ch = text[i]
|
|
161
|
+
if quote:
|
|
162
|
+
if quote == '"' and ch == '\\':
|
|
163
|
+
i += 2
|
|
164
|
+
continue
|
|
165
|
+
if ch == quote:
|
|
166
|
+
quote = None
|
|
167
|
+
i += 1
|
|
168
|
+
continue
|
|
169
|
+
if ch in ('"', "'"):
|
|
170
|
+
quote = ch
|
|
171
|
+
elif ch == '=':
|
|
172
|
+
return i
|
|
173
|
+
i += 1
|
|
174
|
+
raise TomlError(f'第 {line} 行: 缺少 "="')
|
|
175
|
+
|
|
176
|
+
|
|
177
|
+
class _ValueParser:
|
|
178
|
+
def __init__(self, text: str, line: int):
|
|
179
|
+
self.text = text
|
|
180
|
+
self.line = line
|
|
181
|
+
self.pos = 0
|
|
182
|
+
|
|
183
|
+
def error(self, message: str) -> TomlError:
|
|
184
|
+
return TomlError(f'第 {self.line} 行: {message} (在 {self.text!r})')
|
|
185
|
+
|
|
186
|
+
def skip(self) -> None:
|
|
187
|
+
while self.pos < len(self.text) and self.text[self.pos] in ' \t\r\n':
|
|
188
|
+
self.pos += 1
|
|
189
|
+
|
|
190
|
+
def parse(self) -> Any:
|
|
191
|
+
self.skip()
|
|
192
|
+
value = self.value()
|
|
193
|
+
self.skip()
|
|
194
|
+
if self.pos != len(self.text):
|
|
195
|
+
raise self.error(f'值后面有多余内容 {self.text[self.pos:]!r}')
|
|
196
|
+
return value
|
|
197
|
+
|
|
198
|
+
def value(self) -> Any:
|
|
199
|
+
self.skip()
|
|
200
|
+
if self.pos >= len(self.text):
|
|
201
|
+
raise self.error('缺少值')
|
|
202
|
+
ch = self.text[self.pos]
|
|
203
|
+
if ch == '"' or ch == "'":
|
|
204
|
+
return self.string()
|
|
205
|
+
if ch == '[':
|
|
206
|
+
return self.array()
|
|
207
|
+
if ch == '{':
|
|
208
|
+
return self.inline_table()
|
|
209
|
+
return self.scalar()
|
|
210
|
+
|
|
211
|
+
def string(self) -> str:
|
|
212
|
+
quote = self.text[self.pos]
|
|
213
|
+
triple = quote * 3
|
|
214
|
+
if self.text.startswith(triple, self.pos):
|
|
215
|
+
return self.multiline(triple)
|
|
216
|
+
self.pos += 1
|
|
217
|
+
out: List[str] = []
|
|
218
|
+
while self.pos < len(self.text):
|
|
219
|
+
ch = self.text[self.pos]
|
|
220
|
+
if ch == quote:
|
|
221
|
+
self.pos += 1
|
|
222
|
+
return ''.join(out)
|
|
223
|
+
if quote == '"' and ch == '\\':
|
|
224
|
+
out.append(self.escape())
|
|
225
|
+
continue
|
|
226
|
+
out.append(ch)
|
|
227
|
+
self.pos += 1
|
|
228
|
+
raise self.error('未闭合的字符串')
|
|
229
|
+
|
|
230
|
+
def multiline(self, triple: str) -> str:
|
|
231
|
+
self.pos += 3
|
|
232
|
+
# TOML 允许紧跟在开定界符后的一个换行不进入内容
|
|
233
|
+
if self.text.startswith('\r\n', self.pos):
|
|
234
|
+
self.pos += 2
|
|
235
|
+
elif self.text.startswith('\n', self.pos):
|
|
236
|
+
self.pos += 1
|
|
237
|
+
out: List[str] = []
|
|
238
|
+
while self.pos < len(self.text):
|
|
239
|
+
if self.text.startswith(triple, self.pos):
|
|
240
|
+
self.pos += 3
|
|
241
|
+
return ''.join(out)
|
|
242
|
+
ch = self.text[self.pos]
|
|
243
|
+
if triple == '"""' and ch == '\\':
|
|
244
|
+
out.append(self.escape())
|
|
245
|
+
continue
|
|
246
|
+
out.append(ch)
|
|
247
|
+
self.pos += 1
|
|
248
|
+
raise self.error('未闭合的多行字符串')
|
|
249
|
+
|
|
250
|
+
def escape(self) -> str:
|
|
251
|
+
self.pos += 1
|
|
252
|
+
if self.pos >= len(self.text):
|
|
253
|
+
raise self.error('反斜杠后缺少转义字符')
|
|
254
|
+
ch = self.text[self.pos]
|
|
255
|
+
self.pos += 1
|
|
256
|
+
if ch in _ESCAPES:
|
|
257
|
+
return _ESCAPES[ch]
|
|
258
|
+
if ch in ('u', 'U'):
|
|
259
|
+
length = 4 if ch == 'u' else 8
|
|
260
|
+
raw = self.text[self.pos:self.pos + length]
|
|
261
|
+
if len(raw) != length or not re.fullmatch(r'[0-9A-Fa-f]+', raw):
|
|
262
|
+
raise self.error('非法 Unicode 转义')
|
|
263
|
+
self.pos += length
|
|
264
|
+
try:
|
|
265
|
+
return chr(int(raw, 16))
|
|
266
|
+
except ValueError:
|
|
267
|
+
raise self.error('非法 Unicode 码点') from None
|
|
268
|
+
raise self.error(f'未知转义 \\{ch}')
|
|
269
|
+
|
|
270
|
+
def array(self) -> List[Any]:
|
|
271
|
+
self.pos += 1
|
|
272
|
+
out: List[Any] = []
|
|
273
|
+
while True:
|
|
274
|
+
self.skip()
|
|
275
|
+
if self.pos >= len(self.text):
|
|
276
|
+
raise self.error('未闭合的数组')
|
|
277
|
+
if self.text[self.pos] == ']':
|
|
278
|
+
self.pos += 1
|
|
279
|
+
return out
|
|
280
|
+
out.append(self.value())
|
|
281
|
+
self.skip()
|
|
282
|
+
if self.pos < len(self.text) and self.text[self.pos] == ',':
|
|
283
|
+
self.pos += 1
|
|
284
|
+
continue
|
|
285
|
+
if self.pos < len(self.text) and self.text[self.pos] == ']':
|
|
286
|
+
self.pos += 1
|
|
287
|
+
return out
|
|
288
|
+
raise self.error('数组元素之间缺少逗号或 ]')
|
|
289
|
+
|
|
290
|
+
def inline_table(self) -> Dict[str, Any]:
|
|
291
|
+
self.pos += 1
|
|
292
|
+
out: Dict[str, Any] = {}
|
|
293
|
+
while True:
|
|
294
|
+
self.skip()
|
|
295
|
+
if self.pos >= len(self.text):
|
|
296
|
+
raise self.error('未闭合的内联表')
|
|
297
|
+
if self.text[self.pos] == '}':
|
|
298
|
+
self.pos += 1
|
|
299
|
+
return out
|
|
300
|
+
start = self.pos
|
|
301
|
+
quote: Optional[str] = None
|
|
302
|
+
while self.pos < len(self.text):
|
|
303
|
+
ch = self.text[self.pos]
|
|
304
|
+
if quote:
|
|
305
|
+
if ch == quote:
|
|
306
|
+
quote = None
|
|
307
|
+
elif ch in ('"', "'"):
|
|
308
|
+
quote = ch
|
|
309
|
+
elif ch == '=':
|
|
310
|
+
break
|
|
311
|
+
elif ch in (',', '}'):
|
|
312
|
+
raise self.error('内联表缺少 "="')
|
|
313
|
+
self.pos += 1
|
|
314
|
+
key_text = self.text[start:self.pos].strip()
|
|
315
|
+
if not key_text:
|
|
316
|
+
raise self.error('内联表空键')
|
|
317
|
+
self.pos += 1 # '='
|
|
318
|
+
keys = _split_key_path(key_text, self.line)
|
|
319
|
+
value = self.value()
|
|
320
|
+
target = out
|
|
321
|
+
for key in keys[:-1]:
|
|
322
|
+
target = target.setdefault(key, {})
|
|
323
|
+
if not isinstance(target, dict):
|
|
324
|
+
raise self.error(f'键 {key!r} 与已有值类型冲突')
|
|
325
|
+
if keys[-1] in target:
|
|
326
|
+
raise self.error(f'重复键 {keys[-1]!r}')
|
|
327
|
+
target[keys[-1]] = value
|
|
328
|
+
self.skip()
|
|
329
|
+
if self.pos < len(self.text) and self.text[self.pos] == ',':
|
|
330
|
+
self.pos += 1
|
|
331
|
+
continue
|
|
332
|
+
if self.pos < len(self.text) and self.text[self.pos] == '}':
|
|
333
|
+
self.pos += 1
|
|
334
|
+
return out
|
|
335
|
+
raise self.error('内联表元素之间缺少逗号或 }')
|
|
336
|
+
|
|
337
|
+
def scalar(self) -> Any:
|
|
338
|
+
start = self.pos
|
|
339
|
+
while self.pos < len(self.text) and self.text[self.pos] not in ',]}':
|
|
340
|
+
self.pos += 1
|
|
341
|
+
raw = self.text[start:self.pos].strip()
|
|
342
|
+
if not raw:
|
|
343
|
+
raise self.error('缺少值')
|
|
344
|
+
low = raw.lower()
|
|
345
|
+
if low == 'true':
|
|
346
|
+
return True
|
|
347
|
+
if low == 'false':
|
|
348
|
+
return False
|
|
349
|
+
if low in ('inf', '+inf'):
|
|
350
|
+
return float('inf')
|
|
351
|
+
if low == '-inf':
|
|
352
|
+
return float('-inf')
|
|
353
|
+
if low in ('nan', '+nan', '-nan'):
|
|
354
|
+
return float('nan')
|
|
355
|
+
if _DATE_RE.match(raw):
|
|
356
|
+
return raw
|
|
357
|
+
if _NUMBER_RE.match(raw):
|
|
358
|
+
cleaned = raw.replace('_', '')
|
|
359
|
+
try:
|
|
360
|
+
if re.match(r'^[+-]?0[xX]', cleaned):
|
|
361
|
+
return int(cleaned, 16)
|
|
362
|
+
if re.match(r'^[+-]?0[oO]', cleaned):
|
|
363
|
+
return int(cleaned, 8)
|
|
364
|
+
if re.match(r'^[+-]?0[bB]', cleaned):
|
|
365
|
+
return int(cleaned, 2)
|
|
366
|
+
if any(c in cleaned for c in '.eE'):
|
|
367
|
+
return float(cleaned)
|
|
368
|
+
return int(cleaned)
|
|
369
|
+
except ValueError:
|
|
370
|
+
raise self.error(f'非法数字 {raw!r}') from None
|
|
371
|
+
raise self.error(f'非法值 {raw!r} (字符串请加引号)')
|
|
372
|
+
|
|
373
|
+
|
|
374
|
+
def _assign(root: Dict[str, Any], keys: List[str], value: Any, line: int) -> None:
|
|
375
|
+
target = root
|
|
376
|
+
for key in keys[:-1]:
|
|
377
|
+
nxt = target.get(key)
|
|
378
|
+
if nxt is None:
|
|
379
|
+
nxt = {}
|
|
380
|
+
target[key] = nxt
|
|
381
|
+
if isinstance(nxt, list):
|
|
382
|
+
if not nxt or not isinstance(nxt[-1], dict):
|
|
383
|
+
raise TomlError(f'第 {line} 行: 键 {key!r} 不是表')
|
|
384
|
+
nxt = nxt[-1]
|
|
385
|
+
if not isinstance(nxt, dict):
|
|
386
|
+
raise TomlError(f'第 {line} 行: 键 {key!r} 已存在且不是表')
|
|
387
|
+
target = nxt
|
|
388
|
+
last = keys[-1]
|
|
389
|
+
if last in target:
|
|
390
|
+
raise TomlError(f'第 {line} 行: 重复键 {last!r}')
|
|
391
|
+
target[last] = value
|
|
392
|
+
|
|
393
|
+
|
|
394
|
+
def _table_at(root: Dict[str, Any], keys: List[str], line: int,
|
|
395
|
+
array: bool) -> Dict[str, Any]:
|
|
396
|
+
target = root
|
|
397
|
+
for key in keys[:-1]:
|
|
398
|
+
nxt = target.get(key)
|
|
399
|
+
if nxt is None:
|
|
400
|
+
nxt = {}
|
|
401
|
+
target[key] = nxt
|
|
402
|
+
if isinstance(nxt, list):
|
|
403
|
+
if not nxt or not isinstance(nxt[-1], dict):
|
|
404
|
+
raise TomlError(f'第 {line} 行: 键 {key!r} 不是表')
|
|
405
|
+
nxt = nxt[-1]
|
|
406
|
+
if not isinstance(nxt, dict):
|
|
407
|
+
raise TomlError(f'第 {line} 行: 键 {key!r} 已存在且不是表')
|
|
408
|
+
target = nxt
|
|
409
|
+
last = keys[-1]
|
|
410
|
+
if array:
|
|
411
|
+
bucket = target.setdefault(last, [])
|
|
412
|
+
if not isinstance(bucket, list):
|
|
413
|
+
raise TomlError(f'第 {line} 行: 键 {last!r} 已存在且不是表数组')
|
|
414
|
+
entry: Dict[str, Any] = {}
|
|
415
|
+
bucket.append(entry)
|
|
416
|
+
return entry
|
|
417
|
+
nxt = target.get(last)
|
|
418
|
+
if nxt is None:
|
|
419
|
+
nxt = {}
|
|
420
|
+
target[last] = nxt
|
|
421
|
+
if not isinstance(nxt, dict):
|
|
422
|
+
raise TomlError(f'第 {line} 行: 键 {last!r} 已存在且不是表')
|
|
423
|
+
return nxt
|
|
424
|
+
|
|
425
|
+
|
|
426
|
+
def loads(text: str) -> Dict[str, Any]:
|
|
427
|
+
"""解析 TOML 文本为 dict; 语法错误抛 :class:`TomlError`。"""
|
|
428
|
+
root: Dict[str, Any] = {}
|
|
429
|
+
current: Dict[str, Any] = root
|
|
430
|
+
for statement, line in _logical_statements(text):
|
|
431
|
+
if statement.startswith('[['):
|
|
432
|
+
if not statement.endswith(']]'):
|
|
433
|
+
raise TomlError(f'第 {line} 行: 表数组头部格式错误')
|
|
434
|
+
keys = _split_key_path(statement[2:-2].strip(), line)
|
|
435
|
+
current = _table_at(root, keys, line, array=True)
|
|
436
|
+
continue
|
|
437
|
+
if statement.startswith('['):
|
|
438
|
+
if not statement.endswith(']'):
|
|
439
|
+
raise TomlError(f'第 {line} 行: 表头部格式错误')
|
|
440
|
+
keys = _split_key_path(statement[1:-1].strip(), line)
|
|
441
|
+
current = _table_at(root, keys, line, array=False)
|
|
442
|
+
continue
|
|
443
|
+
eq = _find_equals(statement, line)
|
|
444
|
+
keys = _split_key_path(statement[:eq].strip(), line)
|
|
445
|
+
value = _ValueParser(statement[eq + 1:].strip(), line).parse()
|
|
446
|
+
_assign(current, keys, value, line)
|
|
447
|
+
return root
|
|
448
|
+
|
|
449
|
+
|
|
450
|
+
def load(path: str) -> Dict[str, Any]:
|
|
451
|
+
"""从 UTF-8 文件读取 TOML (容忍 BOM 与 CRLF)。"""
|
|
452
|
+
with open(path, encoding='utf-8-sig') as f:
|
|
453
|
+
return loads(f.read())
|
|
454
|
+
|
|
455
|
+
|
|
456
|
+
# ==================== 写入 ====================
|
|
457
|
+
|
|
458
|
+
|
|
459
|
+
def _format_key(key: str) -> str:
|
|
460
|
+
return key if _BARE_KEY_RE.match(key) else json.dumps(key, ensure_ascii=False)
|
|
461
|
+
|
|
462
|
+
|
|
463
|
+
def _format_value(value: Any) -> str:
|
|
464
|
+
if isinstance(value, bool):
|
|
465
|
+
return 'true' if value else 'false'
|
|
466
|
+
if isinstance(value, str):
|
|
467
|
+
return json.dumps(value, ensure_ascii=False)
|
|
468
|
+
if isinstance(value, int):
|
|
469
|
+
return str(value)
|
|
470
|
+
if isinstance(value, float):
|
|
471
|
+
if value != value:
|
|
472
|
+
return 'nan'
|
|
473
|
+
if value == float('inf'):
|
|
474
|
+
return 'inf'
|
|
475
|
+
if value == float('-inf'):
|
|
476
|
+
return '-inf'
|
|
477
|
+
return repr(value)
|
|
478
|
+
if isinstance(value, (datetime, date)):
|
|
479
|
+
return json.dumps(value.isoformat(), ensure_ascii=False)
|
|
480
|
+
if isinstance(value, (list, tuple)):
|
|
481
|
+
return '[' + ', '.join(_format_value(v) for v in value) + ']'
|
|
482
|
+
if isinstance(value, dict):
|
|
483
|
+
return '{' + ', '.join(
|
|
484
|
+
f'{_format_key(k)} = {_format_value(v)}' for k, v in value.items()
|
|
485
|
+
) + '}'
|
|
486
|
+
raise TypeError(f'无法写入 TOML 的类型: {type(value).__name__}')
|
|
487
|
+
|
|
488
|
+
|
|
489
|
+
def _is_table_array(value: Any) -> bool:
|
|
490
|
+
return isinstance(value, list) and bool(value) and all(
|
|
491
|
+
isinstance(v, dict) for v in value)
|
|
492
|
+
|
|
493
|
+
|
|
494
|
+
def _dump_table(data: Dict[str, Any], path: List[str], out: List[str],
|
|
495
|
+
header: bool, sort_keys: bool) -> None:
|
|
496
|
+
items = sorted(data.items()) if sort_keys else list(data.items())
|
|
497
|
+
scalars = [(k, v) for k, v in items
|
|
498
|
+
if not isinstance(v, dict) and not _is_table_array(v)]
|
|
499
|
+
tables = [(k, v) for k, v in items if isinstance(v, dict)]
|
|
500
|
+
arrays = [(k, v) for k, v in items if _is_table_array(v)]
|
|
501
|
+
|
|
502
|
+
if header:
|
|
503
|
+
if out and out[-1] != '':
|
|
504
|
+
out.append('')
|
|
505
|
+
out.append('[' + '.'.join(_format_key(p) for p in path) + ']')
|
|
506
|
+
for key, value in scalars:
|
|
507
|
+
out.append(f'{_format_key(key)} = {_format_value(value)}')
|
|
508
|
+
for key, value in tables:
|
|
509
|
+
_dump_table(value, path + [key], out, header=True, sort_keys=sort_keys)
|
|
510
|
+
for key, values in arrays:
|
|
511
|
+
for value in values:
|
|
512
|
+
if out and out[-1] != '':
|
|
513
|
+
out.append('')
|
|
514
|
+
out.append('[[' + '.'.join(
|
|
515
|
+
_format_key(p) for p in path + [key]) + ']]')
|
|
516
|
+
_dump_table(value, path + [key], out, header=False,
|
|
517
|
+
sort_keys=sort_keys)
|
|
518
|
+
|
|
519
|
+
|
|
520
|
+
def dumps(data: Dict[str, Any], sort_keys: bool = False) -> str:
|
|
521
|
+
"""把 dict 写为 TOML 文本 (末尾带一个换行)。"""
|
|
522
|
+
if not isinstance(data, dict):
|
|
523
|
+
raise TypeError('TOML 顶层必须是 dict')
|
|
524
|
+
out: List[str] = []
|
|
525
|
+
# 顶层标量先写, 再写表; _dump_table(header=False) 正好如此
|
|
526
|
+
top_scalars = [(k, v) for k, v in data.items()
|
|
527
|
+
if not isinstance(v, dict) and not _is_table_array(v)]
|
|
528
|
+
for key, value in top_scalars:
|
|
529
|
+
out.append(f'{_format_key(key)} = {_format_value(value)}')
|
|
530
|
+
for key, value in data.items():
|
|
531
|
+
if isinstance(value, dict):
|
|
532
|
+
_dump_table(value, [key], out, header=True, sort_keys=sort_keys)
|
|
533
|
+
elif _is_table_array(value):
|
|
534
|
+
for entry in value:
|
|
535
|
+
if out and out[-1] != '':
|
|
536
|
+
out.append('')
|
|
537
|
+
out.append('[[' + _format_key(key) + ']]')
|
|
538
|
+
_dump_table(entry, [key], out, header=False,
|
|
539
|
+
sort_keys=sort_keys)
|
|
540
|
+
text = '\n'.join(out).strip() + '\n'
|
|
541
|
+
return text if text.strip() else ''
|