fcdev 0.0.0-stage → 0.1.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.
Files changed (71) hide show
  1. package/LICENSE +201 -0
  2. package/README.md +81 -2
  3. package/bin/fcdev.mjs +17 -0
  4. package/package.json +38 -4
  5. package/src/build/build-plan.mjs +92 -0
  6. package/src/build/dependency-file.mjs +24 -0
  7. package/src/build/disk-builder.mjs +36 -0
  8. package/src/build/index.mjs +31 -0
  9. package/src/build/program-builder.mjs +209 -0
  10. package/src/build/source-collector.mjs +54 -0
  11. package/src/build/tool-arguments.mjs +83 -0
  12. package/src/cli/args-parser.mjs +84 -0
  13. package/src/cli/commands/build-command.mjs +34 -0
  14. package/src/cli/commands/debug-command.mjs +70 -0
  15. package/src/cli/commands/disasm-command.mjs +65 -0
  16. package/src/cli/commands/disk-command.mjs +34 -0
  17. package/src/cli/commands/info-command.mjs +33 -0
  18. package/src/cli/commands/project-info.mjs +57 -0
  19. package/src/cli/commands/run-command.mjs +68 -0
  20. package/src/cli/commands/sync-command.mjs +85 -0
  21. package/src/cli/index.mjs +100 -0
  22. package/src/config/config-loader.mjs +132 -0
  23. package/src/config/index.mjs +9 -0
  24. package/src/disasm/analysis.mjs +97 -0
  25. package/src/disasm/cdl.mjs +35 -0
  26. package/src/disasm/disassembler.mjs +114 -0
  27. package/src/disasm/index.mjs +16 -0
  28. package/src/disasm/info-writer.mjs +72 -0
  29. package/src/disasm/loaders.mjs +69 -0
  30. package/src/disasm/opcode-table.mjs +268 -0
  31. package/src/disasm/roundtrip.mjs +69 -0
  32. package/src/disasm/symbols.mjs +30 -0
  33. package/src/disasm/trace.mjs +25 -0
  34. package/src/emulator/debug-client.mjs +125 -0
  35. package/src/emulator/emulator-launcher.mjs +80 -0
  36. package/src/emulator/emulator-locator.mjs +62 -0
  37. package/src/emulator/index.mjs +11 -0
  38. package/src/packagers/fat-floppy.mjs +22 -0
  39. package/src/packagers/fat12-image.mjs +245 -0
  40. package/src/packagers/flat-binary.mjs +53 -0
  41. package/src/packagers/index.mjs +54 -0
  42. package/src/packagers/ines.mjs +38 -0
  43. package/src/shared/errors.mjs +25 -0
  44. package/src/shared/fs-utils.mjs +66 -0
  45. package/src/shared/index.mjs +11 -0
  46. package/src/shared/process.mjs +50 -0
  47. package/src/targets/index.mjs +17 -0
  48. package/src/targets/name-rules.mjs +33 -0
  49. package/src/targets/target-registry.mjs +187 -0
  50. package/src/toolchain/index.mjs +16 -0
  51. package/src/toolchain/toolchain-locator.mjs +104 -0
  52. package/targets/nes/asminc/fcnes.inc +16 -0
  53. package/targets/nes/chr/ascii-8x8.chr +0 -0
  54. package/targets/nes/chr/font8x8_basic.h +152 -0
  55. package/targets/nes/include/fcnes.h +45 -0
  56. package/targets/nes/lib/fcnes.lib +0 -0
  57. package/targets/nes/lib/nes-font.o +0 -0
  58. package/targets/nes/lib-build.json +9 -0
  59. package/targets/nes/src/fcnes.s +91 -0
  60. package/targets/nes/src/nes-font.s +12 -0
  61. package/targets/nes/target.json +27 -0
  62. package/targets/sb2000/asminc/sb2000.inc +216 -0
  63. package/targets/sb2000/include/sb2000-symbols.h +380 -0
  64. package/targets/sb2000/include/sb2000.h +52 -0
  65. package/targets/sb2000/lib/crt0.o +0 -0
  66. package/targets/sb2000/lib/sb2000.lib +0 -0
  67. package/targets/sb2000/lib-build.json +8 -0
  68. package/targets/sb2000/link.cfg +35 -0
  69. package/targets/sb2000/src/crt0.s +37 -0
  70. package/targets/sb2000/src/sb2000.s +67 -0
  71. package/targets/sb2000/target.json +28 -0
