rcompiler 2.1.0 → 2.2.0
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.
- package/CHANGELOG.md +11 -0
- package/README.md +15 -2
- package/docs/CONFIG.md +1 -1
- package/docs/NATIVE.md +110 -0
- package/exts/args.js +142 -0
- package/exts/fs.js +317 -0
- package/exts/io.js +396 -0
- package/exts/path.js +208 -0
- package/exts/process.js +416 -0
- package/package.json +1 -1
- package/src/analysis.js +8 -0
- package/src/assets.js +2 -2
- package/src/cli.js +2 -0
- package/src/emit.js +3 -3
- package/src/preludes.js +845 -122
- package/src/rcompiler.js +328 -60
- package/src/standard.js +176 -76
- package/src/web.js +0 -10
- /package/exts/{rcrcHelper.js → rcompilerExt.js} +0 -0
package/CHANGELOG.md
CHANGED
|
@@ -1,5 +1,16 @@
|
|
|
1
1
|
# Changelog
|
|
2
2
|
|
|
3
|
+
## 2.2.0 — 2026-11-27
|
|
4
|
+
|
|
5
|
+
- 本机能力矩阵扩展:fs / process / path / args / io(接口参考 Alia 语言标准库)
|
|
6
|
+
- fs:读写/追加/复制/重命名/删除/目录枚举/元信息(写入自动建父目录;递归枚举跨平台固定 `/`)
|
|
7
|
+
- process:进程信息(PID/平台/架构/RSS)、环境变量、exec(shell)与 spawn(无 shell,
|
|
8
|
+
捕获/直通/丢弃三模式)、退出码与子进程 PID 结果报告器
|
|
9
|
+
- path:join/dir/name/stem/ext/normalize/abs/is_abs/sep(POSIX 语义,纯字符串操作)
|
|
10
|
+
- args:argv 位置读取、布尔标志检测、`--x value` 与 `--x=value` 选项取值、程序名
|
|
11
|
+
- io:print/eprint 系列、`{}` 占位符格式化、stdin 读行/读全部、ANSI 清屏/光标/16 色/样式
|
|
12
|
+
- 运行时全部基于 `std`,零外部 crate;按块按需注册;新增端到端测试(test/native.js)
|
|
13
|
+
|
|
3
14
|
## 2.1.0 — 2026-11-05
|
|
4
15
|
|
|
5
16
|
首次公开发布。
|
package/README.md
CHANGED
|
@@ -103,14 +103,14 @@ WASM 舞台由 `scratch-render` 负责 WebGL/SVG/位图/图层/特效/画笔/拾
|
|
|
103
103
|
|
|
104
104
|
## 项目设置
|
|
105
105
|
|
|
106
|
-
在编辑器中通过 `exts/
|
|
106
|
+
在编辑器中通过 `exts/rcompilerExt.js` 打开配置面板;设置保存在项目的 `extensionStorage` 中,随项目保存:
|
|
107
107
|
|
|
108
108
|
- **编译器配置**:安全选项、抗逆向模式(normal / obf / debug)
|
|
109
109
|
- **项目配置**:舞台/帧率/插值三态、手动类型描述、打包选项、自动忽略扩展
|
|
110
110
|
|
|
111
111
|
优先级:面板显式设置 > TurboWarp 舞台注释 > `extensionStorage` > CLI > 默认值。
|
|
112
112
|
|
|
113
|
-
`exts/
|
|
113
|
+
`exts/rcompilerExt.js` 默认从 `https://rcompiler.0832.ink/rcompiler.min.js` 加载浏览器版编译器;自托管时可以覆盖:
|
|
114
114
|
|
|
115
115
|
```js
|
|
116
116
|
localStorage['rcompiler:compilerURL'] = './rcompiler.min.js';
|
|
@@ -134,6 +134,18 @@ localStorage['rcompiler:compilerURL'] = './rcompiler.min.js';
|
|
|
134
134
|
- 原生舞台代码依赖 Skia 预编译包;离线环境需提前准备缓存
|
|
135
135
|
- 无桌面/WASI 目标仅支持纯计算项目
|
|
136
136
|
|
|
137
|
+
## 本机命令行程序(能力矩阵扩展)
|
|
138
|
+
|
|
139
|
+
内置 `fs` / `process` / `path` / `args` / `io` 五个本机能力扩展(接口参考 Alia 语言标准库),
|
|
140
|
+
覆盖文件读写枚举、进程执行与环境变量、路径操作、命令行参数解析、终端输入输出与 ANSI 控制。
|
|
141
|
+
运行时全部基于 Rust `std`:只用这些扩展的项目保持 **Cargo 零依赖**,单进程项目保持零 `tokio`。
|
|
142
|
+
块清单与语义见 [docs/NATIVE.md](docs/NATIVE.md)。
|
|
143
|
+
|
|
144
|
+
```sh
|
|
145
|
+
rcompiler o tool.sb3 dist tool 1.0.0 # Scratch 项目 → 原生命令行工具
|
|
146
|
+
./dist/tool --name Alice --verbose # 配合 args 扩展解析参数
|
|
147
|
+
```
|
|
148
|
+
|
|
137
149
|
## 开发与测试
|
|
138
150
|
|
|
139
151
|
```sh
|
|
@@ -146,6 +158,7 @@ npm test
|
|
|
146
158
|
更多信息:
|
|
147
159
|
|
|
148
160
|
- [docs/CLI.md](docs/CLI.md) — CLI 与目标后端
|
|
161
|
+
- [docs/NATIVE.md](docs/NATIVE.md) — 本机能力矩阵(fs/process/path/args/io 扩展,全 std 零依赖)
|
|
149
162
|
- [docs/CONFIG.md](docs/CONFIG.md) — 帧模型、打包、项目设置
|
|
150
163
|
- [docs/ARCHITECTURE.md](docs/ARCHITECTURE.md) — 架构与选择性运行时
|
|
151
164
|
- [docs/DEBUGGING.md](docs/DEBUGGING.md) — 无头模式、截图、按键注入
|
package/docs/CONFIG.md
CHANGED
|
@@ -1,6 +1,6 @@
|
|
|
1
1
|
# 项目配置
|
|
2
2
|
|
|
3
|
-
项目设置保存在 `.sb3` 的 `extensionStorage` 中;编辑器面板由 `exts/
|
|
3
|
+
项目设置保存在 `.sb3` 的 `extensionStorage` 中;编辑器面板由 `exts/rcompilerExt.js` 提供。
|
|
4
4
|
|
|
5
5
|
- `extensionStorage.rcompiler.config`:安全选项、抗逆向模式
|
|
6
6
|
- `extensionStorage.rcompiler.project`:舞台/帧率/插值、手动类型、打包、自动忽略扩展
|
package/docs/NATIVE.md
ADDED
|
@@ -0,0 +1,110 @@
|
|
|
1
|
+
# 本机能力矩阵(fs / process / path / args / io)
|
|
2
|
+
|
|
3
|
+
rCompiler 内置五个本机能力扩展,让编译产物具备完整本机命令行程序能力。
|
|
4
|
+
接口设计参考 [Alia 语言标准库](https://alia.0832.ink/docs/stdlib/fs)(fs / process / args / io;path 按同一风格补充)。
|
|
5
|
+
|
|
6
|
+
**零外部依赖**:五个扩展的 Rust 运行时全部基于 `std`(fs/process/env/path/io + ANSI 转义序列),
|
|
7
|
+
不引入任何第三方 crate。只用本机能力块的项目保持 Cargo 零依赖;单进程项目同样保持零 `tokio`。
|
|
8
|
+
|
|
9
|
+
## 使用
|
|
10
|
+
|
|
11
|
+
项目扩展列表加入 `fs`、`process`、`path`、`args`、`io`(本地 `exts/` 自动加载),例如项目 JSON:
|
|
12
|
+
|
|
13
|
+
```json
|
|
14
|
+
{
|
|
15
|
+
"extensions": ["fs", "process", "path", "args", "io"],
|
|
16
|
+
"extensionURLs": { "fs": "exts/fs.js", "process": "exts/process.js", "path": "exts/path.js", "args": "exts/args.js", "io": "exts/io.js" }
|
|
17
|
+
}
|
|
18
|
+
```
|
|
19
|
+
|
|
20
|
+
运行时函数按块按需注册:项目未使用的扩展块不会生成任何代码。
|
|
21
|
+
|
|
22
|
+
## fs 文件系统
|
|
23
|
+
|
|
24
|
+
| 块 | 说明 |
|
|
25
|
+
|---|---|
|
|
26
|
+
| 写文件 [内容] 到 [路径] | 写入;父目录不存在自动创建 |
|
|
27
|
+
| 追加 [内容] 到 [路径] | 文件尾追加;不存在则创建 |
|
|
28
|
+
| 复制文件 [源] 到 [目标] | 目标父目录自动创建 |
|
|
29
|
+
| 重命名 [源] 为 [目标] | 同移动 |
|
|
30
|
+
| 删除文件 [路径] | 仅文件 |
|
|
31
|
+
| 删除目录 [路径](含全部内容) | 递归删除 |
|
|
32
|
+
| 创建目录 [路径] | 递归,已存在静默 |
|
|
33
|
+
| 读取文件 [路径] | 返回内容;失败返回空串 |
|
|
34
|
+
| 存在 [路径]? | 布尔 |
|
|
35
|
+
| [路径] 是文件? / 是目录? | 布尔 |
|
|
36
|
+
| [路径] 大小(字节) | 数值 |
|
|
37
|
+
| [路径] 修改时间(Unix 秒) | 数值时间戳 |
|
|
38
|
+
| 列出目录 [路径] | 直接子项名,已排序,换行分隔 |
|
|
39
|
+
| 递归列出 [路径] | 相对路径;目录以 `/` 结尾;分隔符固定 `/`;已排序 |
|
|
40
|
+
|
|
41
|
+
写类操作失败向 stderr 打印一行警告;读类失败返回空值。仅支持 UTF-8 文本内容。
|
|
42
|
+
|
|
43
|
+
## process 进程
|
|
44
|
+
|
|
45
|
+
| 块 | 说明 |
|
|
46
|
+
|---|---|
|
|
47
|
+
| 退出进程,状态码 [码] | `std::process::exit` |
|
|
48
|
+
| 切换工作目录 [路径] | 失败向 stderr 警告 |
|
|
49
|
+
| 设置环境变量 [键] 为 [值] / 删除环境变量 [键] | |
|
|
50
|
+
| 执行命令 [cmd](shell)工作目录 [目录] 留空为当前 | 经 `sh -c` / `cmd /C`;结果存入 last_exec |
|
|
51
|
+
| 运行程序 [程序] 参数 [参数串] 输出 [模式] | 不经 shell(无注入风险);参数串按空白分割,双引号内保留空白 |
|
|
52
|
+
| 上次执行的标准输出 / 标准错误 / 退出码 / 子进程 PID | 读取 last_exec |
|
|
53
|
+
| 进程 PID / 父进程 PID | PPID 仅 Linux(/proc) |
|
|
54
|
+
| 平台 / CPU 架构 | 编译期常量:linux·darwin·win32 / x64·arm64·ia32 |
|
|
55
|
+
| 当前工作目录 / 已运行秒数 / 内存 RSS(字节) | RSS 仅 Linux |
|
|
56
|
+
| 环境变量 [键](缺失空串) / 存在环境变量 [键]? / 全部环境变量 | |
|
|
57
|
+
|
|
58
|
+
spawn 输出模式:**捕获**(stdout/stderr 进结果)/ **直通终端** / **丢弃**。
|
|
59
|
+
命令失败不中断程序——错误写入返回结果的 stderr,退出码 -1。
|
|
60
|
+
|
|
61
|
+
限制:exec/spawn 为同步阻塞(多任务项目中阻塞协作线程);不支持超时与 stdin 注入;
|
|
62
|
+
不含 kill(`std` 无法向任意 PID 发信号,可用 `执行命令 'kill …'` 替代);
|
|
63
|
+
环境变量修改建议在单线程路径使用。
|
|
64
|
+
|
|
65
|
+
## path 路径
|
|
66
|
+
|
|
67
|
+
拼接路径(目标为绝对路径时直接返回目标)、父目录、文件名、去扩展名(stem)、扩展名(不含点,
|
|
68
|
+
`archive.tar.gz → gz`;`.gitignore` 无扩展名)、是绝对路径?、规范化路径(纯字符串处理 `. / ..`,
|
|
69
|
+
不解引用符号链接)、绝对路径(不存在性检查,基于 cwd 拼接)、路径分隔符(平台主分隔符)。
|
|
70
|
+
同时接受 `/` 与 `\` 分隔;join/abs 输出使用平台分隔符。
|
|
71
|
+
|
|
72
|
+
## args 命令行参数
|
|
73
|
+
|
|
74
|
+
| 块 | 说明 |
|
|
75
|
+
|---|---|
|
|
76
|
+
| 参数个数 | 程序名之后的参数数量 |
|
|
77
|
+
| 第 [i] 个参数(从 0 开始) | 越界返回空串 |
|
|
78
|
+
| 全部参数(换行分隔) | |
|
|
79
|
+
| 程序名 | argv[0] |
|
|
80
|
+
| 出现标志 [flag]? | 精确匹配(`-v` 与 `--verbose` 视为不同标志);`--x=y` 视为该标志带值出现;块内无 `-` 前缀时自动补 `--` |
|
|
81
|
+
| 选项 [flag] 的值 默认 [默认] | 支持 `--name value` 与 `--name=value`;未找到返回默认值 |
|
|
82
|
+
|
|
83
|
+
## io 输入输出
|
|
84
|
+
|
|
85
|
+
| 块 | 说明 |
|
|
86
|
+
|---|---|
|
|
87
|
+
| 输出 [文本] / 输出行 [文本] | stdout;行版带换行 |
|
|
88
|
+
| 输出错误 [文本] / 输出错误行 [文本] | stderr |
|
|
89
|
+
| 格式化 [fmt] 用 [值] / 用 [值1] [值2] | `{}` 占位符替换 |
|
|
90
|
+
| 读取一行输入 | 读取前冲刷 stdout(配合"输出"做提示符);EOF 返回空串 |
|
|
91
|
+
| 读取全部输入(管道) | `cat file \| prog` 场景 |
|
|
92
|
+
| 清屏 / 清除当前行 | ANSI |
|
|
93
|
+
| 移动光标 行 [r] 列 [c] | 0-based,与 Alia 一致 |
|
|
94
|
+
| 光标上移/下移/右移/左移 [n] | ANSI |
|
|
95
|
+
| 隐藏光标 / 显示光标 | ANSI |
|
|
96
|
+
| 前景色 [颜色] / 背景色 [颜色] / 重置颜色 | 16 色 + 灰,编译期映射 ANSI |
|
|
97
|
+
| 样式 [样式] | 粗体/斜体/下划线/删除线/反色/重置样式 |
|
|
98
|
+
|
|
99
|
+
终端控制为纯 ANSI 实现,Windows Terminal 与主流终端可用(旧版 Windows 控制台可能不识别)。
|
|
100
|
+
暂缺:原始模式按键读取(readKey)、终端尺寸、鼠标事件(需 termios/libc,保持零依赖暂不引入)。
|
|
101
|
+
|
|
102
|
+
## 端到端验证
|
|
103
|
+
|
|
104
|
+
```sh
|
|
105
|
+
node test/gen-native.js # 生成合成项目(五扩展全块覆盖)
|
|
106
|
+
node test/native.js # 编译 + 三种参数形态运行断言 + obf/multi 变体
|
|
107
|
+
npm test # 主回归矩阵含 native 编译断言
|
|
108
|
+
```
|
|
109
|
+
|
|
110
|
+
验证要点:Cargo 零 `[dependencies]`、单进程无 tokio、混淆模式行为不变、多任务路径编译通过。
|
package/exts/args.js
ADDED
|
@@ -0,0 +1,142 @@
|
|
|
1
|
+
// rCompiler 本机能力扩展 — args 命令行参数
|
|
2
|
+
// 接口参考:Alia 语言标准库 args(https://alia.0832.ink/docs/stdlib/args)
|
|
3
|
+
// 编译期生成零外部依赖 Rust(std::env::args 一次收集到静态表):
|
|
4
|
+
// - args_at 按位置读取(0 = 程序名后的第一个参数,命令行习惯);
|
|
5
|
+
// - args_flag 检测布尔标志(--verbose / -v;--x=y 视为该标志带值出现);
|
|
6
|
+
// - args_value 读取选项值,支持 `--name value` 与 `--name=value` 两种形态;
|
|
7
|
+
// - 无引号解析需求时参数按空白分割由 shell 完成,这里只读已解析的 argv。
|
|
8
|
+
(function (util) {
|
|
9
|
+
const ArgumentType = util.ArgumentType ? util.ArgumentType : { STRING: 'r', NUMBER: 'r', BOOLEAN: 'b' };
|
|
10
|
+
const isC = () => !!util.isCompiler;
|
|
11
|
+
|
|
12
|
+
const stuOf = (x) => (x && typeof x.Stu === 'function') ? x.Stu() : ((typeof x === 'string' && x) ? x : '""');
|
|
13
|
+
const numOf = (x) => (x && typeof x.Num === 'function') ? x.Num() : '0.0';
|
|
14
|
+
|
|
15
|
+
// ---- 运行时(零外部依赖)----
|
|
16
|
+
const RT_ARGS = [
|
|
17
|
+
'pub fn rcompiler_args_vec() -> &\'static Vec<String> {',
|
|
18
|
+
'static A: std::sync::OnceLock<Vec<String>> = std::sync::OnceLock::new();',
|
|
19
|
+
'A.get_or_init(|| std::env::args().skip(1).collect())',
|
|
20
|
+
'}',
|
|
21
|
+
'pub fn rcompiler_args_program() -> String {',
|
|
22
|
+
'std::env::args().next().unwrap_or_default()',
|
|
23
|
+
'}',
|
|
24
|
+
'pub fn rcompiler_args_at(i: usize) -> String {',
|
|
25
|
+
'rcompiler_args_vec().get(i).cloned().unwrap_or_default()',
|
|
26
|
+
'}',
|
|
27
|
+
'fn rcompiler_args_norm_flag(flag: &str) -> String {',
|
|
28
|
+
'let f = flag.trim();',
|
|
29
|
+
'if f.is_empty() { return f.to_string(); }',
|
|
30
|
+
'if f.starts_with(\'-\') { f.to_string() } else { format!("--{}", f) }',
|
|
31
|
+
'}',
|
|
32
|
+
'pub fn rcompiler_args_flag(flag: &str) -> bool {',
|
|
33
|
+
'let f = rcompiler_args_norm_flag(flag);',
|
|
34
|
+
'let mut hit = false;',
|
|
35
|
+
'for a in rcompiler_args_vec().iter() {',
|
|
36
|
+
'if a == &f { hit = true; }',
|
|
37
|
+
'else if a.starts_with(f.as_str()) && a.as_bytes().get(f.len()) == Some(&b\'=\') { hit = true; }',
|
|
38
|
+
'if hit { return true; }',
|
|
39
|
+
'}',
|
|
40
|
+
'false',
|
|
41
|
+
'}',
|
|
42
|
+
'pub fn rcompiler_args_value(flag: &str, dflt: &str) -> String {',
|
|
43
|
+
'let f = rcompiler_args_norm_flag(flag);',
|
|
44
|
+
'let mut next = false;',
|
|
45
|
+
'for a in rcompiler_args_vec().iter() {',
|
|
46
|
+
'if next { return a.clone(); }',
|
|
47
|
+
'if a == &f { next = true; }',
|
|
48
|
+
'else if a.starts_with(f.as_str()) && a.as_bytes().get(f.len()) == Some(&b\'=\') {',
|
|
49
|
+
'return a[f.len() + 1..].to_string();',
|
|
50
|
+
'}',
|
|
51
|
+
'}',
|
|
52
|
+
'dflt.to_string()',
|
|
53
|
+
'}',
|
|
54
|
+
'pub fn rcompiler_args_raw() -> String {',
|
|
55
|
+
'rcompiler_args_vec().join("\\n")',
|
|
56
|
+
'}'
|
|
57
|
+
].join('\n');
|
|
58
|
+
const rt = () => util.Tools.setruntime([RT_ARGS]);
|
|
59
|
+
|
|
60
|
+
class argsExt {
|
|
61
|
+
id = 'args';
|
|
62
|
+
blocks = [
|
|
63
|
+
{
|
|
64
|
+
opcode: 'count',
|
|
65
|
+
blockType: util.BlockType.REPORTER,
|
|
66
|
+
text: '参数个数'
|
|
67
|
+
},
|
|
68
|
+
{
|
|
69
|
+
opcode: 'at',
|
|
70
|
+
blockType: util.BlockType.REPORTER,
|
|
71
|
+
text: '第 [index] 个参数(从 0 开始)',
|
|
72
|
+
arguments: { index: { type: ArgumentType.NUMBER, defaultValue: '0' } }
|
|
73
|
+
},
|
|
74
|
+
{
|
|
75
|
+
opcode: 'raw',
|
|
76
|
+
blockType: util.BlockType.REPORTER,
|
|
77
|
+
text: '全部参数(换行分隔)'
|
|
78
|
+
},
|
|
79
|
+
{
|
|
80
|
+
opcode: 'program',
|
|
81
|
+
blockType: util.BlockType.REPORTER,
|
|
82
|
+
text: '程序名'
|
|
83
|
+
},
|
|
84
|
+
{
|
|
85
|
+
opcode: 'flag',
|
|
86
|
+
blockType: util.BlockType.BOOLEAN,
|
|
87
|
+
text: '出现标志 [flag]?',
|
|
88
|
+
arguments: { flag: { type: ArgumentType.STRING, defaultValue: '--verbose' } }
|
|
89
|
+
},
|
|
90
|
+
{
|
|
91
|
+
opcode: 'value',
|
|
92
|
+
blockType: util.BlockType.REPORTER,
|
|
93
|
+
text: '选项 [flag] 的值 默认 [default]',
|
|
94
|
+
arguments: {
|
|
95
|
+
flag: { type: ArgumentType.STRING, defaultValue: '--name' },
|
|
96
|
+
default: { type: ArgumentType.STRING, defaultValue: '' }
|
|
97
|
+
}
|
|
98
|
+
}
|
|
99
|
+
];
|
|
100
|
+
getInfo() {
|
|
101
|
+
return {
|
|
102
|
+
id: this.id,
|
|
103
|
+
name: '命令行参数',
|
|
104
|
+
color1: '#3dc99a',
|
|
105
|
+
color2: '#5ce0b8',
|
|
106
|
+
blocks: this.blocks
|
|
107
|
+
};
|
|
108
|
+
}
|
|
109
|
+
// ---- VM 端不实现,仅编译期生成 Rust ----
|
|
110
|
+
count(args) {
|
|
111
|
+
if (!isC()) return 0;
|
|
112
|
+
rt();
|
|
113
|
+
return new util.TypeInput.Num('(rcompiler_args_vec().len()) as f64');
|
|
114
|
+
}
|
|
115
|
+
at(args) {
|
|
116
|
+
if (!isC()) return '';
|
|
117
|
+
rt();
|
|
118
|
+
return new util.TypeInput.Stri(`rcompiler_args_at(((${numOf(args.index)}) as f64).max(0.0) as usize)`);
|
|
119
|
+
}
|
|
120
|
+
raw(args) {
|
|
121
|
+
if (!isC()) return '';
|
|
122
|
+
rt();
|
|
123
|
+
return new util.TypeInput.Stri('rcompiler_args_raw()');
|
|
124
|
+
}
|
|
125
|
+
program(args) {
|
|
126
|
+
if (!isC()) return '';
|
|
127
|
+
rt();
|
|
128
|
+
return new util.TypeInput.Stri('rcompiler_args_program()');
|
|
129
|
+
}
|
|
130
|
+
flag(args) {
|
|
131
|
+
if (!isC()) return false;
|
|
132
|
+
rt();
|
|
133
|
+
return new util.TypeInput.Bool(`rcompiler_args_flag(${stuOf(args.flag)})`);
|
|
134
|
+
}
|
|
135
|
+
value(args) {
|
|
136
|
+
if (!isC()) return '';
|
|
137
|
+
rt();
|
|
138
|
+
return new util.TypeInput.Stri(`rcompiler_args_value(${stuOf(args.flag)}, ${stuOf(args.default)})`);
|
|
139
|
+
}
|
|
140
|
+
}
|
|
141
|
+
util.extensions.register(new argsExt());
|
|
142
|
+
})(this.isCompiler ? this : Scratch);
|
package/exts/fs.js
ADDED
|
@@ -0,0 +1,317 @@
|
|
|
1
|
+
// rCompiler 本机能力扩展 — fs 文件系统
|
|
2
|
+
// 接口参考:Alia 语言标准库 fs(https://alia.0832.ink/docs/stdlib/fs)
|
|
3
|
+
// 编译期生成零外部依赖 Rust(std::fs):写入时自动创建父目录;
|
|
4
|
+
// 写类操作失败向 stderr 打印一行警告;读类操作失败返回空值。
|
|
5
|
+
// 项目使用:扩展列表加入 "fs"(本地 exts/fs.js 自动加载)。
|
|
6
|
+
(function (util) {
|
|
7
|
+
const ArgumentType = util.ArgumentType ? util.ArgumentType : { STRING: 'r', NUMBER: 'r', BOOLEAN: 'b' };
|
|
8
|
+
const isC = () => !!util.isCompiler;
|
|
9
|
+
|
|
10
|
+
// ---- 表达式辅助(与 standard.js 同约定)----
|
|
11
|
+
const stuOf = (x) => (x && typeof x.Stu === 'function') ? x.Stu() : ((typeof x === 'string' && x) ? x : '""');
|
|
12
|
+
const striOf = (x) => (x && typeof x.Stri === 'function') ? x.Stri() : ((typeof x === 'string' && x) ? x : 'String::new()');
|
|
13
|
+
|
|
14
|
+
// 菜单/字段值读取:fields 优先,inputs 影子兜底(两种 VM 存储形态)
|
|
15
|
+
const gf = (args, name) => {
|
|
16
|
+
const b = args.scope.block;
|
|
17
|
+
if (b.fields && b.fields[name] != null) return String(b.fields[name][0]);
|
|
18
|
+
const inp = b.inputs && b.inputs[name];
|
|
19
|
+
if (Array.isArray(inp)) {
|
|
20
|
+
const sid = (typeof inp[2] === 'string') ? inp[2] : (inp[0] === 1 && typeof inp[1] === 'string' ? inp[1] : null);
|
|
21
|
+
if (sid != null) {
|
|
22
|
+
const sh = args.scope.target.blocks[sid];
|
|
23
|
+
if (sh && sh.fields && sh.fields[name] != null) return String(sh.fields[name][0]);
|
|
24
|
+
}
|
|
25
|
+
}
|
|
26
|
+
return null;
|
|
27
|
+
};
|
|
28
|
+
|
|
29
|
+
// ---- 运行时(std::fs,零外部依赖;Set 去重,按需注册)----
|
|
30
|
+
const RT_FS = [
|
|
31
|
+
'fn rcompiler_fs_write(path: &str, content: &str) {',
|
|
32
|
+
'let p = std::path::Path::new(path);',
|
|
33
|
+
'if let Some(d) = p.parent() { let _ = std::fs::create_dir_all(d); }',
|
|
34
|
+
'if let Err(e) = std::fs::write(p, content) { eprintln!("fs: 写入失败 {}: {}", path, e); }',
|
|
35
|
+
'}',
|
|
36
|
+
'fn rcompiler_fs_append(path: &str, content: &str) {',
|
|
37
|
+
'let p = std::path::Path::new(path);',
|
|
38
|
+
'if let Some(d) = p.parent() { let _ = std::fs::create_dir_all(d); }',
|
|
39
|
+
'use std::io::Write;',
|
|
40
|
+
'match std::fs::OpenOptions::new().create(true).append(true).open(p) {',
|
|
41
|
+
'Ok(mut f) => { let _ = f.write_all(content.as_bytes()); }',
|
|
42
|
+
'Err(e) => eprintln!("fs: 追加失败 {}: {}", path, e),',
|
|
43
|
+
'}',
|
|
44
|
+
'}',
|
|
45
|
+
'fn rcompiler_fs_copy(src: &str, dst: &str) {',
|
|
46
|
+
'let p = std::path::Path::new(dst);',
|
|
47
|
+
'if let Some(d) = p.parent() { let _ = std::fs::create_dir_all(d); }',
|
|
48
|
+
'if let Err(e) = std::fs::copy(src, p) { eprintln!("fs: 复制失败 {} -> {}: {}", src, dst, e); }',
|
|
49
|
+
'}',
|
|
50
|
+
'fn rcompiler_fs_rename(src: &str, dst: &str) {',
|
|
51
|
+
'let p = std::path::Path::new(dst);',
|
|
52
|
+
'if let Some(d) = p.parent() { let _ = std::fs::create_dir_all(d); }',
|
|
53
|
+
'if let Err(e) = std::fs::rename(src, p) { eprintln!("fs: 重命名失败 {} -> {}: {}", src, dst, e); }',
|
|
54
|
+
'}',
|
|
55
|
+
'fn rcompiler_fs_remove(path: &str) {',
|
|
56
|
+
'if let Err(e) = std::fs::remove_file(path) { eprintln!("fs: 删除失败 {}: {}", path, e); }',
|
|
57
|
+
'}',
|
|
58
|
+
'fn rcompiler_fs_remove_dir(path: &str) {',
|
|
59
|
+
'if let Err(e) = std::fs::remove_dir_all(path) { eprintln!("fs: 删除目录失败 {}: {}", path, e); }',
|
|
60
|
+
'}',
|
|
61
|
+
'fn rcompiler_fs_mkdir(path: &str) {',
|
|
62
|
+
'if let Err(e) = std::fs::create_dir_all(path) { eprintln!("fs: 创建目录失败 {}: {}", path, e); }',
|
|
63
|
+
'}',
|
|
64
|
+
'fn rcompiler_fs_read(path: &str) -> String {',
|
|
65
|
+
'std::fs::read_to_string(path).unwrap_or_default()',
|
|
66
|
+
'}',
|
|
67
|
+
'fn rcompiler_fs_exist(path: &str) -> bool {',
|
|
68
|
+
'std::path::Path::new(path).exists()',
|
|
69
|
+
'}',
|
|
70
|
+
'fn rcompiler_fs_is_file(path: &str) -> bool {',
|
|
71
|
+
'std::fs::metadata(path).map(|m| m.is_file()).unwrap_or(false)',
|
|
72
|
+
'}',
|
|
73
|
+
'fn rcompiler_fs_is_dir(path: &str) -> bool {',
|
|
74
|
+
'std::fs::metadata(path).map(|m| m.is_dir()).unwrap_or(false)',
|
|
75
|
+
'}',
|
|
76
|
+
'fn rcompiler_fs_size(path: &str) -> f64 {',
|
|
77
|
+
'std::fs::metadata(path).map(|m| m.len() as f64).unwrap_or(0.0)',
|
|
78
|
+
'}',
|
|
79
|
+
'fn rcompiler_fs_modified(path: &str) -> f64 {',
|
|
80
|
+
'std::fs::metadata(path).ok()',
|
|
81
|
+
'.and_then(|m| m.modified().ok())',
|
|
82
|
+
'.and_then(|t| t.duration_since(std::time::UNIX_EPOCH).ok())',
|
|
83
|
+
'.map(|d| d.as_secs_f64())',
|
|
84
|
+
'.unwrap_or(0.0)',
|
|
85
|
+
'}',
|
|
86
|
+
'fn rcompiler_fs_list(path: &str) -> String {',
|
|
87
|
+
'let mut names: Vec<String> = Vec::new();',
|
|
88
|
+
'if let Ok(rd) = std::fs::read_dir(path) {',
|
|
89
|
+
'for e in rd.flatten() { names.push(e.file_name().to_string_lossy().into_owned()); }',
|
|
90
|
+
'}',
|
|
91
|
+
'names.sort();',
|
|
92
|
+
'names.join("\\n")',
|
|
93
|
+
'}',
|
|
94
|
+
'fn rcompiler_fs_list_recursive(root: &str) -> String {',
|
|
95
|
+
'let mut out: Vec<String> = Vec::new();',
|
|
96
|
+
'fn walk(dir: &std::path::Path, rel: &str, out: &mut Vec<String>) {',
|
|
97
|
+
'if let Ok(rd) = std::fs::read_dir(dir) {',
|
|
98
|
+
'let mut ents: Vec<std::fs::DirEntry> = rd.flatten().collect();',
|
|
99
|
+
'ents.sort_by(|a, b| a.file_name().cmp(&b.file_name()));',
|
|
100
|
+
'for e in ents {',
|
|
101
|
+
'let name = e.file_name().to_string_lossy().into_owned();',
|
|
102
|
+
'let is_dir = e.file_type().map(|t| t.is_dir()).unwrap_or(false);',
|
|
103
|
+
'let child = if rel.is_empty() { name.clone() } else { format!("{}/{}", rel, name) };',
|
|
104
|
+
'if is_dir { out.push(format!("{}/", child)); walk(&e.path(), &child, out); }',
|
|
105
|
+
'else { out.push(child); }',
|
|
106
|
+
'}',
|
|
107
|
+
'}',
|
|
108
|
+
'}',
|
|
109
|
+
'walk(std::path::Path::new(root), "", &mut out);',
|
|
110
|
+
'out.join("\\n")',
|
|
111
|
+
'}'
|
|
112
|
+
].join('\n');
|
|
113
|
+
const rt = () => util.Tools.setruntime([RT_FS]);
|
|
114
|
+
|
|
115
|
+
class fsExt {
|
|
116
|
+
id = 'fs';
|
|
117
|
+
blocks = [
|
|
118
|
+
// ---- 写类命令 ----
|
|
119
|
+
{
|
|
120
|
+
opcode: 'write',
|
|
121
|
+
blockType: util.BlockType.COMMAND,
|
|
122
|
+
text: '写文件 [content] 到 [path]',
|
|
123
|
+
arguments: {
|
|
124
|
+
content: { type: ArgumentType.STRING, defaultValue: 'Hello' },
|
|
125
|
+
path: { type: ArgumentType.STRING, defaultValue: 'out.txt' }
|
|
126
|
+
}
|
|
127
|
+
},
|
|
128
|
+
{
|
|
129
|
+
opcode: 'append',
|
|
130
|
+
blockType: util.BlockType.COMMAND,
|
|
131
|
+
text: '追加 [content] 到 [path]',
|
|
132
|
+
arguments: {
|
|
133
|
+
content: { type: ArgumentType.STRING, defaultValue: 'more' },
|
|
134
|
+
path: { type: ArgumentType.STRING, defaultValue: 'out.txt' }
|
|
135
|
+
}
|
|
136
|
+
},
|
|
137
|
+
{
|
|
138
|
+
opcode: 'copy',
|
|
139
|
+
blockType: util.BlockType.COMMAND,
|
|
140
|
+
text: '复制文件 [src] 到 [dst]',
|
|
141
|
+
arguments: {
|
|
142
|
+
src: { type: ArgumentType.STRING, defaultValue: 'a.txt' },
|
|
143
|
+
dst: { type: ArgumentType.STRING, defaultValue: 'b.txt' }
|
|
144
|
+
}
|
|
145
|
+
},
|
|
146
|
+
{
|
|
147
|
+
opcode: 'rename',
|
|
148
|
+
blockType: util.BlockType.COMMAND,
|
|
149
|
+
text: '重命名 [src] 为 [dst]',
|
|
150
|
+
arguments: {
|
|
151
|
+
src: { type: ArgumentType.STRING, defaultValue: 'a.txt' },
|
|
152
|
+
dst: { type: ArgumentType.STRING, defaultValue: 'b.txt' }
|
|
153
|
+
}
|
|
154
|
+
},
|
|
155
|
+
{
|
|
156
|
+
opcode: 'remove',
|
|
157
|
+
blockType: util.BlockType.COMMAND,
|
|
158
|
+
text: '删除文件 [path]',
|
|
159
|
+
arguments: { path: { type: ArgumentType.STRING, defaultValue: 'a.txt' } }
|
|
160
|
+
},
|
|
161
|
+
{
|
|
162
|
+
opcode: 'remove_dir',
|
|
163
|
+
blockType: util.BlockType.COMMAND,
|
|
164
|
+
text: '删除目录 [path](含全部内容)',
|
|
165
|
+
arguments: { path: { type: ArgumentType.STRING, defaultValue: 'build' } }
|
|
166
|
+
},
|
|
167
|
+
{
|
|
168
|
+
opcode: 'mkdir',
|
|
169
|
+
blockType: util.BlockType.COMMAND,
|
|
170
|
+
text: '创建目录 [path]',
|
|
171
|
+
arguments: { path: { type: ArgumentType.STRING, defaultValue: 'build' } }
|
|
172
|
+
},
|
|
173
|
+
// ---- 读类报告器 ----
|
|
174
|
+
{
|
|
175
|
+
opcode: 'read',
|
|
176
|
+
blockType: util.BlockType.REPORTER,
|
|
177
|
+
text: '读取文件 [path]',
|
|
178
|
+
arguments: { path: { type: ArgumentType.STRING, defaultValue: 'a.txt' } }
|
|
179
|
+
},
|
|
180
|
+
{
|
|
181
|
+
opcode: 'exist',
|
|
182
|
+
blockType: util.BlockType.BOOLEAN,
|
|
183
|
+
text: '存在 [path]?',
|
|
184
|
+
arguments: { path: { type: ArgumentType.STRING, defaultValue: 'a.txt' } }
|
|
185
|
+
},
|
|
186
|
+
{
|
|
187
|
+
opcode: 'is_file',
|
|
188
|
+
blockType: util.BlockType.BOOLEAN,
|
|
189
|
+
text: '[path] 是文件?',
|
|
190
|
+
arguments: { path: { type: ArgumentType.STRING, defaultValue: 'a.txt' } }
|
|
191
|
+
},
|
|
192
|
+
{
|
|
193
|
+
opcode: 'is_dir',
|
|
194
|
+
blockType: util.BlockType.BOOLEAN,
|
|
195
|
+
text: '[path] 是目录?',
|
|
196
|
+
arguments: { path: { type: ArgumentType.STRING, defaultValue: 'build' } }
|
|
197
|
+
},
|
|
198
|
+
{
|
|
199
|
+
opcode: 'size',
|
|
200
|
+
blockType: util.BlockType.REPORTER,
|
|
201
|
+
text: '[path] 大小(字节)',
|
|
202
|
+
arguments: { path: { type: ArgumentType.STRING, defaultValue: 'a.txt' } }
|
|
203
|
+
},
|
|
204
|
+
{
|
|
205
|
+
opcode: 'modified',
|
|
206
|
+
blockType: util.BlockType.REPORTER,
|
|
207
|
+
text: '[path] 修改时间(Unix 秒)',
|
|
208
|
+
arguments: { path: { type: ArgumentType.STRING, defaultValue: 'a.txt' } }
|
|
209
|
+
},
|
|
210
|
+
{
|
|
211
|
+
opcode: 'list',
|
|
212
|
+
blockType: util.BlockType.REPORTER,
|
|
213
|
+
text: '列出目录 [path]',
|
|
214
|
+
arguments: { path: { type: ArgumentType.STRING, defaultValue: '.' } }
|
|
215
|
+
},
|
|
216
|
+
{
|
|
217
|
+
opcode: 'list_recursive',
|
|
218
|
+
blockType: util.BlockType.REPORTER,
|
|
219
|
+
text: '递归列出 [path]',
|
|
220
|
+
arguments: { path: { type: ArgumentType.STRING, defaultValue: '.' } }
|
|
221
|
+
}
|
|
222
|
+
];
|
|
223
|
+
getInfo() {
|
|
224
|
+
return {
|
|
225
|
+
id: this.id,
|
|
226
|
+
name: '文件系统',
|
|
227
|
+
color1: '#c98a3d',
|
|
228
|
+
color2: '#e0a75c',
|
|
229
|
+
blocks: this.blocks
|
|
230
|
+
};
|
|
231
|
+
}
|
|
232
|
+
// ---- VM 端(编辑器内运行)不实现,仅编译期生成 Rust ----
|
|
233
|
+
write(args) {
|
|
234
|
+
if (!isC()) return;
|
|
235
|
+
rt();
|
|
236
|
+
args.compiler += `rcompiler_fs_write(${stuOf(args.path)}, &${striOf(args.content)});\n`;
|
|
237
|
+
return args.compiler;
|
|
238
|
+
}
|
|
239
|
+
append(args) {
|
|
240
|
+
if (!isC()) return;
|
|
241
|
+
rt();
|
|
242
|
+
args.compiler += `rcompiler_fs_append(${stuOf(args.path)}, &${striOf(args.content)});\n`;
|
|
243
|
+
return args.compiler;
|
|
244
|
+
}
|
|
245
|
+
copy(args) {
|
|
246
|
+
if (!isC()) return;
|
|
247
|
+
rt();
|
|
248
|
+
args.compiler += `rcompiler_fs_copy(${stuOf(args.src)}, ${stuOf(args.dst)});\n`;
|
|
249
|
+
return args.compiler;
|
|
250
|
+
}
|
|
251
|
+
rename(args) {
|
|
252
|
+
if (!isC()) return;
|
|
253
|
+
rt();
|
|
254
|
+
args.compiler += `rcompiler_fs_rename(${stuOf(args.src)}, ${stuOf(args.dst)});\n`;
|
|
255
|
+
return args.compiler;
|
|
256
|
+
}
|
|
257
|
+
remove(args) {
|
|
258
|
+
if (!isC()) return;
|
|
259
|
+
rt();
|
|
260
|
+
args.compiler += `rcompiler_fs_remove(${stuOf(args.path)});\n`;
|
|
261
|
+
return args.compiler;
|
|
262
|
+
}
|
|
263
|
+
remove_dir(args) {
|
|
264
|
+
if (!isC()) return;
|
|
265
|
+
rt();
|
|
266
|
+
args.compiler += `rcompiler_fs_remove_dir(${stuOf(args.path)});\n`;
|
|
267
|
+
return args.compiler;
|
|
268
|
+
}
|
|
269
|
+
mkdir(args) {
|
|
270
|
+
if (!isC()) return;
|
|
271
|
+
rt();
|
|
272
|
+
args.compiler += `rcompiler_fs_mkdir(${stuOf(args.path)});\n`;
|
|
273
|
+
return args.compiler;
|
|
274
|
+
}
|
|
275
|
+
read(args) {
|
|
276
|
+
if (!isC()) return '';
|
|
277
|
+
rt();
|
|
278
|
+
return new util.TypeInput.Stri(`rcompiler_fs_read(${stuOf(args.path)})`);
|
|
279
|
+
}
|
|
280
|
+
exist(args) {
|
|
281
|
+
if (!isC()) return false;
|
|
282
|
+
rt();
|
|
283
|
+
return new util.TypeInput.Bool(`rcompiler_fs_exist(${stuOf(args.path)})`);
|
|
284
|
+
}
|
|
285
|
+
is_file(args) {
|
|
286
|
+
if (!isC()) return false;
|
|
287
|
+
rt();
|
|
288
|
+
return new util.TypeInput.Bool(`rcompiler_fs_is_file(${stuOf(args.path)})`);
|
|
289
|
+
}
|
|
290
|
+
is_dir(args) {
|
|
291
|
+
if (!isC()) return false;
|
|
292
|
+
rt();
|
|
293
|
+
return new util.TypeInput.Bool(`rcompiler_fs_is_dir(${stuOf(args.path)})`);
|
|
294
|
+
}
|
|
295
|
+
size(args) {
|
|
296
|
+
if (!isC()) return 0;
|
|
297
|
+
rt();
|
|
298
|
+
return new util.TypeInput.Num(`rcompiler_fs_size(${stuOf(args.path)})`);
|
|
299
|
+
}
|
|
300
|
+
modified(args) {
|
|
301
|
+
if (!isC()) return 0;
|
|
302
|
+
rt();
|
|
303
|
+
return new util.TypeInput.Num(`rcompiler_fs_modified(${stuOf(args.path)})`);
|
|
304
|
+
}
|
|
305
|
+
list(args) {
|
|
306
|
+
if (!isC()) return '';
|
|
307
|
+
rt();
|
|
308
|
+
return new util.TypeInput.Stri(`rcompiler_fs_list(${stuOf(args.path)})`);
|
|
309
|
+
}
|
|
310
|
+
list_recursive(args) {
|
|
311
|
+
if (!isC()) return '';
|
|
312
|
+
rt();
|
|
313
|
+
return new util.TypeInput.Stri(`rcompiler_fs_list_recursive(${stuOf(args.path)})`);
|
|
314
|
+
}
|
|
315
|
+
}
|
|
316
|
+
util.extensions.register(new fsExt());
|
|
317
|
+
})(this.isCompiler ? this : Scratch);
|