All files / simulator/src/utils functions.ts

67.88% Statements 186/274
58.26% Branches 67/115
79.54% Functions 35/44
69.14% Lines 177/256

Press n or j to go to the next uncovered block, b, p or k for the previous block.

1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98 99 100 101 102 103 104 105 106 107 108 109 110 111 112 113 114 115 116 117 118 119 120 121 122 123 124 125 126 127 128 129 130 131 132 133 134 135 136 137 138 139 140 141 142 143 144 145 146 147 148 149 150 151 152 153 154 155 156 157 158 159 160 161 162 163 164 165 166 167 168 169 170 171 172 173 174 175 176 177 178 179 180 181 182 183 184 185 186 187 188 189 190 191 192 193 194 195 196 197 198 199 200 201 202 203 204 205 206 207 208 209 210 211 212 213 214 215 216 217 218 219 220 221 222 223 224 225 226 227 228 229 230 231 232 233 234 235 236 237 238 239 240 241 242 243 244 245 246 247 248 249 250 251 252 253 254 255 256 257 258 259 260 261 262 263 264 265 266 267 268 269 270 271 272 273 274 275 276 277 278 279 280 281 282 283 284 285 286 287 288 289 290 291 292 293 294 295 296 297 298 299 300 301 302 303 304 305 306 307 308 309 310 311 312 313 314 315 316 317 318 319 320 321 322 323 324 325 326 327 328 329 330 331 332 333 334 335 336 337 338 339 340 341 342 343 344 345 346 347 348 349 350 351 352 353 354 355 356 357 358 359 360 361 362 363 364 365 366 367 368 369 370 371 372 373 374 375 376 377 378 379 380 381 382 383 384 385 386 387 388 389 390 391 392 393 394 395 396 397 398 399 400 401 402 403 404 405 406 407 408 409 410 411 412 413 414 415 416 417 418 419 420 421 422 423 424 425 426 427 428 429 430 431 432 433 434 435 436 437 438 439 440 441 442 443 444 445 446 447 448 449 450 451 452 453 454 455 456 457 458 459 460 461 462 463 464 465 466 467 468 469 470 471 472 473 474 475 476 477 478 479 480 481 482 483 484 485 486 487 488 489 490 491 492 493 494 495 496 497 498 499 500 501 502 503 504 505 506 507 508 509 510 511 512 513 514 515 516 517 518 519 520 521 522 523 524 525 526 527 528 529 530 531 532 533 534 535 536 537 538 539 540 541 542 543 544 545 546 547 548 549 550 551 552 553 554 555 556 557 558 559 560 561 562 563 564 565 566 567 568 569 570 571 572 573 574 575 576 577 578 579 580 581 582 583 584 585 586 587 588 589 590 591 592 593 594 595 596 597 598 599 600 601 602 603 604 605 606 607 608 609 610 611 612 613 614 615 616 617 618 619 620 621 622 623 624 625 626 627 628 629 630 631 632 633 634 635 636 637 638 639 640 641 642 643 644 645 646 647 648 649 650 651 652 653 654 655 656 657 658 659 660 661 662 663 664 665 666 667 668 669 670 671 672 673 674 675 676 677 678 679 680 681 682 683 684 685 686 687 688 689 690 691 692 693 694 695 696 697 698 699 700 701 702 703 704 705 706 707 708 709 710 711 712 713 714 715 716 717 718 719 720 721 722 723 724 725 726 727 728 729 730 731 732 733 734                                                                                                                      132x   132x     132x 45x 45x 45x 45x 45x       87x 6x         81x 81x 81x     132x 132x         19x 19x                                                                                                                                                     958x 934x   24x 24x                   1145578x       123x 123x                   29x 29x                     29x                               15x 15x           15x 15x   15x   15x 15x                                                                                                                       1073779x 1073779x               121420x 121420x   1287229x   1073779x 1073779x     121420x     30355x   111723x   30355x 30355x 30355x 30355x   30355x                           14x 14x           14x 14x   14x   14x 14x                                                                                                                                       8x 8x   8x 215x 215x   215x 8x 8x 207x 22x 22x 22x 22x 185x 8x 8x   177x 177x 185x 185x   177x     215x   215x 223x 223x         223x     215x             8x                         757x                 72143x 145231x       72143x   72143x       72143x                     234x 702x       234x   234x 234x 234x 234x     234x 234x 191x     43x                       3x 9x       3x   3x 3x     3x 3x 3x                         7x 22020096x                     7x 132x 132x 132x 132x 132x 132x 132x 132x 132x                 30334x                       7x 7x   7x 7x 7x                           7x 7x   7x 7x     7x 7x 7x   7x 7x                         30334x 30334x       30348x 30348x 20346x 20346x 20346x 20346x 20346x     30348x 304x 304x 304x 304x 304x     30348x               20650x 20650x 72033x   20650x 20650x               30348x 30348x 30348x 30348x   30348x 971136x     30348x 30348x               7x 7x       7x   7x 30338x 4x 4x   30334x 30334x 30334x 30334x   7x    
import * as path from 'path';
import * as fs from 'fs';
import {exit} from 'process';
 
