Skip to content

Commit

Permalink
refactor gostd
Browse files Browse the repository at this point in the history
  • Loading branch information
hidetatz committed Sep 9, 2023
1 parent b36cc49 commit 91f8c90
Show file tree
Hide file tree
Showing 4 changed files with 43 additions and 19 deletions.
50 changes: 33 additions & 17 deletions gostd.go
Original file line number Diff line number Diff line change
@@ -1,6 +1,9 @@
package main

var gostdmods = &gostdmodules{mods: map[string][]*gostdmodobj{}}
import (
"fmt"
"math"
)

type gostdmodules struct {
mods map[string][]*gostdmodobj
Expand All @@ -11,24 +14,37 @@ type gostdmodobj struct {
o *obj
}

func (g *gostdmodules) reg(modname, objname string, o *obj) {
g.mods[modname] = append(g.mods[modname], &gostdmodobj{name: objname, o: o})
}

func (g *gostdmodules) regF(modname, objname string, fn func(objs ...*obj) (*obj, error)) {
g.mods[modname] = append(g.mods[modname], &gostdmodobj{name: objname, o: &obj{
typ: tGoStdModFunc,
gostdmodfunc: fn,
}})
}

func (g *gostdmodules) objs(modname string) ([]*gostdmodobj, bool) {
objs, ok := g.mods[modname]
return objs, ok
}

func initGoStdMod() {
gostdmods.regF("math", "add", func(objs ...*obj) (*obj, error) {
return &obj{typ: tI64, ival: objs[0].ival + objs[1].ival}, nil
})
}
// register standard module/object which are written in Go here.
var gostdmods = &gostdmodules{mods: map[string][]*gostdmodobj{
"math": {
{
"pi",
&obj{
typ: tF64,
fval: math.Pi,
},
},
{
"add",
&obj{
typ: tGoStdModFunc,
gostdmodfunc: func(objs ...*obj) (*obj, error) {
result := int64(0)
for _, o := range objs {
if o.typ != tI64 {
return NIL, fmt.Errorf("arg for add() must be i64")
}

result += o.ival
}
return &obj{typ: tI64, ival: result}, nil
},
},
},
},
}}
1 change: 0 additions & 1 deletion main.go
Original file line number Diff line number Diff line change
Expand Up @@ -43,7 +43,6 @@ func run(args []string) int {
}

env = &environment{modules: map[string]*module{}}
initGoStdMod()

if len(args) <= 1 {
return repl()
Expand Down
2 changes: 1 addition & 1 deletion shiba.go
Original file line number Diff line number Diff line change
Expand Up @@ -22,9 +22,9 @@ func interpret(target string) int {
} else {
werr("%s", err)
}
// todo: code should be extracted from err
return 1
}

return 0
}

Expand Down
9 changes: 9 additions & 0 deletions tests/gostd.sb
Original file line number Diff line number Diff line change
@@ -0,0 +1,9 @@
import assert

as = assert.assert

import math
as(6, math.add(4, 2))
as(3.14159265358979323846264338327950288419716939937510582097494459, math.pi)

print("gostd test succeeded")

0 comments on commit 91f8c90

Please sign in to comment.