vm.go 10 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468
  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, 0)
  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, vm.sp)
  163. vm.pushFrame(frame)
  164. vm.sp = frame.basePointer + fn.NumLocals
  165. case code.OpReturnValue:
  166. returnValue := vm.pop()
  167. frame := vm.popFrame()
  168. vm.sp = frame.basePointer - 1
  169. err := vm.push(returnValue)
  170. if err != nil {
  171. return err
  172. }
  173. case code.OpReturn:
  174. frame := vm.popFrame()
  175. vm.sp = frame.basePointer - 1
  176. err := vm.push(Null)
  177. if err != nil {
  178. return err
  179. }
  180. case code.OpSetLocal:
  181. localIndex := code.ReadUint8(ins[ip+1:])
  182. vm.currentFrame().ip += 1
  183. frame := vm.currentFrame()
  184. vm.stack[frame.basePointer+int(localIndex)] = vm.pop()
  185. case code.OpGetLocal:
  186. localIndex := code.ReadUint8(ins[ip+1:])
  187. vm.currentFrame().ip += 1
  188. frame := vm.currentFrame()
  189. err := vm.push(vm.stack[frame.basePointer+int(localIndex)])
  190. if err != nil {
  191. return err
  192. }
  193. }
  194. }
  195. return nil
  196. }
  197. func isTruthy(obj object.Object) bool {
  198. switch obj := obj.(type) {
  199. case *object.Boolean:
  200. return obj.Value
  201. case *object.Null:
  202. return false
  203. default:
  204. return true
  205. }
  206. }
  207. func (vm *VM) currentFrame() *Frame {
  208. return vm.frames[vm.framesIndex-1]
  209. }
  210. func (vm *VM) pushFrame(f *Frame) {
  211. vm.frames[vm.framesIndex] = f
  212. vm.framesIndex++
  213. }
  214. func (vm *VM) popFrame() *Frame {
  215. vm.framesIndex--
  216. return vm.frames[vm.framesIndex]
  217. }
  218. func (vm *VM) push(o object.Object) error {
  219. if vm.sp >= StackSize {
  220. return fmt.Errorf("stack overflow")
  221. }
  222. vm.stack[vm.sp] = o
  223. vm.sp++
  224. return nil
  225. }
  226. func (vm *VM) pop() object.Object {
  227. o := vm.stack[vm.sp-1]
  228. vm.sp--
  229. return o
  230. }
  231. func (vm *VM) executeIndexExpression(left, index object.Object) error {
  232. switch {
  233. case left.Type() == object.ArrayObj && index.Type() == object.IntegerObj:
  234. return vm.executeArrayIndex(left, index)
  235. case left.Type() == object.HashObj:
  236. return vm.executeHashIndex(left, index)
  237. default:
  238. return fmt.Errorf("index operator not supported: %s", left.Type())
  239. }
  240. }
  241. func (vm *VM) buildArray(startIndex, endIndex int) object.Object {
  242. elements := make([]object.Object, endIndex-startIndex)
  243. for i := startIndex; i < endIndex; i++ {
  244. elements[i-startIndex] = vm.stack[i]
  245. }
  246. return &object.Array{Elements: elements}
  247. }
  248. func (vm *VM) buildHash(startIndex, endIndex int) (object.Object, error) {
  249. hashPairs := make(map[object.HashKey]object.HashPair)
  250. for i := startIndex; i < endIndex; i += 2 {
  251. key := vm.stack[i]
  252. value := vm.stack[i+1]
  253. pair := object.HashPair{Key: key, Value: value}
  254. hashKey, ok := key.(object.Hashtable)
  255. if !ok {
  256. return nil, fmt.Errorf("unusable as hash key: %s", key.Type())
  257. }
  258. hashPairs[hashKey.HashKey()] = pair
  259. }
  260. return &object.Hash{Pairs: hashPairs}, nil
  261. }
  262. func (vm *VM) executeBinaryOperation(op code.Opcode) error {
  263. right := vm.pop()
  264. left := vm.pop()
  265. leftType := left.Type()
  266. rightType := right.Type()
  267. switch {
  268. case leftType == object.IntegerObj && rightType == object.IntegerObj:
  269. return vm.executeBinaryIntegerOperation(op, left, right)
  270. case leftType == object.StringObj && rightType == object.StringObj:
  271. return vm.executeBinaryStringOperation(op, left, right)
  272. default:
  273. return fmt.Errorf("unsupported types for binary operation: %s %s", leftType, rightType)
  274. }
  275. }
  276. func (vm *VM) executeComparison(op code.Opcode) error {
  277. right := vm.pop()
  278. left := vm.pop()
  279. if left.Type() == object.IntegerObj || right.Type() == object.IntegerObj {
  280. return vm.executeIntegerComparison(op, left, right)
  281. }
  282. switch op {
  283. case code.OpEqual:
  284. return vm.push(nativeBoolToBooleanObject(right == left))
  285. case code.OpNotEqual:
  286. return vm.push(nativeBoolToBooleanObject(right != left))
  287. default:
  288. return fmt.Errorf("unknown operator: %d (%s %s)", op, left.Type(), right.Type())
  289. }
  290. }
  291. func (vm *VM) LastPopStackElem() object.Object {
  292. return vm.stack[vm.sp]
  293. }
  294. func (vm *VM) executeBinaryIntegerOperation(
  295. op code.Opcode,
  296. left, right object.Object,
  297. ) error {
  298. leftValue := left.(*object.Integer).Value
  299. rightValue := right.(*object.Integer).Value
  300. var result int64
  301. switch op {
  302. case code.OpAdd:
  303. result = leftValue + rightValue
  304. case code.OpSub:
  305. result = leftValue - rightValue
  306. case code.OpMul:
  307. result = leftValue * rightValue
  308. case code.OpDiv:
  309. result = leftValue / rightValue
  310. default:
  311. return fmt.Errorf("unknown integer operator: %d", op)
  312. }
  313. return vm.push(&object.Integer{Value: result})
  314. }
  315. func (vm *VM) executeBinaryStringOperation(
  316. op code.Opcode,
  317. left, right object.Object,
  318. ) error {
  319. if op != code.OpAdd {
  320. return fmt.Errorf("unknown string operator: %d", op)
  321. }
  322. leftValue := left.(*object.String).Value
  323. rightValue := right.(*object.String).Value
  324. return vm.push(&object.String{Value: leftValue + rightValue})
  325. }
  326. func (vm *VM) executeIntegerComparison(
  327. op code.Opcode,
  328. left, right object.Object,
  329. ) error {
  330. leftValue := left.(*object.Integer).Value
  331. rightValue := right.(*object.Integer).Value
  332. switch op {
  333. case code.OpEqual:
  334. return vm.push(nativeBoolToBooleanObject(rightValue == leftValue))
  335. case code.OpNotEqual:
  336. return vm.push(nativeBoolToBooleanObject(rightValue != leftValue))
  337. case code.OpGreaterThan:
  338. return vm.push(nativeBoolToBooleanObject(leftValue > rightValue))
  339. default:
  340. return fmt.Errorf("unknown operator: %d", op)
  341. }
  342. }
  343. func (vm *VM) executeMinusOperator() error {
  344. operand := vm.pop()
  345. if operand.Type() != object.IntegerObj {
  346. return fmt.Errorf("unsupported type for nagation: %s", operand.Type())
  347. }
  348. value := operand.(*object.Integer).Value
  349. return vm.push(&object.Integer{Value: -value})
  350. }
  351. func (vm *VM) executeBangOperator() error {
  352. operand := vm.pop()
  353. switch operand {
  354. case True:
  355. return vm.push(False)
  356. case False:
  357. return vm.push(True)
  358. case Null:
  359. return vm.push(True)
  360. default:
  361. return vm.push(False)
  362. }
  363. }
  364. func (vm *VM) executeArrayIndex(array, index object.Object) error {
  365. arrayObject := array.(*object.Array)
  366. i := index.(*object.Integer).Value
  367. max := int64(len(arrayObject.Elements) - 1)
  368. if i < 0 || i > max {
  369. return vm.push(Null)
  370. }
  371. return vm.push(arrayObject.Elements[i])
  372. }
  373. func (vm *VM) executeHashIndex(hash, index object.Object) error {
  374. hashObject := hash.(*object.Hash)
  375. key, ok := index.(object.Hashtable)
  376. if !ok {
  377. return fmt.Errorf("unusable as hash key: %s", index.Type())
  378. }
  379. pair, ok := hashObject.Pairs[key.HashKey()]
  380. if !ok {
  381. return vm.push(Null)
  382. }
  383. return vm.push(pair.Value)
  384. }
  385. func nativeBoolToBooleanObject(input bool) *object.Boolean {
  386. if input {
  387. return True
  388. }
  389. return False
  390. }