import {
  process_instruction,
  setFUNC,
  setIMM,
  setOPCODE,
  setRD,
  setRS,
  setRT,
  setSHAMT,
  setTARGET,
} from '@simulator/run';
 
import {
  bcolors,
  currentState,
  DEBUG,
  DEBUG_SET,
  INST_INFO,
  instAddOne,
  instruction,
  Iinstruction,
  memData,
  memStack,
  memRegions,
  MIPS_REGS,
  MEM_GROW_UP,
  MEM_DUMP_SET,
  MEM_NREGIONS,
  MEM_DATA_START,
  MEM_TEXT_START,
  pType,
  RUN_BIT,
  SYMBOL_TABLE,
  SymbolTableType,
} from '@utils/constants';
 
export interface simulatorOutputType {
  readonly PC: string;
  readonly registers: {[key: string]: string};
  readonly dataSection: {[key: string]: string} | Record<string, never>;
  readonly stackSection: {[key: string]: string} | Record<string, never>;
}
 
export interface IBinaryData {
  readonly lineNumber: number;
  readonly data: string;
}
 
export interface IMapDetail {
  readonly key: number;
  readonly assembly: string;
  readonly binary: IBinaryData[];
}
 
export function parseInstr(buffer: string, index: number): instruction {
  const instr: instruction = new instruction();
 
  setOPCODE(instr, fromBinary(buffer.slice(0, 6)));
 
  // R type
  if (instr.opcode === 0x0) {
    setRS(instr, fromBinary(buffer.slice(6, 11)));
    setRT(instr, fromBinary(buffer.slice(11, 16)));
    setRD(instr, fromBinary(buffer.slice(16, 21)));
    setSHAMT(instr, fromBinary(buffer.slice(21, 26)));
    setFUNC(instr, fromBinary(buffer.slice(26, 32)));
  }
 
  // J type
  else if (instr.opcode === 0x2 || instr.opcode === 0x3) {
    setTARGET(instr, fromBinary(buffer.slice(6, 32)));
  }
 
  // I type
  else {
    setRS(instr, fromBinary(buffer.slice(6, 11)));
    setRT(instr, fromBinary(buffer.slice(11, 16)));
    setIMM(instr, fromBinary(buffer.slice(16, 32)));
  }
 
  memWrite(MEM_TEXT_START + index, fromBinary(buffer));
  return instr;
}
 
export function parseData(buffer: string, index: number) {
  //[TODO] Implement this function
  memWrite(MEM_DATA_START + index, fromBinary(buffer));
  return;
}
 
