Skip to content

Commit

Permalink
implementation of arithmetic operations
Browse files Browse the repository at this point in the history
  • Loading branch information
darkzense committed Nov 19, 2023
1 parent 3dc85ae commit 93c1302
Show file tree
Hide file tree
Showing 2 changed files with 67 additions and 4 deletions.
9 changes: 5 additions & 4 deletions system/cpu/arch.ts
Original file line number Diff line number Diff line change
@@ -1,4 +1,5 @@
import { Push, Pop } from "../instructions/stack.js";
import { Add, Sub, Mul, Div } from "../instructions/arithmetic.js";
import { Executable } from "./interface.js";

const syntax: { [key: string]: RegExp } = {
Expand All @@ -23,22 +24,22 @@ const instructionSet: {
ADD: {
code: 2,
type: "op",
executor: null,
executor: new Add(),
},
SUB: {
code: 3,
type: "op",
executor: null,
executor: new Sub(),
},
MUL: {
code: 4,
type: "op",
executor: null,
executor: new Mul(),
},
DIV: {
code: 5,
type: "op",
executor: null,
executor: new Div(),
},
HALT: {
code: 6,
Expand Down
62 changes: 62 additions & 0 deletions system/instructions/arithmetic.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,62 @@
import cpu from "../cpu/components.js";
import { Instruction, Executable } from "../cpu/interface.js";
import { getDataByAddress } from "../memory/data.js";

const MAX_WORD_VALUE = Math.pow(2, 16) - 1;

function performOp(operation: (x: number, y: number) => number) {
const topOfStackAddress = cpu.stackPointer.parseHex();
if (topOfStackAddress == 0) {
throw new ReferenceError(
"There is not enough data in the stack to perform the operation."
);
}

const topOfStack = getDataByAddress("stack-data", cpu.stackPointer)!;
// cpu.MAR = cpu.stackPointer;
// cpu.MDR = (+topOfStack.value).asHex16();

const nextOfStackAddress = (topOfStackAddress - 1).asHex16();
const nextOfStack = getDataByAddress("stack-data", nextOfStackAddress)!;
cpu.MAR = nextOfStackAddress;
cpu.MDR = (+nextOfStack.value).asHex16();

cpu.aluFlags = "";
const result = operation(+nextOfStack.value, +topOfStack.value);
cpu.aluFlags += `Z=${+(result == 0)}`;
cpu.aluFlags += `, O=${+(result > MAX_WORD_VALUE)}`;

cpu.stackPointer = nextOfStackAddress;
nextOfStack.value = result.toString();
nextOfStack.variable = "";
topOfStack.variable = "";
topOfStack.value = "";
}

export class Add implements Executable {
run(_: Instruction) {
cpu.controlUnit = "ADD";
performOp((x, y) => x + y);
}
}

export class Sub implements Executable {
run(_: Instruction) {
cpu.controlUnit = "SUB";
performOp((x, y) => x - y);
}
}

export class Mul implements Executable {
run(_: Instruction) {
cpu.controlUnit = "MUL";
performOp((x, y) => x * y);
}
}

export class Div implements Executable {
run(_: Instruction) {
cpu.controlUnit = "DIV";
performOp((x, y) => x / y);
}
}

0 comments on commit 93c1302

Please sign in to comment.