github.com/egonelbre/exp@v0.0.0-20240430123955-ed1d3aa93911/bench/vm/main.go (about)

     1  // +build ignore
     2  
     3  package main
     4  
     5  type VM struct {
     6  	R0, R1 byte
     7  	IP     int
     8  	Memory [1 << 10]byte
     9  }
    10  
    11  const (
    12  	STOP = byte(iota)
    13  	CONST0
    14  	CONST1
    15  	ADD0
    16  	PRINT0
    17  	PRINT1
    18  
    19  	BACKNZ0
    20  	BACKNZ1
    21  
    22  	DEC0
    23  	DEC1
    24  
    25  	LOAD0
    26  	LOAD1
    27  
    28  	STORE0
    29  	STORE1
    30  )
    31  
    32  func (vm *VM) Run() {
    33  	for {
    34  		instr := vm.Memory[vm.IP]
    35  		vm.IP++
    36  		switch instr {
    37  		case STOP:
    38  			return
    39  		case CONST0:
    40  			val := vm.Memory[vm.IP]
    41  			vm.IP++
    42  			vm.R0 = val
    43  		case CONST1:
    44  			val := vm.Memory[vm.IP]
    45  			vm.IP++
    46  			vm.R1 = val
    47  		case ADD0:
    48  			vm.R0 += vm.R1
    49  		case PRINT0:
    50  			println("r0 ", vm.R0)
    51  		case PRINT1:
    52  			println("r1 ", vm.R1)
    53  		case BACKNZ0:
    54  			if vm.R0 != 0 {
    55  				vm.IP -= int(vm.Memory[vm.IP])
    56  			} else {
    57  				vm.IP++
    58  			}
    59  		case BACKNZ1:
    60  			if vm.R1 != 0 {
    61  				vm.IP -= int(vm.Memory[vm.IP])
    62  			} else {
    63  				vm.IP++
    64  			}
    65  		case DEC0:
    66  			vm.R0 -= 1
    67  		case DEC1:
    68  			vm.R1 -= 1
    69  		}
    70  	}
    71  }
    72  
    73  var code = []byte{
    74  	CONST0, 0x05,
    75  	CONST1, 0x05,
    76  	PRINT0,
    77  	PRINT1,
    78  	ADD0,
    79  	DEC1,
    80  	BACKNZ1, 5,
    81  	STOP,
    82  }
    83  
    84  func main() {
    85  	vm := VM{}
    86  	vm.IP = 0
    87  	copy(vm.Memory[:], code)
    88  	vm.Run()
    89  }