export function printParseResult(
  INST_INFO: Iinstruction[],
  textSize: number,
  dataSize: number,
) {
  console.log('Instruction Information');
  /*
    TYPE I
    0x8: (0x001000)ADDI
    0x9: (0x001001)ADDIU
    0xc: (0x001100)ANDI
    0x4: (0x000100)BEQ
    0x5: (0x000101)BNE
    0x25: (0x011001)LHU
    0xf: (0x001111)LUI
    0x23: (0x100011)LW
    0xd: (0x001101)ORI
    0xa: (0x001010)SLTI
    0xb: (0x001011)SLTIU
    0x29: (0x011101)SH
    0x2b: (0x101011)SW
 
    TYPE R
    0x0: (0x000000)ADD, ADDU, AND, NOR, OR, SLT, SLTU, SLL, SRL, SUB, SUBU  if JR
 
    TYPE J
    0x2: (0x000010)J
    0x3: (0x000011)JAL
    */
 
  const TypeIList = [
    0x8, 0x9, 0xc, 0x4, 0x5, 0x25, 0xf, 0x23, 0xd, 0xa, 0xb, 0x29, 0x2b,
  ];
  const TypeRList = [0x0];
  const TypeJList = [0x2, 0x3];
 
  for (let i = 0; i < textSize / 4; i++) {
    console.log(`INST_INFO[${i}].value : 0x${INST_INFO[i].value.toString(16)}`);
    console.log(`INST_INFO[${i}].opcode : ${INST_INFO[i].opcode}`);
 
    if (INST_INFO[i].opcode in TypeIList) {
      console.log(`INST_INFO[${i}].rs : ${INST_INFO[i].rs}`);
      console.log(`INST_INFO[${i}].rt : ${INST_INFO[i].rt}`);
      console.log(`INST_INFO[${i}].imm : ${INST_INFO[i].imm}`);
    } else if (INST_INFO[i].opcode in TypeRList) {
      console.log(`INST_INFO[${i}].funcCode : ${INST_INFO[i].funcCode}`);
      console.log(`INST_INFO[${i}].rs : ${INST_INFO[i].rs}`);
      console.log(`INST_INFO[${i}].rt : ${INST_INFO[i].rt}`);
      console.log(`INST_INFO[${i}].rd : ${INST_INFO[i].rd}`);
      console.log(`INST_INFO[${i}].shamt : ${INST_INFO[i].shamt}`);
    } else if (INST_INFO[i].opcode in TypeJList) {
      console.log(`INST_INFO[${i}].target : ${INST_INFO[i].target}`);
    } else {
      console.log('Not available instrution\n');
    }
  }
  console.log('Memory Dump - Text Segment\n');
  for (let i = 0; i < textSize; i += 4) {
    console.log(
      `text_seg[${i}] : 0x${memRead(MEM_TEXT_START + i).toString(16)}`,
    );
  }
  for (let i = 0; i < dataSize; i += 4) {
    console.log(
      `text_seg[${i}] : 0x${memRead(MEM_DATA_START + i).toString(16)}`,
    );
  }
  console.log(`Current PC: ${currentState.PC.toString(16)}`);
}
 
export function numToBits(num: number, pad = 32): string {
  // 10진수 정수를 2진수 bit로 변경해서 return
  if (num >= 0) {
    return num.toString(2).padStart(pad, '0'); //양수일때
  } else {
    num = 2 ** pad + num;
    return num.toString(2).padStart(pad, '0'); //음수일때;
  }
}
 
export function toHexAndPad(num: number, pad = 8): string {
  /*
   * num : Number or String(숫자 형식, 10진법), pad : Number
   * input : 18 => output: '00000012'
   * Recommend | num을 Number 타입으로 넣을 것
   */
  return Number(num).toString(16).padStart(pad, '0');
}
 
export function symbolTableAddEntry(symbol: SymbolTableType) {
  SYMBOL_TABLE[symbol.name] = symbol.address;
  Iif (DEBUG) {
    log(1, `${symbol.name}: 0x${toHexAndPad(symbol.address)}`);
  }
}
 
export function log(printType: number, content: string) {
  console.log(pType[printType] + content);
}
 
