Computer.js 20 KB

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