@@ -0,0 +1,57 @@
1
+ // ------------------------------------------------------------------------
2
+ // 名称:project-info.mjs
3
+ // 说明:汇总当前项目的目标、工具链与头文件目录,供 info 与 sync 命令使用。
4
+ // 作者:sungbin
5
+ // 邮箱:sungbin@3578.cn
6
+ // 日期:2026-11-10
7
+ // 备注:从终端当前目录向上查找 fcdev.json;没有配置时必须用 --target 指定目标。
8
+ // 预定义宏里带一组编辑器兼容宏:cc65 的头文件大量使用 __fastcall__ 这类关键字,
9
+ // C/C++ 扩展与 clangd 不认识,定义成空宏才不会报语法错误;只用于智能感知,不影响构建。
10
+ // ------------------------------------------------------------------------
11
+ import path from 'node:path';
12
+ import { loadProjectConfig } from '../../config/index.mjs';
13
+ import { FcdevError } from '../../shared/index.mjs';
14
+ import { loadTarget, resolveTargetPath } from '../../targets/index.mjs';
15
+ import { getToolchainVersion, locateToolchain } from '../../toolchain/index.mjs';
16
+
17
+ /** 只供编辑器使用的兼容宏:cc65 的调用约定关键字定义成空 */
18
+ const EDITOR_COMPATIBILITY_DEFINES = { __fastcall__: '', __cdecl__: '' };
19
+
20
+ /**
21
+ * @typedef {object} ProjectInfo
22
+ * @property {string} root 项目根目录
23
+ * @property {string|null} configFile 配置文件路径
24
+ * @property {{name: string, title: string}} target 目标
25
+ * @property {{home: string, source: string, version: string}} toolchain 工具链
26
+ * @property {string[]} includeDirs C 头文件目录
27
+ * @property {string[]} asmIncludeDirs 汇编引入目录
28
+ * @property {Record<string, string|number>} defines 预定义宏(含 cc65 自带的目标宏与编辑器兼容宏)
29
+ * @property {string} outDir 输出目录
30
+ */
31
+
32
+ /**
33
+ * 汇总项目信息。
34
+ * @param {{cwd: string, targetOverride?: string, env?: NodeJS.ProcessEnv}} input 终端目录、目标覆盖与环境变量
35
+ * @returns {Promise<ProjectInfo>} 项目信息
36
+ * @throws {FcdevError} 没有指定目标,或找不到工具链
37
+ */
38
+ export async function describeProject({ cwd, targetOverride, env }) {
39
+ const config = loadProjectConfig(cwd, cwd);
40
+ const targetName = targetOverride ?? config.target;
41
+ if (!targetName) {
42
+ throw new FcdevError('没有指定目标', { code: 'TARGET_MISSING', hint: '在 fcdev.json 里写 "target",或用 --target <名> 指定' });
43
+ }
44
+ const target = loadTarget(targetName);
45
+ const toolchain = locateToolchain({ configured: config.toolchain, env });
46
+ const resolveAll = (values) => values.map((value) => resolveTargetPath(target, value, toolchain.home));
47
+ return {
48
+ root: config.root,
49
+ configFile: config.file,
50
+ target: { name: target.name, title: target.title },
51
+ toolchain: { home: toolchain.home, source: toolchain.source, version: await getToolchainVersion(toolchain) },
52
+ includeDirs: [...resolveAll(target.include), ...config.include, path.join(toolchain.home, 'include')],
53
+ asmIncludeDirs: [...resolveAll(target.asminclude), ...config.include, path.join(toolchain.home, 'asminc')],
54
+ defines: { ...EDITOR_COMPATIBILITY_DEFINES, __CC65__: 1, [`__${target.cc65Target.toUpperCase()}__`]: 1, ...target.defines, ...config.define },
55
+ outDir: config.outDir,
56
+ };
57
+ }
@@ -0,0 +1,68 @@
1
+ // ------------------------------------------------------------------------
2
+ // 名称:run-command.mjs
3
+ // 说明:run 命令:构建程序后在模拟器里运行;--debug 时启动调试模式,由 debug 命令继续操作。
4
+ // 作者:sungbin
5
+ // 邮箱:sungbin@3578.cn
6
+ // 日期:2026-11-10
7
+ // 备注:运行方案由目标的 run 字段声明:rom 直接加载产物;firmware-disk 加载固件(fcdev.json 的 firmware),挂载磁盘镜像后复位。
8
+ // firmware-disk 方案需要调试服务挂载镜像,挂载完成后用 live 命令转为自由运行(加 --debug 则保持调试模式)。
9
+ // ------------------------------------------------------------------------
10
+ import path from 'node:path';
11
+ import { buildDiskImage, buildPath } from '../../build/index.mjs';
12
+ import { DEFAULT_DEBUG_PORT, launchEmulator, locateEmulator } from '../../emulator/index.mjs';
13
+ import { FcdevError } from '../../shared/index.mjs';
14
+
15
+ /**
16
+ * 执行 run 命令。
17
+ * @param {{positionals: string[], options: {target?: string, debug: boolean, port?: number}, context: import('../index.mjs').CliContext}} input 参数与运行环境
18
+ * @returns {Promise<number>} 退出码
19
+ * @throws {FcdevError} 目标没有运行方案、找不到模拟器或构建失败
20
+ */
21
+ export async function runRunCommand({ positionals, options, context }) {
22
+ if (positionals.length > 1) {
23
+ throw new FcdevError('run 只接受一个路径参数', { code: 'ARGUMENT_INVALID', hint: '用法:fcdev run [目录或文件]' });
24
+ }
25
+ const reporter = {
26
+ log: (message) => context.stdout.write(`${message}\n`),
27
+ write: (text) => context.stderr.write(text),
28
+ };
29
+ const { plan, result } = await buildPath(
30
+ { pathArg: positionals[0], cwd: context.cwd, targetOverride: options.target, env: context.env },
31
+ reporter,
32
+ );
33
+ const run = plan.target.run;
34
+ if (!run) {
35
+ throw new FcdevError(`目标 ${plan.target.name} 没有运行方案`, { code: 'TARGET_NO_RUN' });
36
+ }
37
+ const emulator = locateEmulator({ configured: plan.config.emulator, env: context.env });
38
+ const port = options.port ?? DEFAULT_DEBUG_PORT;
39
+
40
+ if (run.mode === 'rom') {
41
+ const { pid, client } = await launchEmulator({ executable: emulator.executable, romFile: result.outputFile, debug: options.debug, port });
42
+ client?.close();
43
+ context.stdout.write(`已启动模拟器(进程 ${pid}),加载 ${result.outputFile}\n`);
44
+ } else {
45
+ if (!plan.config.firmware) {
46
+ throw new FcdevError(`目标 ${plan.target.name} 的运行需要固件(BIOS)`, {
47
+ code: 'FIRMWARE_MISSING',
48
+ hint: '在 fcdev.json 里用 firmware 指定固件文件;fcdev 不提供任何 BIOS 或 ROM',
49
+ });
50
+ }
51
+ const { imageFile } = buildDiskImage(plan, result);
52
+ const { pid, client } = await launchEmulator({ executable: emulator.executable, romFile: plan.config.firmware, debug: true, port });
53
+ try {
54
+ for (const command of [`disk ${imageFile}`, 'reset', ...(options.debug ? [] : ['live'])]) {
55
+ const reply = await client.send(command);
56
+ if (!reply.ok) throw new FcdevError(`模拟器拒绝命令“${command}”:${reply.head}`, { code: 'EMULATOR_COMMAND_FAILED' });
57
+ }
58
+ } finally {
59
+ client.close();
60
+ }
61
+ context.stdout.write(`已启动模拟器(进程 ${pid}),固件 ${plan.config.firmware},磁盘镜像 ${imageFile}\n`);
62
+ context.stdout.write(`等 DOS 启动后,在提示符下输入 ${path.basename(result.outputFile, path.extname(result.outputFile))} 运行程序\n`);
63
+ }
64
+ if (options.debug) {
65
+ context.stdout.write(`调试模式:端口 ${port},模拟器只在收到 run 命令时运行,例如 fcdev debug run 60\n`);
66
+ }
67
+ return 0;
68
+ }
@@ -0,0 +1,85 @@
1
+ // ------------------------------------------------------------------------
2
+ // 名称:sync-command.mjs
3
+ // 说明:sync 命令:生成 IDE 的 C/C++ 配置,让智能提示找到 cc65 与目标的头文件。
4
+ // 作者:sungbin
5
+ // 邮箱:sungbin@3578.cn
6
+ // 日期:2026-11-10
7
+ // 备注:写 .vscode/c_cpp_properties.json 里名为 fcdev 的配置(保留其他配置)与项目根的 compile_flags.txt;
8
+ // compile_flags.txt 的第一行是标记 -DFCDEV_GENERATED,没有标记的同名文件视为用户自己的,不覆盖。
9
+ // ------------------------------------------------------------------------
10
+ import { existsSync, mkdirSync, readFileSync, writeFileSync } from 'node:fs';
11
+ import path from 'node:path';
12
+ import { FcdevError, readJsonFile } from '../../shared/index.mjs';
13
+ import { describeProject } from './project-info.mjs';
14
+
15
+ /** compile_flags.txt 里标记“由 fcdev 生成”的第一行 */
16
+ const GENERATED_MARKER = '-DFCDEV_GENERATED';
17
+
18
+ /** c_cpp_properties.json 里 fcdev 管理的配置名 */
19
+ const CONFIGURATION_NAME = 'fcdev';
20
+
21
+ /**
22
+ * 把预定义宏转成 NAME=VALUE 形式。
23
+ * @param {Record<string, string|number>} defines 宏表
24
+ * @returns {string[]} 宏列表
25
+ */
26
+ function formatDefines(defines) {
27
+ return Object.entries(defines).map(([name, value]) => `${name}=${value}`);
28
+ }
29
+
30
+ /**
31
+ * 写入或更新 .vscode/c_cpp_properties.json 里 fcdev 的配置。
32
+ * @param {string} root 项目根目录
33
+ * @param {import('./project-info.mjs').ProjectInfo} info 项目信息
34
+ * @returns {string} 写入的文件
35
+ * @throws {FcdevError} 已有文件不是合法的配置
36
+ */
37
+ function writeCppProperties(root, info) {
38
+ const file = path.join(root, '.vscode', 'c_cpp_properties.json');
39
+ const document = existsSync(file) ? readJsonFile(file) : { version: 4, configurations: [] };
40
+ if (!Array.isArray(document.configurations)) {
41
+ throw new FcdevError(`${file} 缺少 configurations 数组`, { code: 'SYNC_FILE_INVALID' });
42
+ }
43
+ const configuration = {
44
+ name: CONFIGURATION_NAME,
45
+ includePath: info.includeDirs,
46
+ defines: formatDefines(info.defines),
47
+ cStandard: 'c89',
48
+ intelliSenseMode: 'clang-x86',
49
+ };
50
+ const index = document.configurations.findIndex((item) => item.name === CONFIGURATION_NAME);
51
+ if (index >= 0) document.configurations[index] = configuration;
52
+ else document.configurations.push(configuration);
53
+ mkdirSync(path.dirname(file), { recursive: true });
54
+ writeFileSync(file, `${JSON.stringify(document, null, 2)}\n`);
55
+ return file;
56
+ }
57
+
58
+ /**
59
+ * 写入 compile_flags.txt。
60
+ * @param {string} root 项目根目录
61
+ * @param {import('./project-info.mjs').ProjectInfo} info 项目信息
62
+ * @returns {string|null} 写入的文件;已有用户自己的同名文件时为 null
63
+ */
64
+ function writeCompileFlags(root, info) {
65
+ const file = path.join(root, 'compile_flags.txt');
66
+ if (existsSync(file) && readFileSync(file, 'utf8').split(/\r?\n/)[0] !== GENERATED_MARKER) return null;
67
+ const lines = [GENERATED_MARKER, ...info.includeDirs.map((dir) => `-I${dir}`), ...formatDefines(info.defines).map((item) => `-D${item}`)];
68
+ writeFileSync(file, `${lines.join('\n')}\n`);
69
+ return file;
70
+ }
71
+
72
+ /**
73
+ * 执行 sync 命令。
74
+ * @param {{options: {target?: string}, context: import('../index.mjs').CliContext}} input 选项与运行环境
75
+ * @returns {Promise<number>} 退出码
76
+ */
77
+ export async function runSyncCommand({ options, context }) {
78
+ const info = await describeProject({ cwd: context.cwd, targetOverride: options.target, env: context.env });
79
+ const written = [writeCppProperties(info.root, info)];
80
+ const flags = writeCompileFlags(info.root, info);
81
+ if (flags) written.push(flags);
82
+ else context.stderr.write('compile_flags.txt 已存在且不是 fcdev 生成的,没有覆盖\n');
83
+ context.stdout.write(`已生成:\n${written.map((file) => ` ${path.relative(context.cwd, file)}`).join('\n')}\n`);
84
+ return 0;
85
+ }
@@ -0,0 +1,100 @@
1
+ // ------------------------------------------------------------------------
2
+ // 名称:index.mjs
3
+ // 说明:命令行入口:解析参数、分发命令、把错误翻译成用户能看懂的提示。
4
+ // 作者:sungbin
5
+ // 邮箱:sungbin@3578.cn
6
+ // 日期:2026-11-10
7
+ // 备注:runCli 不直接读写进程状态,终端目录、环境变量与输出流都由调用者传入,便于测试。
8
+ // ------------------------------------------------------------------------
9
+ import { FcdevError, readJsonFile } from '../shared/index.mjs';
10
+ import { fileURLToPath } from 'node:url';
11
+ import { parseArguments } from './args-parser.mjs';
12
+ import { runBuildCommand } from './commands/build-command.mjs';
13
+ import { runDebugCommand } from './commands/debug-command.mjs';
14
+ import { runDiskCommand } from './commands/disk-command.mjs';
15
+ import { runDisasmCommand } from './commands/disasm-command.mjs';
16
+ import { runInfoCommand } from './commands/info-command.mjs';
17
+ import { runRunCommand } from './commands/run-command.mjs';
18
+ import { runSyncCommand } from './commands/sync-command.mjs';
19
+
20
+ /**
21
+ * @typedef {object} CliContext
22
+ * @property {string} cwd 终端当前目录
23
+ * @property {NodeJS.ProcessEnv} env 环境变量
24
+ * @property {{write: (text: string) => unknown}} stdout 标准输出
25
+ * @property {{write: (text: string) => unknown}} stderr 标准错误
26
+ */
27
+
28
+ /** 命令表:命令名到处理函数 */
29
+ const COMMANDS = {
30
+ build: runBuildCommand,
31
+ debug: runDebugCommand,
32
+ disasm: runDisasmCommand,
33
+ disk: runDiskCommand,
34
+ info: runInfoCommand,
35
+ run: runRunCommand,
36
+ sync: runSyncCommand,
37
+ };
38
+
39
+ /** 帮助文字 */
40
+ const HELP_TEXT = `fcdev:6502 兼容机的开发工具
41
+
42
+ 用法:fcdev <命令> [选项]
43
+
44
+ 命令:
45
+ build [目录或文件] 构建:无参数为当前目录;目录整体构成一个程序;文件单独构成一个程序
46
+ run [目录或文件] 构建后在模拟器里运行(--debug 启动调试模式)
47
+ disk [目录或文件] 构建后把程序放进磁盘镜像(只有支持磁盘的目标可用)
48
+ disasm <文件> 反汇编 NES 程序或平铺二进制为 ca65 源码,并回读校验
49
+ debug <命令> 把命令转发给模拟器的调试服务,如 debug run 60、debug shot out.png
50
+ sync 生成 IDE 的 C/C++ 配置
51
+ info [--json] 显示目标、工具链与头文件目录
52
+
53
+ 选项:
54
+ --target <名> 指定目标,覆盖 fcdev.json
55
+ --debug run 以调试模式启动模拟器
56
+ --port <端口> run 的调试端口,默认 5699;debug 命令读环境变量 FCDEV_DEBUG_PORT,默认也是 5699
57
+ --json info 输出机器可读格式
58
+
59
+ disasm 的选项:
60
+ --format ines|binary 输入格式,缺省时按文件头判断
61
+ --base <地址> 平铺二进制的加载地址(十六进制)
62
+ --entry <地址> 追踪代码的入口,可重复;iNES 会自动使用中断向量
63
+ --cdl <文件> CDL(FCEUX、Mesen 格式),代码段的起点也当作入口
64
+ --trace <文件> 模拟器 trace 命令记录的指令轨迹,执行过的指令地址都当作入口
65
+ --symbols <文件> 符号文件,每行“名字 = $地址”
66
+ --out <目录> 输出目录,默认 build/disasm/<文件名>
67
+ -h, --help 显示帮助
68
+ -v, --version 显示版本
69
+ `;
70
+
71
+ /**
72
+ * 运行命令行。
73
+ * @param {string[]} argv 去掉 node 与脚本路径后的参数
74
+ * @param {CliContext} context 运行环境
75
+ * @returns {Promise<number>} 进程退出码
76
+ */
77
+ export async function runCli(argv, context) {
78
+ try {
79
+ const { command, positionals, options } = parseArguments(argv);
80
+ if (options.version) {
81
+ const packageFile = fileURLToPath(new URL('../../package.json', import.meta.url));
82
+ context.stdout.write(`${readJsonFile(packageFile).version}\n`);
83
+ return 0;
84
+ }
85
+ if (options.help || command === null || command === 'help') {
86
+ context.stdout.write(HELP_TEXT);
87
+ return 0;
88
+ }
89
+ const handler = COMMANDS[command];
90
+ if (!handler) {
91
+ throw new FcdevError(`未知的命令:${command}`, { code: 'ARGUMENT_INVALID', hint: '用 fcdev --help 查看可用的命令' });
92
+ }
93
+ return await handler({ positionals, options, context });
94
+ } catch (error) {
95
+ if (!(error instanceof FcdevError)) throw error;
96
+ context.stderr.write(`错误:${error.message}\n`);
97
+ if (error.hint) context.stderr.write(`${error.hint}\n`);
98
+ return 1;
99
+ }
100
+ }
@@ -0,0 +1,132 @@
1
+ // ------------------------------------------------------------------------
2
+ // 名称:config-loader.mjs
3
+ // 说明:查找并读取项目配置 fcdev.json:校验键与类型,补默认值,把相对路径换成绝对路径。
4
+ // 作者:sungbin
5
+ // 邮箱:sungbin@3578.cn
6
+ // 日期:2026-11-10
7
+ // 备注:未知的键直接报错,避免拼写错误被忽略;配置项含义见 docs/02-命令行与构建.md 第 3 节。
8
+ // ------------------------------------------------------------------------
9
+ import { existsSync } from 'node:fs';
10
+ import path from 'node:path';
11
+ import { FcdevError, readJsonFile } from '../shared/index.mjs';
12
+
13
+ /** 配置文件名 */
14
+ export const CONFIG_FILE_NAME = 'fcdev.json';
15
+
16
+ /** 配置项的类型描述 */
17
+ const KEY_TYPES = {
18
+ target: 'string',
19
+ name: 'string',
20
+ out: 'string',
21
+ optimize: 'boolean',
22
+ define: 'object',
23
+ include: 'string-array',
24
+ toolchain: 'string',
25
+ firmware: 'string',
26
+ emulator: 'string',
27
+ targetOptions: 'object',
28
+ };
29
+
30
+ /**
31
+ * @typedef {object} ProjectConfig
32
+ * @property {string|null} file 配置文件路径;没有配置文件时为 null
33
+ * @property {string} root 项目根目录(配置文件所在目录,没有配置时为起始目录)
34
+ * @property {string|undefined} target 目标名
35
+ * @property {string|undefined} name 目录构建时的程序名
36
+ * @property {string} outDir 输出目录的绝对路径
37
+ * @property {boolean} optimize 是否优化
38
+ * @property {Record<string, string|number>} define 预定义宏
39
+ * @property {string[]} include 额外头文件目录的绝对路径
40
+ * @property {string|undefined} toolchain 自备 cc65 根目录的绝对路径
41
+ * @property {string|undefined} firmware 固件文件的绝对路径
42
+ * @property {string|undefined} emulator 自备模拟器路径
43
+ * @property {Record<string, unknown>} targetOptions 目标专用选项
44
+ */
45
+
46
+ /**
47
+ * 从起始目录向上查找最近的 fcdev.json。
48
+ * @param {string} startDir 起始目录
49
+ * @returns {string|null} 配置文件的绝对路径;找不到时为 null
50
+ */
51
+ export function findConfigFile(startDir) {
52
+ let current = path.resolve(startDir);
53
+ for (;;) {
54
+ const candidate = path.join(current, CONFIG_FILE_NAME);
55
+ if (existsSync(candidate)) return candidate;
56
+ const parent = path.dirname(current);
57
+ if (parent === current) return null;
58
+ current = parent;
59
+ }
60
+ }
61
+
62
+ /**
63
+ * 检查一个配置值是否符合类型描述。
64
+ * @param {unknown} value 配置值
65
+ * @param {string} type 类型描述
66
+ * @returns {boolean} 符合时为 true
67
+ */
68
+ function matchesType(value, type) {
69
+ if (type === 'string-array') return Array.isArray(value) && value.every((item) => typeof item === 'string');
70
+ if (type === 'object') return typeof value === 'object' && value !== null && !Array.isArray(value);
71
+ return typeof value === type;
72
+ }
73
+
74
+ /**
75
+ * 校验并规范化配置内容。
76
+ * @param {unknown} raw 解析后的 JSON
77
+ * @param {string|null} file 配置文件路径,用于出错提示与解析相对路径
78
+ * @param {string} fallbackRoot 没有配置文件时的项目根目录
79
+ * @returns {ProjectConfig} 规范化后的配置
80
+ * @throws {FcdevError} 出现未知的键或类型不对
81
+ */
82
+ export function normalizeConfig(raw, file, fallbackRoot) {
83
+ const where = file ?? CONFIG_FILE_NAME;
84
+ if (typeof raw !== 'object' || raw === null || Array.isArray(raw)) {
85
+ throw new FcdevError(`${where} 的内容必须是对象`, { code: 'CONFIG_INVALID' });
86
+ }
87
+ for (const [key, value] of Object.entries(raw)) {
88
+ const type = KEY_TYPES[key];
89
+ if (!type) {
90
+ throw new FcdevError(`${where} 中有未知的配置项:${key}`, {
91
+ code: 'CONFIG_UNKNOWN_KEY',
92
+ hint: `可用的配置项:${Object.keys(KEY_TYPES).join('、')}`,
93
+ });
94
+ }
95
+ if (!matchesType(value, type)) {
96
+ throw new FcdevError(`${where} 中的 ${key} 类型不对,应为 ${type}`, { code: 'CONFIG_INVALID_TYPE' });
97
+ }
98
+ }
99
+ const root = file ? path.dirname(file) : path.resolve(fallbackRoot);
100
+ const resolveFromRoot = (value) => (value === undefined ? undefined : path.resolve(root, value));
101
+ for (const [key, value] of Object.entries(raw.define ?? {})) {
102
+ if (typeof value !== 'string' && typeof value !== 'number') {
103
+ throw new FcdevError(`${where} 的 define.${key} 必须是字符串或数字`, { code: 'CONFIG_INVALID_TYPE' });
104
+ }
105
+ }
106
+ return {
107
+ file,
108
+ root,
109
+ target: raw.target,
110
+ name: raw.name,
111
+ outDir: path.resolve(root, raw.out ?? 'build'),
112
+ optimize: raw.optimize ?? true,
113
+ define: raw.define ?? {},
114
+ include: (raw.include ?? []).map((item) => path.resolve(root, item)),
115
+ toolchain: resolveFromRoot(raw.toolchain),
116
+ firmware: resolveFromRoot(raw.firmware),
117
+ emulator: resolveFromRoot(raw.emulator),
118
+ targetOptions: raw.targetOptions ?? {},
119
+ };
120
+ }
121
+
122
+ /**
123
+ * 读取构建路径对应的项目配置。
124
+ * @param {string} startPath 构建路径(文件或目录)所在的起始目录
125
+ * @param {string} fallbackRoot 找不到配置文件时用作项目根的目录(终端当前目录)
126
+ * @returns {ProjectConfig} 项目配置
127
+ */
128
+ export function loadProjectConfig(startPath, fallbackRoot) {
129
+ const file = findConfigFile(startPath);
130
+ if (!file) return normalizeConfig({}, null, fallbackRoot);
131
+ return normalizeConfig(readJsonFile(file), file, fallbackRoot);
132
+ }
@@ -0,0 +1,9 @@
1
+ // ------------------------------------------------------------------------
2
+ // 名称:index.mjs
3
+ // 说明:config 目录的对外入口。
4
+ // 作者:sungbin
5
+ // 邮箱:sungbin@3578.cn
6
+ // 日期:2026-11-10
7
+ // 备注:无
8
+ // ------------------------------------------------------------------------
9
+ export { CONFIG_FILE_NAME, findConfigFile, loadProjectConfig, normalizeConfig } from './config-loader.mjs';
@@ -0,0 +1,97 @@
1
+ // ------------------------------------------------------------------------
2
+ // 名称:analysis.mjs
3
+ // 说明:静态追踪:从入口出发沿控制流标出哪些字节是指令的操作码、哪些是操作数;CDL 里的代码段起点也当作入口。
4
+ // 作者:sungbin
5
+ // 邮箱:sungbin@3578.cn
6
+ // 日期:2026-11-10
7
+ // 备注:处理规则:顺序执行继续,条件分支两路都追,JMP 只追目标,JSR 追目标并假定会返回,RTS、RTI、BRK、间接 JMP 结束这一路;
8
+ // 遇到非法操作码、越界或与已识别指令重叠时放弃这一路并记入警告。没被追到的字节都算数据,这不影响回读校验(da65 对非法操作码输出 .byte)。
9
+ // ------------------------------------------------------------------------
10
+ import { CDL_CODE } from './cdl.mjs';
11
+ import { OPCODES } from './opcode-table.mjs';
12
+
13
+ /** 字节分类:没有被标成指令 */
14
+ export const KIND_UNKNOWN = 0;
15
+
16
+ /** 字节分类:指令的第一个字节 */
17
+ export const KIND_OPCODE = 1;
18
+
19
+ /** 字节分类:指令的操作数 */
20
+ export const KIND_OPERAND = 2;
21
+
22
+ /**
23
+ * @typedef {object} Analysis
24
+ * @property {Uint8Array} kinds 每个字节的分类
25
+ * @property {number} instructions 识别出的指令条数
26
+ * @property {string[]} warnings 追踪中放弃某一路的原因
27
+ */
28
+
29
+ /**
30
+ * 格式化地址,写进警告。
31
+ * @param {number} address 地址
32
+ * @returns {string} 如 $C000
33
+ */
34
+ function hex(address) {
35
+ return `$${address.toString(16).toUpperCase().padStart(4, '0')}`;
36
+ }
37
+
38
+ /**
39
+ * 从入口出发追踪代码。
40
+ * @param {{bytes: Buffer, base: number, entries: number[], cdl?: Uint8Array|null}} input 映像字节、第一个字节的地址、入口地址与可选的 CDL 标志
41
+ * @returns {Analysis} 分析结果
42
+ */
43
+ export function analyzeCode({ bytes, base, entries, cdl = null }) {
44
+ const kinds = new Uint8Array(bytes.length);
45
+ const warnings = [];
46
+ const pending = [...entries];
47
+ let instructions = 0;
48
+
49
+ if (cdl) {
50
+ // CDL 里每段连续的代码字节,起点一定是被执行过的指令的开头
51
+ for (let offset = 0; offset < cdl.length; offset += 1) {
52
+ if ((cdl[offset] & CDL_CODE) !== 0 && (offset === 0 || (cdl[offset - 1] & CDL_CODE) === 0)) pending.push(base + offset);
53
+ }
54
+ }
55
+
56
+ while (pending.length > 0) {
57
+ let address = pending.pop();
58
+ // 沿着顺序执行一路走下去,遇到分支目标或调用目标就放进待办
59
+ for (;;) {
60
+ const offset = address - base;
61
+ if (offset < 0 || offset >= bytes.length) break;
62
+ if (kinds[offset] === KIND_OPCODE) break;
63
+ const entry = OPCODES[bytes[offset]];
64
+ if (entry === null) {
65
+ warnings.push(`${hex(address)}:操作码 $${bytes[offset].toString(16).toUpperCase().padStart(2, '0')} 不是官方 6502 指令,放弃这一路`);
66
+ break;
67
+ }
68
+ const [, size, flow] = entry;
69
+ if (offset + size > bytes.length) {
70
+ warnings.push(`${hex(address)}:指令超出映像末尾,放弃这一路`);
71
+ break;
72
+ }
73
+ let overlaps = false;
74
+ for (let index = 0; index < size; index += 1) {
75
+ // 操作码位置必须是未知,操作数位置不能是别的指令的开头,也不能是别的指令的操作数
76
+ if (kinds[offset + index] !== KIND_UNKNOWN) overlaps = true;
77
+ }
78
+ if (overlaps) {
79
+ warnings.push(`${hex(address)}:与已识别的指令重叠,放弃这一路`);
80
+ break;
81
+ }
82
+ kinds[offset] = KIND_OPCODE;
83
+ for (let index = 1; index < size; index += 1) kinds[offset + index] = KIND_OPERAND;
84
+ instructions += 1;
85
+
86
+ if (flow === 'branch') {
87
+ const displacement = bytes.readInt8(offset + 1);
88
+ pending.push((address + 2 + displacement) & 0xffff);
89
+ } else if (flow === 'jump' || flow === 'call') {
90
+ pending.push(bytes.readUInt16LE(offset + 1));
91
+ }
92
+ if (flow === 'jump' || flow === 'jump-indirect' || flow === 'return' || flow === 'stop') break;
93
+ address += size;
94
+ }
95
+ }
96
+ return { kinds, instructions, warnings };
97
+ }
@@ -0,0 +1,35 @@
1
+ // ------------------------------------------------------------------------
2
+ // 名称:cdl.mjs
3
+ // 说明:读取 CDL(代码数据日志):每个字节一个标志,位 0 表示被当作代码执行过,位 1 表示被当作数据读取过。
4
+ // 作者:sungbin
5
+ // 邮箱:sungbin@3578.cn
6
+ // 日期:2026-11-10
7
+ // 备注:这是 FCEUX 与 Mesen 的通用格式;Mesen 的新格式在开头多 9 个字节(CDLv2 加校验值),会自动跳过;只取与 PRG 对应的前 PRG 大小个字节。
8
+ // ------------------------------------------------------------------------
9
+ import { FcdevError } from '../shared/index.mjs';
10
+
11
+ /** CDL 标志:被当作代码执行过 */
12
+ export const CDL_CODE = 0x01;
13
+
14
+ /** CDL 标志:被当作数据读取过 */
15
+ export const CDL_DATA = 0x02;
16
+
17
+ /** Mesen CDLv2 的头:魔数 5 字节加 CRC32 4 字节 */
18
+ const MESEN_HEADER = { magic: 'CDLv2', size: 9 };
19
+
20
+ /**
21
+ * 解析 CDL 文件。
22
+ * @param {Buffer} buffer 文件内容
23
+ * @param {number} prgSize PRG 大小
24
+ * @returns {Uint8Array} 长度为 prgSize 的标志数组,只保留代码与数据两位
25
+ * @throws {FcdevError} 文件比 PRG 短
26
+ */
27
+ export function parseCdl(buffer, prgSize) {
28
+ const start = buffer.subarray(0, MESEN_HEADER.magic.length).toString('latin1') === MESEN_HEADER.magic ? MESEN_HEADER.size : 0;
29
+ if (buffer.length - start < prgSize) {
30
+ throw new FcdevError(`CDL 只有 ${buffer.length - start} 字节,少于 PRG 的 ${prgSize} 字节`, { code: 'DISASM_CDL_INVALID', hint: '确认 CDL 是用同一个 ROM 记录的' });
31
+ }
32
+ const flags = new Uint8Array(prgSize);
33
+ for (let index = 0; index < prgSize; index += 1) flags[index] = buffer[start + index] & (CDL_CODE | CDL_DATA);
34
+ return flags;
35
+ }