2022-11-04 09:38:01 -07:00
|
|
|
#include <intcode/Interpreter.hpp>
|
2022-11-03 08:15:17 -07:00
|
|
|
|
2022-11-03 12:53:10 -07:00
|
|
|
namespace intcode {
|
|
|
|
|
2022-11-03 14:43:47 -07:00
|
|
|
BadInstruction::BadInstruction(char const* what)
|
|
|
|
: std::runtime_error{what} {}
|
2022-11-03 12:53:10 -07:00
|
|
|
|
2022-11-04 08:29:02 -07:00
|
|
|
auto Step(Machine & m) -> std::variant<Input, Output, Halt> {
|
2022-11-03 12:53:10 -07:00
|
|
|
for (;;) {
|
2022-11-04 08:29:02 -07:00
|
|
|
auto instruction = m.Next();
|
|
|
|
auto modes = instruction / 10;
|
|
|
|
|
|
|
|
auto arg = [&]() -> ValueType & {
|
|
|
|
auto &v = m.Next();
|
|
|
|
switch ((modes /= 10) % 10) {
|
|
|
|
case 0:
|
|
|
|
return m.At(v);
|
|
|
|
case 1:
|
|
|
|
return v;
|
|
|
|
case 2:
|
|
|
|
return m.Rel(v);
|
|
|
|
default:
|
|
|
|
throw BadInstruction{"invalid addressing mode"};
|
|
|
|
}
|
|
|
|
};
|
2022-11-03 12:53:10 -07:00
|
|
|
|
|
|
|
switch (instruction % 100) {
|
2022-11-04 08:29:02 -07:00
|
|
|
case 1: {
|
2022-11-04 21:27:08 -07:00
|
|
|
arg() = arg() + arg();
|
2022-11-03 12:53:10 -07:00
|
|
|
break;
|
2022-11-04 08:29:02 -07:00
|
|
|
}
|
2022-11-03 12:53:10 -07:00
|
|
|
|
2022-11-04 08:29:02 -07:00
|
|
|
case 2: {
|
2022-11-04 21:27:08 -07:00
|
|
|
arg() = arg() * arg();
|
2022-11-03 12:53:10 -07:00
|
|
|
break;
|
2022-11-04 08:29:02 -07:00
|
|
|
}
|
2022-11-03 12:53:10 -07:00
|
|
|
|
|
|
|
case 3: {
|
2022-11-04 08:29:02 -07:00
|
|
|
return Input{arg()};
|
2022-11-03 12:53:10 -07:00
|
|
|
}
|
|
|
|
|
|
|
|
case 4: {
|
2022-11-04 08:29:02 -07:00
|
|
|
return Output{arg()};
|
2022-11-03 12:53:10 -07:00
|
|
|
}
|
|
|
|
|
2022-11-04 08:29:02 -07:00
|
|
|
case 5: {
|
|
|
|
auto a = arg();
|
|
|
|
auto b = arg();
|
|
|
|
if (a) { m.Goto(b); }
|
2022-11-03 12:53:10 -07:00
|
|
|
break;
|
2022-11-04 08:29:02 -07:00
|
|
|
}
|
2022-11-03 12:53:10 -07:00
|
|
|
|
2022-11-04 08:29:02 -07:00
|
|
|
case 6: {
|
|
|
|
auto a = arg();
|
|
|
|
auto b = arg();
|
|
|
|
if (!a) { m.Goto(b); }
|
2022-11-03 12:53:10 -07:00
|
|
|
break;
|
2022-11-04 08:29:02 -07:00
|
|
|
}
|
2022-11-03 12:53:10 -07:00
|
|
|
|
2022-11-04 08:29:02 -07:00
|
|
|
case 7: {
|
|
|
|
auto a = arg();
|
|
|
|
auto b = arg();
|
2022-11-04 21:27:08 -07:00
|
|
|
arg() = a < b; // order matters
|
2022-11-03 12:53:10 -07:00
|
|
|
break;
|
2022-11-04 08:29:02 -07:00
|
|
|
}
|
2022-11-03 12:53:10 -07:00
|
|
|
|
2022-11-04 08:29:02 -07:00
|
|
|
case 8: {
|
2022-11-04 21:27:08 -07:00
|
|
|
arg() = arg() == arg();
|
2022-11-03 12:53:10 -07:00
|
|
|
break;
|
2022-11-04 08:29:02 -07:00
|
|
|
}
|
2022-11-03 12:53:10 -07:00
|
|
|
|
|
|
|
case 9:
|
2022-11-04 08:29:02 -07:00
|
|
|
m.Rebase(arg());
|
2022-11-03 12:53:10 -07:00
|
|
|
break;
|
|
|
|
|
|
|
|
case 99:
|
|
|
|
return Halt{};
|
|
|
|
|
|
|
|
default:
|
2022-11-03 14:43:47 -07:00
|
|
|
throw BadInstruction{"invalid opcode"};
|
2022-11-03 12:53:10 -07:00
|
|
|
}
|
|
|
|
}
|
|
|
|
}
|
|
|
|
|
2022-11-04 09:38:01 -07:00
|
|
|
} // namespace
|