vm.go 9.7 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451
  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. const MaxFrames = 1024
  15. var True = &object.Boolean{Value: true}
  16. var False = &object.Boolean{Value: false}
  17. var Null = &object.Null{}
  18. type VM struct {
  19. constants []object.Object
  20. instructions code.Instructions
  21. stack []object.Object
  22. sp int // Always points to the next value. Top of stack is stack[sp-1]
  23. globals []object.Object
  24. frames []*Frame
  25. framesIndex int
  26. }
  27. func New(byteCode *compiler.ByteCode) *VM {
  28. mainFn := &object.CompileFunction{Instructions: byteCode.Instructions}
  29. mainFrame := NewFrame(mainFn)
  30. frames := make([]*Frame, MaxFrames)
  31. frames[0] = mainFrame
  32. return &VM{
  33. instructions: byteCode.Instructions,
  34. constants: byteCode.Constants,
  35. stack: make([]object.Object, StackSize),
  36. sp: 0,
  37. globals: make([]object.Object, GlobalSize),
  38. frames: frames,
  39. framesIndex: 1,
  40. }
  41. }
  42. func NewWithGlobalsStore(byteCode *compiler.ByteCode, s []object.Object) *VM {
  43. vm := New(byteCode)
  44. vm.globals = s
  45. return vm
  46. }
  47. // func (vm *VM) StackTop() object.Object {
  48. // if vm.sp == 0 {
  49. // return nil
  50. // }
  51. // return vm.stack[vm.sp-1]
  52. // }
  53. func (vm *VM) Run() error {
  54. var ip int
  55. var ins code.Instructions
  56. var op code.Opcode
  57. for vm.currentFrame().ip < len(vm.currentFrame().Instructions())-1 {
  58. vm.currentFrame().ip++
  59. ip = vm.currentFrame().ip
  60. ins = vm.currentFrame().Instructions()
  61. op = code.Opcode(ins[ip])
  62. switch op {
  63. case code.OpConstant:
  64. constIndex := code.ReadUint16(ins[ip+1:])
  65. vm.currentFrame().ip += 2
  66. // 执行
  67. err := vm.push(vm.constants[constIndex])
  68. if err != nil {
  69. return err
  70. }
  71. case code.OpTrue:
  72. err := vm.push(True)
  73. if err != nil {
  74. return err
  75. }
  76. case code.OpFalse:
  77. err := vm.push(False)
  78. if err != nil {
  79. return err
  80. }
  81. case code.OpAdd, code.OpSub, code.OpMul, code.OpDiv:
  82. err := vm.executeBinaryOperation(op)
  83. if err != nil {
  84. return err
  85. }
  86. case code.OpEqual, code.OpNotEqual, code.OpGreaterThan:
  87. err := vm.executeComparison(op)
  88. if err != nil {
  89. return err
  90. }
  91. case code.OpMinus:
  92. err := vm.executeMinusOperator()
  93. if err != nil {
  94. return err
  95. }
  96. case code.OpBang:
  97. err := vm.executeBangOperator()
  98. if err != nil {
  99. return err
  100. }
  101. case code.OpPop:
  102. vm.pop()
  103. case code.OpJump:
  104. pos := int(code.ReadUint16(ins[ip+1:]))
  105. vm.currentFrame().ip = pos - 1
  106. case code.OpJumpNotTruthy:
  107. pos := int(code.ReadUint16(ins[ip+1:]))
  108. vm.currentFrame().ip += 2
  109. condition := vm.pop()
  110. if !isTruthy(condition) {
  111. vm.currentFrame().ip = pos - 1
  112. }
  113. case code.OpNull:
  114. err := vm.push(Null)
  115. if err != nil {
  116. return err
  117. }
  118. case code.OpSetGlobal:
  119. globalIndex := code.ReadUint16(ins[ip+1:])
  120. vm.currentFrame().ip += 2
  121. vm.globals[globalIndex] = vm.pop()
  122. case code.OpGetGlobal:
  123. globalIndex := code.ReadUint16(ins[ip+1:])
  124. vm.currentFrame().ip += 2
  125. err := vm.push(vm.globals[globalIndex])
  126. if err != nil {
  127. return err
  128. }
  129. case code.OpArray:
  130. numElements := int(code.ReadUint16(ins[ip+1:]))
  131. vm.currentFrame().ip += 2
  132. array := vm.buildArray(vm.sp-numElements, vm.sp)
  133. vm.sp -= numElements
  134. err := vm.push(array)
  135. if err != nil {
  136. return err
  137. }
  138. case code.OpHash:
  139. numElements := int(code.ReadUint16(ins[ip+1:]))
  140. vm.currentFrame().ip += 2
  141. hash, err := vm.buildHash(vm.sp-numElements, vm.sp)
  142. if err != nil {
  143. return err
  144. }
  145. vm.sp -= numElements
  146. err = vm.push(hash)
  147. if err != nil {
  148. return err
  149. }
  150. case code.OpIndex:
  151. index := vm.pop()
  152. left := vm.pop()
  153. err := vm.executeIndexExpression(left, index)
  154. if err != nil {
  155. return err
  156. }
  157. case code.OpCall:
  158. fn, ok := vm.stack[vm.sp-1].(*object.CompileFunction)
  159. if !ok {
  160. return fmt.Errorf("calling non-function")
  161. }
  162. frame := NewFrame(fn)
  163. vm.pushFrame(frame)
  164. case code.OpReturnValue:
  165. returnValue := vm.pop()
  166. vm.popFrame()
  167. vm.pop()
  168. err := vm.push(returnValue)
  169. if err != nil {
  170. return err
  171. }
  172. case code.OpReturn:
  173. vm.popFrame()
  174. vm.pop()
  175. err := vm.push(Null)
  176. if err != nil {
  177. return err
  178. }
  179. }
  180. }
  181. return nil
  182. }
  183. func isTruthy(obj object.Object) bool {
  184. switch obj := obj.(type) {
  185. case *object.Boolean:
  186. return obj.Value
  187. case *object.Null:
  188. return false
  189. default:
  190. return true
  191. }
  192. }
  193. func (vm *VM) currentFrame() *Frame {
  194. return vm.frames[vm.framesIndex-1]
  195. }
  196. func (vm *VM) pushFrame(f *Frame) {
  197. vm.frames[vm.framesIndex] = f
  198. vm.framesIndex++
  199. }
  200. func (vm *VM) popFrame() *Frame {
  201. vm.framesIndex--
  202. return vm.frames[vm.framesIndex]
  203. }
  204. func (vm *VM) push(o object.Object) error {
  205. if vm.sp >= StackSize {
  206. return fmt.Errorf("stack overflow")
  207. }
  208. vm.stack[vm.sp] = o
  209. vm.sp++
  210. return nil
  211. }
  212. func (vm *VM) pop() object.Object {
  213. o := vm.stack[vm.sp-1]
  214. vm.sp--
  215. return o
  216. }
  217. func (vm *VM) executeIndexExpression(left, index object.Object) error {
  218. switch {
  219. case left.Type() == object.ArrayObj && index.Type() == object.IntegerObj:
  220. return vm.executeArrayIndex(left, index)
  221. case left.Type() == object.HashObj:
  222. return vm.executeHashIndex(left, index)
  223. default:
  224. return fmt.Errorf("index operator not supported: %s", left.Type())
  225. }
  226. }
  227. func (vm *VM) buildArray(startIndex, endIndex int) object.Object {
  228. elements := make([]object.Object, endIndex-startIndex)
  229. for i := startIndex; i < endIndex; i++ {
  230. elements[i-startIndex] = vm.stack[i]
  231. }
  232. return &object.Array{Elements: elements}
  233. }
  234. func (vm *VM) buildHash(startIndex, endIndex int) (object.Object, error) {
  235. hashPairs := make(map[object.HashKey]object.HashPair)
  236. for i := startIndex; i < endIndex; i += 2 {
  237. key := vm.stack[i]
  238. value := vm.stack[i+1]
  239. pair := object.HashPair{Key: key, Value: value}
  240. hashKey, ok := key.(object.Hashtable)
  241. if !ok {
  242. return nil, fmt.Errorf("unusable as hash key: %s", key.Type())
  243. }
  244. hashPairs[hashKey.HashKey()] = pair
  245. }
  246. return &object.Hash{Pairs: hashPairs}, nil
  247. }
  248. func (vm *VM) executeBinaryOperation(op code.Opcode) error {
  249. right := vm.pop()
  250. left := vm.pop()
  251. leftType := left.Type()
  252. rightType := right.Type()
  253. switch {
  254. case leftType == object.IntegerObj && rightType == object.IntegerObj:
  255. return vm.executeBinaryIntegerOperation(op, left, right)
  256. case leftType == object.StringObj && rightType == object.StringObj:
  257. return vm.executeBinaryStringOperation(op, left, right)
  258. default:
  259. return fmt.Errorf("unsupported types for binary operation: %s %s", leftType, rightType)
  260. }
  261. }
  262. func (vm *VM) executeComparison(op code.Opcode) error {
  263. right := vm.pop()
  264. left := vm.pop()
  265. if left.Type() == object.IntegerObj || right.Type() == object.IntegerObj {
  266. return vm.executeIntegerComparison(op, left, right)
  267. }
  268. switch op {
  269. case code.OpEqual:
  270. return vm.push(nativeBoolToBooleanObject(right == left))
  271. case code.OpNotEqual:
  272. return vm.push(nativeBoolToBooleanObject(right != left))
  273. default:
  274. return fmt.Errorf("unknown operator: %d (%s %s)", op, left.Type(), right.Type())
  275. }
  276. }
  277. func (vm *VM) LastPopStackElem() object.Object {
  278. return vm.stack[vm.sp]
  279. }
  280. func (vm *VM) executeBinaryIntegerOperation(
  281. op code.Opcode,
  282. left, right object.Object,
  283. ) error {
  284. leftValue := left.(*object.Integer).Value
  285. rightValue := right.(*object.Integer).Value
  286. var result int64
  287. switch op {
  288. case code.OpAdd:
  289. result = leftValue + rightValue
  290. case code.OpSub:
  291. result = leftValue - rightValue
  292. case code.OpMul:
  293. result = leftValue * rightValue
  294. case code.OpDiv:
  295. result = leftValue / rightValue
  296. default:
  297. return fmt.Errorf("unknown integer operator: %d", op)
  298. }
  299. return vm.push(&object.Integer{Value: result})
  300. }
  301. func (vm *VM) executeBinaryStringOperation(
  302. op code.Opcode,
  303. left, right object.Object,
  304. ) error {
  305. if op != code.OpAdd {
  306. return fmt.Errorf("unknown string operator: %d", op)
  307. }
  308. leftValue := left.(*object.String).Value
  309. rightValue := right.(*object.String).Value
  310. return vm.push(&object.String{Value: leftValue + rightValue})
  311. }
  312. func (vm *VM) executeIntegerComparison(
  313. op code.Opcode,
  314. left, right object.Object,
  315. ) error {
  316. leftValue := left.(*object.Integer).Value
  317. rightValue := right.(*object.Integer).Value
  318. switch op {
  319. case code.OpEqual:
  320. return vm.push(nativeBoolToBooleanObject(rightValue == leftValue))
  321. case code.OpNotEqual:
  322. return vm.push(nativeBoolToBooleanObject(rightValue != leftValue))
  323. case code.OpGreaterThan:
  324. return vm.push(nativeBoolToBooleanObject(leftValue > rightValue))
  325. default:
  326. return fmt.Errorf("unknown operator: %d", op)
  327. }
  328. }
  329. func (vm *VM) executeMinusOperator() error {
  330. operand := vm.pop()
  331. if operand.Type() != object.IntegerObj {
  332. return fmt.Errorf("unsupported type for nagation: %s", operand.Type())
  333. }
  334. value := operand.(*object.Integer).Value
  335. return vm.push(&object.Integer{Value: -value})
  336. }
  337. func (vm *VM) executeBangOperator() error {
  338. operand := vm.pop()
  339. switch operand {
  340. case True:
  341. return vm.push(False)
  342. case False:
  343. return vm.push(True)
  344. case Null:
  345. return vm.push(True)
  346. default:
  347. return vm.push(False)
  348. }
  349. }
  350. func (vm *VM) executeArrayIndex(array, index object.Object) error {
  351. arrayObject := array.(*object.Array)
  352. i := index.(*object.Integer).Value
  353. max := int64(len(arrayObject.Elements) - 1)
  354. if i < 0 || i > max {
  355. return vm.push(Null)
  356. }
  357. return vm.push(arrayObject.Elements[i])
  358. }
  359. func (vm *VM) executeHashIndex(hash, index object.Object) error {
  360. hashObject := hash.(*object.Hash)
  361. key, ok := index.(object.Hashtable)
  362. if !ok {
  363. return fmt.Errorf("unusable as hash key: %s", index.Type())
  364. }
  365. pair, ok := hashObject.Pairs[key.HashKey()]
  366. if !ok {
  367. return vm.push(Null)
  368. }
  369. return vm.push(pair.Value)
  370. }
  371. func nativeBoolToBooleanObject(input bool) *object.Boolean {
  372. if input {
  373. return True
  374. }
  375. return False
  376. }