vm.go 6.2 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289
  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. switch {
  147. case leftType == object.IntegerObj && rightType == object.IntegerObj:
  148. return vm.executeBinaryIntegerOperation(op, left, right)
  149. case leftType == object.StringObj && rightType == object.StringObj:
  150. return vm.executeBinaryStringOperation(op, left, right)
  151. default:
  152. return fmt.Errorf("unsupported types for binary operation: %s %s", leftType, rightType)
  153. }
  154. }
  155. func (vm *VM) executeComparison(op code.Opcode) error {
  156. right := vm.pop()
  157. left := vm.pop()
  158. if left.Type() == object.IntegerObj || right.Type() == object.IntegerObj {
  159. return vm.executeIntegerComparison(op, left, right)
  160. }
  161. switch op {
  162. case code.OpEqual:
  163. return vm.push(nativeBoolToBooleanObject(right == left))
  164. case code.OpNotEqual:
  165. return vm.push(nativeBoolToBooleanObject(right != left))
  166. default:
  167. return fmt.Errorf("unknown operator: %d (%s %s)", op, left.Type(), right.Type())
  168. }
  169. }
  170. func (vm *VM) LastPopStackElem() object.Object {
  171. return vm.stack[vm.sp]
  172. }
  173. func (vm *VM) executeBinaryIntegerOperation(
  174. op code.Opcode,
  175. left, right object.Object,
  176. ) error {
  177. leftValue := left.(*object.Integer).Value
  178. rightValue := right.(*object.Integer).Value
  179. var result int64
  180. switch op {
  181. case code.OpAdd:
  182. result = leftValue + rightValue
  183. case code.OpSub:
  184. result = leftValue - rightValue
  185. case code.OpMul:
  186. result = leftValue * rightValue
  187. case code.OpDiv:
  188. result = leftValue / rightValue
  189. default:
  190. return fmt.Errorf("unknown integer operator: %d", op)
  191. }
  192. return vm.push(&object.Integer{Value: result})
  193. }
  194. func (vm *VM) executeBinaryStringOperation(
  195. op code.Opcode,
  196. left, right object.Object,
  197. ) error {
  198. if op != code.OpAdd {
  199. return fmt.Errorf("unknown string operator: %d", op)
  200. }
  201. leftValue := left.(*object.String).Value
  202. rightValue := right.(*object.String).Value
  203. return vm.push(&object.String{Value: leftValue + rightValue})
  204. }
  205. func (vm *VM) executeIntegerComparison(
  206. op code.Opcode,
  207. left, right object.Object,
  208. ) error {
  209. leftValue := left.(*object.Integer).Value
  210. rightValue := right.(*object.Integer).Value
  211. switch op {
  212. case code.OpEqual:
  213. return vm.push(nativeBoolToBooleanObject(rightValue == leftValue))
  214. case code.OpNotEqual:
  215. return vm.push(nativeBoolToBooleanObject(rightValue != leftValue))
  216. case code.OpGreaterThan:
  217. return vm.push(nativeBoolToBooleanObject(leftValue > rightValue))
  218. default:
  219. return fmt.Errorf("unknown operator: %d", op)
  220. }
  221. }
  222. func (vm *VM) executeMinusOperator() error {
  223. operand := vm.pop()
  224. if operand.Type() != object.IntegerObj {
  225. return fmt.Errorf("unsupported type for nagation: %s", operand.Type())
  226. }
  227. value := operand.(*object.Integer).Value
  228. return vm.push(&object.Integer{Value: -value})
  229. }
  230. func (vm *VM) executeBangOperator() error {
  231. operand := vm.pop()
  232. switch operand {
  233. case True:
  234. return vm.push(False)
  235. case False:
  236. return vm.push(True)
  237. case Null:
  238. return vm.push(True)
  239. default:
  240. return vm.push(False)
  241. }
  242. }
  243. func nativeBoolToBooleanObject(input bool) *object.Boolean {
  244. if input {
  245. return True
  246. }
  247. return False
  248. }