vm.go 6.6 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310
  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. case code.OpArray:
  115. numElements := int(code.ReadUint16(vm.instructions[ip+1:]))
  116. ip += 2
  117. array := vm.buildArray(vm.sp-numElements, vm.sp)
  118. vm.sp -= numElements
  119. err := vm.push(array)
  120. if err != nil {
  121. return err
  122. }
  123. }
  124. }
  125. return nil
  126. }
  127. func isTruthy(obj object.Object) bool {
  128. switch obj := obj.(type) {
  129. case *object.Boolean:
  130. return obj.Value
  131. case *object.Null:
  132. return false
  133. default:
  134. return true
  135. }
  136. }
  137. func (vm *VM) push(o object.Object) error {
  138. if vm.sp >= StackSize {
  139. return fmt.Errorf("stack overflow")
  140. }
  141. vm.stack[vm.sp] = o
  142. vm.sp++
  143. return nil
  144. }
  145. func (vm *VM) pop() object.Object {
  146. o := vm.stack[vm.sp-1]
  147. vm.sp--
  148. return o
  149. }
  150. func (vm *VM) buildArray(startIndex, endIndex int) object.Object {
  151. elements := make([]object.Object, endIndex-startIndex)
  152. for i := startIndex; i < endIndex; i++ {
  153. elements[i-startIndex] = vm.stack[i]
  154. }
  155. return &object.Array{Elements: elements}
  156. }
  157. func (vm *VM) executeBinaryOperation(op code.Opcode) error {
  158. right := vm.pop()
  159. left := vm.pop()
  160. leftType := left.Type()
  161. rightType := right.Type()
  162. switch {
  163. case leftType == object.IntegerObj && rightType == object.IntegerObj:
  164. return vm.executeBinaryIntegerOperation(op, left, right)
  165. case leftType == object.StringObj && rightType == object.StringObj:
  166. return vm.executeBinaryStringOperation(op, left, right)
  167. default:
  168. return fmt.Errorf("unsupported types for binary operation: %s %s", leftType, rightType)
  169. }
  170. }
  171. func (vm *VM) executeComparison(op code.Opcode) error {
  172. right := vm.pop()
  173. left := vm.pop()
  174. if left.Type() == object.IntegerObj || right.Type() == object.IntegerObj {
  175. return vm.executeIntegerComparison(op, left, right)
  176. }
  177. switch op {
  178. case code.OpEqual:
  179. return vm.push(nativeBoolToBooleanObject(right == left))
  180. case code.OpNotEqual:
  181. return vm.push(nativeBoolToBooleanObject(right != left))
  182. default:
  183. return fmt.Errorf("unknown operator: %d (%s %s)", op, left.Type(), right.Type())
  184. }
  185. }
  186. func (vm *VM) LastPopStackElem() object.Object {
  187. return vm.stack[vm.sp]
  188. }
  189. func (vm *VM) executeBinaryIntegerOperation(
  190. op code.Opcode,
  191. left, right object.Object,
  192. ) error {
  193. leftValue := left.(*object.Integer).Value
  194. rightValue := right.(*object.Integer).Value
  195. var result int64
  196. switch op {
  197. case code.OpAdd:
  198. result = leftValue + rightValue
  199. case code.OpSub:
  200. result = leftValue - rightValue
  201. case code.OpMul:
  202. result = leftValue * rightValue
  203. case code.OpDiv:
  204. result = leftValue / rightValue
  205. default:
  206. return fmt.Errorf("unknown integer operator: %d", op)
  207. }
  208. return vm.push(&object.Integer{Value: result})
  209. }
  210. func (vm *VM) executeBinaryStringOperation(
  211. op code.Opcode,
  212. left, right object.Object,
  213. ) error {
  214. if op != code.OpAdd {
  215. return fmt.Errorf("unknown string operator: %d", op)
  216. }
  217. leftValue := left.(*object.String).Value
  218. rightValue := right.(*object.String).Value
  219. return vm.push(&object.String{Value: leftValue + rightValue})
  220. }
  221. func (vm *VM) executeIntegerComparison(
  222. op code.Opcode,
  223. left, right object.Object,
  224. ) error {
  225. leftValue := left.(*object.Integer).Value
  226. rightValue := right.(*object.Integer).Value
  227. switch op {
  228. case code.OpEqual:
  229. return vm.push(nativeBoolToBooleanObject(rightValue == leftValue))
  230. case code.OpNotEqual:
  231. return vm.push(nativeBoolToBooleanObject(rightValue != leftValue))
  232. case code.OpGreaterThan:
  233. return vm.push(nativeBoolToBooleanObject(leftValue > rightValue))
  234. default:
  235. return fmt.Errorf("unknown operator: %d", op)
  236. }
  237. }
  238. func (vm *VM) executeMinusOperator() error {
  239. operand := vm.pop()
  240. if operand.Type() != object.IntegerObj {
  241. return fmt.Errorf("unsupported type for nagation: %s", operand.Type())
  242. }
  243. value := operand.(*object.Integer).Value
  244. return vm.push(&object.Integer{Value: -value})
  245. }
  246. func (vm *VM) executeBangOperator() error {
  247. operand := vm.pop()
  248. switch operand {
  249. case True:
  250. return vm.push(False)
  251. case False:
  252. return vm.push(True)
  253. case Null:
  254. return vm.push(True)
  255. default:
  256. return vm.push(False)
  257. }
  258. }
  259. func nativeBoolToBooleanObject(input bool) *object.Boolean {
  260. if input {
  261. return True
  262. }
  263. return False
  264. }