This repository has been archived by the owner on May 23, 2021. It is now read-only.
-
Notifications
You must be signed in to change notification settings - Fork 5
/
sabre.go
78 lines (65 loc) · 1.76 KB
/
sabre.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
// Package sabre provides data structures, reader for reading LISP source
// into data structures and functions for evluating forms against a context.
package sabre
import (
"fmt"
"io"
"strings"
)
// Eval evaluates the given form against the scope and returns the result
// of evaluation.
func Eval(scope Scope, form Value) (Value, error) {
if form == nil {
return Nil{}, nil
}
v, err := form.Eval(scope)
if err != nil {
return v, newEvalErr(form, err)
}
return v, nil
}
// ReadEval consumes data from reader 'r' till EOF, parses into forms
// and evaluates all the forms obtained and returns the result.
func ReadEval(scope Scope, r io.Reader) (Value, error) {
mod, err := NewReader(r).All()
if err != nil {
return nil, err
}
return Eval(scope, mod)
}
// ReadEvalStr is a convenience wrapper for Eval that reads forms from
// string and evaluates for result.
func ReadEvalStr(scope Scope, src string) (Value, error) {
return ReadEval(scope, strings.NewReader(src))
}
// Scope implementation is responsible for managing value bindings.
type Scope interface {
Parent() Scope
Bind(symbol string, v Value) error
Resolve(symbol string) (Value, error)
}
func newEvalErr(v Value, err error) EvalError {
if ee, ok := err.(EvalError); ok {
return ee
} else if ee, ok := err.(*EvalError); ok && ee != nil {
return *ee
}
return EvalError{
Position: getPosition(v),
Cause: err,
Form: v,
}
}
// EvalError represents error during evaluation.
type EvalError struct {
Position
Cause error
Form Value
}
// Unwrap returns the underlying cause of this error.
func (ee EvalError) Unwrap() error { return ee.Cause }
func (ee EvalError) Error() string {
return fmt.Sprintf("eval-error in '%s' (at line %d:%d): %v",
ee.File, ee.Line, ee.Column, ee.Cause,
)
}