517 lines
22 KiB
C++
517 lines
22 KiB
C++
#include "ActionFile.h"
|
|
|
|
#include <algorithm>
|
|
#include <charconv>
|
|
#include <cstdint>
|
|
#include <fstream>
|
|
#include <stdexcept>
|
|
#include <string_view>
|
|
#include <system_error>
|
|
#include <utility>
|
|
|
|
namespace Bilicraft
|
|
{
|
|
namespace
|
|
{
|
|
constexpr std::size_t kMaxDepth = 32;
|
|
constexpr std::size_t kMaxCommands = 100000;
|
|
constexpr std::size_t kMaxLoads = 4096;
|
|
constexpr std::size_t kMaxFileBytes = 1024 * 1024;
|
|
constexpr std::size_t kMaxTotalBytes = 16 * kMaxFileBytes;
|
|
|
|
bool IsSpace(char c)
|
|
{
|
|
return c == ' ' || c == '\t' || c == '\r' || c == '\n' || c == '\v' || c == '\f';
|
|
}
|
|
|
|
std::string_view Trim(std::string_view text)
|
|
{
|
|
while (!text.empty() && IsSpace(text.front()))
|
|
text.remove_prefix(1);
|
|
while (!text.empty() && IsSpace(text.back()))
|
|
text.remove_suffix(1);
|
|
return text;
|
|
}
|
|
|
|
std::string_view TakeToken(std::string_view &text)
|
|
{
|
|
text = Trim(text);
|
|
const auto end = text.find_first_of(" \t\r\n\v\f");
|
|
const auto token = text.substr(0, end);
|
|
text.remove_prefix(end == std::string_view::npos ? text.size() : end);
|
|
return token;
|
|
}
|
|
|
|
[[noreturn]] void Fail(const std::filesystem::path &source, std::size_t line, const std::string &message)
|
|
{
|
|
throw std::runtime_error(source.string() + ":" + std::to_string(line) + ": " + message);
|
|
}
|
|
|
|
bool IsSimpleName(std::string_view name)
|
|
{
|
|
if (name.empty() || name == "." || name == ".." || name.back() == '.' || name.ends_with(".act"))
|
|
return false;
|
|
// Also reject Windows separators/drive syntax when parsing on POSIX.
|
|
for (const unsigned char c : name)
|
|
if (c <= 32 || c == 127 || std::string_view("/\\:<>\"|?*").find(c) != std::string_view::npos)
|
|
return false;
|
|
return true;
|
|
}
|
|
|
|
int Integer(std::string_view token, const ActionCommand &command)
|
|
{
|
|
int value = 0;
|
|
// from_chars intentionally does not accept '+', but signed decimal does.
|
|
if (!token.empty() && token.front() == '+')
|
|
{
|
|
token.remove_prefix(1);
|
|
if (token.empty() || token.front() == '-' || token.front() == '+')
|
|
Fail(command.source, command.line, "expected a decimal integer");
|
|
}
|
|
const auto result = std::from_chars(token.data(), token.data() + token.size(), value);
|
|
if (token.empty() || result.ec != std::errc{} || result.ptr != token.data() + token.size())
|
|
Fail(command.source, command.line, "expected a decimal integer: '" + std::string(token) + "'");
|
|
return value;
|
|
}
|
|
|
|
std::chrono::milliseconds ParseWaitDuration(std::string_view number, std::string_view unit,
|
|
const ActionCommand &command)
|
|
{
|
|
std::int64_t multiplier = 0;
|
|
if (unit.empty() || unit == "s")
|
|
multiplier = 1000;
|
|
else if (unit == "ms")
|
|
multiplier = 1;
|
|
else if (unit == "min")
|
|
multiplier = 60000;
|
|
else if (unit == "h")
|
|
multiplier = 3600000;
|
|
else if (unit == "d")
|
|
multiplier = 86400000;
|
|
else
|
|
Fail(command.source, command.line, "unknown wait unit (expected s, ms, min, h or d)");
|
|
|
|
// Plain unsigned decimal: digits, optionally followed by '.' and digits.
|
|
// Validate before arithmetic; in particular no signs, exponent, NaN or Inf.
|
|
const auto dot = number.find('.');
|
|
const auto whole = number.substr(0, dot);
|
|
const auto fraction = dot == std::string_view::npos ? std::string_view{} : number.substr(dot + 1);
|
|
const auto digits = [](std::string_view text) {
|
|
return std::all_of(text.begin(), text.end(), [](char c) { return c >= '0' && c <= '9'; });
|
|
};
|
|
if (whole.empty() || !digits(whole) || (dot != std::string_view::npos && fraction.empty()) || !digits(fraction))
|
|
Fail(command.source, command.line, "wait requires a nonnegative plain decimal number (digits[.digits])");
|
|
|
|
// Bound before multiplication, including arbitrarily long numeric tokens.
|
|
// A short fixed cap also keeps scheduling far below steady_clock's range.
|
|
constexpr std::int64_t max_milliseconds = 365LL * 24 * 60 * 60 * 1000;
|
|
const auto limit = max_milliseconds / multiplier;
|
|
std::int64_t integral = 0;
|
|
for (const char c : whole)
|
|
{
|
|
const int digit = c - '0';
|
|
if (integral > (limit - digit) / 10)
|
|
Fail(command.source, command.line, "wait duration exceeds the 365 days limit");
|
|
integral = integral * 10 + digit;
|
|
}
|
|
|
|
// Decimal multiplication from right to left. Each discarded fractional
|
|
// digit must be zero, so we never round or use floating-point arithmetic.
|
|
// The carry is always < multiplier, regardless of the token's length.
|
|
std::int64_t fractional_milliseconds = 0;
|
|
for (auto it = fraction.rbegin(); it != fraction.rend(); ++it)
|
|
{
|
|
const auto product = (*it - '0') * multiplier + fractional_milliseconds;
|
|
if (product % 10 != 0)
|
|
Fail(command.source, command.line, "wait duration must be an exact whole number of milliseconds");
|
|
fractional_milliseconds = product / 10;
|
|
}
|
|
const auto milliseconds = integral * multiplier + fractional_milliseconds;
|
|
if (milliseconds > max_milliseconds)
|
|
Fail(command.source, command.line, "wait duration exceeds the 365 days limit");
|
|
return std::chrono::milliseconds{milliseconds};
|
|
}
|
|
|
|
std::optional<EntityFace> ParseEntityFace(std::string_view token)
|
|
{
|
|
if (token == "t" || token == "top")
|
|
return EntityFace::Top;
|
|
if (token == "b" || token == "bottom")
|
|
return EntityFace::Bottom;
|
|
if (token == "s" || token == "south")
|
|
return EntityFace::South;
|
|
if (token == "n" || token == "north")
|
|
return EntityFace::North;
|
|
if (token == "w" || token == "west")
|
|
return EntityFace::West;
|
|
if (token == "e" || token == "east")
|
|
return EntityFace::East;
|
|
return std::nullopt;
|
|
}
|
|
|
|
ActionCommand ParseCommand(std::string_view verb, std::string_view line, const std::filesystem::path &source,
|
|
std::size_t line_number)
|
|
{
|
|
ActionCommand command{};
|
|
command.source = source;
|
|
command.line = line_number;
|
|
if (verb == "sendcmd" || verb == "sendmsg")
|
|
{
|
|
command.kind = verb == "sendcmd" ? ActionKind::SendCommand : ActionKind::SendMessage;
|
|
line = Trim(line);
|
|
if (verb == "sendmsg" && line.starts_with('@'))
|
|
{
|
|
const auto recipient = TakeToken(line).substr(1);
|
|
if (recipient.empty())
|
|
Fail(source, line_number, "sendmsg recipient must not be empty");
|
|
command.recipient = recipient;
|
|
}
|
|
command.text = Trim(line);
|
|
if (command.text.empty())
|
|
Fail(source, line_number, "message or command text must not be empty");
|
|
if (verb == "sendcmd" && command.text.starts_with('/') &&
|
|
Trim(std::string_view(command.text).substr(1)).empty())
|
|
Fail(source, line_number, "command text after '/' must not be empty");
|
|
}
|
|
else
|
|
{
|
|
std::vector<std::string_view> args;
|
|
while (!Trim(line).empty())
|
|
args.push_back(TakeToken(line));
|
|
const auto count_is = [&](std::size_t count) {
|
|
if (args.size() != count)
|
|
Fail(source, line_number, std::string(verb) + " requires " + std::to_string(count) + " arguments");
|
|
};
|
|
if (verb == "wait")
|
|
{
|
|
if (args.empty() || args.size() > 2)
|
|
Fail(source, line_number, "wait requires a duration and optional unit: wait times [s|ms|min|h|d]");
|
|
command.kind = ActionKind::Wait;
|
|
command.waitDuration = ParseWaitDuration(args[0], args.size() == 2 ? args[1] : std::string_view{}, command);
|
|
}
|
|
else if (verb == "goto" || verb == "rclick" || verb == "lclick")
|
|
{
|
|
const auto max_args = verb == "goto" ? 3U : verb == "rclick" ? 6U : 7U;
|
|
if (args.size() < 3 || args.size() > max_args)
|
|
Fail(source, line_number, "invalid coordinate/flag argument count for " + std::string(verb));
|
|
command.kind = verb == "goto" ? ActionKind::Goto
|
|
: verb == "rclick" ? ActionKind::RightClick
|
|
: ActionKind::LeftClick;
|
|
command.x = Integer(args[0], command);
|
|
command.y = Integer(args[1], command);
|
|
command.z = Integer(args[2], command);
|
|
for (std::size_t i = 3; i < args.size(); ++i)
|
|
{
|
|
if (verb != "goto" && args[i] == "entry" && !command.entity)
|
|
{
|
|
command.entity = true;
|
|
// Only an immediately adjacent face belongs to entry.
|
|
// Otherwise leave the next token for normal flag parsing.
|
|
if (i + 1 < args.size())
|
|
{
|
|
if (const auto face = ParseEntityFace(args[i + 1]))
|
|
{
|
|
command.entityFace = *face;
|
|
++i;
|
|
}
|
|
}
|
|
}
|
|
else if (args[i] == "shift" && !command.shift)
|
|
command.shift = true;
|
|
else if (verb == "lclick" && (args[i] == "destory" || args[i] == "destroy") && !command.destroy)
|
|
command.destroy = true;
|
|
else
|
|
Fail(source, line_number, "unknown or duplicate flag: " + std::string(args[i]));
|
|
}
|
|
}
|
|
else if (verb == "grclick" || verb == "glclick" || verb == "swb")
|
|
{
|
|
count_is(verb == "swb" ? 3 : 2);
|
|
command.kind = verb == "grclick" ? ActionKind::GuiRightClick
|
|
: verb == "glclick" ? ActionKind::GuiLeftClick
|
|
: ActionKind::SwapBackpack;
|
|
command.row = Integer(args[0], command);
|
|
command.col = Integer(args[1], command);
|
|
if (command.row < 1 || command.col < 1 || command.col > 9 || (verb == "swb" && command.row > 3))
|
|
Fail(source, line_number,
|
|
"row/column out of range (rows start at 1; columns 1..9; backpack rows 1..3)");
|
|
if (verb == "swb")
|
|
command.slot = Integer(args[2], command);
|
|
}
|
|
else if (verb == "drop")
|
|
{
|
|
command.kind = ActionKind::Drop;
|
|
if (args.size() > 2)
|
|
Fail(source, line_number, "drop accepts an optional hotbar slot and optional all flag");
|
|
for (const auto argument : args)
|
|
{
|
|
if (argument == "all")
|
|
{
|
|
if (command.all)
|
|
Fail(source, line_number, "duplicate drop flag: all");
|
|
command.all = true;
|
|
}
|
|
else
|
|
{
|
|
if (command.slot != 0)
|
|
Fail(source, line_number, "duplicate drop hotbar slot");
|
|
command.slot = Integer(argument, command);
|
|
if (command.slot < 1 || command.slot > 9)
|
|
Fail(source, line_number, "drop hotbar slot must be in 1..9");
|
|
}
|
|
}
|
|
}
|
|
else if (verb == "sw")
|
|
{
|
|
count_is(1);
|
|
command.kind = ActionKind::SelectHotbar;
|
|
command.slot = Integer(args[0], command);
|
|
}
|
|
else
|
|
Fail(source, line_number, "unknown instruction: " + std::string(verb));
|
|
if ((verb == "sw" || verb == "swb") && (command.slot < 1 || command.slot > 9))
|
|
Fail(source, line_number, "hotbar slot must be in 1..9");
|
|
}
|
|
return command;
|
|
}
|
|
|
|
struct Loader
|
|
{
|
|
CommandBindings bindings;
|
|
std::size_t expandedBytes = 0;
|
|
ActionProgram program;
|
|
std::vector<std::filesystem::path> active;
|
|
std::size_t loads = 0;
|
|
std::size_t total_bytes = 0;
|
|
|
|
void Append(ActionCommand command)
|
|
{
|
|
if (program.commands.size() >= kMaxCommands)
|
|
Fail(command.source, command.line, "expanded command limit exceeded (100000)");
|
|
program.commands.push_back(std::move(command));
|
|
}
|
|
|
|
void LoadInstruction(std::string_view verb, std::string_view line, const std::filesystem::path &source,
|
|
std::size_t line_number)
|
|
{
|
|
if (verb == "import")
|
|
{
|
|
const auto name = TakeToken(line);
|
|
if (!IsSimpleName(name) || !Trim(line).empty())
|
|
Fail(source, line_number, "import requires exactly one simple action name");
|
|
const auto imported = source.parent_path() / (std::string(name) + ".act");
|
|
std::error_code ec;
|
|
const auto resolved = std::filesystem::canonical(imported, ec);
|
|
if (ec)
|
|
Fail(source, line_number, "cannot import '" + std::string(name) + "': " + ec.message());
|
|
if (resolved.parent_path() != source.parent_path())
|
|
Fail(source, line_number, "import escapes its action directory");
|
|
try
|
|
{
|
|
Load(resolved, name);
|
|
}
|
|
catch (const std::runtime_error &error)
|
|
{
|
|
Fail(source, line_number, "import '" + std::string(name) + "': " + error.what());
|
|
}
|
|
return;
|
|
}
|
|
Append(ParseCommand(verb, line, source, line_number));
|
|
}
|
|
|
|
void Load(const std::filesystem::path &path, std::string_view expected_name = {})
|
|
{
|
|
std::error_code ec;
|
|
const auto source = std::filesystem::canonical(path, ec);
|
|
if (ec)
|
|
Fail(path, 1, "cannot resolve action file: " + ec.message());
|
|
if (!std::filesystem::is_regular_file(source, ec) || ec)
|
|
Fail(source, 1, "action file is not a regular file");
|
|
if (active.size() >= kMaxDepth)
|
|
Fail(source, 1, "import depth limit exceeded (32)");
|
|
if (std::find(active.begin(), active.end(), source) != active.end())
|
|
Fail(source, 1, "cyclic import");
|
|
if (++loads > kMaxLoads)
|
|
Fail(source, 1, "file load limit exceeded (4096)");
|
|
|
|
std::ifstream input(source, std::ios::binary);
|
|
if (!input)
|
|
Fail(source, 1, "cannot open action file");
|
|
// A bounded read also protects against files that grow after stat().
|
|
std::string contents(kMaxFileBytes + 1, '\0');
|
|
input.read(contents.data(), static_cast<std::streamsize>(contents.size()));
|
|
const auto count = static_cast<std::size_t>(input.gcount());
|
|
if (input.bad() || (input.fail() && !input.eof()))
|
|
Fail(source, 1, "cannot read action file");
|
|
if (count > kMaxFileBytes)
|
|
Fail(source, 1, "action file size limit exceeded (1 MiB)");
|
|
contents.resize(count);
|
|
total_bytes += count;
|
|
if (total_bytes > kMaxTotalBytes)
|
|
Fail(source, 1, "total action input limit exceeded (16 MiB)");
|
|
|
|
active.push_back(source);
|
|
struct PopActive
|
|
{
|
|
std::vector<std::filesystem::path> &paths;
|
|
~PopActive()
|
|
{
|
|
paths.pop_back();
|
|
}
|
|
} pop{active};
|
|
std::string_view remaining(contents);
|
|
if (remaining.starts_with("\xEF\xBB\xBF"))
|
|
remaining.remove_prefix(3);
|
|
bool header_seen = false;
|
|
std::size_t line_number = 0;
|
|
struct OpenLoop
|
|
{
|
|
std::size_t start;
|
|
bool block;
|
|
};
|
|
// Each file must balance its own blocks, including when imported as a single statement.
|
|
std::vector<OpenLoop> loops;
|
|
const auto closeLoop = [&] {
|
|
auto &start = program.commands[loops.back().start];
|
|
start.loopEnd = program.commands.size();
|
|
ActionCommand end{};
|
|
end.kind = ActionKind::LoopEnd;
|
|
end.source = source;
|
|
end.line = line_number;
|
|
Append(std::move(end));
|
|
loops.pop_back();
|
|
};
|
|
while (!remaining.empty())
|
|
{
|
|
++line_number;
|
|
const auto newline = remaining.find('\n');
|
|
auto line = Trim(remaining.substr(0, newline));
|
|
remaining.remove_prefix(newline == std::string_view::npos ? remaining.size() : newline + 1);
|
|
if (line.find('\0') != std::string_view::npos)
|
|
Fail(source, line_number, "NUL bytes are not allowed");
|
|
if (line.starts_with('#'))
|
|
{
|
|
auto comment = Trim(line.substr(1));
|
|
if (comment.starts_with("action:"))
|
|
{
|
|
if (header_seen)
|
|
Fail(source, line_number, "duplicate action header");
|
|
const auto name = Trim(comment.substr(7, comment.find('#', 7) == std::string_view::npos
|
|
? std::string_view::npos
|
|
: comment.find('#', 7) - 7));
|
|
if (!IsSimpleName(name))
|
|
Fail(source, line_number,
|
|
"action name must be a nonempty simple filename without a path or .act suffix");
|
|
if (!expected_name.empty() && name != expected_name)
|
|
Fail(source, line_number,
|
|
"action header name '" + std::string(name) + "' does not match imported name '" +
|
|
std::string(expected_name) + "'");
|
|
if (active.size() == 1)
|
|
program.name = name;
|
|
header_seen = true;
|
|
}
|
|
continue;
|
|
}
|
|
line = Trim(line.substr(0, line.find('#')));
|
|
if (line.empty())
|
|
continue;
|
|
if (!header_seen)
|
|
Fail(source, line_number, "missing action header before first instruction");
|
|
// A single-line body may itself begin with another do. Parse it iteratively.
|
|
std::string expanded;
|
|
for (;;)
|
|
{
|
|
try
|
|
{
|
|
expanded = bindings.Expand(line, kMaxFileBytes);
|
|
}
|
|
catch (const std::runtime_error &error)
|
|
{
|
|
Fail(source, line_number, error.what());
|
|
}
|
|
expandedBytes += expanded.size();
|
|
if (expandedBytes > kMaxTotalBytes)
|
|
Fail(source, line_number, "total expanded action text exceeds 16 MiB");
|
|
line = expanded;
|
|
const auto verb = TakeToken(line);
|
|
line = Trim(line);
|
|
if (verb == "do")
|
|
{
|
|
ActionCommand start{};
|
|
start.kind = ActionKind::LoopBegin;
|
|
start.source = source;
|
|
start.line = line_number;
|
|
const auto count = TakeToken(line);
|
|
if (count != "always")
|
|
{
|
|
std::uint64_t repetitions = 0;
|
|
const auto parsed = std::from_chars(count.data(), count.data() + count.size(), repetitions);
|
|
if (count.empty() || parsed.ec != std::errc{} || parsed.ptr != count.data() + count.size())
|
|
Fail(source, line_number, "do requires a nonnegative integer or always");
|
|
start.repetitions = repetitions;
|
|
}
|
|
loops.push_back({program.commands.size(), false});
|
|
Append(std::move(start));
|
|
line = Trim(line);
|
|
if (line.empty()) break;
|
|
continue;
|
|
}
|
|
if (verb == "begin")
|
|
{
|
|
if (loops.empty() || loops.back().block || !line.empty())
|
|
Fail(source, line_number, "expected begin only after do <count>");
|
|
loops.back().block = true;
|
|
break;
|
|
}
|
|
if (verb == "end")
|
|
{
|
|
if (loops.empty() || !loops.back().block || !line.empty())
|
|
Fail(source, line_number, "end requires a matching do block with a complete body");
|
|
closeLoop();
|
|
}
|
|
else if (!verb.empty()) // alias and define were processed while expanding.
|
|
LoadInstruction(verb, line, source, line_number);
|
|
|
|
// A complete statement also completes enclosing unbracketed loops.
|
|
while (!loops.empty() && !loops.back().block)
|
|
closeLoop();
|
|
break;
|
|
}
|
|
}
|
|
if (!loops.empty())
|
|
Fail(source, program.commands[loops.back().start].line,
|
|
loops.back().block ? "missing end for do block" : "missing statement after do");
|
|
if (!header_seen)
|
|
Fail(source, line_number == 0 ? 1 : line_number, "missing action header");
|
|
}
|
|
};
|
|
} // namespace
|
|
|
|
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);
|
|
}
|
|
|
|
std::optional<ActionCommand> ParseInteractiveCommand(std::string_view text)
|
|
{
|
|
const std::filesystem::path source{"<console>"};
|
|
// Validate the entire input, even comments and text that would be trimmed.
|
|
if (text.find('\0') != std::string_view::npos)
|
|
Fail(source, 1, "NUL bytes are not allowed");
|
|
if (text.find_first_of("\r\n") != std::string_view::npos)
|
|
Fail(source, 1, "console input must contain exactly one line (no CR or LF)");
|
|
text = Trim(text.substr(0, text.find('#')));
|
|
if (text.empty())
|
|
return std::nullopt;
|
|
const auto verb = TakeToken(text);
|
|
if (verb == "wait" || verb == "import" || verb == "do" || verb == "begin" || verb == "end")
|
|
Fail(source, 1, std::string(verb) + " is only available in action files; use run file.act");
|
|
return ParseCommand(verb, text, source, 1);
|
|
}
|
|
} // namespace Bilicraft
|