export function isEmpty(value: string | null | undefined | object) {
  const emptyArray: string[] = [''];
  Iif (
    value === '' ||
    value === null ||
    value === undefined ||
    (value !== null &&
      typeof value === 'object' &&
      !Object.keys(value).length) ||
    value === emptyArray
  ) {
    return true;
  } else {
    return false;
  }
}
 
// Parsing an assembly file(*.s) into a list
export function makeInput(
  inputFolderName: string,
  inputFileName: string,
): string[] {
  /*
   if the inputFilePath is /Users/junghaejune/simulator/sample_input/sample/example1.s,
    currDirectory : /Users/junghaejune/simulator
    inputFolderPath : sample_input/sample
    inputFileName: example1.s
  */
 
  const currDirectory: string = process.cwd();
  const inputFilePath: string = path.join(
    currDirectory,
    inputFolderName,
    inputFileName,
  );
 
  try {
    Iif (fs.existsSync(inputFilePath) === false) throw 'INPUT_PATH_ERROR';
 
    const input: string = fs.readFileSync(inputFilePath, 'utf-8');
 
    Iif (isEmpty(input)) throw 'INPUT_EMPTY';
    return input.split('\n');
  } catch (err) {
    if (err === 'INPUT_PATH_ERROR') {
      log(
        3,
        `No input file ${inputFileName} exists. Please check the file name and path.`,
      );
    } else if (err === 'INPUT_EMPTY') {
      log(
        3,
        `input file ${inputFileName} is not opened. Please check the file`,
      );
    } else console.error(err);
    exit(1);
  }
}
 
export function simulatorUnitTest(
  testCase: simulatorOutputType,
  output: simulatorOutputType,
) {
  function printResult(
    origin: {[key: string]: string} | Record<string, never>,
    compare: {[key: string]: string} | Record<string, never>,
  ) {
    Object.keys(origin).map(key => {
      if (compare[key]) {
        const color =
          origin[key] === compare[key] ? bcolors.GREEN : bcolors.RED;
        console.log(
          `${color}${key} : ${origin[key]}          ${key} : ${compare[key]}${bcolors.ENDC}`,
        );
      } else {
        console.log(`${bcolors.RED}${key} : ${origin[key]}${bcolors.ENDC}`);
      }
    });
  }
 
  type keyType = 'registers' | 'dataSection' | 'stackSection';
  const keyList: keyType[] = ['registers', 'dataSection', 'stackSection'];
 
  console.log(`---------------PC---------------`);
  console.log(
    `${testCase.PC === output.PC ? bcolors.GREEN : bcolors.RED}PC : ${
      testCase.PC
    }          PC : ${output.PC}${bcolors.ENDC}\n`,
  );
 
  keyList.map(key => {
    console.log(`---------------${key}---------------`);
    printResult(testCase[key], output[key]);
    console.log('\n');
  });
}
 
export function parseSimulatorOutput(rawOutput: string): simulatorOutputType {
  //input : test simulator input
  //ouput : object type -> { register : {PC:, R0:,...}, dataSection:{}, stackSection{}}
 
  function splitHelper(input: string): [string, string] {
    const returnValue = input.split(/:|\n/);
    return returnValue.length === 2
      ? [returnValue[0], returnValue[1].trim()]
      : null;
  }
 
  function setTypeParser(
    input: string,
  ): {[key: string]: string} | Record<string, never> {
    const returnSet = {};
    input
      .split(/\n/)
      .filter(e => e !== '')
      .map(element => {
        const result = splitHelper(element);
        result ? (returnSet[result[0]] = result[1]) : null;
      });
 
    return returnSet;
  }
 
  const outputList = rawOutput
    .split(/Program Counter\n|Registers\n|Data section|Stack section\n/)
    .filter(e => e !== '');
 
  const PC = setTypeParser(outputList[0]);
  const registers = setTypeParser(outputList[1]);
  const dataSection = setTypeParser(outputList[2] || '');
  const stackSection = setTypeParser(outputList[3] || '');
 
  return {PC: PC.PC, registers, dataSection, stackSection};
}
 
