-
Notifications
You must be signed in to change notification settings - Fork 2
Expand file tree
/
Copy pathlambda.go
More file actions
355 lines (338 loc) · 8.15 KB
/
lambda.go
File metadata and controls
355 lines (338 loc) · 8.15 KB
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
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
// Copyright (c) 2022, Peter Ohler, All rights reserved.
package slip
import (
"fmt"
"strings"
)
const (
reqMode = 0
optMode = 1
restMode = 2
keyMode = 3
auxMode = 4
)
// Lambda is a Caller for forms/objects. It provides a level of
// indirection so that functions can be defined without regard to the order
// defined.
type Lambda struct {
Doc *FuncDoc
Forms List
Closure *Scope
Macro bool
}
// Call the the function with the arguments provided.
func (lam *Lambda) Call(s *Scope, args List, depth int) (result Object) {
ss := s.NewScope()
if lam.Closure != nil {
ss.parents = append(ss.parents, lam.Closure)
ss.Macro = lam.Closure.Macro
} else if s.Keep { // flavors instance uses this
ss.parents = append(ss.parents, s)
}
ss.Macro = ss.Macro || lam.Macro
ss.Block = true
if 0 < len(lam.Doc.Name) {
ss.Name = Symbol(lam.Doc.Name)
}
mode := reqMode
ai := 0
var (
rest List
restSym Symbol
)
Aux:
for i, ad := range lam.Doc.Args {
if len(args) <= ai {
break
}
Mode:
switch mode {
case reqMode:
switch strings.ToLower(ad.Name) {
case AmpOptional:
mode = optMode
case AmpRest, AmpBody:
mode = restMode
case AmpKey:
mode = keyMode
case AmpAux: // should not be possible to get here without an error later
break Aux
case AmpAllowOtherKeys:
// ignore
default:
ss.Let(Symbol(ad.Name), args[ai])
ai++
}
case optMode:
switch strings.ToLower(ad.Name) {
case AmpRest, AmpBody:
mode = restMode
case AmpKey:
mode = keyMode
case AmpAux:
break Aux
case AmpAllowOtherKeys:
// ignore
default:
ss.Let(Symbol(ad.Name), args[ai])
ai++
}
case restMode:
for ai < len(args) {
a := args[ai]
if sym, ok := a.(Symbol); ok && 0 < len(sym) && sym[0] == ':' {
sym = sym[1:]
for j := i + 1; j < len(lam.Doc.Args); j++ {
if string(sym) == lam.Doc.Args[j].Name {
mode = keyMode
break Mode
}
}
}
ai++
if len(restSym) == 0 {
restSym = Symbol(ad.Name)
}
rest = append(rest, a)
}
case keyMode:
for ai < len(args) {
a := args[ai]
ai++
if sym, ok := a.(Symbol); ok && 0 < len(sym) && sym[0] == ':' {
sym = sym[1:]
if len(args) <= ai {
panic(fmt.Sprintf("Missing value for key :%s.", sym))
}
ss.Let(sym, args[ai])
ai++
continue
}
TypePanic(s, depth, "keyword to function", a, "symbol")
}
}
}
if ai < len(args) {
ErrorPanic(s, depth, "Too many arguments to %s. There are %d extra.", lam, ai+1)
}
if 0 < len(rest) {
ss.Let(restSym, rest)
}
// Next bind any unbound &key vars
mode = reqMode
for _, ad := range lam.Doc.Args {
switch mode {
case reqMode:
switch strings.ToLower(ad.Name) {
case AmpOptional:
mode = optMode
case AmpRest, AmpBody:
mode = restMode
case AmpKey:
mode = keyMode
case AmpAux:
mode = auxMode
case AmpAllowOtherKeys:
// ignore
}
case optMode:
switch strings.ToLower(ad.Name) {
case AmpRest, AmpBody:
mode = restMode
case AmpKey:
mode = keyMode
case AmpAux:
mode = auxMode
case AmpAllowOtherKeys:
// ignore
default:
if !ss.Bound(Symbol(ad.Name)) {
ss.Let(Symbol(ad.Name), ad.Default)
}
}
case restMode:
switch strings.ToLower(ad.Name) {
case AmpKey:
mode = keyMode
case AmpAux:
mode = auxMode
case AmpAllowOtherKeys:
// ignore
default:
if !ss.Bound(Symbol(ad.Name)) {
ss.Let(Symbol(ad.Name), ad.Default)
}
}
case keyMode:
asym := Symbol(ad.Name)
if AmpAux == asym {
mode = auxMode
} else if !ss.Bound(asym) {
ss.Let(asym, ad.Default)
}
case auxMode:
val := ad.Default
if list, ok := val.(List); ok && 1 < len(list) {
d2 := depth + 1
val = ss.Eval(ListToFunc(ss, list, d2), d2)
}
ss.Let(Symbol(ad.Name), val)
}
}
return lam.BoundCall(ss, depth)
}
// BoundCall the the function with the bindings provided.
func (lam *Lambda) BoundCall(s *Scope, depth int) (result Object) {
d2 := depth + 1
for _, form := range lam.Forms {
result = s.Eval(form, d2)
if rr, ok := result.(*ReturnResult); ok {
if rr.Tag == s.Name && s.Name != Symbol("lambda") {
result = rr.Result
}
break
}
}
return
}
// DefLambda parses arguments into a Lambda. Arguments should be a lambda-list
// followed by an optional documentation strings and then the forms to
// evaluate when the Lambda is called. The extraVars is a list of variables
// that will be defined when the lambda is called. This is used for methods
// where the scope will be an instance of a flavor/class.
func DefLambda(defName string, s *Scope, args List, extraVars ...string) (lam *Lambda) {
var ll List
switch tl := args[0].(type) {
case List:
ll = tl
case nil:
// leave as empty list
default:
TypePanic(s, 0, fmt.Sprintf("lambda list of %s", defName), tl, "list")
}
var (
docStr String
ok bool
)
args = args[1:]
if 1 < len(args) {
if docStr, ok = args[0].(String); ok {
args = args[1:]
}
}
lam = &Lambda{
Doc: &FuncDoc{
Name: defName,
Return: "object",
Text: string(docStr),
Kind: LambdaSymbol,
},
Forms: args,
}
for _, a := range ll {
switch ta := a.(type) {
case Symbol: // variable name
lam.Doc.Args = append(lam.Doc.Args, &DocArg{Name: string(ta), Type: "object"})
case List: // variable name and default value
if len(ta) != 2 {
TypePanic(s, 0, "lambda list element with default value", ta, "list of two elements")
}
var name Symbol
if name, ok = ta[0].(Symbol); !ok {
TypePanic(s, 0, "lambda list element with default value", ta, "list with a symbol as the first element")
}
if ta[1] == nil {
lam.Doc.Args = append(lam.Doc.Args, &DocArg{Name: string(name), Type: "object"})
} else {
lam.Doc.Args = append(lam.Doc.Args,
&DocArg{Name: string(name), Type: string(ta[1].Hierarchy()[0]), Default: ta[1]})
}
default:
TypePanic(s, 0, "lambda list element", ta, "symbol", "list")
}
}
lam.Compile(s, extraVars...)
return
}
// Compile forms while in the current package instead of waiting until
// invoked.
func (lam *Lambda) Compile(s *Scope, extraVars ...string) {
for i, f := range lam.Forms {
expand:
switch tf := f.(type) {
case Symbol:
if s.has(string(tf)) || lam.Doc.getArg(string(tf)) != nil {
break
}
for _, vn := range extraVars {
if vn == string(tf) {
break expand
}
}
vv := CurrentPackage.GetVarVal(string(tf))
if vv == nil {
CurrentPackage.mu.Lock()
if vv = CurrentPackage.vars[string(tf)]; vv == nil {
vv = newUnboundVar(string(tf))
CurrentPackage.vars[string(tf)] = vv
}
CurrentPackage.mu.Unlock()
}
lam.Forms[i] = vv
case List:
lam.Forms[i] = CompileList(tf)
}
}
}
// String representation of the Object.
func (lam *Lambda) String() string {
return string(lam.Append([]byte{}))
}
// Append a buffer with a representation of the Object.
func (lam *Lambda) Append(b []byte) []byte {
return printer.Append(b, lam, 0)
}
// Equal returns true if this Object and the other are equal in value.
func (lam *Lambda) Equal(other Object) bool {
return lam == other
}
// Hierarchy returns the class hierarchy as symbols for the instance.
func (lam *Lambda) Hierarchy() []Symbol {
return []Symbol{LambdaSymbol, TrueSymbol}
}
// Simplify the function.
func (lam *Lambda) Simplify() any {
simple := make([]any, 0, len(lam.Forms)+2)
simple = append(simple, "lambda")
args := make([]any, 0, len(lam.Doc.Args))
for _, ad := range lam.Doc.Args {
args = append(args, ad.Name)
}
simple = append(simple, args)
for i := len(lam.Forms) - 1; 0 <= i; i-- {
simple = append(simple, Simplify(lam.Forms[i]))
}
return simple
}
// Eval the object.
func (lam *Lambda) Eval(s *Scope, depth int) (result Object) {
return lam
}
// Docs returns the documentation of the instance.
func (lam *Lambda) Docs() (docs string) {
if lam.Doc != nil {
docs = lam.Doc.Text
}
return
}
// LoadForm returns a definition list such as (lambda (x) (1+ x)).
func (lam *Lambda) LoadForm() Object {
var dl List
dl = append(dl, Symbol("lambda"))
dl = append(dl, lam.Doc.LoadForm())
if 0 < len(lam.Doc.Text) {
dl = append(dl, String(lam.Doc.Text))
}
dl = append(dl, lam.Forms...)
return dl
}