vm.go 5.2 KB

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