vm.go 5.7 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273
  1. // Author: simon
  2. // Author: ynwdlxm@163.com
  3. // Date: 2022/10/22 13:55
  4. // Desc: Stack VM implement
  5. package vm
  6. import (
  7. "fmt"
  8. "github/runnignwater/monkey/code"
  9. "github/runnignwater/monkey/compiler"
  10. "github/runnignwater/monkey/object"
  11. )
  12. const StackSize = 2048
  13. const GlobalSize = 65535
  14. var True = &object.Boolean{Value: true}
  15. var False = &object.Boolean{Value: false}
  16. var Null = &object.Null{}
  17. type VM struct {
  18. constants []object.Object
  19. instructions code.Instructions
  20. stack []object.Object
  21. sp int // Always points to the next value. Top of stack is stack[sp-1]
  22. globals []object.Object
  23. }
  24. func New(byteCode *compiler.ByteCode) *VM {
  25. return &VM{
  26. instructions: byteCode.Instructions,
  27. constants: byteCode.Constants,
  28. stack: make([]object.Object, StackSize),
  29. sp: 0,
  30. globals: make([]object.Object, GlobalSize),
  31. }
  32. }
  33. func NewWithGlobalsStore(byteCode *compiler.ByteCode, s []object.Object) *VM {
  34. vm := New(byteCode)
  35. vm.globals = s
  36. return vm
  37. }
  38. // func (vm *VM) StackTop() object.Object {
  39. // if vm.sp == 0 {
  40. // return nil
  41. // }
  42. // return vm.stack[vm.sp-1]
  43. // }
  44. func (vm *VM) Run() error {
  45. for ip := 0; ip < len(vm.instructions); ip++ {
  46. op := code.Opcode(vm.instructions[ip])
  47. switch op {
  48. case code.OpConstant:
  49. constIndex := code.ReadUint16(vm.instructions[ip+1:])
  50. ip += 2
  51. // 执行
  52. err := vm.push(vm.constants[constIndex])
  53. if err != nil {
  54. return err
  55. }
  56. case code.OpTrue:
  57. err := vm.push(True)
  58. if err != nil {
  59. return err
  60. }
  61. case code.OpFalse:
  62. err := vm.push(False)
  63. if err != nil {
  64. return err
  65. }
  66. case code.OpAdd, code.OpSub, code.OpMul, code.OpDiv:
  67. err := vm.executeBinaryOperation(op)
  68. if err != nil {
  69. return err
  70. }
  71. case code.OpEqual, code.OpNotEqual, code.OpGreaterThan:
  72. err := vm.executeComparison(op)
  73. if err != nil {
  74. return err
  75. }
  76. case code.OpMinus:
  77. err := vm.executeMinusOperator()
  78. if err != nil {
  79. return err
  80. }
  81. case code.OpBang:
  82. err := vm.executeBangOperator()
  83. if err != nil {
  84. return err
  85. }
  86. case code.OpPop:
  87. vm.pop()
  88. case code.OpJump:
  89. pos := int(code.ReadUint16(vm.instructions[ip+1:]))
  90. ip = pos - 1
  91. case code.OpJumpNotTruthy:
  92. pos := int(code.ReadUint16(vm.instructions[ip+1:]))
  93. ip += 2
  94. condition := vm.pop()
  95. if !isTruthy(condition) {
  96. ip = pos - 1
  97. }
  98. case code.OpNull:
  99. err := vm.push(Null)
  100. if err != nil {
  101. return err
  102. }
  103. case code.OpSetGlobal:
  104. globalIndex := code.ReadUint16(vm.instructions[ip+1:])
  105. ip += 2
  106. vm.globals[globalIndex] = vm.pop()
  107. case code.OpGetGlobal:
  108. globalIndex := code.ReadUint16(vm.instructions[ip+1:])
  109. ip += 2
  110. err := vm.push(vm.globals[globalIndex])
  111. if err != nil {
  112. return err
  113. }
  114. }
  115. }
  116. return nil
  117. }
  118. func isTruthy(obj object.Object) bool {
  119. switch obj := obj.(type) {
  120. case *object.Boolean:
  121. return obj.Value
  122. case *object.Null:
  123. return false
  124. default:
  125. return true
  126. }
  127. }
  128. func (vm *VM) push(o object.Object) error {
  129. if vm.sp >= StackSize {
  130. return fmt.Errorf("stack overflow")
  131. }
  132. vm.stack[vm.sp] = o
  133. vm.sp++
  134. return nil
  135. }
  136. func (vm *VM) pop() object.Object {
  137. o := vm.stack[vm.sp-1]
  138. vm.sp--
  139. return o
  140. }
  141. func (vm *VM) executeBinaryOperation(op code.Opcode) error {
  142. right := vm.pop()
  143. left := vm.pop()
  144. leftType := left.Type()
  145. rightType := right.Type()
  146. if leftType == object.IntegerObj && rightType == object.IntegerObj {
  147. return vm.executeBinaryIntegerOperation(op, left, right)
  148. }
  149. return fmt.Errorf("unsupported types of binary operation: %s %s", leftType, rightType)
  150. }
  151. func (vm *VM) executeComparison(op code.Opcode) error {
  152. right := vm.pop()
  153. left := vm.pop()
  154. if left.Type() == object.IntegerObj || right.Type() == object.IntegerObj {
  155. return vm.executeIntegerComparison(op, left, right)
  156. }
  157. switch op {
  158. case code.OpEqual:
  159. return vm.push(nativeBoolToBooleanObject(right == left))
  160. case code.OpNotEqual:
  161. return vm.push(nativeBoolToBooleanObject(right != left))
  162. default:
  163. return fmt.Errorf("unknown operator: %d (%s %s)", op, left.Type(), right.Type())
  164. }
  165. }
  166. func (vm *VM) LastPopStackElem() object.Object {
  167. return vm.stack[vm.sp]
  168. }
  169. func (vm *VM) executeBinaryIntegerOperation(
  170. op code.Opcode,
  171. left, right object.Object,
  172. ) error {
  173. leftValue := left.(*object.Integer).Value
  174. rightValue := right.(*object.Integer).Value
  175. var result int64
  176. switch op {
  177. case code.OpAdd:
  178. result = leftValue + rightValue
  179. case code.OpSub:
  180. result = leftValue - rightValue
  181. case code.OpMul:
  182. result = leftValue * rightValue
  183. case code.OpDiv:
  184. result = leftValue / rightValue
  185. default:
  186. return fmt.Errorf("unknown integer operator: %d", op)
  187. }
  188. return vm.push(&object.Integer{Value: result})
  189. }
  190. func (vm *VM) executeIntegerComparison(
  191. op code.Opcode,
  192. left, right object.Object,
  193. ) error {
  194. leftValue := left.(*object.Integer).Value
  195. rightValue := right.(*object.Integer).Value
  196. switch op {
  197. case code.OpEqual:
  198. return vm.push(nativeBoolToBooleanObject(rightValue == leftValue))
  199. case code.OpNotEqual:
  200. return vm.push(nativeBoolToBooleanObject(rightValue != leftValue))
  201. case code.OpGreaterThan:
  202. return vm.push(nativeBoolToBooleanObject(leftValue > rightValue))
  203. default:
  204. return fmt.Errorf("unknown operator: %d", op)
  205. }
  206. }
  207. func (vm *VM) executeMinusOperator() error {
  208. operand := vm.pop()
  209. if operand.Type() != object.IntegerObj {
  210. return fmt.Errorf("unsupported type for nagation: %s", operand.Type())
  211. }
  212. value := operand.(*object.Integer).Value
  213. return vm.push(&object.Integer{Value: -value})
  214. }
  215. func (vm *VM) executeBangOperator() error {
  216. operand := vm.pop()
  217. switch operand {
  218. case True:
  219. return vm.push(False)
  220. case False:
  221. return vm.push(True)
  222. case Null:
  223. return vm.push(True)
  224. default:
  225. return vm.push(False)
  226. }
  227. }
  228. func nativeBoolToBooleanObject(input bool) *object.Boolean {
  229. if input {
  230. return True
  231. }
  232. return False
  233. }