-
Notifications
You must be signed in to change notification settings - Fork 0
Commit
This commit does not belong to any branch on this repository, and may belong to a fork outside of the repository.
implementation of arithmetic operations
- Loading branch information
Showing
2 changed files
with
67 additions
and
4 deletions.
There are no files selected for viewing
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
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); | ||
} | ||
} |