vm.go 8.5 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390
  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. case code.OpHash:
  124. numElements := int(code.ReadUint16(vm.instructions[ip+1:]))
  125. ip += 2
  126. hash, err := vm.buildHash(vm.sp-numElements, vm.sp)
  127. if err != nil {
  128. return err
  129. }
  130. vm.sp -= numElements
  131. err = vm.push(hash)
  132. if err != nil {
  133. return err
  134. }
  135. case code.OpIndex:
  136. index := vm.pop()
  137. left := vm.pop()
  138. err := vm.executeIndexExpression(left, index)
  139. if err != nil {
  140. return err
  141. }
  142. }
  143. }
  144. return nil
  145. }
  146. func isTruthy(obj object.Object) bool {
  147. switch obj := obj.(type) {
  148. case *object.Boolean:
  149. return obj.Value
  150. case *object.Null:
  151. return false
  152. default:
  153. return true
  154. }
  155. }
  156. func (vm *VM) push(o object.Object) error {
  157. if vm.sp >= StackSize {
  158. return fmt.Errorf("stack overflow")
  159. }
  160. vm.stack[vm.sp] = o
  161. vm.sp++
  162. return nil
  163. }
  164. func (vm *VM) pop() object.Object {
  165. o := vm.stack[vm.sp-1]
  166. vm.sp--
  167. return o
  168. }
  169. func (vm *VM) executeIndexExpression(left, index object.Object) error {
  170. switch {
  171. case left.Type() == object.ArrayObj && index.Type() == object.IntegerObj:
  172. return vm.executeArrayIndex(left, index)
  173. case left.Type() == object.HashObj:
  174. return vm.executeHashIndex(left, index)
  175. default:
  176. return fmt.Errorf("index operator not supported: %s", left.Type())
  177. }
  178. }
  179. func (vm *VM) buildArray(startIndex, endIndex int) object.Object {
  180. elements := make([]object.Object, endIndex-startIndex)
  181. for i := startIndex; i < endIndex; i++ {
  182. elements[i-startIndex] = vm.stack[i]
  183. }
  184. return &object.Array{Elements: elements}
  185. }
  186. func (vm *VM) buildHash(startIndex, endIndex int) (object.Object, error) {
  187. hashPairs := make(map[object.HashKey]object.HashPair)
  188. for i := startIndex; i < endIndex; i += 2 {
  189. key := vm.stack[i]
  190. value := vm.stack[i+1]
  191. pair := object.HashPair{Key: key, Value: value}
  192. hashKey, ok := key.(object.Hashtable)
  193. if !ok {
  194. return nil, fmt.Errorf("unusable as hash key: %s", key.Type())
  195. }
  196. hashPairs[hashKey.HashKey()] = pair
  197. }
  198. return &object.Hash{Pairs: hashPairs}, nil
  199. }
  200. func (vm *VM) executeBinaryOperation(op code.Opcode) error {
  201. right := vm.pop()
  202. left := vm.pop()
  203. leftType := left.Type()
  204. rightType := right.Type()
  205. switch {
  206. case leftType == object.IntegerObj && rightType == object.IntegerObj:
  207. return vm.executeBinaryIntegerOperation(op, left, right)
  208. case leftType == object.StringObj && rightType == object.StringObj:
  209. return vm.executeBinaryStringOperation(op, left, right)
  210. default:
  211. return fmt.Errorf("unsupported types for binary operation: %s %s", leftType, rightType)
  212. }
  213. }
  214. func (vm *VM) executeComparison(op code.Opcode) error {
  215. right := vm.pop()
  216. left := vm.pop()
  217. if left.Type() == object.IntegerObj || right.Type() == object.IntegerObj {
  218. return vm.executeIntegerComparison(op, left, right)
  219. }
  220. switch op {
  221. case code.OpEqual:
  222. return vm.push(nativeBoolToBooleanObject(right == left))
  223. case code.OpNotEqual:
  224. return vm.push(nativeBoolToBooleanObject(right != left))
  225. default:
  226. return fmt.Errorf("unknown operator: %d (%s %s)", op, left.Type(), right.Type())
  227. }
  228. }
  229. func (vm *VM) LastPopStackElem() object.Object {
  230. return vm.stack[vm.sp]
  231. }
  232. func (vm *VM) executeBinaryIntegerOperation(
  233. op code.Opcode,
  234. left, right object.Object,
  235. ) error {
  236. leftValue := left.(*object.Integer).Value
  237. rightValue := right.(*object.Integer).Value
  238. var result int64
  239. switch op {
  240. case code.OpAdd:
  241. result = leftValue + rightValue
  242. case code.OpSub:
  243. result = leftValue - rightValue
  244. case code.OpMul:
  245. result = leftValue * rightValue
  246. case code.OpDiv:
  247. result = leftValue / rightValue
  248. default:
  249. return fmt.Errorf("unknown integer operator: %d", op)
  250. }
  251. return vm.push(&object.Integer{Value: result})
  252. }
  253. func (vm *VM) executeBinaryStringOperation(
  254. op code.Opcode,
  255. left, right object.Object,
  256. ) error {
  257. if op != code.OpAdd {
  258. return fmt.Errorf("unknown string operator: %d", op)
  259. }
  260. leftValue := left.(*object.String).Value
  261. rightValue := right.(*object.String).Value
  262. return vm.push(&object.String{Value: leftValue + rightValue})
  263. }
  264. func (vm *VM) executeIntegerComparison(
  265. op code.Opcode,
  266. left, right object.Object,
  267. ) error {
  268. leftValue := left.(*object.Integer).Value
  269. rightValue := right.(*object.Integer).Value
  270. switch op {
  271. case code.OpEqual:
  272. return vm.push(nativeBoolToBooleanObject(rightValue == leftValue))
  273. case code.OpNotEqual:
  274. return vm.push(nativeBoolToBooleanObject(rightValue != leftValue))
  275. case code.OpGreaterThan:
  276. return vm.push(nativeBoolToBooleanObject(leftValue > rightValue))
  277. default:
  278. return fmt.Errorf("unknown operator: %d", op)
  279. }
  280. }
  281. func (vm *VM) executeMinusOperator() error {
  282. operand := vm.pop()
  283. if operand.Type() != object.IntegerObj {
  284. return fmt.Errorf("unsupported type for nagation: %s", operand.Type())
  285. }
  286. value := operand.(*object.Integer).Value
  287. return vm.push(&object.Integer{Value: -value})
  288. }
  289. func (vm *VM) executeBangOperator() error {
  290. operand := vm.pop()
  291. switch operand {
  292. case True:
  293. return vm.push(False)
  294. case False:
  295. return vm.push(True)
  296. case Null:
  297. return vm.push(True)
  298. default:
  299. return vm.push(False)
  300. }
  301. }
  302. func (vm *VM) executeArrayIndex(array, index object.Object) error {
  303. arrayObject := array.(*object.Array)
  304. i := index.(*object.Integer).Value
  305. max := int64(len(arrayObject.Elements) - 1)
  306. if i < 0 || i > max {
  307. return vm.push(Null)
  308. }
  309. return vm.push(arrayObject.Elements[i])
  310. }
  311. func (vm *VM) executeHashIndex(hash, index object.Object) error {
  312. hashObject := hash.(*object.Hash)
  313. key, ok := index.(object.Hashtable)
  314. if !ok {
  315. return fmt.Errorf("unusable as hash key: %s", index.Type())
  316. }
  317. pair, ok := hashObject.Pairs[key.HashKey()]
  318. if !ok {
  319. return vm.push(Null)
  320. }
  321. return vm.push(pair.Value)
  322. }
  323. func nativeBoolToBooleanObject(input bool) *object.Boolean {
  324. if input {
  325. return True
  326. }
  327. return False
  328. }