@@ -12,7 +12,11 @@ module StackVM::Machine
1212 property instruction : Instruction
1313 property executable_size : UInt64
1414
15- def initialize (memory_size = DEFAULT_MEMORY_SIZE )
15+ property input : IO
16+ property output : IO
17+ property error : IO
18+
19+ def initialize (memory_size = DEFAULT_MEMORY_SIZE , @input = STDIN , @output = STDOUT , @error = STDERR )
1620 @regs = Slice (UInt64 ).new(20 , 0 _u64 )
1721 @memory = Slice (UInt8 ).new(memory_size, 0 _u8 )
1822 @instruction = Instruction .new 0b00000000 _00110000_u16
@@ -123,6 +127,10 @@ module StackVM::Machine
123127 return op_exp
124128 when OP ::LOADI
125129 return op_loadi
130+ when OP ::NOP
131+ return false
132+ when OP ::PUTS
133+ return op_puts
126134 when OP ::HALT
127135 return op_halt
128136 else
@@ -256,6 +264,11 @@ module StackVM::Machine
256264 value
257265 end
258266
267+ # Reads *amount* of bytes from the stack
268+ def stack_read_bytes (amount )
269+ memory_read @regs [Reg ::SP ] - amount, amount
270+ end
271+
259272 # Pops a *type* value from the stack
260273 def stack_read_value (type : Number .class)
261274 memory_read_value @regs [Reg ::SP ] - sizeof(typeof (type )), type
@@ -505,16 +518,35 @@ module StackVM::Machine
505518
506519 # Decodes the amount of bytes that are being pushed
507520 type = memory_read(@regs [Reg ::IP ] + 2 , 2 )
508- type = Pointer (UInt32 ).new type .to_unsafe.address
509- amount_of_bytes = type [0 ]
521+ amount_of_bytes = IO ::ByteFormat ::LittleEndian .decode UInt16 , type
510522
511- # Reads *type * bytes
523+ # Reads *amount_of_bytes * bytes
512524 value = memory_read(@regs [Reg ::IP ] + 6 , amount_of_bytes)
513525 stack_push value
514526
515527 return false
516528 end
517529
530+ # Executes a PUTS instruction
531+ #
532+ # ```
533+ # LOADI BYTE 25
534+ # LOADI BYTE 50
535+ # PUTS WORD # => prints [25, 50]
536+ # ```
537+ def op_puts
538+
539+ # Decodes the amount of bytes that are being read
540+ type = memory_read(@regs [Reg ::IP ] + 2 , 2 )
541+ amount_of_bytes = IO ::ByteFormat ::LittleEndian .decode UInt16 , type
542+
543+ # Reads *amount_of_bytes* bytes
544+ value = stack_read_bytes amount_of_bytes
545+ @output .puts value
546+
547+ return false
548+ end
549+
518550 # Executes a HALT instruction
519551 #
520552 # ```
0 commit comments