export function makeOutput(
  inputFolderName: string,
  inputFileName: string,
): string {
  /*
   if the inputFilePath is /Users/junghaejune/simulator/sample_input/sample/example1.s,
    currDirectory : /Users/junghaejune/simulator
    inputFolderPath : sample_input/sample
    inputFileName: example1.s
  */
 
  const currDirectory: string = process.cwd();
  const inputFilePath: string = path.join(
    currDirectory,
    inputFolderName,
    inputFileName,
  );
 
  try {
    Iif (fs.existsSync(inputFilePath) === false) throw 'INPUT_PATH_ERROR';
 
    const input: string = fs.readFileSync(inputFilePath, 'utf-8');
 
    Iif (isEmpty(input)) throw 'INPUT_EMPTY';
    return input;
  } catch (err) {
    if (err === 'INPUT_PATH_ERROR') {
      log(
        3,
        `No input file ${inputFileName} exists. Please check the file name and path.`,
      );
    } else if (err === 'INPUT_EMPTY') {
      log(
        3,
        `input file ${inputFileName} is not opened. Please check the file`,
      );
    } else console.error(err);
    exit(1);
  }
}
 
// Create an Object file(*.o) in the desired path
export function makeObjectFile(
  outputFolderPath: string,
  outputFileName: string,
  content: string[],
) {
  /*
   if the outputFilePath is /Users/junghaejune/simulator/sample_input/sample/example1.s,
    currDirectory : /Users/junghaejune/simulator
    outputFolderPath : sample_input/sample
    outputFileName: example1.o 
    content : ['01010', '01010']
  */
 
  const currDirectory: string = process.cwd();
  const outputFilePath: string = path.join(
    currDirectory,
    outputFolderPath,
    outputFileName,
  );
 
  try {
    if (fs.existsSync(outputFilePath) === true) {
      fs.unlink(outputFilePath, err => {
        err
          ? console.error(err)
          : log(0, `Output file ${outputFileName} exists. Remake the file`);
      });
    } else throw 'OUTPUT_NOT_EXISTS';
    const fd: number = fs.openSync(outputFilePath, 'a');
 
    content.forEach(item => {
      fs.appendFileSync(fd, item + '\n', 'utf-8');
    });
 
    fs.closeSync(fd);
  } catch (err) {
    if (err === 'OUTPUT_NOT_EXISTS') {
      log(0, `Output file ${outputFileName} does not exists. Make the file`);
    } else console.error(err);
    exit(1);
  }
}
 
export function makeMappingDetail(
  assemblyFile: string[],
  dataSeg: string[],
  textSeg: string[],
  mappingTable: number[][],
  output: string[],
) {
  const mappingDetail: IMapDetail[] | null = [] as IMapDetail[];
  let textCounter = 0;
 
  assemblyFile.forEach((assemblyLine, i) => {
    const binaryInstructionNumbers: number[] = [];
    let binaryInstructions: string[] = [];
 
    if (assemblyLine.includes('.data')) {
      binaryInstructionNumbers.push(0);
      binaryInstructions = [output[0]];
    } else if (assemblyLine.includes('.word')) {
      const dataSegIndex = dataSeg.indexOf(assemblyLine.split('\t')[2]);
      const dataIndex = output.length - dataSeg.length + dataSegIndex;
      binaryInstructionNumbers.push(dataIndex);
      binaryInstructions = [output[dataIndex]];
    } else if (assemblyLine.includes('.text')) {
      binaryInstructionNumbers.push(1);
      binaryInstructions = [output[1]];
    } else {
      const binaryIndexes = mappingTable[textCounter];
      binaryInstructions = binaryIndexes.map(index => {
        binaryInstructionNumbers.push(index + 2);
        return output[index + 2];
      });
      assemblyLine === textSeg[textCounter] && textCounter++;
    }
 
    const binaryData: IBinaryData[] = [];
 
    binaryInstructions.forEach((inst, j) => {
      const binaryInstructionIndex = binaryInstructionNumbers[j];
      const temp: IBinaryData = {
        lineNumber: binaryInstructionIndex,
        data: inst,
      };
 
      binaryData.push(temp);
    });
 
    mappingDetail.push({
      key: i,
      assembly: assemblyLine,
      binary: binaryData,
    });
  });
 
  return mappingDetail;
}
 
