/
atoms.go
287 lines (223 loc) · 6.31 KB
/
atoms.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
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
package internal
import (
"fmt"
"reflect"
"strconv"
"strings"
"sync"
"unicode/utf8"
)
// Nil represents a nil value.
type Nil struct{}
// Eval returns the underlying value.
func (n Nil) Eval(_ Scope) (Value, error) { return n, nil }
func (n Nil) String() string { return "nil" }
// Bool represents a boolean value.
type Bool bool
// Eval returns the underlying value.
func (b Bool) Eval(_ Scope) (Value, error) { return b, nil }
func (b Bool) String() string { return fmt.Sprintf("%t", b) }
// Number represents double precision floating point numbers
type Number float64
// Eval simply returns itself since Floats evaluate to themselves.
func (n Number) Eval(_ Scope) (Value, error) { return n, nil }
func (n Number) String() string {
return strconv.FormatFloat(float64(n), 'f', -1, 64)
}
// String represents double-quoted string literals. String Form represents
// the true string value obtained from the reader. Escape sequences are not
// applicable at this level.
type String string
// Eval simply returns itself since Strings evaluate to themselves.
func (se String) Eval(_ Scope) (Value, error) { return se, nil }
func (se String) String() string { return fmt.Sprintf("\"%s\"", string(se)) }
// First returns the first character if string is not empty, nil otherwise.
func (se String) First() Value {
if len(se) == 0 {
return Nil{}
}
return Character(se[0])
}
// Next slices the string by excluding first character and returns the
// remainder.
func (se String) Next() Seq {
if len(se) <= 1 {
return nil
}
return String(se[1:])
}
// Cons converts the string to character sequence and adds the given value
// to the beginning of the list.
func (se String) Cons(v Value) Seq { return se.castString(v) + se }
// Conj joins the given values to list of characters of the string and returns
// the new sequence.
func (se String) Conj(vals ...Value) Seq {
result := se
for _, val := range vals {
result += se.castString(val)
}
return result
}
func (se String) Size() int { return utf8.RuneCountInString(string(se)) }
func (se String) castString(val Value) String {
switch v := val.(type) {
case String:
return v
case Character:
return String(v)
default:
return String(v.String())
}
}
func (se String) chars() Values {
var vals Values
for _, r := range se {
vals = append(vals, Character(r))
}
return vals
}
// Character represents a character literal. For example, \a, \b, \1, \∂ etc
// are valid character literals. In addition, special literals like \newline,
// \space etc are supported by the reader.
type Character rune
// Eval simply returns itself since Chracters evaluate to themselves.
func (char Character) Eval(_ Scope) (Value, error) { return char, nil }
func (char Character) String() string { return fmt.Sprintf("\\%c", rune(char)) }
// Keyword represents a keyword literal.
type Keyword string
// Eval simply returns itself since Keywords evaluate to themselves.
func (kw Keyword) Eval(_ Scope) (Value, error) { return kw, nil }
func (kw Keyword) String() string { return fmt.Sprintf(":%s", string(kw)) }
// Invoke enables keyword lookup for maps.
func (kw Keyword) Invoke(scope Scope, args ...Value) (Value, error) {
if err := verifyArgCount([]int{1, 2}, args); err != nil {
return nil, err
}
argVals, err := EvalValueList(scope, args)
if err != nil {
return nil, err
}
hm, ok := argVals[0].(*HashMap)
if !ok {
return Nil{}, nil
}
value := hm.Get(kw)
if len(argVals) == 2 && value == nil {
return value, nil
}
return value, nil
}
// Symbol represents a name given to a value in memory.
type Symbol struct {
Position
Value string
}
// Eval returns the value bound to this symbol in current context. If the
// symbol is in fully qualified form (i.e., separated by '.'), eval does
// recursive member access.
func (sym Symbol) Eval(scope Scope) (Value, error) {
target, err := sym.resolveValue(scope)
if err != nil {
return nil, err
}
if _, isSpecial := target.(SpecialForm); isSpecial {
return nil, fmt.Errorf("can't take value of special form '%s'", sym.Value)
}
if isMacro(target) {
return nil, fmt.Errorf("can't take value of macro '%s'", sym.Value)
}
return target, nil
}
// Compare compares this symbol to the given value. Returns true if
// the given value is a symbol with same data.
func (sym Symbol) Compare(v Value) bool {
other, ok := v.(Symbol)
if !ok {
return false
}
return other.Value == sym.Value
}
func (sym Symbol) String() string { return sym.Value }
func (sym Symbol) resolveValue(scope Scope) (Value, error) {
fields := strings.Split(sym.Value, ".")
if sym.Value == "." {
fields = []string{"."}
}
target, err := scope.Resolve(fields[0])
if len(fields) == 1 || err != nil {
return target, err
}
rv := reflect.ValueOf(target)
for i := 1; i < len(fields); i++ {
if rv.Type() == reflect.TypeOf(Any{}) {
rv = rv.Interface().(Any).V
}
rv, err = accessMember(rv, fields[i])
if err != nil {
return nil, err
}
}
if isKind(rv.Type(), reflect.Chan, reflect.Array,
reflect.Func, reflect.Ptr) && rv.IsNil() {
return Nil{}, nil
}
if object, ok := target.(Object); ok {
fn, ok := rv.Interface().(Invokable)
if !ok {
return ValueOf(rv.Interface()), nil
}
// if it is a method call, supply the instance as the first param
return &Fn{
Args: []string{"instance"},
Func: func(scope Scope, args []Value) (Value, error) {
args = append([]Value{object}, args...)
return fn.Invoke(scope, args...)
},
}, nil
}
return ValueOf(rv.Interface()), nil
}
func resolveSpecial(scope Scope, v Value) (*SpecialForm, error) {
sym, isSymbol := v.(Symbol)
if !isSymbol {
return nil, nil
}
v, err := sym.resolveValue(scope)
if err != nil {
return nil, nil
}
sf, ok := v.(SpecialForm)
if !ok {
return nil, nil
}
return &sf, nil
}
// Atom is a thread-safe reference type
type Atom struct {
mu sync.RWMutex
Val Value
}
func (a *Atom) UpdateState(scope Scope, fn Invokable) (Value, error) {
a.mu.Lock()
defer a.mu.Unlock()
res, err := fn.Invoke(scope, a.Val)
if err != nil {
return nil, err
}
a.Val = res
return res, nil
}
func (a *Atom) GetVal() Value {
a.mu.RLock()
defer a.mu.RUnlock()
return a.Val
}
func (a *Atom) String() string {
return fmt.Sprintf("(atom %v)", a.GetVal())
}
func (a *Atom) Eval(_ Scope) (Value, error) {
return ValueOf(a), nil
}
func NewAtom(val Value) *Atom {
return &Atom{Val: val}
}