vm.go 10 KB

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