/*
assignment2 util
*/
 
/*
  Procedure: fromBinary
  Purpose: From binary to integer
*/
 
export function fromBinary(bits: string): number {
  return parseInt(bits, 2);
}
 
/*
  Procedure: memRead
  Purpose: read a 32-bit word from memory
*/
 
export function memRead(address: number): number {
  for (let i = 0; i < MEM_NREGIONS; ++i) {
    if (
      address >= memRegions[i].start &&
      address < memRegions[i].start + memRegions[i].size
    ) {
      const offset = address - memRegions[i].start;
      const result =
        (memRegions[i].mem[offset + 3] << 24) |
        (memRegions[i].mem[offset + 2] << 16) |
        (memRegions[i].mem[offset + 1] << 8) |
        (memRegions[i].mem[offset + 0] << 0);
      return result;
    }
  }
}
 
/*
  Procedure: memWrite
  Purpose: Write a 32-bit word to memory
*/
 
export function memWrite(address: number, value: number): void {
  memRegions.forEach(memRegion => {
    if (
      address >= memRegion.start &&
      address < memRegion.start + memRegion.size
    ) {
      const offset = address - memRegion.start;
 
      memRegion.mem[offset + 3] = (value >> 24) & 0xff;
      memRegion.mem[offset + 2] = (value >> 16) & 0xff;
      memRegion.mem[offset + 1] = (value >> 8) & 0xff;
      memRegion.mem[offset + 0] = (value >> 0) & 0xff;
 
      /* set_offBound */
      memRegion.dirty = true;
      if (memRegion.type === MEM_GROW_UP) {
        memRegion.offBound =
          offset + 4 > memRegion.offBound ? offset + 4 : memRegion.offBound;
      } else
        memRegion.offBound =
          offset + 4 < memRegion.offBound ? offset + 4 : memRegion.offBound;
    }
  });
}
 
/*
  Procedure: memWriteHalf
  Purpose: Write a half of 32-bit word to memory
*/
 
export function memWriteHalf(address: number, value: number): void {
  memRegions.forEach(memRegion => {
    if (
      address >= memRegion.start &&
      address < memRegion.start + memRegion.size
    ) {
      const offset = address - memRegion.start;
 
      memRegion.mem[offset + 1] = (value >> 8) & 0xff;
      memRegion.mem[offset + 0] = (value >> 0) & 0xff;
 
      /* set_offBound */
      memRegion.dirty = true;
      if (memRegion.type === MEM_GROW_UP)
        memRegion.offBound =
          offset + 2 > memRegion.offBound ? offset + 2 : memRegion.offBound;
      else
        EmemRegion.offBound =
          offset + 2 < memRegion.offBound ? offset + 2 : memRegion.offBound;
    }
  });
}
 
/*
  Procedure: initMemory
*/
export function initMemory(): void {
  for (let i = 0; i < MEM_NREGIONS; ++i) {
    memRegions[i].mem = Array.from({length: memRegions[i].size}, () => 0);
  }
}
 
/*
  Procedure: initInstInfo
*/
export function initInstInfo(
  NUM_INST: number,
  INST_INFO: Iinstruction[],
): void {
  for (let i = 0; i < NUM_INST; ++i) {
    INST_INFO[i].value = 0;
    INST_INFO[i].opcode = 0;
    INST_INFO[i].funcCode = 0;
    INST_INFO[i].rs = 0;
    INST_INFO[i].rt = 0;
    INST_INFO[i].rd = 0;
    INST_INFO[i].imm = 0;
    INST_INFO[i].shamt = 0;
    INST_INFO[i].target = 0;
  }
}
 
