-
Notifications
You must be signed in to change notification settings - Fork 0
/
compiler.go
533 lines (507 loc) · 13.9 KB
/
compiler.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
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
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
/*
Copyright 2015 Lee Boynton
Licensed under the Apache License, Version 2.0 (the "License");
you may not use this file except in compliance with the License.
You may obtain a copy of the License at
http://www.apache.org/licenses/LICENSE-2.0
Unless required by applicable law or agreed to in writing, software
distributed under the License is distributed on an "AS IS" BASIS,
WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
See the License for the specific language governing permissions and
limitations under the License.
*/
package ell
import (
"fmt"
. "github.com/boynton/ell/data"
)
var _ = fmt.Println
// Compile - compile the source into a code object.
func Compile(expr Value) (*Code, error) {
target := MakeCode(0, nil, nil, "")
err := compileExpr(target, EmptyList, expr, false, false, "")
if err != nil {
return nil, err
}
target.emitReturn()
return target, nil
}
func calculateLocation(sym Value, env *List) (int, int, bool) {
i := 0
for env != EmptyList {
j := 0
ee := env.Car
for ee != EmptyList {
if Car(ee) == sym {
return i, j, true
}
j++
ee = Cdr(ee)
}
i++
env = env.Cdr
}
return -1, -1, false
}
func compileSelfEvalLiteral(target *Code, expr Value, isTail bool, ignoreResult bool) error {
if !ignoreResult {
target.emitLiteral(expr)
if isTail {
target.emitReturn()
}
}
return nil
}
func compileSymbol(target *Code, env *List, expr Value, isTail bool, ignoreResult bool) error {
if GetMacro(expr) != nil {
return NewError(Intern("macro-error"), "Cannot use macro as a value: ", expr)
}
if i, j, ok := calculateLocation(expr, env); ok {
target.emitLocal(i, j)
} else {
target.emitGlobal(expr)
}
if ignoreResult {
target.emitPop()
} else if isTail {
target.emitReturn()
}
return nil
}
func compileQuote(target *Code, expr Value, isTail bool, ignoreResult bool, lstlen int) error {
if lstlen != 2 {
return NewError(SyntaxErrorKey, expr)
}
if !ignoreResult {
target.emitLiteral(Cadr(expr))
if isTail {
target.emitReturn()
}
}
return nil
}
func compileDef(target *Code, env *List, lst Value, isTail bool, ignoreResult bool, lstlen int) error {
if lstlen < 3 {
return NewError(SyntaxErrorKey, lst)
}
sym := Cadr(lst)
val := Caddr(lst)
err := compileExpr(target, env, val, false, false, sym.String())
if err == nil {
target.emitDefGlobal(sym)
if ignoreResult {
target.emitPop()
} else if isTail {
target.emitReturn()
}
}
return err
}
func compileUndef(target *Code, lst Value, isTail bool, ignoreResult bool, lstlen int) error {
if lstlen != 2 {
return NewError(SyntaxErrorKey, lst)
}
sym := Cadr(lst)
if !IsSymbol(sym) {
return NewError(SyntaxErrorKey, lst)
}
target.emitUndefGlobal(sym)
if ignoreResult {
} else {
target.emitLiteral(sym)
if isTail {
target.emitReturn()
}
}
return nil
}
func compileMacro(target *Code, env *List, expr Value, isTail bool, ignoreResult bool, lstlen int) error {
if lstlen != 3 {
return NewError(SyntaxErrorKey, expr)
}
var sym = Cadr(expr)
if !IsSymbol(sym) {
return NewError(SyntaxErrorKey, expr)
}
err := compileExpr(target, env, Caddr(expr), false, false, sym.String())
if err != nil {
return err
}
if err == nil {
target.emitDefMacro(sym)
if ignoreResult {
target.emitPop()
} else if isTail {
target.emitReturn()
}
}
return err
}
func compileSet(target *Code, env *List, lst Value, isTail bool, ignoreResult bool, context string, lstlen int) error {
if lstlen != 3 {
return NewError(SyntaxErrorKey, lst)
}
var sym = Cadr(lst)
if !IsSymbol(sym) {
return NewError(SyntaxErrorKey, lst)
}
err := compileExpr(target, env, Caddr(lst), false, false, context)
if err != nil {
return err
}
if i, j, ok := calculateLocation(sym, env); ok {
target.emitSetLocal(i, j)
} else {
target.emitDefGlobal(sym) //fix, should be SetGlobal
}
if ignoreResult {
target.emitPop()
} else if isTail {
target.emitReturn()
}
return nil
}
func compileList(target *Code, env *List, expr Value, isTail bool, ignoreResult bool, context string) error {
if expr == EmptyList {
if !ignoreResult {
target.emitLiteral(expr)
if isTail {
target.emitReturn()
}
}
return nil
}
lst := expr
lstlen := ListLength(lst)
if lstlen == 0 {
return NewError(SyntaxErrorKey, lst)
}
fn := Car(lst)
switch fn {
case Intern("quote"):
// (quote <datum>)
return compileQuote(target, expr, isTail, ignoreResult, lstlen)
case Intern("do"): // a sequence of expressions, for side-effect only
// (do <expr> ...)
return compileSequence(target, env, Cdr(lst), isTail, ignoreResult, context)
case Intern("if"):
// (if pred consequent)
// (if pred consequent antecedent)
if lstlen == 3 || lstlen == 4 {
return compileIfElse(target, env, Cadr(expr), Caddr(expr), Cdddr(expr), isTail, ignoreResult, context)
}
return NewError(SyntaxErrorKey, expr)
case Intern("def"):
// (def <name> <val>)
return compileDef(target, env, expr, isTail, ignoreResult, lstlen)
case Intern("undef"):
// (undef <name>)
return compileUndef(target, expr, isTail, ignoreResult, lstlen)
case Intern("defmacro"):
// (defmacro <name> (fn args & body))
return compileMacro(target, env, expr, isTail, ignoreResult, lstlen)
case Intern("fn"):
// (fn () <expr> ...)
// (fn (sym ...) <expr> ...) ;; binds arguments to successive syms
// (fn (sym ... & rsym) <expr> ...) ;; all args after the & are collected and bound to rsym
// (fn (sym ... [sym sym]) <expr> ...) ;; all args up to the vector are required, the rest are optional
// (fn (sym ... [(sym val) sym]) <expr> ...) ;; default values can be provided to optional args
// (fn (sym ... {sym: def sym: def}) <expr> ...) ;; required args, then keyword args
// (fn (& sym) <expr> ...) ;; all args in a list, bound to sym. Same as the following form.
// (fn sym <expr> ...) ;; all args in a list, bound to sym
if lstlen < 3 {
return NewError(SyntaxErrorKey, expr)
}
body := Cddr(lst)
args := Cadr(lst)
return compileFn(target, env, args, body, isTail, ignoreResult, context)
case Intern("set!"):
// (set! <sym> <val>)
return compileSet(target, env, expr, isTail, ignoreResult, context, lstlen)
case Intern("code"):
// (code <instruction> ...)
return target.loadOps(Cdr(expr))
case Intern("use"):
// (use module_name)
return compileUse(target, Cdr(lst))
default: // a funcall
// (<fn>)
// (<fn> <arg> ...)
fn, args := fn, Cdr(lst)
if optimize {
fn, args = optimizeFuncall(fn, args)
}
return compileFuncall(target, env, fn, args, isTail, ignoreResult, context)
}
}
func compileVector(target *Code, env *List, vec *Vector, isTail bool, ignoreResult bool, context string) error {
//vector literal: the elements are evaluated
vlen := len(vec.Elements)
for i := vlen - 1; i >= 0; i-- {
obj := vec.Elements[i]
err := compileExpr(target, env, obj, false, false, context)
if err != nil {
return err
}
}
if !ignoreResult {
target.emitVector(vlen)
if isTail {
target.emitReturn()
}
}
return nil
}
func compileStruct(target *Code, env *List, strct *Struct, isTail bool, ignoreResult bool, context string) error {
//struct literal: the elements are evaluated
vlen := len(strct.Bindings) * 2
vals := make([]Value, 0, vlen)
for k, v := range strct.Bindings {
vals = append(vals, k.ToValue())
vals = append(vals, v)
}
for i := vlen - 1; i >= 0; i-- {
obj := vals[i]
err := compileExpr(target, env, obj, false, false, context)
if err != nil {
return err
}
}
if !ignoreResult {
target.emitStruct(vlen)
if isTail {
target.emitReturn()
}
}
return nil
}
func compileExpr(target *Code, env *List, expr Value, isTail bool, ignoreResult bool, context string) error {
switch p := expr.(type) {
case *Keyword:
return compileSelfEvalLiteral(target, expr, isTail, ignoreResult)
case *Type:
return compileSelfEvalLiteral(target, expr, isTail, ignoreResult)
case *Symbol:
return compileSymbol(target, env, p, isTail, ignoreResult)
case *List:
return compileList(target, env, p, isTail, ignoreResult, context)
case *Vector:
return compileVector(target, env, p, isTail, ignoreResult, context)
case *Struct:
return compileStruct(target, env, p, isTail, ignoreResult, context)
}
if !ignoreResult {
target.emitLiteral(expr)
if isTail {
target.emitReturn()
}
}
return nil
}
func compileFn(target *Code, env *List, args Value, body *List, isTail bool, ignoreResult bool, context string) error {
argc := 0
var syms []Value
var defaults []Value
var keys []Value
tmp := args
rest := false
if !IsSymbol(args) {
if IsVector(tmp) {
//clojure style. Should this be an error?
tmp, _ = ToList(tmp)
}
for tmp != EmptyList {
a := Car(tmp)
if vec, ok := a.(*Vector); ok {
//i.e. (x [y (z 23)]) is for optional y and z, but bound, z with default 23
if Cdr(tmp) != EmptyList {
return NewError(SyntaxErrorKey, tmp)
}
defaults = make([]Value, 0, len(vec.Elements))
for _, sym := range vec.Elements {
def := Null
if lst, ok := sym.(*List); ok {
def = Cadr(lst)
sym = lst.Car
}
if !IsSymbol(sym) {
return NewError(SyntaxErrorKey, tmp)
}
syms = append(syms, sym)
defaults = append(defaults, def)
}
tmp = EmptyList
break
} else if strct, ok := a.(*Struct); ok {
//i.e. (x {y: 23, z: 57}]) is for optional y and z, keyword args, with defaults
if Cdr(tmp) != EmptyList {
return NewError(SyntaxErrorKey, tmp)
}
slen := len(strct.Bindings)
defaults = make([]Value, 0, slen)
keys = make([]Value, 0, slen)
for k, defValue := range strct.Bindings {
sym := k.ToValue()
if IsList(sym) && Car(sym) == Intern("quote") && Cdr(sym) != EmptyList {
sym = Cadr(sym)
} else {
var err error
sym, err = Unkeyworded(sym) //returns sym itself if not a keyword, otherwise strips the colon
if err != nil { //not a symbol or keyword
return NewError(SyntaxErrorKey, tmp)
}
}
if !IsSymbol(sym) {
return NewError(SyntaxErrorKey, tmp)
}
syms = append(syms, sym)
keys = append(keys, sym)
defaults = append(defaults, defValue)
}
tmp = EmptyList
break
} else if !IsSymbol(a) {
return NewError(SyntaxErrorKey, tmp)
}
if a == Intern("&") { //the rest of the arglist is bound to a single variable
//note that the & annotation is optional if what follows is a struct or vector
rest = true
} else {
if rest {
syms = append(syms, a) //note: added, but argv not incremented
defaults = make([]Value, 0)
tmp = EmptyList
break
}
argc++
syms = append(syms, a)
}
tmp = Cdr(tmp)
}
}
if tmp != EmptyList { //remainder of the arglist bound to a single variable
if IsSymbol(tmp) {
syms = append(syms, tmp) //note: added, but argv not incremented
defaults = make([]Value, 0)
} else {
return NewError(SyntaxErrorKey, tmp)
}
}
args = ListFromValues(syms) //why not just use the vector format in general?
newEnv := Cons(args, env)
fnCode := MakeCode(argc, defaults, keys, context)
err := compileSequence(fnCode, newEnv, body, true, false, context)
if err == nil {
if !ignoreResult {
target.emitClosure(fnCode)
if isTail {
target.emitReturn()
}
}
}
return err
}
func compileSequence(target *Code, env *List, exprs *List, isTail bool, ignoreResult bool, context string) error {
if exprs != EmptyList {
for Cdr(exprs) != EmptyList {
err := compileExpr(target, env, Car(exprs), false, true, context)
if err != nil {
return err
}
exprs = Cdr(exprs)
}
return compileExpr(target, env, Car(exprs), isTail, ignoreResult, context)
}
return NewError(SyntaxErrorKey, Cons(Intern("do"), exprs))
}
func optimizeFuncall(fn Value, args *List) (Value, *List) {
size := ListLength(args)
if size == 2 {
switch fn {
case Intern("+"):
if Equal(One, Car(args)) { // (+ 1 x) -> inc x)
return Intern("inc"), Cdr(args)
} else if Equal(One, Cadr(args)) { // (+ x 1) -> (inc x)
return Intern("inc"), NewList(Car(args))
}
case Intern("-"):
if Equal(One, Cadr(args)) { // (- x 1) -> (dec x)
return Intern("dec"), NewList(Car(args))
}
}
}
return fn, args
}
func compileFuncall(target *Code, env *List, fn Value, args *List, isTail bool, ignoreResult bool, context string) error {
argc := ListLength(args)
if argc < 0 {
return NewError(SyntaxErrorKey, Cons(fn, args))
}
err := compileArgs(target, env, args, context)
if err != nil {
return err
}
err = compileExpr(target, env, fn, false, false, context)
if err != nil {
return err
}
if isTail {
target.emitTailCall(argc)
} else {
target.emitCall(argc)
if ignoreResult {
target.emitPop()
}
}
return nil
}
func compileArgs(target *Code, env *List, args Value, context string) error {
if args != EmptyList {
err := compileArgs(target, env, Cdr(args), context)
if err != nil {
return err
}
return compileExpr(target, env, Car(args), false, false, context)
}
return nil
}
func compileIfElse(target *Code, env *List, predicate Value, Consequent Value, antecedentOptional Value, isTail bool, ignoreResult bool, context string) error {
antecedent := Null
if antecedentOptional != EmptyList {
antecedent = Car(antecedentOptional)
}
err := compileExpr(target, env, predicate, false, false, context)
if err != nil {
return err
}
loc1 := target.emitJumpFalse(0) //returns the location just *after* the jump. setJumpLocation knows this.
err = compileExpr(target, env, Consequent, isTail, ignoreResult, context)
if err != nil {
return err
}
loc2 := 0
if !isTail {
loc2 = target.emitJump(0)
}
target.setJumpLocation(loc1)
err = compileExpr(target, env, antecedent, isTail, ignoreResult, context)
if err == nil {
if !isTail {
target.setJumpLocation(loc2)
}
}
return err
}
func compileUse(target *Code, rest *List) error {
lstlen := ListLength(rest)
if lstlen != 1 {
//to do: other options for use.
return NewError(SyntaxErrorKey, Cons(Intern("use"), rest))
}
sym := Car(rest)
if !IsSymbol(sym) {
return NewError(SyntaxErrorKey, rest)
}
target.emitUse(sym)
return nil
}