Computer.js 21 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570
  1. const prompt = require("prompt-sync")({ sigint: true });
  2. const util = require("util");
  3. const uuid = require("uuid");
  4. const Stack = require("./Stack");
  5. const ComputerParameterMode = require("./ComputerParameterMode");
  6. const InputModes = require("./InputModes");
  7. const { DeepClone } = require("./common");
  8. module.exports = class Computer {
  9. /**
  10. * An Intcode Computer for the Advent of Code 2019 challenge
  11. *
  12. * @author Apis Necros
  13. *
  14. * @param {number[]} stack The initial memory to load into the computer
  15. * @param {Object} options Options that can be enabled within the computer
  16. * @param {object} options.debug A set of debugging options
  17. * @param {number} options.debug.tickRate The number of milliseconds between calls to Execute. Initializes to 0.
  18. * @param {boolean} options.debug.followPointer When true, the memory will be dumped during every call to Execute with the current instruction highlighted
  19. * @param {boolean} options.debug.followRuntimeInput When true, the runtime input array will be dumped during every call to Execute
  20. * @param {boolean} options.debug.followOutputValues When true, the output values array will be dumped during every call to Execute
  21. * @param {boolean} options.debug.followRelativeBaseOffset When true, the stack's relative base offset will be dumped during every call to Execute
  22. * @param {boolean} options.inputFromConsole When true, the computer will prompt for input on the console. If false, it will check for an linked computer and, if one exists, will wait for input from that computer.
  23. * @param {boolean} options.outputToConsole When true, the computer will print the output of opcode 4 to the console. If false, it will check for an linked computer and, if one exists, pass the output to that computer.
  24. * @param {number[]} options.inputModeMap Map calls to the INPUT opcode to user input or the input array
  25. */
  26. constructor(stack, options = {}) {
  27. this.name = uuid.v4();
  28. this._initialMemory = DeepClone(stack);
  29. this.stack = new Stack(stack);
  30. this.OPCODES = {
  31. ADD: 1,
  32. MULTIPLY: 2,
  33. INPUT: 3,
  34. OUTPUT: 4,
  35. JUMP_IF_TRUE: 5,
  36. JUMP_IF_FALSE: 6,
  37. LESS_THAN: 7,
  38. EQUALS: 8,
  39. MODIFY_RELATIVE_BASE: 9,
  40. HALT: 99,
  41. };
  42. this.EQUALITY = {
  43. EQUALS: 0,
  44. LESS_THAN: 1,
  45. };
  46. this.parameterMode = ComputerParameterMode.POSITION_MODE;
  47. /**
  48. * Whether the Execute loop should skip moving the pointer after running the opcode
  49. *
  50. * Some opcodes, such as JUMP_IF_TRUE set the stack pointer, and as such shouldn't have
  51. * the Execute function move it after the opcode finishes executing.
  52. */
  53. this.skipNext = false;
  54. this.options = {
  55. debug: {
  56. followPointer: options?.debug?.followPointer ?? false,
  57. followRuntimeInput: options?.debug?.followRuntimeInput ?? false,
  58. followOutputValues: options?.debug?.followOutputValues ?? false,
  59. followRelativeBaseOffset: options?.debug?.followRelativeBaseOffset ?? false,
  60. tickRate: options?.debug?.tickRate ?? 0,
  61. },
  62. inputFromConsole: options.inputFromConsole ?? false,
  63. outputToConsole: options.outputToConsole ?? false,
  64. inputModeMap: options.inputModeMap ?? [],
  65. _initialInputModeMap: options.inputModeMap ?? [],
  66. };
  67. /**
  68. * A function to pass the value from OUTPUT opcodes to
  69. *
  70. * If the outputToConsole option is false, and a function is provided here,
  71. * any values from an OUTPUT opcode will be passed here.
  72. * @type {?Computer}
  73. */
  74. this.outputComputer = null;
  75. /**
  76. * An array of input values provided at runtime
  77. *
  78. * This value will be passed to the first INPUT opcode made by the computer,
  79. * and will then be cleared. If the program being ran tries to make another
  80. * call to INPUT, and `options.inputFromConsole` is false, then an error
  81. * will be thrown.
  82. * @type {number[]}
  83. */
  84. this.runtimeInput = [];
  85. /**
  86. * An array of outputs from the computer
  87. *
  88. * Outputs from the computer that weren't output to the console, or to a
  89. * callback function.
  90. *
  91. * Ideally, when not in outputToConsole mode, the computer should only ever have
  92. * one output, but I'm not certain that will be the case. In that case, this array
  93. * will have the outputs in chronological order.
  94. * @type {number[]}
  95. */
  96. this.outputValues = [];
  97. /**
  98. * Is the computer currently running
  99. * @type {boolean}
  100. */
  101. this.running = false;
  102. /**
  103. * Is the computer waiting for input
  104. *
  105. * Triggered by the INPUT opcode when the runtimeInputs array is empty
  106. * @type {boolean}
  107. */
  108. this.awaitingInput = false;
  109. }
  110. /**
  111. * Run the computer
  112. *
  113. * Runs opcodes on the stack until either the a HALT command is
  114. * encountered, or an error is thrown.
  115. * @returns {void}
  116. */
  117. async Run() {
  118. while (this.Execute(this.stack.Get(ComputerParameterMode.IMMEDIATE_MODE)) === true) {
  119. if (this.options.debug.tickRate) {
  120. // Sleep
  121. // eslint-disable-next-line no-await-in-loop, no-promise-executor-return, arrow-parens
  122. await new Promise(resolve => setTimeout(resolve, this.options.debug.tickRate));
  123. }
  124. }
  125. }
  126. /**
  127. * Run the computer with an initial input value
  128. *
  129. * Runs opcodes on the stack until either the a HALT command is
  130. * encountered, or an error is thrown. Stores the input to be used
  131. * by the first INPUT opcode encountered.
  132. * @param {number[]} input An array of input values to initialize the comptuer with
  133. * @returns {void}
  134. */
  135. async RunWithInput(input) {
  136. this.runtimeInput = input;
  137. while (this.Execute(this.stack.Get(ComputerParameterMode.IMMEDIATE_MODE)) === true) {
  138. if (this.options.debug.tickRate) {
  139. // Sleep
  140. // eslint-disable-next-line no-await-in-loop, no-promise-executor-return, arrow-parens
  141. await new Promise(resolve => setTimeout(resolve, this.options.debug.tickRate));
  142. }
  143. }
  144. }
  145. /**
  146. * Execute a call using the provided opcode
  147. *
  148. * @param {number} rawOpcode A opcode to execute
  149. * @returns {boolean} False if the opcode was HALT, otherwise true
  150. */
  151. Execute(rawOpcode) {
  152. let status = true;
  153. this.running = true;
  154. this.skipNext = false;
  155. this.FollowExecution();
  156. const opcode = rawOpcode % 100;
  157. // console.log(`DEBUG: opcode: ${opcode}`);
  158. switch (opcode) {
  159. case this.OPCODES.ADD: {
  160. this.Operation_Add(rawOpcode);
  161. break;
  162. }
  163. case this.OPCODES.MULTIPLY: {
  164. this.Operation_Multiply(rawOpcode);
  165. break;
  166. }
  167. case this.OPCODES.INPUT: {
  168. // If we're awaiting input, and still haven't received any, keep waiting
  169. if (this.awaitingInput == true && this.runtimeInput.length == 0) {
  170. this.skipNext = true;
  171. status = false;
  172. break;
  173. }
  174. this.Operation_Input(rawOpcode);
  175. break;
  176. }
  177. case this.OPCODES.OUTPUT: {
  178. this.Operation_Output(rawOpcode);
  179. break;
  180. }
  181. case this.OPCODES.JUMP_IF_TRUE: {
  182. this.Operation_JumpIf(rawOpcode, true);
  183. break;
  184. }
  185. case this.OPCODES.JUMP_IF_FALSE: {
  186. this.Operation_JumpIf(rawOpcode, false);
  187. break;
  188. }
  189. case this.OPCODES.LESS_THAN: {
  190. this.Operation_Equality(rawOpcode, this.EQUALITY.LESS_THAN);
  191. break;
  192. }
  193. case this.OPCODES.EQUALS: {
  194. this.Operation_Equality(rawOpcode, this.EQUALITY.EQUALS);
  195. break;
  196. }
  197. case this.OPCODES.HALT:
  198. this.running = false;
  199. status = false;
  200. break;
  201. case this.OPCODES.MODIFY_RELATIVE_BASE: {
  202. this.Operation_ModifyRelativeBase(rawOpcode);
  203. break;
  204. }
  205. default:
  206. this.ThrowError(`Opcode ${opcode} not found`);
  207. }
  208. if (!this.skipNext) {
  209. this.stack.Next();
  210. }
  211. return status;
  212. }
  213. /**
  214. * Parse operands based on the current parameter mode
  215. *
  216. * When the int computer is in Immediate Mode, the values are returned
  217. * as-is. When in Position Mode, the operands are used as memory
  218. * addresses, and the values at those addresses are returned instead.
  219. *
  220. * @private
  221. * @returns {number[]} The parsed list of operands
  222. */
  223. _ParseOperands(...operands) {
  224. if (this.parameterMode == ComputerParameterMode.IMMEDIATE_MODE) { return operands; }
  225. return operands.map((operand) => this.stack.Get(operand));
  226. }
  227. /**
  228. * Execute the Add opcode
  229. *
  230. * Adds two numbers and stores the result at the provided position
  231. * on the stack.
  232. *
  233. * Parses the operand Parameter Mode out of the opcode used to make
  234. * this call.
  235. *
  236. * @param {number} rawOpcode The opcode in memory used to make this call
  237. * @private
  238. * @returns {void}
  239. */
  240. Operation_Add(rawOpcode) {
  241. const operandLeftMode = ComputerParameterMode.ParseParameterMode(rawOpcode, 1);
  242. const operandRightMode = ComputerParameterMode.ParseParameterMode(rawOpcode, 2);
  243. const operandLeft = this.stack.Next().Get(operandLeftMode);
  244. const operandRight = this.stack.Next().Get(operandRightMode);
  245. const outputPosition = this.stack.Next().Get(ComputerParameterMode.IMMEDIATE_MODE);
  246. const newValue = operandLeft + operandRight;
  247. this.stack.Put(outputPosition, newValue);
  248. }
  249. /**
  250. * Execute the Multiply opcode
  251. *
  252. * Multiplies two numbers and stores the result at the provided
  253. * position on the stack.
  254. *
  255. * @param {number} rawOpcode The opcode in memory used to make this call
  256. * @private
  257. * @returns {void}
  258. */
  259. Operation_Multiply(rawOpcode) {
  260. const operandLeftMode = ComputerParameterMode.ParseParameterMode(rawOpcode, 1);
  261. const operandRightMode = ComputerParameterMode.ParseParameterMode(rawOpcode, 2);
  262. const operandLeft = this.stack.Next().Get(operandLeftMode);
  263. const operandRight = this.stack.Next().Get(operandRightMode);
  264. const outputPosition = this.stack.Next().Get(ComputerParameterMode.IMMEDIATE_MODE);
  265. const newValue = operandLeft * operandRight;
  266. this.stack.Put(outputPosition, newValue);
  267. }
  268. /**
  269. * Execute the Input opcode
  270. *
  271. * Checks to see if the computer's `runtimeInput` is set. If so, uses that
  272. * value as the input, and stores that at a specified address, and then
  273. * empties the `runtimeInput` value. If `runtimeInput` is empty, and if
  274. * the computer is set to accept input from the console, prompts the
  275. * user for input.
  276. *
  277. * @private
  278. * @param {number} rawOpcode The opcode in memory used to make this call
  279. * @returns {void}
  280. */
  281. Operation_Input(rawOpcode) {
  282. // Disallow Position Parameter Mode
  283. const outputParamMode = ComputerParameterMode.ParseParameterMode(rawOpcode, 1) || 1;
  284. const outputPosition = this.stack.Next().Get(outputParamMode);
  285. /** A variable to store the input in before putting it on the stack */
  286. let userInput;
  287. /** The input mode to use to get the value */
  288. let inputMode = this.options.inputModeMap.shift();
  289. // If no input mode was found, attempt to set on using the runtime options
  290. if (inputMode === undefined) {
  291. if (this.options.inputFromConsole) { inputMode = InputModes.INPUT_FROM_CONSOLE; }
  292. else { inputMode = InputModes.INPUT_FROM_RUNTIME_STACK; }
  293. }
  294. // Get the input based on the input mode
  295. switch (inputMode) {
  296. case InputModes.INPUT_FROM_RUNTIME_STACK: {
  297. userInput = this.runtimeInput.shift();
  298. // If no input was found, await input
  299. if (userInput === undefined) {
  300. // Set the stack back to the INPUT opcode
  301. this.stack.Prev();
  302. this.stack.Prev();
  303. // Set the awaitingInput flag
  304. this.awaitingInput = true;
  305. // Exit the function
  306. return;
  307. }
  308. this.awaitingInput = false;
  309. break;
  310. }
  311. case InputModes.INPUT_FROM_CONSOLE: {
  312. do {
  313. userInput = Number(prompt("Please enter a number: "));
  314. } while (Number.isNaN(userInput));
  315. break;
  316. }
  317. default:
  318. this.ThrowError("No input found");
  319. }
  320. // Put the input value onto the stack
  321. this.stack.Put(outputPosition, userInput);
  322. }
  323. /**
  324. * Execute the OUTPUT opcode
  325. *
  326. * @param {number} rawOpcode The opcode in memory used to make this call
  327. * @private
  328. * @returns {void}
  329. */
  330. Operation_Output(rawOpcode) {
  331. const currAddress = this.options.outputToConsole ? this.stack.pointer : undefined;
  332. const outputPositionMode = ComputerParameterMode.ParseParameterMode(rawOpcode, 1);
  333. const output = this.stack.Next().Get(outputPositionMode);
  334. if (this.options.outputToConsole) {
  335. console.log(`OUTPUT FROM ADDRESS ${currAddress}: ${output}`);
  336. }
  337. else if (this.outputComputer !== null) {
  338. this.outputComputer.Input(output);
  339. }
  340. else {
  341. this.outputValues.push(output);
  342. }
  343. }
  344. /**
  345. * Execute the Jump_If_True and Jump_If_False opcodes
  346. *
  347. * Jumps to a given address in memory if the value at next address is memory matches
  348. * the given true/false condition.
  349. *
  350. * @param {number} rawOpcode The opcode in memory used to make this call
  351. * @param {boolean} testCondition The value the memory value should be compared against
  352. * @private
  353. * @returns {void}
  354. */
  355. Operation_JumpIf(rawOpcode, testCondition) {
  356. const paramMode = ComputerParameterMode.ParseParameterMode(rawOpcode, 1);
  357. const jumpAddressMode = ComputerParameterMode.ParseParameterMode(rawOpcode, 2);
  358. const param = this.stack.Next().Get(paramMode);
  359. const jumpAddress = this.stack.Next().Get(jumpAddressMode);
  360. const performJump = !!param == testCondition;
  361. if (performJump) {
  362. this.skipNext = true;
  363. this.stack.SetPointerAddress(jumpAddress);
  364. }
  365. }
  366. /**
  367. * Execute the various equality checking opcodes
  368. *
  369. * @param {number} rawOpcode The opcode in memory used to make this call
  370. * @param {number} testCondition The type of equality check to perform as defined in the computer's constructor
  371. * @private
  372. * @returns {void}
  373. */
  374. Operation_Equality(rawOpcode, testCondition) {
  375. const operandLeftMode = ComputerParameterMode.ParseParameterMode(rawOpcode, 1);
  376. const operandRightMode = ComputerParameterMode.ParseParameterMode(rawOpcode, 2);
  377. const operandLeft = this.stack.Next().Get(operandLeftMode);
  378. const operandRight = this.stack.Next().Get(operandRightMode);
  379. const outputPosition = this.stack.Next().Get(ComputerParameterMode.IMMEDIATE_MODE);
  380. let testPassed = false;
  381. switch (testCondition) {
  382. case this.EQUALITY.EQUALS:
  383. testPassed = operandLeft == operandRight;
  384. break;
  385. case this.EQUALITY.LESS_THAN:
  386. testPassed = operandLeft < operandRight;
  387. break;
  388. default:
  389. break;
  390. }
  391. this.stack.Put(outputPosition, Number(testPassed));
  392. }
  393. /**
  394. * Adjusts the current relative base offset of the computer
  395. *
  396. * @param {number} rawOpcode The opcode in memory used to make this call
  397. * @returns {void}
  398. */
  399. Operation_ModifyRelativeBase(rawOpcode) {
  400. const operandMode = ComputerParameterMode.ParseParameterMode(rawOpcode, 1);
  401. const adjustmentValue = this.stack.Next().Get(operandMode);
  402. this.stack.AdjustRelativeBaseOffset(adjustmentValue);
  403. }
  404. /**
  405. * Inspects various parts of the computer before every call to Execution
  406. *
  407. * Based on the debug options set at runtime, may output any combination of the
  408. * computer's core memory, the runtime input stack, and or the output values
  409. * array.
  410. *
  411. * @returns {void}
  412. */
  413. FollowExecution() {
  414. if (this.options.debug.followPointer) { this.DumpMemory(true); }
  415. if (this.options.debug.followRuntimeInput) { this.InspectProperty("Inputs", "runtimeInput"); }
  416. if (this.options.debug.followOutputValues) { this.InspectProperty("Outputs", "outputValues"); }
  417. if (this.options.debug.followRelativeBaseOffset) { this.InspectProperty("Relative Base Offset", null, this.stack.relativeBaseOffset); }
  418. }
  419. /**
  420. * Outputs the computer's stack to the console
  421. *
  422. * @param {boolean} [highlightPointer=false] Should the memory address of the current pointer be highlighted
  423. * @returns {void}
  424. */
  425. DumpMemory(highlightPointer = false) {
  426. let memory = this.stack.Dump();
  427. if (highlightPointer) {
  428. memory = memory.map((instruction, idx) => (idx == this.stack.pointer ? `{${instruction}}` : instruction));
  429. }
  430. this.InspectProperty("Memory", null, memory);
  431. }
  432. /**
  433. * Inspect a property of this object in the console
  434. *
  435. * @param {string} [outputMessage] An optional message to prepend the inspection with
  436. * @param {?string} [propertyName] The name of the Computer class property to inspect
  437. * @param {?unknown} [overrideValue] If provided, this value is inspected as-is instead of the class property
  438. * @returns {void}
  439. */
  440. InspectProperty(outputMessage = "", propertyName = null, overrideValue = null) {
  441. let toInspect;
  442. if (overrideValue !== null) {
  443. toInspect = overrideValue;
  444. }
  445. else if (this[propertyName] !== undefined) {
  446. toInspect = this[propertyName];
  447. }
  448. console.log(this.name, outputMessage, util.inspect(toInspect, { breakLength: Infinity, colors: true, compact: true }));
  449. }
  450. /**
  451. * Check if the computer has any values in the output array
  452. *
  453. * @returns {boolean} True or false if there are any values in the output array
  454. */
  455. HasOutput() {
  456. return !!this.outputValues.length;
  457. }
  458. /**
  459. * Get a value from the unhandled OUTPUT values in FIFO order
  460. *
  461. * @returns {number|undefined} An unhandled value from an output call, or undefined if the array is empty
  462. */
  463. FetchOutputValue() {
  464. return this.HasOutput() ? this.outputValues.shift() : undefined;
  465. }
  466. /**
  467. * Accept input from an external source
  468. *
  469. * The input given here is pushed onto the end of the computer's runtime
  470. * input array.
  471. *
  472. * @param {number} inputValue The number to push onto the runtime input array
  473. * @returns {void}
  474. */
  475. Input(inputValue) {
  476. this.runtimeInput.push(inputValue);
  477. if (this.running && this.awaitingInput) { this.Run(); }
  478. }
  479. /**
  480. * Resets the computer's memory to the value it was created with
  481. *
  482. * @returns {void}
  483. */
  484. Reset() {
  485. this.stack = new Stack(DeepClone(this._initialMemory));
  486. this.outputValues = [];
  487. this.options.inputModeMap = DeepClone(this.options._initialInputModeMap);
  488. this.running = false;
  489. this.awaitingInput = false;
  490. }
  491. /**
  492. * Sets the computer's memory to a new stack
  493. *
  494. * Note: This resets the computer's initial memory, so `Reset` will use this value
  495. *
  496. * @param {number[]} stack The new memory stack for the computer
  497. * @returns {void}
  498. */
  499. SetMemory(stack) {
  500. this._initialMemory = DeepClone(stack);
  501. this.stack = new Stack(stack);
  502. }
  503. /**
  504. * Throws an error with the given message and a memory dump
  505. *
  506. * @param {string} [msg] The error message to display to the user
  507. * @returns {void}
  508. */
  509. ThrowError(msg = "") {
  510. throw new Error(`** IntCode Computer Error **\nError Message: ${msg}\nMemdump: ${JSON.stringify(this.stack.Dump())}\nPointer: ${this.stack.pointer}`);
  511. }
  512. };