Skip to content

Commit

Permalink
Refactor LC-3 machine execution into a separate run method
Browse files Browse the repository at this point in the history
  • Loading branch information
ibrahimcetin committed Dec 18, 2024
1 parent 769db8f commit 44d7bda
Show file tree
Hide file tree
Showing 2 changed files with 48 additions and 41 deletions.
43 changes: 2 additions & 41 deletions Sources/LC3VM/LC3VM.swift
Original file line number Diff line number Diff line change
Expand Up @@ -29,47 +29,8 @@ struct LC3VM: AsyncParsableCommand {
// Disable input buffering
disable_input_buffering()

// Start the LC-3 machine
hardware.isRunning = true

while hardware.isRunning {
let instruction = hardware.readNextInstruction()

switch try instruction.opcode {
case .br:
try BR.execute(instruction)
case .add:
try ADD.execute(instruction)
case .ld:
try LD.execute(instruction)
case .st:
try ST.execute(instruction)
case .jsr:
try JSR.execute(instruction)
case .and:
try AND.execute(instruction)
case .ldr:
try LDR.execute(instruction)
case .str:
try STR.execute(instruction)
case .rti:
try RTI.execute(instruction)
case .not:
try NOT.execute(instruction)
case .ldi:
try LDI.execute(instruction)
case .sti:
try STI.execute(instruction)
case .jmp:
try JMP.execute(instruction)
case .res:
try RES.execute(instruction)
case .lea:
try LEA.execute(instruction)
case .trap:
try TRAP.execute(instruction)
}
}
// Run the LC-3 machine
try hardware.run()

// Restore input buffering
restore_input_buffering()
Expand Down
46 changes: 46 additions & 0 deletions Sources/LC3VMCore/Hardware.swift
Original file line number Diff line number Diff line change
Expand Up @@ -151,6 +151,52 @@ public class Hardware {
}
}

/// Runs the LC-3 machine.
///
/// - Throws: An error if the instruction is invalid.
public func run() throws {
isRunning = true

while isRunning {
let instruction = readNextInstruction()

switch try instruction.opcode {
case .br:
try BR.execute(instruction)
case .add:
try ADD.execute(instruction)
case .ld:
try LD.execute(instruction)
case .st:
try ST.execute(instruction)
case .jsr:
try JSR.execute(instruction)
case .and:
try AND.execute(instruction)
case .ldr:
try LDR.execute(instruction)
case .str:
try STR.execute(instruction)
case .rti:
try RTI.execute(instruction)
case .not:
try NOT.execute(instruction)
case .ldi:
try LDI.execute(instruction)
case .sti:
try STI.execute(instruction)
case .jmp:
try JMP.execute(instruction)
case .res:
try RES.execute(instruction)
case .lea:
try LEA.execute(instruction)
case .trap:
try TRAP.execute(instruction)
}
}
}

/// Initializes the LC-3 hardware.
///
/// - Note: Sets the condition register to zero and the program counter to the default starting location.
Expand Down

0 comments on commit 44d7bda

Please sign in to comment.