/*
  Procedure: get_inst_info
  Purpose: Read instruction information
*/
export function getInstInfo(pc: number): instruction {
  return INST_INFO[(pc - MEM_TEXT_START) >> 2];
}
 
/*
  Procedure: main process
*/
 
export async function mainProcess(
  INST_INFO: instruction[],
  cycles: number,
  CYCLES: simulatorOutputType[],
): Promise<simulatorOutputType> {
  let i = cycles;
  let result = '';
 
  return new Promise<simulatorOutputType>((resolve, reject) => {
    try {
      Iif (DEBUG_SET) {
        console.log(`Simulating for ${cycles} cycles...!\n`);
        console.log('MAIN PROCESS', CYCLES);
        while (i > 0) {
          cycle();
          rdump();
 
          if (MEM_DUMP_SET) dumpMemory();
 
          i -= 1;
 
          if (RUN_BIT === 0) break;
        }
      } else {
        running(i, CYCLES);
        result += rdump();
 
        Eif (MEM_DUMP_SET) {
          result += dumpMemory();
        }
 
        let EachCycle: string = rdump();
        Eif (MEM_DUMP_SET) EachCycle += dumpMemory();
        CYCLES.push(parseSimulatorOutput(EachCycle));
      }
      const returnObject = parseSimulatorOutput(result);
      resolve(returnObject);
    } catch (error) {
      reject(error);
    }
  });
}
 
/*
  Procedure: cycle
  Purpose: Execute a cycle
*/
 
export function cycle(): void {
  process_instruction();
  instAddOne();
}
 
export function dumpMemory(): string {
  let dump_string = '';
  if (memData.dirty) {
    const dstart = memData.start;
    const dstop = memData.start + memData.offBound;
    dump_string += `Data section\n`;
    dump_string += mdump(dstart, dstop);
    dump_string += '\n';
  }
 
  if (memStack.dirty) {
    const dstart = memStack.start + memStack.offBound;
    const dstop = memStack.start + memStack.size - 4;
    dump_string += `Stack section\n`;
    dump_string += mdump(dstart, dstop);
    dump_string += '\n';
  }
 
  return dump_string;
}
 
/*
  Procedure: mdump
  Purpose: Dump a word-aligned region of memory to the output file.
*/
export function mdump(start: number, stop: number): string {
  let mdump_string = '';
  for (let i = start; i < stop + 1; i += 4) {
    mdump_string += `0x${toHexAndPad(i)}: 0x${toHexAndPad(memRead(i))}\n`;
  }
  mdump_string += '\n';
  return mdump_string;
}
 
/*
  Procedure: rdump
  Purpose:  Dump current register and bus values to the output file.
*/
export function rdump(): string {
  let rdump_string = '';
  rdump_string += 'Program Counter\n';
  rdump_string += `PC: 0x${toHexAndPad(currentState.PC)}\n`;
  rdump_string += `Registers\n`;
 
  for (let k = 0; k < MIPS_REGS; ++k) {
    rdump_string += `R${k}: 0x${toHexAndPad((currentState.REGS[k] >>>= 0))}\n`;
  }
 
  rdump_string += '\n';
  return rdump_string;
}
 
/*
  Procedure: run n
  Purpose: Simulate MIPS for n cycles
*/
export function running(num_cycles: number, CYCLES: simulatorOutputType[]) {
  let running_string = '';
  Iif (RUN_BIT === 0) {
    running_string = "Can't simulate, Simulator is halted\n";
  }
 
  running_string = `Simulating for ${num_cycles} cycles...!\n\n`;
 
  for (let i = 0; i < num_cycles; ++i) {
    if (RUN_BIT === 0) {
      running_string += `Simulator halted ${i}th cycle.\n\n`;
      break;
    }
    let EachCycle: string = rdump();
    Eif (MEM_DUMP_SET) EachCycle += dumpMemory();
    CYCLES.push(parseSimulatorOutput(EachCycle));
    cycle();
  }
  console.log(running_string);
}