diff --git a/cmd/root.go b/cmd/root.go index b732288..846886c 100644 --- a/cmd/root.go +++ b/cmd/root.go @@ -24,8 +24,10 @@ var rootCommand = &cobra.Command{ RunE: runRootCommand, } +var debug bool + func init() { - rootCommand.Flags().BoolP("debug", "d", false, "Enable debug mode") + rootCommand.Flags().BoolVarP(&debug, "debug", "d", false, "Enable debug mode") } func runRootCommand(cmd *cobra.Command, args []string) error { @@ -50,6 +52,6 @@ func runRootCommand(cmd *cobra.Command, args []string) error { if err != nil { return err } - hal.NewHALModule(program, 256) + hal.NewHALModule(program, 256, debug) return nil } diff --git a/hal/instructions.go b/hal/instructions.go index ceed661..043c272 100644 --- a/hal/instructions.go +++ b/hal/instructions.go @@ -11,6 +11,7 @@ type ProgrammedInstruction struct { func (pi *ProgrammedInstruction) Execute(module *Module) { if pi.Instruction.ExecuteWithOperand != nil { + module.debug("Operand: %d", pi.Operand) pi.Instruction.ExecuteWithOperand(module, pi.Operand) } else if pi.Instruction.Execute != nil { pi.Instruction.Execute(module) diff --git a/hal/module.go b/hal/module.go index 09ded49..d4b4779 100644 --- a/hal/module.go +++ b/hal/module.go @@ -10,7 +10,9 @@ type Module struct { Accumulator float64 ProgramStorage Program Register []float64 - isStopped bool + + isStopped bool + debugEnabled bool } func (h *Module) ProgramCounter() int64 { @@ -21,13 +23,23 @@ func (h *Module) increaseProgramCounter() { h.Register[0]++ } +func (h *Module) debug(format string, args ...interface{}) { + if !h.debugEnabled { + return + } + fmt.Printf("[DEBUG] "+format, args...) +} + func (h *Module) Step() { instruction := h.ProgramStorage[h.ProgramCounter()] h.increaseProgramCounter() if instruction == nil { return } + h.debug("Instruction: %s", instruction.Instruction.Name) + h.debug("Accumulator before: %d", h.Accumulator) instruction.Execute(h) + h.debug("Accumulator after: %d", h.Accumulator) } func (h *Module) Run() error { @@ -40,12 +52,13 @@ func (h *Module) Run() error { return nil } -func NewHALModule(program Program, registerSize uint64) (*Module, error) { +func NewHALModule(program Program, registerSize uint64, debug bool) (*Module, error) { if registerSize <= 10 { return nil, fmt.Errorf("register size must be greater then 10 [ registerSize = %d ]", registerSize) } return &Module{ ProgramStorage: program, Register: make([]float64, registerSize), + debugEnabled: debug, }, nil }