-
Notifications
You must be signed in to change notification settings - Fork 2
Expand file tree
/
Copy pathfunction.go
More file actions
477 lines (438 loc) · 11.2 KB
/
function.go
File metadata and controls
477 lines (438 loc) · 11.2 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
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
// Copyright (c) 2022, Peter Ohler, All rights reserved.
package slip
import (
"fmt"
"strings"
)
const (
// BuiltInSymbol is the symbol with a value of "built-in".
BuiltInSymbol = Symbol("built-in")
// FunctionSymbol is the symbol with a value of "function".
FunctionSymbol = Symbol("function")
// MacroSymbol is the symbol with a value of "macro".
MacroSymbol = Symbol("macro")
// LambdaSymbol is the symbol with a value of "lambda".
LambdaSymbol = Symbol("lambda")
// FlosSymbol is the symbol with a value of "flos-function" for FLOS functions.
FlosSymbol = Symbol("flos-function")
// MethodSymbol is the symbol with a value of "method" for Flavors
// methods.
MethodSymbol = Symbol("method")
// GenericFunctionSymbol is the symbol with a value of "generic-function"
// for CLOS generics and methods.
GenericFunctionSymbol = Symbol("generic-function")
)
// Function is the base type for most if not all functions.
type Function struct {
// Name of the function.
Name string
// Args are the un-evaluated and un-compiled arguments.
Args List
// Self points to the encapsulating object.
Self Caller
// SkipEval is a slice of flags indicating which arguments should be
// evaluated before calling Self.Call(). The last bool is the value used
// for &rest arguments if present.
SkipEval []bool
Pkg *Package
}
// Define a new golang function. If the package is provided the function is
// added to that package otherwise it is added to CurrentPackage (*package*).
func Define(creator func(args List) Object, doc *FuncDoc, pkgs ...*Package) {
pkg := CurrentPackage
if 0 < len(pkgs) {
pkg = pkgs[0]
}
_ = pkg.Define(creator, doc)
}
// NewFunc creates a new instance of the named function with the arguments
// provided.
func NewFunc(name string, args List, pkgs ...*Package) Funky {
fi := MustFindFunc(name, pkgs...)
f, _ := fi.Create(args).(Funky)
f.setPkg(fi.Pkg)
return f
}
// MustFindFunc finds the FuncInfo for a provided name or panics if none exists.
func MustFindFunc(name string, pkgs ...*Package) *FuncInfo {
if fi := FindFunc(name, pkgs...); fi != nil {
return fi
}
pkg := CurrentPackage
if 0 < len(pkgs) {
pkg = pkgs[0]
}
panic(UndefinedFunctionNew(NewScope(), 0, Symbol(name), "Function %s is not defined in %s.",
printer.caseName(name), pkg.Name))
}
// FindFunc finds the FuncInfo for a provided name or return nil if none exists.
func FindFunc(name string, pkgs ...*Package) (fi *FuncInfo) {
// private indicates non-exported okay, referenced with ::
pkg, vname, private := UnpackName(name)
if pkg == nil {
pkg = CurrentPackage
if 0 < len(pkgs) {
pkg = pkgs[0]
}
}
if fi = pkg.funcs[vname]; fi == nil {
vname = strings.ToLower(vname)
fi = pkg.funcs[vname]
}
if fi != nil {
if private || fi.Export || CurrentPackage == fi.Pkg {
return fi
}
fi = nil
}
return
}
// Eval the object.
func (f *Function) Eval(s *Scope, depth int) (result Object) {
beforeEval(s, f.Name, f.Args, depth)
defer afterEval(s, f.Name, f.Args, depth, &result)
args := make(List, len(f.Args))
d2 := depth + 1
si := -1
var update []int
for i, arg := range f.Args {
si++
skip := false
if 0 < len(f.SkipEval) {
if len(f.SkipEval) <= si {
if f.SkipEval[len(f.SkipEval)-1] {
skip = true
args[i] = arg
if _, ok := arg.(List); ok {
update = append(update, i)
}
continue
}
} else if f.SkipEval[si] {
skip = true
args[i] = arg
if _, ok := arg.(List); ok {
update = append(update, i)
}
continue
}
}
if list, ok := arg.(List); ok {
arg = ListToFunc(s, list, depth+1)
f.Args[i] = arg
}
v := s.Eval(arg, d2)
if vs, ok := v.(Values); ok && !skip {
v = vs[0]
}
args[i] = v
}
result = f.Self.Call(s, args, depth)
// If there are any .Args that need updating to the function version do
// that by taking the compiled version from the args.
for _, u := range update {
a := args[u]
if _, ok := a.(Funky); ok {
f.Args[u] = a
}
}
return
}
// SkipArgEval returns true if the argument eval should be skipped.
func (f *Function) SkipArgEval(i int) (skip bool) {
if 0 < len(f.SkipEval) {
if i < len(f.SkipEval) {
skip = f.SkipEval[i]
} else {
skip = f.SkipEval[len(f.SkipEval)-1]
}
}
return
}
// Apply evaluates with the need to evaluate the args.
func (f *Function) Apply(s *Scope, args List, depth int) (result Object) {
beforeEval(s, f.Name, args, depth)
defer afterEval(s, f.Name, args, depth, &result)
return f.Self.Call(s, args, depth)
}
// String representation of the Object.
func (f *Function) String() string {
return string(f.Append([]byte{}))
}
// Append a buffer with a representation of the Object.
func (f *Function) Append(b []byte) []byte {
b = append(b, '(')
b = printer.Append(b, Symbol(f.Name), 0)
for _, a := range f.Args {
b = append(b, ' ')
b = Append(b, a)
}
return append(b, ')')
}
// Simplify the function.
func (f *Function) Simplify() any {
simple := make([]any, 0, len(f.Args)+1)
simple = append(simple, f.Name)
for _, a := range f.Args {
simple = append(simple, Simplify(a))
}
return simple
}
// Equal returns true if this Object and the other are equal in value.
func (f *Function) Equal(other Object) bool {
if of, ok := other.(Funky); ok {
if f.Name == of.GetName() {
oargs := of.GetArgs()
if len(f.Args) == len(oargs) {
for i, a := range f.Args {
if !ObjectEqual(a, oargs[i]) {
return false
}
}
return true
}
}
}
return false
}
// Hierarchy returns the class hierarchy as symbols for the instance.
func (f *Function) Hierarchy() []Symbol {
var fi *FuncInfo
if f.Pkg == nil {
fi = FindFunc(f.Name)
} else {
fi = FindFunc(f.Name, f.Pkg)
}
if fi != nil {
return fi.Hierarchy()
}
for _, skip := range f.SkipEval {
if skip {
return []Symbol{MacroSymbol, TrueSymbol}
}
}
return []Symbol{FunctionSymbol, TrueSymbol}
}
// GetArgs returns the function arguments.
func (f *Function) GetArgs() List {
return f.Args
}
// GetName returns the function name.
func (f *Function) GetName() string {
return f.Name
}
// LoadForm returns a form that can be evaluated to create the object.
func (f *Function) LoadForm() Object {
form := make(List, len(f.Args)+1)
form[0] = Symbol(f.Name)
for i, a := range f.Args {
if a != nil {
if f.SkipArgEval(i) {
form[i+1] = a
} else {
switch ta := a.(type) {
case nil:
// already nil
case LoadFormer:
form[i+1] = ta.LoadForm()
default:
PrintNotReadablePanic(NewScope(), 0, ta, "Can not make a load form for %s.", ta)
}
}
}
}
return form
}
// ListToFunc converts a list to a function.
func ListToFunc(s *Scope, list List, depth int) Object {
if len(list) == 0 {
return nil
}
switch ta := list[0].(type) {
case Symbol:
return NewFunc(string(ta), list[1:])
case List:
if 1 < len(ta) {
if sym, ok := ta[0].(Symbol); ok {
if strings.EqualFold("lambda", string(sym)) {
lambdaDef := ListToFunc(s, ta, depth+1)
lc := s.Eval(lambdaDef, depth).(*Lambda)
return &Dynamic{
Function: Function{
Self: lc,
Args: list[1:],
},
}
}
}
}
}
cond := ErrorNew(s, depth, "|%s| is not a function", ObjectString(list[0]))
panic(cond)
}
// CompileArgs for the function.
func (f *Function) CompileArgs() {
si := -1
for i := 0; i < len(f.Args); i++ {
si++
arg := f.Args[i]
if 0 < len(f.SkipEval) {
if len(f.SkipEval) <= si {
if !f.SkipEval[len(f.SkipEval)-1] {
if alist, ok := arg.(List); ok {
f.Args[i] = CompileList(alist)
}
}
} else if !f.SkipEval[si] {
if alist, ok := arg.(List); ok {
f.Args[i] = CompileList(alist)
}
}
} else if alist, ok := arg.(List); ok {
f.Args[i] = CompileList(alist)
}
}
}
// Caller returns the function's Caller (Self).
func (f *Function) Caller() Caller {
return f.Self
}
// CompileList a list into a function or an undefined function.
func CompileList(list List) (f Object) {
if 0 < len(list) {
switch ta := list[0].(type) {
case Symbol:
name := strings.ToLower(string(ta))
if fi := CurrentPackage.funcs[name]; fi != nil {
f = fi.Create(list[1:])
} else {
lc := Lambda{
Doc: &FuncDoc{
Name: name,
Args: []*DocArg{},
},
Forms: List{Undefined(name)},
}
CurrentPackage.lambdas[name] = &lc
fc := func(args List) Object {
return &Dynamic{
Function: Function{
Name: name,
Self: &lc,
},
}
}
CurrentPackage.funcs[name] = &FuncInfo{Create: fc, Pkg: CurrentPackage, Export: true}
f = fc(list[1:])
}
if funk, ok := f.(Funky); ok {
funk.CompileArgs()
}
case List:
if 1 < len(ta) {
if sym, ok := ta[0].(Symbol); ok {
if strings.EqualFold("lambda", string(sym)) {
s := NewScope()
lambdaDef := ListToFunc(s, ta, 0)
lc := s.Eval(lambdaDef, 0).(*Lambda)
return &Dynamic{
Function: Function{
Self: lc,
Args: list[1:],
},
}
}
}
}
}
}
return
}
// DescribeFunction returns the documentation for the function bound to the
// sym argument.
func DescribeFunction(sym Symbol, pkg ...*Package) *FuncDoc {
name := strings.ToLower(string(sym))
p := CurrentPackage
if 0 < len(pkg) {
p = pkg[0]
}
if fi, has := p.funcs[name]; has {
return fi.Doc
}
return nil
}
// EvalArg converts lists arguments to functions and replaces the
// argument. Then the argument is evaluated and returned. Non-list arguments
// are just evaluated.
func EvalArg(s *Scope, args List, index, depth int) (v Object) {
if list, ok := args[index].(List); ok {
args[index] = ListToFunc(s, list, depth+1)
}
v = s.Eval(args[index], depth)
if list, ok := v.(List); ok && len(list) == 0 {
v = nil
}
return
}
// GetArgsKeyValue returns the value for a key in args. Args must be the
// arguments after any required or optional arguments.
func GetArgsKeyValue(args List, key Symbol) (value Object, has bool) {
for pos := 0; pos < len(args); pos += 2 {
sym, ok := args[pos].(Symbol)
if !ok {
TypePanic(NewScope(), 0, "keyword", args[pos], "keyword")
}
if len(args)-1 <= pos {
panic(fmt.Sprintf("%s missing an argument", sym))
}
if strings.EqualFold(string(key), string(sym)) {
value = args[pos+1]
has = true
break
}
}
return
}
// MustBeString returns a string if the arg is a symbol or string. If not a
// type error is raised with the name argument as the expected field in the
// error.
func MustBeString(arg Object, name string) (str string) {
switch ta := arg.(type) {
case String:
str = string(ta)
case Symbol:
if 0 < len(ta) && ta[0] == ':' {
str = string(ta[1:])
} else {
str = string(ta)
}
default:
TypePanic(NewScope(), 0, name, arg, "string", "symbol")
}
return
}
func (f *Function) setPkg(p *Package) {
f.Pkg = p
}
// GetPkg returns the package the function was defined in.
func (f *Function) GetPkg() *Package {
return f.Pkg
}
// PackageFromArg returns a package from an argument or panics.
func PackageFromArg(arg Object) (pkg *Package) {
switch tv := arg.(type) {
case Symbol:
if 0 < len(tv) && tv[0] == ':' {
pkg = FindPackage(string(tv[1:]))
} else {
pkg = FindPackage(string(tv))
}
case String:
pkg = FindPackage(string(tv))
case *Package:
pkg = tv
default:
TypePanic(NewScope(), 0, "package", tv, "symbol", "string", "package")
}
return
}