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
codecin/nativegen.py
ADDED
|
@@ -0,0 +1,786 @@
|
|
|
1
|
+
"""LEGACY: CIN AST -> C 的后端。编译器入口已切到 Go 的 cincc(直接出机器码),
|
|
2
|
+
本模块仅保留给 --build-backend 的 C 路径与历史测试,不再由 CLI/mkn 调用。"""
|
|
3
|
+
"""直接 AST → C 的原生代码生成(不经过 UCPU 指令集)。
|
|
4
|
+
|
|
5
|
+
这是「移除自带指令集」迁移的第 0 阶段:把 CIN 源码解析成 AST 后,直接生成 C
|
|
6
|
+
并交给本机/交叉 C 编译器产出设备本机的机器码,中间不再产生任何 UCPU 操作码、
|
|
7
|
+
BIN/UCBC 字节码或 .sdgcc 容器。
|
|
8
|
+
|
|
9
|
+
当前覆盖的语言子集(有意收窄,超出即报错,绝不静默降级):
|
|
10
|
+
|
|
11
|
+
* ``int`` 局部变量/参数/返回值(``int64_t``);
|
|
12
|
+
* 算术与比较:``+ - * / %``、``< <= > >= == !=``;
|
|
13
|
+
* 语句:``decl`` / 赋值 / ``expr`` 调用 / ``while`` / ``block`` / ``return``;
|
|
14
|
+
* 内建输出:``print(x)`` / ``println(x)``,仅整数。
|
|
15
|
+
|
|
16
|
+
不支持的结构(struct/数组/字符串/浮点/指针/if 等)会抛
|
|
17
|
+
:class:`NativeGenError`,由调用方决定回退到既有编译器。
|
|
18
|
+
"""
|
|
19
|
+
|
|
20
|
+
import os
|
|
21
|
+
import subprocess
|
|
22
|
+
import tempfile
|
|
23
|
+
from typing import Any, Dict, List, Optional, Sequence, Tuple
|
|
24
|
+
|
|
25
|
+
from . import toolchain
|
|
26
|
+
|
|
27
|
+
__all__ = ['NativeGenError', 'emit_c', 'compile_native', 'supports_source']
|
|
28
|
+
|
|
29
|
+
AST = Any
|
|
30
|
+
|
|
31
|
+
_BINOPS = {'+': '+', '-': '-', '*': '*', '/': '/', '%': '%',
|
|
32
|
+
'<': '<', '<=': '<=', '>': '>', '>=': '>=', '==': '==', '!=': '!=',
|
|
33
|
+
'&&': '&&', '||': '||', '&': '&', '|': '|', '^': '^',
|
|
34
|
+
'<<': '<<', '>>': '>>'}
|
|
35
|
+
_BUILTINS = {
|
|
36
|
+
'strlen': ('__cin_strlen', 1, 'int'),
|
|
37
|
+
'abs': ('__cin_abs', 1, 'int'),
|
|
38
|
+
'indexof': ('__cin_indexof', 2, 'int'),
|
|
39
|
+
'atoi': ('__cin_atoi', 1, 'int'),
|
|
40
|
+
'idiv': ('__cin_idiv', 2, 'int'),
|
|
41
|
+
'min': ('__cin_min', 2, 'int'),
|
|
42
|
+
'max': ('__cin_max', 2, 'int'),
|
|
43
|
+
'substr': ('__cin_substr', 3, 'str'),
|
|
44
|
+
'upper': ('__cin_case', 1, 'str'),
|
|
45
|
+
'lower': ('__cin_case', 1, 'str'),
|
|
46
|
+
'int_to_str': ('__cin_itoa', 1, 'str'),
|
|
47
|
+
'strcmp': ('__cin_strcmp', 2, 'int'),
|
|
48
|
+
'trim': ('__cin_trim', 1, 'str'),
|
|
49
|
+
'sqrt': ('__cin_sqrt', 1, 'float'),
|
|
50
|
+
'pow': ('pow', 2, 'float'),
|
|
51
|
+
'floor': ('floor', 1, 'float'),
|
|
52
|
+
'ceil': ('ceil', 1, 'float'),
|
|
53
|
+
'round': ('round', 1, 'float'),
|
|
54
|
+
'sin': ('sin', 1, 'float'),
|
|
55
|
+
'cos': ('cos', 1, 'float'),
|
|
56
|
+
'tan': ('tan', 1, 'float'),
|
|
57
|
+
'fabs': ('fabs', 1, 'float'),
|
|
58
|
+
'float_to_str': ('__cin_ftoa', 1, 'str'),
|
|
59
|
+
'time': ('__cin_time', 0, 'int'),
|
|
60
|
+
'rand': ('__cin_rand', 0, 'int'),
|
|
61
|
+
'srand': ('__cin_srand', 1, 'int'),
|
|
62
|
+
}
|
|
63
|
+
|
|
64
|
+
_PREAMBLE = ('#include <stdint.h>\n#include <stdio.h>\n#include <string.h>\n'
|
|
65
|
+
'#include <stdlib.h>\n#include <math.h>\n#include <time.h>\n\n'
|
|
66
|
+
'static double __cin_sqrt(double x) { return sqrt(x); }\n'
|
|
67
|
+
'static int64_t __cin_time(void) { return (int64_t)time(NULL); }\n'
|
|
68
|
+
'static int64_t __cin_rand(void) { return (int64_t)rand(); }\n'
|
|
69
|
+
'static int64_t __cin_srand(int64_t seed) { '
|
|
70
|
+
'srand((unsigned)seed); return 0; }\n'
|
|
71
|
+
'static int64_t __cin_strlen(const char *s) { '
|
|
72
|
+
'return (int64_t)strlen(s); }\n'
|
|
73
|
+
'static int64_t __cin_abs(int64_t v) { return v < 0 ? -v : v; }\n'
|
|
74
|
+
'static int64_t __cin_indexof(const char *h, const char *n) {\n'
|
|
75
|
+
' const char *p = strstr(h, n);\n'
|
|
76
|
+
' return p ? (int64_t)(p - h) : -1;\n'
|
|
77
|
+
'}\n'
|
|
78
|
+
'static int64_t __cin_atoi(const char *s) { '
|
|
79
|
+
'return (int64_t)strtoll(s, NULL, 10); }\n'
|
|
80
|
+
'static int64_t __cin_idiv(int64_t a, int64_t b) { '
|
|
81
|
+
'return b ? a / b : 0; }\n'
|
|
82
|
+
'static int64_t __cin_min(int64_t a, int64_t b) { '
|
|
83
|
+
'return a < b ? a : b; }\n'
|
|
84
|
+
'static int64_t __cin_max(int64_t a, int64_t b) { '
|
|
85
|
+
'return a > b ? a : b; }\n'
|
|
86
|
+
'static void __cin_print_int(int64_t v) { printf("%lld", '
|
|
87
|
+
'(long long)v); }\n'
|
|
88
|
+
'static void __cin_println_int(int64_t v) { '
|
|
89
|
+
'printf("%lld\\n", (long long)v); }\n'
|
|
90
|
+
'static void __cin_print_bool(int64_t v) { '
|
|
91
|
+
'printf("%s", v ? "true" : "false"); }\n'
|
|
92
|
+
'static void __cin_println_bool(int64_t v) { '
|
|
93
|
+
'printf("%s\\n", v ? "true" : "false"); }\n'
|
|
94
|
+
'static void __cin_print_str(const char *s) { printf("%s", s); }\n'
|
|
95
|
+
'static void __cin_println_str(const char *s) { '
|
|
96
|
+
'printf("%s\\n", s); }\n'
|
|
97
|
+
'static void __cin_print_float(double v) { printf("%g", v); }\n'
|
|
98
|
+
'static void __cin_println_float(double v) { '
|
|
99
|
+
'printf("%g\\n", v); }\n'
|
|
100
|
+
'static char __cin_arena[65536];\n'
|
|
101
|
+
'static size_t __cin_arena_used = 0;\n'
|
|
102
|
+
'static char *__cin_alloc(size_t n) {\n'
|
|
103
|
+
' char *p;\n'
|
|
104
|
+
' if (__cin_arena_used + n > sizeof(__cin_arena)) return NULL;\n'
|
|
105
|
+
' p = __cin_arena + __cin_arena_used;\n'
|
|
106
|
+
' __cin_arena_used += n;\n'
|
|
107
|
+
' return p;\n'
|
|
108
|
+
'}\n'
|
|
109
|
+
'static const char *__cin_substr(const char *s, int64_t start, '
|
|
110
|
+
'int64_t len) {\n'
|
|
111
|
+
' int64_t n = (int64_t)strlen(s), e;\n'
|
|
112
|
+
' char *p;\n'
|
|
113
|
+
' if (start < 0) start = 0;\n'
|
|
114
|
+
' if (start > n) start = n;\n'
|
|
115
|
+
' if (len < 0) len = 0;\n'
|
|
116
|
+
' e = start + len;\n'
|
|
117
|
+
' if (e > n) e = n;\n'
|
|
118
|
+
' p = __cin_alloc((size_t)(e - start) + 1);\n'
|
|
119
|
+
' if (!p) return "";\n'
|
|
120
|
+
' memcpy(p, s + start, (size_t)(e - start));\n'
|
|
121
|
+
' p[e - start] = 0;\n'
|
|
122
|
+
' return p;\n'
|
|
123
|
+
'}\n'
|
|
124
|
+
'static const char *__cin_case(const char *s, int up) {\n'
|
|
125
|
+
' size_t n = strlen(s), i;\n'
|
|
126
|
+
' char *p = __cin_alloc(n + 1);\n'
|
|
127
|
+
' if (!p) return "";\n'
|
|
128
|
+
' for (i = 0; i < n; i++) {\n'
|
|
129
|
+
' char c = s[i];\n'
|
|
130
|
+
' if (up && c >= 97 && c <= 122) c -= 32;\n'
|
|
131
|
+
' if (!up && c >= 65 && c <= 90) c += 32;\n'
|
|
132
|
+
' p[i] = c;\n'
|
|
133
|
+
' }\n'
|
|
134
|
+
' p[n] = 0;\n'
|
|
135
|
+
' return p;\n'
|
|
136
|
+
'}\n'
|
|
137
|
+
'static const char *__cin_itoa(int64_t v) {\n'
|
|
138
|
+
' char *p = __cin_alloc(32);\n'
|
|
139
|
+
' if (!p) return "";\n'
|
|
140
|
+
' snprintf(p, 32, "%lld", (long long)v);\n'
|
|
141
|
+
' return p;\n'
|
|
142
|
+
'}\n'
|
|
143
|
+
'static int64_t __cin_strcmp(const char *a, const char *b) {\n'
|
|
144
|
+
' return (int64_t)strcmp(a, b);\n'
|
|
145
|
+
'}\n'
|
|
146
|
+
'static const char *__cin_ftoa(double v) {\n'
|
|
147
|
+
' char *p = __cin_alloc(64);\n'
|
|
148
|
+
' if (!p) return "";\n'
|
|
149
|
+
' snprintf(p, 64, "%g", v);\n'
|
|
150
|
+
' return p;\n'
|
|
151
|
+
'}\n'
|
|
152
|
+
'static const char *__cin_trim(const char *s) {\n'
|
|
153
|
+
' size_t b = 0, e = strlen(s);\n'
|
|
154
|
+
' char *p;\n'
|
|
155
|
+
' while (s[b] == 32 || s[b] == 9 || s[b] == 10 || s[b] == 13)\n'
|
|
156
|
+
' b++;\n'
|
|
157
|
+
' while (e > b && (s[e-1] == 32 || s[e-1] == 9 || '
|
|
158
|
+
's[e-1] == 10 || s[e-1] == 13)) e--;\n'
|
|
159
|
+
' p = __cin_alloc(e - b + 1);\n'
|
|
160
|
+
' if (!p) return "";\n'
|
|
161
|
+
' memcpy(p, s + b, e - b);\n'
|
|
162
|
+
' p[e - b] = 0;\n'
|
|
163
|
+
' return p;\n'
|
|
164
|
+
'}\n'
|
|
165
|
+
'static const char *__cin_concat(const char *a, const char *b) {\n'
|
|
166
|
+
' size_t na = strlen(a), nb = strlen(b);\n'
|
|
167
|
+
' char *p;\n'
|
|
168
|
+
' if (__cin_arena_used + na + nb + 1 > sizeof(__cin_arena))\n'
|
|
169
|
+
' return "";\n'
|
|
170
|
+
' p = __cin_arena + __cin_arena_used;\n'
|
|
171
|
+
' memcpy(p, a, na);\n'
|
|
172
|
+
' memcpy(p + na, b, nb + 1);\n'
|
|
173
|
+
' __cin_arena_used += na + nb + 1;\n'
|
|
174
|
+
' return p;\n'
|
|
175
|
+
'}\n\n')
|
|
176
|
+
|
|
177
|
+
|
|
178
|
+
def _c_string(text: str) -> str:
|
|
179
|
+
out = []
|
|
180
|
+
for byte in text.encode('utf-8'):
|
|
181
|
+
if byte == 0x22 or byte == 0x5C:
|
|
182
|
+
out.append('\\' + chr(byte))
|
|
183
|
+
elif 32 <= byte < 127:
|
|
184
|
+
out.append(chr(byte))
|
|
185
|
+
else:
|
|
186
|
+
out.append('\\%03o' % byte)
|
|
187
|
+
return '"' + ''.join(out) + '"'
|
|
188
|
+
|
|
189
|
+
|
|
190
|
+
class NativeGenError(RuntimeError):
|
|
191
|
+
"""AST 超出直接原生后端当前支持的语言子集。"""
|
|
192
|
+
|
|
193
|
+
|
|
194
|
+
def _typename(t: Any) -> str:
|
|
195
|
+
if isinstance(t, tuple) and t[0] == 'struct':
|
|
196
|
+
return f'cin_{t[1]}'
|
|
197
|
+
if isinstance(t, tuple) and t[0] == 'ptrarray':
|
|
198
|
+
return 'int64_t *'
|
|
199
|
+
if t == 'int':
|
|
200
|
+
return 'int64_t'
|
|
201
|
+
if t == 'bool':
|
|
202
|
+
return 'int64_t'
|
|
203
|
+
if t == 'float':
|
|
204
|
+
return 'double'
|
|
205
|
+
if t == 'string':
|
|
206
|
+
return 'const char *'
|
|
207
|
+
if t == 'void':
|
|
208
|
+
return 'void'
|
|
209
|
+
raise NativeGenError(f'直接原生后端暂不支持类型: {t!r}')
|
|
210
|
+
|
|
211
|
+
|
|
212
|
+
def _field_ctype(t: Any) -> str:
|
|
213
|
+
if t == 'int':
|
|
214
|
+
return 'int64_t'
|
|
215
|
+
if t == 'bool':
|
|
216
|
+
return 'int64_t'
|
|
217
|
+
if t == 'float':
|
|
218
|
+
return 'double'
|
|
219
|
+
if t == 'string':
|
|
220
|
+
return 'const char *'
|
|
221
|
+
raise NativeGenError(f'struct 字段类型 {t!r} 暂不支持')
|
|
222
|
+
|
|
223
|
+
|
|
224
|
+
class _Generator:
|
|
225
|
+
def __init__(self, functions: Dict[str, Any],
|
|
226
|
+
structs: Optional[Dict[str, Any]] = None,
|
|
227
|
+
globals_: Optional[List[Any]] = None):
|
|
228
|
+
self.functions = functions
|
|
229
|
+
self.structs = structs or {}
|
|
230
|
+
self.globals = globals_ or []
|
|
231
|
+
self.global_names = {self._sanitize(g.name) for g in self.globals}
|
|
232
|
+
self.lines: List[str] = []
|
|
233
|
+
self.vars: List[str] = []
|
|
234
|
+
self.types: Dict[str, str] = {}
|
|
235
|
+
self.arrays: Dict[str, int] = {}
|
|
236
|
+
self.buf: List[str] = []
|
|
237
|
+
|
|
238
|
+
# ---------- 发射 ----------
|
|
239
|
+
|
|
240
|
+
def emit(self, text: str = '') -> None:
|
|
241
|
+
self.lines.append(text)
|
|
242
|
+
|
|
243
|
+
@staticmethod
|
|
244
|
+
def _sanitize(name: str) -> str:
|
|
245
|
+
out = ''.join(c if c.isalnum() or c == '_' else '_' for c in name)
|
|
246
|
+
return 'v_' + out if out[:1].isdigit() else out
|
|
247
|
+
|
|
248
|
+
@classmethod
|
|
249
|
+
def _fname(cls, name: str) -> str:
|
|
250
|
+
# 用户函数统一加前缀, 避免与 C 的 main / 运行库符号冲突
|
|
251
|
+
return 'fn_' + cls._sanitize(name)
|
|
252
|
+
|
|
253
|
+
# ---------- 表达式 ----------
|
|
254
|
+
|
|
255
|
+
def expr(self, node: AST) -> str:
|
|
256
|
+
kind = node[0]
|
|
257
|
+
if kind == 'num':
|
|
258
|
+
value = node[1]
|
|
259
|
+
if node[2]: # 浮点字面量
|
|
260
|
+
return f'{float(value)!r}'
|
|
261
|
+
return f'INT64_C({int(value)})'
|
|
262
|
+
if kind == 'var':
|
|
263
|
+
return self._sanitize(node[1])
|
|
264
|
+
if kind == 'bool':
|
|
265
|
+
return '1' if node[1] else '0'
|
|
266
|
+
if kind == 'not':
|
|
267
|
+
return f'(!{self.expr(node[1])})'
|
|
268
|
+
if kind == 'bitnot':
|
|
269
|
+
return f'(~{self.expr(node[1])})'
|
|
270
|
+
if kind == 'neg':
|
|
271
|
+
return f'(-{self.expr(node[1])})'
|
|
272
|
+
if kind == 'binop':
|
|
273
|
+
op = node[1]
|
|
274
|
+
lt, rt = self.arg_type(node[2]), self.arg_type(node[3])
|
|
275
|
+
if 'str' in (lt, rt):
|
|
276
|
+
if op in ('==', '!='):
|
|
277
|
+
cmp = '==' if op == '==' else '!='
|
|
278
|
+
return (f'(strcmp({self.expr(node[2])}, '
|
|
279
|
+
f'{self.expr(node[3])}) {cmp} 0)')
|
|
280
|
+
if op == '+':
|
|
281
|
+
return (f'__cin_concat({self.expr(node[2])}, '
|
|
282
|
+
f'{self.expr(node[3])})')
|
|
283
|
+
raise NativeGenError(f'字符串不支持运算符: {op!r}')
|
|
284
|
+
if op in _BINOPS:
|
|
285
|
+
return (f'({self.expr(node[2])} {_BINOPS[op]} '
|
|
286
|
+
f'{self.expr(node[3])})')
|
|
287
|
+
raise NativeGenError(f'直接原生后端暂不支持运算符: {op!r}')
|
|
288
|
+
if kind == 'index':
|
|
289
|
+
return f'{self.expr(node[1])}[{self.expr(node[2])}]'
|
|
290
|
+
if kind == 'member':
|
|
291
|
+
if node[1][0] != 'var':
|
|
292
|
+
raise NativeGenError('暂不支持嵌套 struct 成员访问')
|
|
293
|
+
base = self._sanitize(node[1][1])
|
|
294
|
+
return f'{base}.{node[2]}'
|
|
295
|
+
if kind == 'str':
|
|
296
|
+
return _c_string(node[1])
|
|
297
|
+
if kind == 'call':
|
|
298
|
+
return self.call(node[1], node[2])
|
|
299
|
+
raise NativeGenError(f'直接原生后端暂不支持表达式节点: {kind!r}')
|
|
300
|
+
|
|
301
|
+
def arg_type(self, arg: AST) -> str:
|
|
302
|
+
kind = arg[0]
|
|
303
|
+
if kind == 'str':
|
|
304
|
+
return 'str'
|
|
305
|
+
if kind == 'num':
|
|
306
|
+
return 'float' if arg[2] else 'int'
|
|
307
|
+
if kind == 'var':
|
|
308
|
+
t = self.types.get(arg[1], 'int')
|
|
309
|
+
return 'str' if t == 'string' else t
|
|
310
|
+
if kind == 'index':
|
|
311
|
+
base = arg[1]
|
|
312
|
+
if base[0] == 'var':
|
|
313
|
+
t = str(self.types.get(base[1], ''))
|
|
314
|
+
if t.startswith('array:') or t.startswith('ptrarray:'):
|
|
315
|
+
elem = t.split(':', 1)[1]
|
|
316
|
+
return 'str' if elem == 'string' else elem
|
|
317
|
+
return 'int'
|
|
318
|
+
if kind == 'member':
|
|
319
|
+
if arg[1][0] != 'var':
|
|
320
|
+
return 'int'
|
|
321
|
+
t = str(self.types.get(arg[1][1], ''))
|
|
322
|
+
if not t.startswith('struct:'):
|
|
323
|
+
return 'int'
|
|
324
|
+
sd = self.structs.get(t.split(':', 1)[1])
|
|
325
|
+
if sd is not None:
|
|
326
|
+
for fname, ftype in sd.fields:
|
|
327
|
+
if fname == arg[2]:
|
|
328
|
+
return 'str' if ftype == 'string' else ftype
|
|
329
|
+
return 'int'
|
|
330
|
+
if kind == 'neg':
|
|
331
|
+
return self.arg_type(arg[1])
|
|
332
|
+
if kind == 'not':
|
|
333
|
+
return 'bool'
|
|
334
|
+
if kind == 'bool':
|
|
335
|
+
return 'bool'
|
|
336
|
+
if kind == 'binop':
|
|
337
|
+
lt, rt = self.arg_type(arg[2]), self.arg_type(arg[3])
|
|
338
|
+
if arg[1] in ('==', '!=', '<', '<=', '>', '>=', '&&', '||'):
|
|
339
|
+
return 'bool'
|
|
340
|
+
if 'str' in (lt, rt):
|
|
341
|
+
return 'str'
|
|
342
|
+
return 'float' if 'float' in (lt, rt) else 'int'
|
|
343
|
+
if kind == 'call':
|
|
344
|
+
if arg[1] in _BUILTINS:
|
|
345
|
+
return _BUILTINS[arg[1]][2]
|
|
346
|
+
fn = self.functions.get(arg[1])
|
|
347
|
+
ret = (fn.ret_type if fn is not None else None) or 'int'
|
|
348
|
+
if isinstance(ret, tuple) and ret[0] == 'struct':
|
|
349
|
+
return 'struct:' + ret[1]
|
|
350
|
+
return 'str' if ret == 'string' else ret
|
|
351
|
+
return 'int'
|
|
352
|
+
|
|
353
|
+
def call(self, name: str, args: Sequence[AST]) -> str:
|
|
354
|
+
if name in ('print', 'println'):
|
|
355
|
+
if len(args) != 1:
|
|
356
|
+
raise NativeGenError(f'{name}() 需要恰好 1 个参数')
|
|
357
|
+
arg = args[0]
|
|
358
|
+
kind = self.arg_type(arg)
|
|
359
|
+
suffix = 'ln' if name == 'println' else ''
|
|
360
|
+
if kind == 'str':
|
|
361
|
+
inner = _c_string(arg[1]) if arg[0] == 'str' \
|
|
362
|
+
else self.expr(arg)
|
|
363
|
+
return f'__cin_print{suffix}_str({inner})'
|
|
364
|
+
if kind == 'bool':
|
|
365
|
+
return f'__cin_print{suffix}_bool({self.expr(arg)})'
|
|
366
|
+
if kind == 'float':
|
|
367
|
+
return f'__cin_print{suffix}_float({self.expr(arg)})'
|
|
368
|
+
return f'__cin_print{suffix}_int({self.expr(arg)})'
|
|
369
|
+
if name in _BUILTINS:
|
|
370
|
+
fn, arity, _ret = _BUILTINS[name]
|
|
371
|
+
if len(args) != arity:
|
|
372
|
+
raise NativeGenError(f'{name}() 需要 {arity} 个参数')
|
|
373
|
+
if name in ('upper', 'lower'):
|
|
374
|
+
flag = 1 if name == 'upper' else 0
|
|
375
|
+
return f'{fn}({self.expr(args[0])}, {flag})'
|
|
376
|
+
return f'{fn}({", ".join(self.expr(a) for a in args)})'
|
|
377
|
+
if name not in self.functions:
|
|
378
|
+
raise NativeGenError(f'直接原生后端暂不支持内建/外部函数: {name!r}')
|
|
379
|
+
callee = self.functions[name]
|
|
380
|
+
if len(callee.params) != len(args):
|
|
381
|
+
raise NativeGenError(f'{name}() 参数数量不匹配')
|
|
382
|
+
rendered = ', '.join(self.expr(a) for a in args)
|
|
383
|
+
return f'{self._fname(name)}({rendered})'
|
|
384
|
+
|
|
385
|
+
# ---------- 语句 ----------
|
|
386
|
+
|
|
387
|
+
def declare(self, name: str, typ: Any) -> str:
|
|
388
|
+
cname = self._sanitize(name)
|
|
389
|
+
if isinstance(typ, tuple) and typ[0] == 'array':
|
|
390
|
+
base, size = typ[1], typ[2]
|
|
391
|
+
if base not in ('int', 'float', 'string', 'bool'):
|
|
392
|
+
raise NativeGenError(f'数组元素类型 {base!r} 暂不支持')
|
|
393
|
+
if not isinstance(size, int):
|
|
394
|
+
raise NativeGenError('数组长度必须是整数字面量')
|
|
395
|
+
self.arrays[cname] = int(size)
|
|
396
|
+
self.types[cname] = 'array:' + base
|
|
397
|
+
elif isinstance(typ, tuple) and typ[0] == 'ptrarray':
|
|
398
|
+
if typ[1] != 'int':
|
|
399
|
+
raise NativeGenError(f'数组类型 {typ[1]!r} 暂不支持')
|
|
400
|
+
self.types[cname] = 'ptrarray'
|
|
401
|
+
elif isinstance(typ, tuple) and typ[0] == 'struct':
|
|
402
|
+
if typ[1] not in self.structs:
|
|
403
|
+
raise NativeGenError(f'未知 struct 类型: {typ[1]!r}')
|
|
404
|
+
self.types[cname] = 'struct:' + typ[1]
|
|
405
|
+
elif typ in ('int', 'bool', 'float', 'string'):
|
|
406
|
+
self.types[cname] = typ
|
|
407
|
+
else:
|
|
408
|
+
raise NativeGenError(f'直接原生后端暂不支持声明类型: {typ!r}')
|
|
409
|
+
if cname not in self.vars:
|
|
410
|
+
self.vars.append(cname)
|
|
411
|
+
return cname
|
|
412
|
+
|
|
413
|
+
def assign(self, target: AST, value: str) -> str:
|
|
414
|
+
if target[0] == 'var':
|
|
415
|
+
cname = self._sanitize(target[1])
|
|
416
|
+
if cname not in self.vars and cname not in self.global_names:
|
|
417
|
+
self.vars.append(cname)
|
|
418
|
+
self.types.setdefault(cname, 'int')
|
|
419
|
+
return f'{cname} = {value}'
|
|
420
|
+
if target[0] == 'index':
|
|
421
|
+
return f'{self.expr(target[1])}[{self.expr(target[2])}] = {value}'
|
|
422
|
+
if target[0] == 'member':
|
|
423
|
+
return f'{self.expr(target)} = {value}'
|
|
424
|
+
raise NativeGenError('直接原生后端暂不支持该赋值目标')
|
|
425
|
+
|
|
426
|
+
def simple_stmt(self, node: AST) -> str:
|
|
427
|
+
"""for 的 init/step 这类单行语句, 返回 C 片段 (不含分号)。"""
|
|
428
|
+
if node[0] == 'decl':
|
|
429
|
+
name, typ, init, _extra = node[1][0]
|
|
430
|
+
cname = self.declare(name, typ)
|
|
431
|
+
if isinstance(typ, tuple):
|
|
432
|
+
raise NativeGenError('for 初始化里不能声明数组')
|
|
433
|
+
return f'{cname} = {self.expr(init) if init else 0}'
|
|
434
|
+
if node[0] == 'expr':
|
|
435
|
+
inner = node[1]
|
|
436
|
+
if inner[0] == 'binop' and inner[1] == '=':
|
|
437
|
+
return self.assign(inner[2], self.expr(inner[3]))
|
|
438
|
+
if inner[0] == 'call':
|
|
439
|
+
return self.call(inner[1], inner[2])
|
|
440
|
+
raise NativeGenError(f'for 的 init/step 不支持该语句: {node[0]!r}')
|
|
441
|
+
|
|
442
|
+
def stmt(self, node: AST, indent: int) -> None:
|
|
443
|
+
pad = ' ' * indent
|
|
444
|
+
kind = node[0]
|
|
445
|
+
if kind == 'decl':
|
|
446
|
+
for name, typ, init, _extra in node[1]:
|
|
447
|
+
cname = self.declare(name, typ)
|
|
448
|
+
if isinstance(typ, tuple) and typ[0] == 'array':
|
|
449
|
+
if init is not None:
|
|
450
|
+
raise NativeGenError('暂不支持数组初始化列表')
|
|
451
|
+
continue
|
|
452
|
+
if init is None:
|
|
453
|
+
if isinstance(typ, tuple) and typ[0] == 'struct':
|
|
454
|
+
continue # 已在 hoist 处零初始化
|
|
455
|
+
if typ == 'string':
|
|
456
|
+
self.emit(f'{pad}{cname} = "";')
|
|
457
|
+
else:
|
|
458
|
+
self.emit(f'{pad}{cname} = 0;')
|
|
459
|
+
else:
|
|
460
|
+
if typ != 'string' and init[0] == 'str':
|
|
461
|
+
raise NativeGenError(
|
|
462
|
+
f'{name}: 字符串字面量不能赋给 {typ!r} 变量')
|
|
463
|
+
self.emit(f'{pad}{cname} = {self.expr(init)};')
|
|
464
|
+
return
|
|
465
|
+
if kind == 'block':
|
|
466
|
+
for child in node[1]:
|
|
467
|
+
self.stmt(child, indent)
|
|
468
|
+
return
|
|
469
|
+
if kind == 'if':
|
|
470
|
+
self.emit(f'{pad}if ({self.expr(node[1])}) {{')
|
|
471
|
+
self.stmt(node[2], indent + 1)
|
|
472
|
+
if node[3] is not None:
|
|
473
|
+
self.emit(f'{pad}}} else {{')
|
|
474
|
+
self.stmt(node[3], indent + 1)
|
|
475
|
+
self.emit(f'{pad}}}')
|
|
476
|
+
return
|
|
477
|
+
if kind == 'while':
|
|
478
|
+
self.emit(f'{pad}while ({self.expr(node[1])}) {{')
|
|
479
|
+
self.stmt(node[2], indent + 1)
|
|
480
|
+
self.emit(f'{pad}}}')
|
|
481
|
+
return
|
|
482
|
+
if kind == 'for':
|
|
483
|
+
init = self.simple_stmt(node[1]) if node[1] else ''
|
|
484
|
+
cond = self.expr(node[2])
|
|
485
|
+
step = self.simple_stmt(node[3]) if node[3] else ''
|
|
486
|
+
self.emit(f'{pad}for ({init}; {cond}; {step}) {{')
|
|
487
|
+
self.stmt(node[4], indent + 1)
|
|
488
|
+
self.emit(f'{pad}}}')
|
|
489
|
+
return
|
|
490
|
+
if kind == 'break':
|
|
491
|
+
self.emit(f'{pad}break;')
|
|
492
|
+
return
|
|
493
|
+
if kind == 'continue':
|
|
494
|
+
self.emit(f'{pad}continue;')
|
|
495
|
+
return
|
|
496
|
+
if kind == 'return':
|
|
497
|
+
value = node[1]
|
|
498
|
+
self.emit(f'{pad}return {self.expr(value) if value else 0};')
|
|
499
|
+
return
|
|
500
|
+
if kind == 'expr':
|
|
501
|
+
inner = node[1]
|
|
502
|
+
if inner[0] == 'call' and inner[1] in ('print', 'println'):
|
|
503
|
+
self.emit(f'{pad}{self.call(inner[1], inner[2])};')
|
|
504
|
+
return
|
|
505
|
+
if inner[0] == 'binop' and inner[1] == '=':
|
|
506
|
+
self.emit(f'{pad}{self.assign(inner[2], self.expr(inner[3]))};')
|
|
507
|
+
return
|
|
508
|
+
if inner[0] == 'call':
|
|
509
|
+
self.emit(f'{pad}{self.call(inner[1], inner[2])};')
|
|
510
|
+
return
|
|
511
|
+
raise NativeGenError(f'直接原生后端暂不支持表达式语句: {inner[0]!r}')
|
|
512
|
+
raise NativeGenError(f'直接原生后端暂不支持语句: {kind!r}')
|
|
513
|
+
|
|
514
|
+
# ---------- 函数 ----------
|
|
515
|
+
|
|
516
|
+
def globals_block(self) -> None:
|
|
517
|
+
for gv in self.globals:
|
|
518
|
+
name = self._sanitize(gv.name)
|
|
519
|
+
vtype = gv.vtype
|
|
520
|
+
if isinstance(vtype, tuple) and vtype[0] == 'array':
|
|
521
|
+
self.emit(f'static int64_t {name}[{vtype[2]}];')
|
|
522
|
+
elif vtype == 'float':
|
|
523
|
+
self.emit(f'static double {name} = 0.0;')
|
|
524
|
+
elif vtype == 'string':
|
|
525
|
+
self.emit(f'static const char *{name} = "";')
|
|
526
|
+
elif isinstance(vtype, tuple) and vtype[0] == 'struct':
|
|
527
|
+
self.emit(f'static cin_{vtype[1]} {name};')
|
|
528
|
+
else:
|
|
529
|
+
self.emit(f'static int64_t {name} = 0;')
|
|
530
|
+
if self.globals:
|
|
531
|
+
self.emit('')
|
|
532
|
+
|
|
533
|
+
def globals_init(self) -> None:
|
|
534
|
+
for gv in self.globals:
|
|
535
|
+
vtype = gv.vtype
|
|
536
|
+
key = self._sanitize(gv.name)
|
|
537
|
+
if isinstance(vtype, tuple) and vtype[0] == 'struct':
|
|
538
|
+
self.types[key] = 'struct:' + vtype[1]
|
|
539
|
+
elif isinstance(vtype, tuple):
|
|
540
|
+
self.types[key] = 'array'
|
|
541
|
+
else:
|
|
542
|
+
self.types[key] = vtype
|
|
543
|
+
assigns: List[str] = []
|
|
544
|
+
for gv in self.globals:
|
|
545
|
+
if gv.init is None or gv.array_lit is not None:
|
|
546
|
+
continue
|
|
547
|
+
name = self._sanitize(gv.name)
|
|
548
|
+
assigns.append(f' {name} = {self.expr(gv.init)};')
|
|
549
|
+
self.emit('static void __cin_init_globals(void) {')
|
|
550
|
+
for line in assigns:
|
|
551
|
+
self.emit(line)
|
|
552
|
+
self.emit('}')
|
|
553
|
+
self.emit('')
|
|
554
|
+
|
|
555
|
+
def params_of(self, fdef: Any) -> List[str]:
|
|
556
|
+
params: List[str] = []
|
|
557
|
+
for pname, ptype in fdef.params:
|
|
558
|
+
if isinstance(ptype, tuple) and ptype[0] == 'struct':
|
|
559
|
+
if ptype[1] not in self.structs:
|
|
560
|
+
raise NativeGenError(f'未知 struct 类型: {ptype[1]!r}')
|
|
561
|
+
ctype = f'cin_{ptype[1]}'
|
|
562
|
+
elif isinstance(ptype, tuple) and ptype[0] == 'ptrarray':
|
|
563
|
+
if ptype[1] == 'int':
|
|
564
|
+
ctype = 'int64_t *'
|
|
565
|
+
elif ptype[1] == 'float':
|
|
566
|
+
ctype = 'double *'
|
|
567
|
+
elif ptype[1] == 'string':
|
|
568
|
+
ctype = 'const char **'
|
|
569
|
+
else:
|
|
570
|
+
raise NativeGenError(
|
|
571
|
+
f'数组参数元素类型 {ptype[1]!r} 暂不支持')
|
|
572
|
+
elif ptype in ('int', 'bool', 'float', 'string'):
|
|
573
|
+
ctype = 'double' if ptype == 'float' else (
|
|
574
|
+
'const char *' if ptype == 'string' else 'int64_t')
|
|
575
|
+
else:
|
|
576
|
+
raise NativeGenError(
|
|
577
|
+
f'{fdef.name}: 参数类型 {ptype!r} 暂不支持')
|
|
578
|
+
params.append(f'{ctype} {self._sanitize(pname)}')
|
|
579
|
+
return params
|
|
580
|
+
|
|
581
|
+
def signature(self, fdef: Any) -> str:
|
|
582
|
+
ret = _typename(fdef.ret_type)
|
|
583
|
+
params = self.params_of(fdef)
|
|
584
|
+
return (f'static {ret} {self._fname(fdef.name)}('
|
|
585
|
+
f'{", ".join(params) if params else "void"})')
|
|
586
|
+
|
|
587
|
+
def function(self, fdef: Any) -> None:
|
|
588
|
+
ret = _typename(fdef.ret_type)
|
|
589
|
+
param_names = {self._sanitize(p[0]) for p in fdef.params}
|
|
590
|
+
self.vars = list(param_names)
|
|
591
|
+
self.arrays = {}
|
|
592
|
+
self.types = {}
|
|
593
|
+
for _pname, _ptype in fdef.params:
|
|
594
|
+
_key = self._sanitize(_pname)
|
|
595
|
+
if isinstance(_ptype, tuple) and _ptype[0] == 'struct':
|
|
596
|
+
self.types[_key] = 'struct:' + _ptype[1]
|
|
597
|
+
elif isinstance(_ptype, tuple) and _ptype[0] == 'ptrarray':
|
|
598
|
+
self.types[_key] = 'ptrarray:' + str(_ptype[1])
|
|
599
|
+
else:
|
|
600
|
+
self.types[_key] = _ptype
|
|
601
|
+
body: List[str] = []
|
|
602
|
+
saved = self.lines
|
|
603
|
+
self.lines = body
|
|
604
|
+
try:
|
|
605
|
+
for stmt in fdef.body:
|
|
606
|
+
self.stmt(stmt, 1)
|
|
607
|
+
finally:
|
|
608
|
+
self.lines = saved
|
|
609
|
+
head = self.signature(fdef) + ' {\n'
|
|
610
|
+
local = [v for v in self.vars if v not in param_names]
|
|
611
|
+
decls = ''
|
|
612
|
+
if local:
|
|
613
|
+
parts = []
|
|
614
|
+
for v in local:
|
|
615
|
+
size = self.arrays.get(v)
|
|
616
|
+
if size is not None:
|
|
617
|
+
base = str(self.types.get(v, 'array:int')).split(':', 1)[-1]
|
|
618
|
+
ctype = {'float': 'double', 'string': 'const char *',
|
|
619
|
+
'bool': 'int64_t'}.get(base, 'int64_t')
|
|
620
|
+
parts.append(f'{ctype} {v}[{size}] = {{0}};')
|
|
621
|
+
elif self.types.get(v) == 'float':
|
|
622
|
+
parts.append(f'double {v} = 0.0;')
|
|
623
|
+
elif self.types.get(v) == 'string':
|
|
624
|
+
parts.append(f'const char *{v} = "";')
|
|
625
|
+
elif self.types.get(v) == 'ptrarray':
|
|
626
|
+
parts.append(f'int64_t *{v} = 0;')
|
|
627
|
+
elif str(self.types.get(v, '')).startswith('struct:'):
|
|
628
|
+
name = self.types[v].split(':', 1)[1]
|
|
629
|
+
parts.append(f'cin_{name} {v} = {{0}};')
|
|
630
|
+
else:
|
|
631
|
+
parts.append(f'int64_t {v} = 0;')
|
|
632
|
+
decls = ' ' + ' '.join(parts) + '\n'
|
|
633
|
+
self.emit(head + decls + '\n'.join(body) + '\n}\n')
|
|
634
|
+
|
|
635
|
+
|
|
636
|
+
def supports_source(source: str) -> bool:
|
|
637
|
+
"""该源码能否由直接原生后端编译(不抛异常)。"""
|
|
638
|
+
try:
|
|
639
|
+
emit_c(source)
|
|
640
|
+
return True
|
|
641
|
+
except NativeGenError:
|
|
642
|
+
return False
|
|
643
|
+
|
|
644
|
+
|
|
645
|
+
def _strip_imports(text: str) -> str:
|
|
646
|
+
"""去掉 ``import`` 行(Parser 不认 import, 由调用方先展开闭包)。"""
|
|
647
|
+
import re
|
|
648
|
+
return re.sub(r'(?m)^[ \t]*import[ \t]+[^\n]*\n?', '', text)
|
|
649
|
+
|
|
650
|
+
|
|
651
|
+
def _parse_one(source: str):
|
|
652
|
+
from .cin import Parser, tokenize
|
|
653
|
+
return Parser(tokenize(_strip_imports(source))).parse_program()
|
|
654
|
+
|
|
655
|
+
|
|
656
|
+
def _merge(parsed_list):
|
|
657
|
+
structs: Dict[str, Any] = {}
|
|
658
|
+
functions: Dict[str, Any] = {}
|
|
659
|
+
globals_: List[Any] = []
|
|
660
|
+
seen_globals = set()
|
|
661
|
+
for structs_i, globals_i, functions_i, _enums_i in parsed_list:
|
|
662
|
+
for name, sd in structs_i.items():
|
|
663
|
+
if name in structs:
|
|
664
|
+
raise NativeGenError(f'struct 重复定义: {name}')
|
|
665
|
+
structs[name] = sd
|
|
666
|
+
for name, fd in functions_i.items():
|
|
667
|
+
if name in functions:
|
|
668
|
+
raise NativeGenError(f'函数重复定义: {name}')
|
|
669
|
+
functions[name] = fd
|
|
670
|
+
for gv in globals_i:
|
|
671
|
+
if gv.extern:
|
|
672
|
+
continue
|
|
673
|
+
if gv.name in seen_globals:
|
|
674
|
+
raise NativeGenError(f'全局变量重复定义: {gv.name}')
|
|
675
|
+
seen_globals.add(gv.name)
|
|
676
|
+
globals_.append(gv)
|
|
677
|
+
return structs, functions, globals_
|
|
678
|
+
|
|
679
|
+
|
|
680
|
+
def emit_c(source: str, filename: Optional[str] = None,
|
|
681
|
+
require_main: bool = True) -> str:
|
|
682
|
+
"""把 CIN 源码编译成 C 源码(不经过任何指令集)。
|
|
683
|
+
|
|
684
|
+
``filename`` 给出时会解析其 ``import`` 闭包并合并为同一编译单元。
|
|
685
|
+
"""
|
|
686
|
+
from .cin import collect_imported_files
|
|
687
|
+
|
|
688
|
+
parsed = []
|
|
689
|
+
if filename:
|
|
690
|
+
for path in collect_imported_files(filename):
|
|
691
|
+
try:
|
|
692
|
+
with open(path, encoding='utf-8-sig') as f:
|
|
693
|
+
text = f.read()
|
|
694
|
+
parsed.append(_parse_one(text))
|
|
695
|
+
except NativeGenError:
|
|
696
|
+
raise
|
|
697
|
+
except Exception as e: # noqa: BLE001
|
|
698
|
+
raise NativeGenError(f'{path}: 解析失败: {e}') from e
|
|
699
|
+
if not parsed:
|
|
700
|
+
try:
|
|
701
|
+
parsed = [_parse_one(source)]
|
|
702
|
+
except Exception as e: # noqa: BLE001 - 统一转换为 NativeGenError
|
|
703
|
+
raise NativeGenError(f'解析失败: {e}') from e
|
|
704
|
+
|
|
705
|
+
structs, functions, globals_ = _merge(parsed)
|
|
706
|
+
|
|
707
|
+
if 'main' not in functions:
|
|
708
|
+
if require_main:
|
|
709
|
+
raise NativeGenError('缺少 main 函数')
|
|
710
|
+
main_fn = None
|
|
711
|
+
else:
|
|
712
|
+
main_fn = functions['main']
|
|
713
|
+
if main_fn.ret_type not in (None, 'int', 'void'):
|
|
714
|
+
raise NativeGenError('main 必须返回 int 或 void')
|
|
715
|
+
|
|
716
|
+
gen = _Generator(functions, structs, globals_)
|
|
717
|
+
gen.emit(_PREAMBLE)
|
|
718
|
+
for sd in (structs or {}).values():
|
|
719
|
+
fields = ' '.join(f'{_field_ctype(t)} {n};' for n, t in sd.fields)
|
|
720
|
+
gen.emit(f'typedef struct {{ {fields} }} cin_{sd.name};')
|
|
721
|
+
if structs:
|
|
722
|
+
gen.emit('')
|
|
723
|
+
gen.globals_block()
|
|
724
|
+
for fdef in functions.values():
|
|
725
|
+
gen.emit(gen.signature(fdef) + ';')
|
|
726
|
+
gen.emit('')
|
|
727
|
+
gen.globals_init()
|
|
728
|
+
for fdef in functions.values():
|
|
729
|
+
gen.function(fdef)
|
|
730
|
+
if main_fn is not None:
|
|
731
|
+
gen.emit('int main(void) {')
|
|
732
|
+
gen.emit(' __cin_init_globals();')
|
|
733
|
+
if main_fn.ret_type == 'void':
|
|
734
|
+
gen.emit(f' {_Generator._fname("main")}();')
|
|
735
|
+
gen.emit(' return 0;')
|
|
736
|
+
else:
|
|
737
|
+
gen.emit(f' int64_t rc = {_Generator._fname("main")}();')
|
|
738
|
+
gen.emit(' return (int)rc;')
|
|
739
|
+
gen.emit('}')
|
|
740
|
+
return '\n'.join(gen.lines) + '\n'
|
|
741
|
+
|
|
742
|
+
|
|
743
|
+
def compile_native(source: str, out: str, *,
|
|
744
|
+
filename: Optional[str] = None,
|
|
745
|
+
target: Optional[str] = None,
|
|
746
|
+
optimize: int = 2,
|
|
747
|
+
keep_c: bool = False) -> str:
|
|
748
|
+
"""源码 → C → 设备本机可执行文件; 返回产物路径。
|
|
749
|
+
|
|
750
|
+
``filename`` 给出时会编译其 ``import`` 闭包(多文件项目)。
|
|
751
|
+
"""
|
|
752
|
+
from .cbackend import CBackendError, c_target, _host_target_name
|
|
753
|
+
|
|
754
|
+
c_source = emit_c(source, filename=filename)
|
|
755
|
+
target_name = target or _host_target_name()
|
|
756
|
+
spec = toolchain.get_target(target_name)
|
|
757
|
+
info = toolchain.find_compiler(spec)
|
|
758
|
+
zig = None if info is not None else toolchain.find_zig()
|
|
759
|
+
if info is None and zig is None:
|
|
760
|
+
raise toolchain.ToolchainError(toolchain.hint(spec))
|
|
761
|
+
out = os.path.abspath(out)
|
|
762
|
+
if spec.exe and not out.lower().endswith(spec.exe):
|
|
763
|
+
out += spec.exe
|
|
764
|
+
os.makedirs(os.path.dirname(out) or '.', exist_ok=True)
|
|
765
|
+
workdir = tempfile.mkdtemp(prefix='.nativegen-')
|
|
766
|
+
try:
|
|
767
|
+
c_path = os.path.join(workdir, 'program.c')
|
|
768
|
+
with open(c_path, 'w', encoding='utf-8', newline='\n') as f:
|
|
769
|
+
f.write(c_source)
|
|
770
|
+
if keep_c:
|
|
771
|
+
import shutil
|
|
772
|
+
shutil.copyfile(c_path, out + '.c')
|
|
773
|
+
if info is not None:
|
|
774
|
+
cmd = [info.path, f'-O{optimize}', '-std=c11', '-o', out, c_path]
|
|
775
|
+
else:
|
|
776
|
+
cmd = [zig, 'cc', '-target', spec.triple, f'-O{optimize}',
|
|
777
|
+
'-std=c11', '-o', out, c_path]
|
|
778
|
+
result = subprocess.run(cmd, capture_output=True, text=True,
|
|
779
|
+
timeout=600, check=False)
|
|
780
|
+
if result.returncode != 0:
|
|
781
|
+
raise NativeGenError(
|
|
782
|
+
f'C 编译失败:\n{(result.stderr or result.stdout).strip()[:2000]}')
|
|
783
|
+
finally:
|
|
784
|
+
import shutil
|
|
785
|
+
shutil.rmtree(workdir, ignore_errors=True)
|
|
786
|
+
return out
|