-
Notifications
You must be signed in to change notification settings - Fork 0
/
ghoul.go
93 lines (77 loc) · 2.21 KB
/
ghoul.go
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
package ghoul
import (
"fmt"
"io"
ev "github.com/archevel/ghoul/evaluator"
e "github.com/archevel/ghoul/expressions"
"github.com/archevel/ghoul/logging"
m "github.com/archevel/ghoul/macromancy"
"github.com/archevel/ghoul/parser"
)
type Ghoul interface {
Process(exprReader io.Reader) (e.Expr, error)
}
func New() Ghoul {
return NewLoggingGhoul(logging.VerboseLogger)
}
func NewLoggingGhoul(logger logging.Logger) Ghoul {
evaluator := prepareEvaluator(logger)
mancer := m.NewMacromancer(logger)
return ghoul{evaluator, mancer}
}
type ghoul struct {
evaluator *ev.Evaluator
macromancer *m.Macromancer
}
func (g ghoul) Process(exprReader io.Reader) (e.Expr, error) {
parseRes, parsed := parser.Parse(exprReader)
if parseRes != 0 {
return nil, fmt.Errorf("Failed to parse code")
}
manced := g.macromancer.Transform(parsed.Expressions)
result, err := g.evaluator.Evaluate(manced)
return result, err
}
func prepareEvaluator(logger logging.Logger) *ev.Evaluator {
env := ev.NewEnvironment()
env.Register("eq?", func(args e.List, ev *ev.Evaluator) (e.Expr, error) {
fst := args.First()
t, _ := args.Tail()
snd := t.First()
return e.Boolean(fst.Equiv(snd)), nil
})
env.Register("and", func(args e.List, ev *ev.Evaluator) (e.Expr, error) {
fst := args.First().(e.Boolean)
t, _ := args.Tail()
snd := t.First().(e.Boolean)
return e.Boolean(fst && snd), nil
})
env.Register("<", func(args e.List, ev *ev.Evaluator) (e.Expr, error) {
fst := args.First().(e.Integer)
t, _ := args.Tail()
snd := t.First().(e.Integer)
return e.Boolean(fst < snd), nil
})
env.Register("mod", func(args e.List, ev *ev.Evaluator) (e.Expr, error) {
fst := args.First().(e.Integer)
t, _ := args.Tail()
snd := t.First().(e.Integer)
return e.Integer(fst % snd), nil
})
env.Register("+", func(args e.List, ev *ev.Evaluator) (e.Expr, error) {
fst := args.First().(e.Integer)
t, _ := args.Tail()
snd := t.First().(e.Integer)
return e.Integer(fst + snd), nil
})
env.Register("println", func(args e.List, ev *ev.Evaluator) (e.Expr, error) {
fst, ok := args.First().(e.String)
if ok {
fmt.Println(fst)
} else {
fmt.Println(args.First().Repr())
}
return e.NIL, nil
})
return ev.New(logger, env)
}