Skip to content

Commit

Permalink
Implement stack struct to keep callinfo
Browse files Browse the repository at this point in the history
  • Loading branch information
elct9620 committed Nov 22, 2023
1 parent 18d81ea commit 683c9b1
Show file tree
Hide file tree
Showing 4 changed files with 44 additions and 15 deletions.
7 changes: 4 additions & 3 deletions context.go
Original file line number Diff line number Diff line change
@@ -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()
}
5 changes: 3 additions & 2 deletions mruby.go
Original file line number Diff line number Diff line change
@@ -1,5 +1,7 @@
package mruby

import "github.com/elct9620/mruby-go/stack"

type (
Value = any
Symbol = string
Expand Down Expand Up @@ -27,8 +29,7 @@ type State struct {
func New() *State {
return &State{
context: &context{
ciCursor: -1,
callinfos: []*callinfo{},
callinfo: stack.New[*callinfo](),
},
falseClass: &RClass{},
}
Expand Down
35 changes: 35 additions & 0 deletions stack/stack.go
Original file line number Diff line number Diff line change
@@ -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
}
12 changes: 2 additions & 10 deletions vm.go
Original file line number Diff line number Diff line change
Expand Up @@ -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()
}

0 comments on commit 683c9b1

Please sign in to comment.