From 683c9b112d754569d0c75ea48b588fa8b08f0ba9 Mon Sep 17 00:00:00 2001 From: Aotokitsuruya Date: Wed, 22 Nov 2023 21:03:02 +0800 Subject: [PATCH] Implement stack struct to keep callinfo --- context.go | 7 ++++--- mruby.go | 5 +++-- stack/stack.go | 35 +++++++++++++++++++++++++++++++++++ vm.go | 12 ++---------- 4 files changed, 44 insertions(+), 15 deletions(-) create mode 100644 stack/stack.go diff --git a/context.go b/context.go index 8b13207..c68dfa0 100644 --- a/context.go +++ b/context.go @@ -1,10 +1,11 @@ package mruby +import "github.com/elct9620/mruby-go/stack" + type context struct { - ciCursor int - callinfos []*callinfo + callinfo *stack.Stack[*callinfo] } func (ctx *context) GetCallinfo() *callinfo { - return ctx.callinfos[len(ctx.callinfos)-1] + return ctx.callinfo.Peek() } diff --git a/mruby.go b/mruby.go index a84dcce..428b7cc 100644 --- a/mruby.go +++ b/mruby.go @@ -1,5 +1,7 @@ package mruby +import "github.com/elct9620/mruby-go/stack" + type ( Value = any Symbol = string @@ -27,8 +29,7 @@ type State struct { func New() *State { return &State{ context: &context{ - ciCursor: -1, - callinfos: []*callinfo{}, + callinfo: stack.New[*callinfo](), }, falseClass: &RClass{}, } diff --git a/stack/stack.go b/stack/stack.go new file mode 100644 index 0000000..15df023 --- /dev/null +++ b/stack/stack.go @@ -0,0 +1,35 @@ +package stack + +type Stack[T any] struct { + container []T +} + +func New[T any]() *Stack[T] { + return &Stack[T]{container: []T{}} +} + +func (s *Stack[T]) Push(v T) { + s.container = append(s.container, v) +} + +func (s *Stack[T]) Pop() T { + v := s.container[len(s.container)-1] + s.container = s.container[:len(s.container)-1] + return v +} + +func (s *Stack[T]) Peek() T { + return s.container[len(s.container)-1] +} + +func (s *Stack[T]) Len() int { + return len(s.container) +} + +func (s *Stack[T]) Get(idx int) T { + return s.container[idx] +} + +func (s *Stack[T]) Set(idx int, v T) { + s.container[idx] = v +} diff --git a/vm.go b/vm.go index fc9f55f..99cf32b 100644 --- a/vm.go +++ b/vm.go @@ -9,20 +9,12 @@ func (state *State) PushCallinfo(mid string, argc byte, targetClass *RClass) *ca stack: []Value{nil}, targetClass: targetClass, } - - ctx.ciCursor++ - - if ctx.ciCursor >= len(state.context.callinfos) { - ctx.callinfos = append(state.context.callinfos, callinfo) - } else { - ctx.callinfos[ctx.ciCursor] = callinfo - } + ctx.callinfo.Push(callinfo) return callinfo } func (state *State) PopCallinfo() { ctx := state.context - ctx.callinfos[ctx.ciCursor] = nil - ctx.ciCursor-- + ctx.callinfo.Pop() }