From 0a6193f68e481790f418cdb111b32f6560854ba3 Mon Sep 17 00:00:00 2001 From: Jeffrey Hsu Date: Tue, 24 Nov 2026 13:45:18 +0800 Subject: [PATCH] Add define parameters and support aliases and definitions in action files --- CMakeLists.txt | 2 +- README.md | 52 +++++++++++----- include/ActionFile.h | 4 +- include/CommandBindings.h | 21 +++++++ include/ConsoleCommand.h | 5 +- main.cpp | 2 +- src/ActionFile.cpp | 19 +++++- src/AppConfig.cpp | 2 +- src/CommandBindings.cpp | 109 ++++++++++++++++++++++++++++++++++ src/ConsoleCommand.cpp | 62 +++++++------------ tests/ActionFileTests.cpp | 39 ++++++++++++ tests/ConsoleCommandTests.cpp | 37 ++++++++++++ 12 files changed, 291 insertions(+), 63 deletions(-) create mode 100644 include/CommandBindings.h create mode 100644 src/CommandBindings.cpp diff --git a/CMakeLists.txt b/CMakeLists.txt index 47fc274..eb3bc0a 100644 --- a/CMakeLists.txt +++ b/CMakeLists.txt @@ -37,7 +37,7 @@ add_library(bilicraft_bot_config STATIC src/AppConfig.cpp) target_include_directories(bilicraft_bot_config PUBLIC "${CMAKE_CURRENT_SOURCE_DIR}/include") target_compile_definitions(bilicraft_bot_config PUBLIC BILICRAFT_BOT_GAME_VERSION="${BOTCRAFT_GAME_VERSION}") -add_library(bilicraft_bot_actions STATIC src/ActionFile.cpp src/ActionScheduler.cpp src/ConsoleCommand.cpp +add_library(bilicraft_bot_actions STATIC src/CommandBindings.cpp src/ActionFile.cpp src/ActionScheduler.cpp src/ConsoleCommand.cpp src/TerminalInput.cpp src/LineEditor.cpp src/TerminalConsole.cpp) target_include_directories(bilicraft_bot_actions PUBLIC "${CMAKE_CURRENT_SOURCE_DIR}/include") find_package(Threads REQUIRED) diff --git a/README.md b/README.md index 10a54ae..be41baf 100644 --- a/README.md +++ b/README.md @@ -112,25 +112,13 @@ bilicraft-bot [--server host:port] [--account cache-key] | 命令 | 说明 | | --- | --- | | `alias [名称 [命令 参数...]]` | 定义或覆盖别名,单给名称查看定义,不带参数列出全部别名 | +| `define [名称 [值...]]` | 定义或更新参数,单给名称查看定义,不带参数列出全部定义 | | `run 路径.act` | 完整检查脚本及导入后入队,路径可用成对引号包裹 | | `tasks` | 显示任务编号、状态、命令进度和等待剩余时间 | | `help` | 显示终端帮助 | | `quit` / `exit` | 取消队列并断开连接 | -游戏命令与脚本共用下文语法,但 `wait` 和 `import` 仅能写在操作文件中。单条交互游戏命令提交后,终端会等它完成或失败,再接收下一条输入。 - -### 命令别名 - -在终端输入 `alias 名称 命令 参数...` 保存快捷命令,定义时不会执行。调用时,名称后的参数会接在已保存的命令后面。例如: - -```text ->>> alias tell sendmsg @Steve ->>> tell 收获完成 ->>> alias demo run "../../actions/demo.act" ->>> demo -``` - -第二行等同于 `sendmsg @Steve 收获完成`,第四行会将示例脚本加入队列。别名仅在本次终端会话有效。支持引用其他别名,也可以用 `alias drop drop all` 给同名游戏命令预设参数。循环引用会报错。`alias` 本身是保留名称。 +终端和脚本都支持[命令别名与参数定义](#命令别名与参数定义)。游戏命令与脚本共用下文语法,但 `wait` 和 `import` 仅能写在操作文件中。单条交互游戏命令提交后,终端会等它完成或失败,再接收下一条输入。 ### 调度与退出 @@ -168,6 +156,42 @@ sendmsg 操作完成 名称是非空简单名称,不含目录、路径分隔符或 `.act` 扩展名。坐标均为绝对整数方块坐标,不支持 `~`、`^` 或小数。下表中的方括号表示可选参数,实际输入时不写方括号;标志区分大小写。 +### 命令别名与参数定义 + +交互终端和 `.act` 共用两条声明语法: + +- `define 名称 值...` 保存一组参数。比如 `define pos1 1 1 1` 之后,`goto $pos1` 等同于 `goto 1 1 1`。 +- `alias 名称 命令 参数...` 保存一条快捷命令。调用时可以再追加参数,比如定义 `alias tell sendmsg @Steve` 后,`tell 收获完成` 会向 Steve 发送私信。 + +要在多个脚本中使用同一组坐标,可以把这两条声明放在 `common.act` 中: + +```text +# action: common +define pos1 1 1 1 +alias home goto $pos1 +``` + +在同目录的 `route.act` 中导入它: + +```text +# action: route +import common +home +define pos1 20 64 -8 +home +``` + +加载脚本时按行展开。第一次 `home` 使用坐标 `1 1 1`,第二次使用新坐标 `20 64 -8`。每次调用先展开命令别名,再用当前定义替换完整的 `$名称` 参数一次。`sendmsg pos1` 会发送原文。参数名称由英文字母、数字和下划线组成,首字符为字母或下划线。引用未定义的参数或循环引用别名都会报错。 + +别名可以指向其他别名,也可以给同名命令预设参数,例如 `alias drop drop all`。`alias` 和 `define` 是保留命令名。 + +| 使用位置 | 定义的来源和作用范围 | +| --- | --- | +| 交互终端 | 定义保存在当前会话。输入 `alias` 或 `define` 列出对应定义,追加名称可查看单项。 | +| `run 路径.act` | 脚本继承加载时的终端定义。脚本里的新增和覆盖仅对本次加载有效。 | +| `--action`、`--check-action` | 从空的定义表开始。脚本要自行声明或导入所需定义。 | +| `import 名称` | 导入文件和调用文件共享定义。导入返回后,后续各行可使用导入文件中的声明。 | + ### 游戏命令 | 命令 | 说明 | diff --git a/include/ActionFile.h b/include/ActionFile.h index 3a483d3..fc547ae 100644 --- a/include/ActionFile.h +++ b/include/ActionFile.h @@ -1,5 +1,7 @@ #pragma once +#include "CommandBindings.h" + #include #include #include @@ -71,7 +73,7 @@ struct ActionProgram // Clicks optionally accept entry [t|b|s|n|w|e] (or full face names), with // the face immediately after entry. Existing shift and left-click destroy flags // may appear before or after entry; omitted entry retains block-click behavior. -ActionProgram LoadActionFile(const std::filesystem::path &path); +ActionProgram LoadActionFile(const std::filesystem::path &path, CommandBindings bindings = {}); // Parse one console game instruction using the .act grammar, without file I/O. // Blank/comment lines return nullopt. Wait/import require `run file.act` instead. diff --git a/include/CommandBindings.h b/include/CommandBindings.h new file mode 100644 index 0000000..35a4921 --- /dev/null +++ b/include/CommandBindings.h @@ -0,0 +1,21 @@ +#pragma once + +#include +#include +#include + +namespace Bilicraft +{ +class CommandBindings +{ + public: + // Process one trimmed, comment-free line. Declarations return an empty string. + // A console caller can supply display to enable list and lookup commands. + std::string Expand(std::string_view line, std::size_t maxLength, std::string *display = nullptr); + + private: + using Bindings = std::map>; + Bindings aliases; + Bindings definitions; +}; +} // namespace Bilicraft diff --git a/include/ConsoleCommand.h b/include/ConsoleCommand.h index c8f1ce5..59bc75b 100644 --- a/include/ConsoleCommand.h +++ b/include/ConsoleCommand.h @@ -1,6 +1,5 @@ #pragma once #include "ActionFile.h" -#include #include #include #include @@ -19,8 +18,10 @@ class ConsoleCommandParser public: ConsoleCommand Parse(std::string_view line); + const CommandBindings &GetBindings() const { return bindings; } + private: - std::map> aliases; + CommandBindings bindings; }; std::string ConsoleHelp(); } // namespace Bilicraft diff --git a/main.cpp b/main.cpp index bc2a359..4e42bba 100644 --- a/main.cpp +++ b/main.cpp @@ -118,7 +118,7 @@ int main(int argc, char **argv) case ConsoleKind::Help: console->Out() << ConsoleHelp(); break; case ConsoleKind::Quit: stopRequested = 1; break; case ConsoleKind::Run: - scheduler.Enqueue(LoadActionFile(request.argument)); + scheduler.Enqueue(LoadActionFile(request.argument, commandParser.GetBindings())); break; case ConsoleKind::Tasks: { diff --git a/src/ActionFile.cpp b/src/ActionFile.cpp index 06ffecc..c784fcd 100644 --- a/src/ActionFile.cpp +++ b/src/ActionFile.cpp @@ -277,6 +277,8 @@ ActionCommand ParseCommand(std::string_view verb, std::string_view line, const s struct Loader { + CommandBindings bindings; + std::size_t expandedBytes = 0; ActionProgram program; std::vector active; std::size_t loads = 0; @@ -363,6 +365,20 @@ struct Loader continue; if (!header_seen) Fail(source, line_number, "missing action header before first instruction"); + std::string expanded; + try + { + expanded = bindings.Expand(line, kMaxFileBytes); + } + catch (const std::runtime_error &error) + { + Fail(source, line_number, error.what()); + } + if (expanded.empty()) continue; + expandedBytes += expanded.size(); + if (expandedBytes > kMaxTotalBytes) + Fail(source, line_number, "total expanded action text exceeds 16 MiB"); + line = expanded; const auto verb = TakeToken(line); if (verb == "import") { @@ -396,11 +412,12 @@ struct Loader }; } // namespace -ActionProgram LoadActionFile(const std::filesystem::path &path) +ActionProgram LoadActionFile(const std::filesystem::path &path, CommandBindings bindings) { if (path.extension() != ".act") Fail(path, 1, "action file must have the .act extension"); Loader loader; + loader.bindings = std::move(bindings); loader.Load(path); return std::move(loader.program); } diff --git a/src/AppConfig.cpp b/src/AppConfig.cpp index 0908ce2..e560545 100644 --- a/src/AppConfig.cpp +++ b/src/AppConfig.cpp @@ -46,7 +46,7 @@ std::string Usage() " --action Queue an initial .act task after login and start the console\n" " --check-action Validate a .act file and imports offline, then exit\n" " --help Show help without connecting or authenticating\n" - "Console: alias [name [command args...]], run file.act, tasks, help, quit, or a single game command (no wait).\n" + "Console: alias [name [command args...]], define [name [value...]], run file.act, tasks, help, quit, or a single game command (no wait).\n" "Microsoft authentication is required. Ctrl+C requests shutdown.\n"; } } // namespace Bilicraft diff --git a/src/CommandBindings.cpp b/src/CommandBindings.cpp new file mode 100644 index 0000000..56c901d --- /dev/null +++ b/src/CommandBindings.cpp @@ -0,0 +1,109 @@ +#include "CommandBindings.h" +#include +#include +#include + +namespace Bilicraft +{ +namespace +{ +constexpr std::string_view whitespace = " \t\r\n\v\f"; + +bool IsDefinitionName(std::string_view name) +{ + constexpr std::string_view letters = "abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ_"; + return !name.empty() && letters.find(name.front()) != letters.npos && + name.find_first_not_of("abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ_0123456789") == name.npos; +} + +std::string_view Trim(std::string_view text) +{ + const auto first = text.find_first_not_of(whitespace); + if (first == std::string_view::npos) return {}; + return text.substr(first, text.find_last_not_of(whitespace) - first + 1); +} +std::pair SplitFirst(std::string_view text) +{ + const auto split = text.find_first_of(whitespace); + return {text.substr(0, split), split == text.npos ? std::string_view{} : Trim(text.substr(split))}; +} +} + +std::string CommandBindings::Expand(std::string_view line, std::size_t maxLength, std::string *display) +{ + auto [verb, rest] = SplitFirst(line); + std::set expanded; // Views refer to stable map keys. + std::string buffer; + for (auto it = aliases.find(verb); it != aliases.end(); it = aliases.find(verb)) + { + if (!expanded.insert(it->first).second) + throw std::runtime_error("alias cycle at " + it->first); + std::string next = it->second; + if (!rest.empty()) next.append(" ").append(rest); + if (next.size() > maxLength) throw std::runtime_error("expanded command exceeds length limit"); + buffer = std::move(next); + line = buffer; + const auto parts = SplitFirst(line); + verb = parts.first; + rest = parts.second; + if (verb == it->first) break; // Allow a shortcut such as "alias drop drop all". + } + if (verb == "alias" || verb == "define") + { + auto &bindings = verb == "alias" ? aliases : definitions; + const std::string keyword(verb); + const auto [name, body] = SplitFirst(rest); + if (body.empty() && !display) + throw std::runtime_error(keyword + " requires a name and value in an action file"); + if (name.empty()) + { + std::string output; + for (const auto &[key, value] : bindings) + output += keyword + " " + key + " " + value + "\n"; + if (output.empty()) output = verb == "alias" ? "No aliases defined.\n" : "No definitions.\n"; + *display = std::move(output); + return {}; + } + if (body.empty()) + { + const auto it = bindings.find(name); + if (it == bindings.end()) throw std::runtime_error("unknown " + keyword + ": " + std::string(name)); + *display = keyword + " " + it->first + " " + it->second + "\n"; + return {}; + } + if (verb == "alias" && (name == "alias" || name == "define")) + throw std::runtime_error("reserved command name: " + std::string(name)); + if (verb == "define" && !IsDefinitionName(name)) + throw std::runtime_error("expected a definition name matching [A-Za-z_][A-Za-z0-9_]*"); + bindings.insert_or_assign(std::string(name), std::string(body)); + return {}; + } + + // Substitute whole argument tokens once, after aliases have resolved to a command. + std::string substituted; + if (rest.find('$') != rest.npos) + { + substituted.assign(verb); + substituted.push_back(' '); + while (!rest.empty()) + { + auto token = rest.substr(0, rest.find_first_of(whitespace)); + rest.remove_prefix(token.size()); + if (token.starts_with('$') && IsDefinitionName(token.substr(1))) + { + const auto it = definitions.find(token.substr(1)); + if (it == definitions.end()) + throw std::runtime_error("undefined parameter: " + std::string(token)); + token = it->second; + } + auto spaces = rest.substr(0, rest.find_first_not_of(whitespace)); + if (substituted.size() + token.size() + spaces.size() > maxLength) + throw std::runtime_error("expanded command exceeds length limit"); + substituted.append(token).append(spaces); + rest.remove_prefix(spaces.size()); + } + return substituted; + } + return std::string(line); +} +} // namespace Bilicraft diff --git a/src/ConsoleCommand.cpp b/src/ConsoleCommand.cpp index a2d69c0..c2079e1 100644 --- a/src/ConsoleCommand.cpp +++ b/src/ConsoleCommand.cpp @@ -1,5 +1,4 @@ #include "ConsoleCommand.h" -#include #include #include @@ -7,63 +6,41 @@ namespace Bilicraft { namespace { +constexpr std::size_t maxLength = 65536; +constexpr std::string_view whitespace = " \t\v\f"; + std::string_view Trim(std::string_view text) { - const auto first = text.find_first_not_of(" \t\v\f"); + const auto first = text.find_first_not_of(whitespace); if (first == std::string_view::npos) return {}; - return text.substr(first, text.find_last_not_of(" \t\v\f") - first + 1); + return text.substr(first, text.find_last_not_of(whitespace) - first + 1); } std::pair SplitFirst(std::string_view text) { - const auto split = text.find_first_of(" \t\v\f"); + const auto split = text.find_first_of(whitespace); return {text.substr(0, split), split == text.npos ? std::string_view{} : Trim(text.substr(split))}; } } ConsoleCommand ConsoleCommandParser::Parse(std::string_view line) { - constexpr std::size_t maxLength = 65536; if (line.size() > maxLength || line.find_first_of("\r\n") != line.npos || line.find('\0') != line.npos) throw std::runtime_error(":1: expected a single line of at most 64 KiB"); line = Trim(line.substr(0, line.find('#'))); if (line.empty()) return {}; + std::string display; + std::string expanded; + try + { + expanded = bindings.Expand(line, maxLength, &display); + } + catch (const std::runtime_error &error) + { + throw std::runtime_error(std::string(":1: ") + error.what()); + } + if (!display.empty()) return {ConsoleKind::Display, std::move(display), {}}; + if (expanded.empty()) return {}; + line = expanded; auto [verb, rest] = SplitFirst(line); - std::set expanded; // Views refer to stable map keys. - std::string buffer; - for (auto it = aliases.find(verb); it != aliases.end(); it = aliases.find(verb)) - { - if (!expanded.insert(it->first).second) - throw std::runtime_error(":1: alias cycle at " + it->first); - std::string next = it->second; - if (!rest.empty()) next.append(" ").append(rest); - if (next.size() > maxLength) throw std::runtime_error(":1: expanded command exceeds 64 KiB"); - buffer = std::move(next); - line = buffer; - const auto parts = SplitFirst(line); - verb = parts.first; - rest = parts.second; - if (verb == it->first) break; // Allow a shortcut such as "alias drop drop all". - } - if (verb == "alias") - { - const auto [name, body] = SplitFirst(rest); - if (name.empty()) - { - std::string output; - for (const auto &[key, value] : aliases) - output += "alias " + key + " " + value + "\n"; - return {ConsoleKind::Display, output.empty() ? "No aliases defined.\n" : std::move(output), {}}; - } - if (body.empty()) - { - const auto it = aliases.find(name); - if (it == aliases.end()) throw std::runtime_error(":1: unknown alias: " + std::string(name)); - return {ConsoleKind::Display, "alias " + it->first + " " + it->second + "\n", {}}; - } - if (name == "alias") throw std::runtime_error(":1: alias is a reserved name"); - aliases.insert_or_assign(std::string(name), std::string(body)); - return {}; - } - if (verb == "run") { if (rest.size() >= 2 && ((rest.front() == '"' && rest.back() == '"') || @@ -84,6 +61,7 @@ ConsoleCommand ConsoleCommandParser::Parse(std::string_view line) std::string ConsoleHelp() { return "Console: alias [name [command args...]] | run | tasks | help | quit (or exit)\n" + "define [name [value...]]: store session parameters; use $name as a whole argument.\n" "Game commands: goto, rclick, lclick, grclick, glclick, sw, swb, drop, sendcmd, sendmsg\n" "rclick/lclick: add entry [t|b|s|n|w|e] for item frames; omit face to require a unique frame.\n" "A game command waits until the running action finishes or reaches wait.\n" diff --git a/tests/ActionFileTests.cpp b/tests/ActionFileTests.cpp index fdb4dc3..9191180 100644 --- a/tests/ActionFileTests.cpp +++ b/tests/ActionFileTests.cpp @@ -1,4 +1,5 @@ #include "ActionFile.h" +#include "ConsoleCommand.h" #include #include @@ -112,6 +113,44 @@ class ActionFileTest : public ::testing::Test } }; +TEST_F(ActionFileTest, ExpandsBindingsInSourceOrderAcrossImports) +{ + Write("child.act", "# action: child\nhome\ndefine pos1 20 64 -8\nalias pause wait 1 s\n"); + const auto program = Parse("# action: root\ndefine pos1 1 1 1\nalias home goto $pos1\n" + "define file child\nalias include import\ninclude $file\nhome\npause\n"); + ASSERT_EQ(program.commands.size(), 3u); + const auto &first = program.commands[0]; + EXPECT_EQ(first.kind, ActionKind::Goto); + EXPECT_EQ(first.x, 1); + EXPECT_EQ(first.source.filename(), "child.act"); + EXPECT_EQ(first.line, 2u); + EXPECT_EQ(program.commands[1].x, 20); + EXPECT_EQ(program.commands[1].y, 64); + EXPECT_EQ(program.commands[1].z, -8); + EXPECT_EQ(program.commands[2].waitDuration, std::chrono::seconds(1)); +} + +TEST_F(ActionFileTest, RunInheritsConsoleBindingsAndKeepsOverridesLocal) +{ + Bilicraft::ConsoleCommandParser console; + console.Parse("define slot 1"); + console.Parse("alias pick sw $slot"); + const auto path = Write("test.act", "# action: test\npick\ndefine slot 3\npick\n"); + const auto program = LoadActionFile(path, console.GetBindings()); + ASSERT_EQ(program.commands.size(), 2u); + EXPECT_EQ(program.commands[0].slot, 1); + EXPECT_EQ(program.commands[1].slot, 3); + EXPECT_EQ(console.Parse("pick").action->slot, 1); + EXPECT_THROW(LoadActionFile(path), std::runtime_error); +} + +TEST_F(ActionFileTest, ReportsBindingErrorsAtTheSourceLine) +{ + Reject("# action: test\ngoto $missing\n", "undefined parameter: $missing"); + Reject("# action: test\nalias a b\nalias b a\na\n", "alias cycle", 4); + Reject("# action: test\ndefine name\n", "requires a name and value"); +} + TEST_F(ActionFileTest, ParsesEveryInstructionAndStoresSourceLocations) { const auto program = Parse("# action: farming\n" diff --git a/tests/ConsoleCommandTests.cpp b/tests/ConsoleCommandTests.cpp index fda92bd..3166239 100644 --- a/tests/ConsoleCommandTests.cpp +++ b/tests/ConsoleCommandTests.cpp @@ -78,6 +78,43 @@ TEST(ConsoleCommand, SupportsSameNameDefaultsAndRejectsAliasCyclesAndOversizedEx EXPECT_THROW(parser.Parse("m " + std::string(65534, 'x')), std::exception); } +TEST(ConsoleCommand, ExpandsCoordinatesDirectlyAndReadsDefinitionsWhenCallingAliases) +{ + ConsoleCommandParser parser; + parser.Parse("alias home goto $pos1"); + parser.Parse("define pos1 1 1 1"); + const auto direct = parser.Parse("goto $pos1"); + ASSERT_TRUE(direct.action); + EXPECT_EQ(direct.action->kind, ActionKind::Goto); + EXPECT_EQ(direct.action->x, 1); + EXPECT_EQ(direct.action->y, 1); + EXPECT_EQ(direct.action->z, 1); + parser.Parse("define pos1 20 64 -8"); + const auto home = parser.Parse("home"); + ASSERT_TRUE(home.action); + EXPECT_EQ(home.action->x, 20); + EXPECT_EQ(home.action->y, 64); + EXPECT_EQ(home.action->z, -8); + EXPECT_EQ(parser.Parse("define pos1").argument, "define pos1 20 64 -8\n"); + EXPECT_EQ(parser.Parse("define").argument, "define pos1 20 64 -8\n"); +} + +TEST(ConsoleCommand, SubstitutesOnlyExplicitWholeArgumentsOnceAndPreservesTextSpacing) +{ + ConsoleCommandParser parser; + parser.Parse("define point 1 2 3"); + parser.Parse("define literal $point"); + const auto message = parser.Parse("sendmsg point prefix$point $point $literal $point"); + ASSERT_TRUE(message.action); + EXPECT_EQ(message.action->text, "point prefix$point 1 2 3 $point 1 2 3"); + EXPECT_THROW(parser.Parse("goto $missing"), std::exception); + EXPECT_THROW(parser.Parse("define 1point 5"), std::exception); + EXPECT_THROW(parser.Parse("alias define quit"), std::exception); + EXPECT_THROW(ConsoleCommandParser{}.Parse("goto $point"), std::exception); + parser.Parse("define big " + std::string(33000, 'x')); + EXPECT_THROW(parser.Parse("sendmsg $big $big"), std::exception); +} + #ifndef _WIN32 TEST(ConsoleCommand, NativePseudoTerminalWaitsForEnterAndParsesTheCommand) {