summaryrefslogtreecommitdiff
path: root/module/language/lua/compile-tree-il.scm
blob: 4472b05f3829119c8a08c23d38082b7c46035e87 (plain)
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
;;; Guile Lua --- compiler

;;; Copyright (C) 2010 Free Software Foundation, Inc.
;;;
;;; This library is free software; you can redistribute it and/or
;;; modify it under the terms of the GNU Lesser General Public
;;; License as published by the Free Software Foundation; either
;;; version 3 of the License, or (at your option) any later version.
;;;
;;; This library is distributed in the hope that it will be useful,
;;; but WITHOUT ANY WARRANTY; without even the implied warranty of
;;; MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the GNU
;;; Lesser General Public License for more details.
;;;
;;; You should have received a copy of the GNU Lesser General Public
;;; License along with this library; if not, write to the Free Software
;;; Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA

;;; Code:

(define-module (language lua compile-tree-il)
  #:use-module (language tree-il)
  #:use-module (srfi srfi-1)
  #:use-module (srfi srfi-39)
  #:use-module ((system base syntax) #:select (record-case))
  #:use-module (rnrs control)
  #:use-module (language lua common)
  #:use-module (language lua parser)
  #:use-module (language lua runtime)
  #:export (compile-tree-il))

;; utilities

(define *runtime-name* '(language lua runtime))
(define no-arguments '(() #f #f #f () ()))


(define (ref-runtime src name)
  "Shorthand for referring to a variable in the (language lua runtime) module"
  (make-module-ref src *runtime-name* name #t))

(define (make-runtime-application src name arguments)
  "Shorthand for creating an application of a function in the (language lua runtime) module"
  (make-call src (ref-runtime src name) arguments))

(define (make-table-ref src table index)
  "Shorthand for calling the index function in (language lua runtime)"
  (make-runtime-application src 'index
    (list table (if (symbol? index) (make-const src (symbol->string index)) index))))

(define (make-table-set! src table index exp)
  "Shorthand for calling the new-index! function in (language lua runtime)"
  (make-runtime-application src 'new-index!
    (list table (if (symbol? index) (make-const src (symbol->string index)) index) exp)))

(define (make-sequence src body)
  (if (null? (cdr body))
      (car body)
      (make-seq src (car body) (make-sequence #f (cdr body)))))

;; Calling conventions
(define* (make-plain-lambda-case src args gensyms body #:optional alternate)
  (make-lambda-case src args #f #f #f '() (or gensyms args) body alternate))

(define* (make-plain-lambda src args gensyms body #:optional alternate)
  (make-lambda src '()
               (make-plain-lambda-case src args gensyms body alternate)))

(define (make-arg-ignoring-lambda src body)
  (make-lambda src '()
               (make-lambda-case src '() #f '_ #f '() (list (gensym "_"))
                                 body #f)))

(define (make-catch-all-lambda src body rest-gensym)
  (make-lambda src '()
               (make-lambda-case src '() #f 'rest #f '() (list rest-gensym)
                                 body #f)))

(define (make-argless-lambda src body)
  (make-plain-lambda src '() #f body))


;; FIXME: use prompt and abort rather than catch and throw
(define (apply-named-lua-function src name get-body)
  (let* ((name (gensym (string-append " " name)))
         (parameters (list name)))
    (make-call
     src
     (make-module-ref src '(guile) 'catch #t)
     (list
      (make-const src 'lua-break)
      (make-argless-lambda src
        (make-letrec #f
         src
         parameters parameters
         (list (make-argless-lambda src (get-body name)))
         (make-call src (make-lexical-ref src name name) '())))
      (make-arg-ignoring-lambda src
       (make-void src))))))

(define (while-loop->tree-il src condition body)
  "Create a WHILE loop, used by both WHILE and REPEAT."
  (apply-named-lua-function
   src "while"
   (lambda (loop)
     (make-conditional
      src
      condition
      (make-sequence
       src
       (list body
             (make-call src (make-lexical-ref src loop loop) '())))
      (make-void src)))))

(define (could-result-in-multiple-values? x)
  (if (not (null? x))
      (let ((last-expr (last x)))
        (or (ast-function-call? last-expr) (ast-variable-arguments? last-expr)))
      #f))

;; TODO REMOVE
#;(define (adjust-to-single-value src exp)
  "Adjust an expression so that it only returns one result; the rest are
dropped silently"
  ;; Rely on the truncating behavior of returning multiple values to a
  ;; singly-valued continuation.
  (make-application src (make-primitive-ref src 'values) (list exp)))

;; main compiler

(define context (make-parameter #f))

(define* (compile exp #:optional tail?)
  (define* (map-compile exps #:optional (tail? #f))
    (let lp ((ls exps)
             (tree '()))
      (if (null? ls)
          (reverse! tree)
          (lp (cdr ls)
              (cons (compile (car ls) (and tail? (null? (cdr ls))))
                    tree)))))

  (record-case exp
    ((ast-sequence src exps)
     (if (null? exps)
         (make-void src)
         (make-sequence src (map-compile exps tail?))))

    ((ast-literal src exp)
     (if (eq? exp *unspecified*)
         (make-void src)
         (make-const src exp)))

    ((ast-return src exp)
     (if tail?
         (if (and (list? exp) (not (= (length exp) 1)))
             (make-call src (make-primitive-ref src 'values)
                               (map-compile exp))
             (compile (if (list? exp) (car exp) exp) #t))
         (make-call
          src (make-primitive-ref src 'return/values)
          (if (list? exp) (map-compile exp #t) (list (compile exp))))))

    ((ast-function src name arguments argument-gensyms variable-arguments? vararg-gensym body)
     ;; ... is always attached because lua functions must ignore
     ;; variable arguments; the parser will catch it if ... is used in a
     ;; function that doesn't have ... in the parameter list
     (let ((meta (if name `((name . ,name)) '())))
       (make-lambda
        src meta
        (make-lambda-case src '() arguments '... #f
                          (map (lambda (x) (make-const src #nil)) arguments)
                          (append argument-gensyms (list vararg-gensym))
                          (compile body)
                          #f))))

    ((ast-function-call src operator operands)
     (let* ((proc (compile operator))
            ;; will be #t if the the last expression in the list is a
            ;; function call or variable arguments, which means we need
            ;; to account for #<values>
            (need-to-apply-multiple-values? (could-result-in-multiple-values? operands))
            (args (map-compile operands)))
       (define app
         (if need-to-apply-multiple-values?
             ;; Get the last function's (the one that could result in
             ;; multiple values) return values using call-with-values
             ;; and a function that takes variable arguments. Then
             ;; append those variable arguments to the rest of the
             ;; expression, and apply the first function to it)
             (make-call src
               (make-primitive-ref src 'call-with-values)
               (list
                 (make-argless-lambda src (make-sequence src (last-pair args)))
                 (let ((rest-gensym (gensym "rest")))
                   (make-catch-all-lambda src
                     (make-call src (make-primitive-ref src 'apply)
                       (list
                         proc
                         (make-call src
                           (make-module-ref src '(srfi srfi-1) 'append! #t)
                           (list
                             (make-call src (make-primitive-ref src 'list) (drop-right args 1))
                             (make-lexical-ref src 'rest rest-gensym)))))
                       rest-gensym))))

             (make-call src proc args)))

       ;; If this is function is a global variable, prepend a call to
       ;; check-global-function to make sure it's defined before
       ;; applying it
       (if (ast-global-ref? operator)
           (make-sequence
            src (list
                 ;; FIXME: use module binders instead
                 (make-call
                  src (make-module-ref src '(language lua runtime)
                                       'check-global-function #t)
                  (list (make-const src (ast-global-ref-name operator))
                        proc))
                 app))
           app)))

    ((ast-local-block src names gensyms initial-values exp)
     (make-let src names gensyms (map-compile initial-values) (compile exp)))

    ((ast-local-ref src name gensym)
     (make-lexical-ref src name gensym))

    ((ast-local-set src name gensym exp)
     (make-lexical-set src name gensym (compile exp)))

    ((ast-global-ref src name)
     (make-table-ref src (ref-runtime src '*global-env-table*) name))

    ((ast-global-set src name exp)
     (make-table-set! src (ref-runtime src '*global-env-table*) name (compile exp)))

    ((ast-table-ref src table key)
     (make-table-ref src (compile table) (compile key)))

    ((ast-table-set src table key exp)
     (make-table-set! src (compile table) (compile key) (compile exp)))

    ((ast-condition src test then else)
     (make-conditional src (compile test) (compile then) (compile else)))

    ((ast-while-loop src condition body)
     (parameterize ((context 'while-loop))
       (while-loop->tree-il src (compile condition) (compile body))))

    ;; TODO: in order for this to have the same semantics as lua, all
    ;; potential subforms of while should introduce their own context,
    ;; so you can't use break inside of a function inside a while loop
    ;; for instance
    ((ast-break src)
     (unless (memq (context) '(while-loop list-for-loop numeric-for-loop))
       (syntax-error src "no loop to break"))
     ;; FIXME: use abort instead of throw
     (make-call src (make-module-ref src '(guile) 'throw #t)
                       (list (make-const src 'lua-break))))

    ;; FIXME: use prompt and abort instead of throw and catch
    ((ast-list-for-loop src names gs-names exps body)
     (let* ((gs-iterator (gensym "iterator"))
            (gs-state (gensym "state"))
            (gs-variable (gensym "variable"))
            (gs-iterator2 (gensym "iterator"))
            (gs-state2 (gensym "state"))
            (gs-variable2 (gensym "variable"))
            (gs-loop (gensym "loop")))
       (parse-tree-il
        `(letrec*
           ;; names
           (iterator state variable loop)
           ;; gensyms
           (,gs-iterator ,gs-state ,gs-variable ,gs-loop)
           ;; vals
           ((void) (void) (void)
            (lambda ()
              (lambda-case
                  (,no-arguments
                   (begin
                     ;; even more complicated, assigning the values to
                     ;; the loop variables
                     (call (primitive call-with-values)
                           (lambda ()
                             (lambda-case
                              (,no-arguments
                               (call (lexical iterator ,gs-iterator)
                                     (lexical state ,gs-state)
                                     (lexical variable ,gs-variable)))))
                           (lambda ()
                             (lambda-case
                              ((,names #f #f #f () ,gs-names)
                               ;; almost to the actual loop body, hang
                               ;; in there
                               (begin
                                 (set! (lexical variable ,gs-variable)
                                       (lexical ,(car names) ,(car gs-names)))
                                 (if (call (primitive eq?)
                                           (lexical variable ,gs-variable)
                                           (const #nil))
                                     (call (@ (guile) throw) (const lua-break))
                                     (void))
                                 ,(parameterize ((context 'list-for-loop))
                                    (unparse-tree-il (compile body)))
                                 (call (lexical loop ,gs-loop))))))))))))
           ;; initialize variables and start loop
           (begin
             (call (primitive call-with-values)
                    (lambda ()
                      (lambda-case
                       (,no-arguments
                        ,(unparse-tree-il
                          (make-sequence src (map-compile exps))))))
                    (lambda ()
                      (lambda-case
                       (((iterator state variable) #f #f #f ()
                         (,gs-iterator2 ,gs-state2 ,gs-variable2))
                        (begin
                          (set! (lexical iterator ,gs-iterator)
                                (lexical iterator ,gs-iterator2))
                          (set! (lexical state ,gs-state)
                                (lexical state ,gs-state2))
                          (set! (lexical variable ,gs-variable)
                                (lexical variable ,gs-variable2)))))))
             (call (@ (guile) catch)
                    (const lua-break)
                    (lambda ()
                      (lambda-case
                       (,no-arguments
                        (call (lexical loop ,gs-loop)))))
                    (lambda ()
                      (lambda-case
                       (((key) #f #f #f () (,(gensym "key")))
                        (void))))))))))

    ;; TODO: in order for this to have the same semantics as lua, all
    ;; potential subforms of while should introduce their own context,
    ;; so you can't use break inside of a function inside a while loop
    ;; for instance

    ((ast-numeric-for-loop src named initial limit step body)
     ;; as per 5.1 manual 2.4.5, the numeric for loop can be decomposed
     ;; into simpler forms
     ;;
     ;; still doesn't have proper behavior, should be able to return and
     ;; break inside a loop
     (let* ((gs-named (gensym (symbol->string named)))
            (gs-variable (gensym "variable"))
            (gs-limit (gensym "limit"))
            (gs-step (gensym "step"))
            (gs-loop (gensym "loop"))
            (while-condition
             `(if (call (primitive >) (lexical step ,gs-step) (const 0))
                 (if (call (primitive <=)
                            (lexical variable ,gs-variable)
                            (lexical limit ,gs-limit))
                     (call (lexical loop ,gs-loop))
                     (void))
                 (void))))
       (parse-tree-il
        `(letrec*
           ;; names
           (,named variable limit step loop)
           ;; gensyms
           (,gs-named ,gs-variable ,gs-limit ,gs-step ,gs-loop)
           ;; vals
           ,(cons
              '(const #f)
              (append
               (map (lambda (x)
                      `(call (@ (language lua runtime) tonumber)
                             ,(unparse-tree-il (compile x))))
                    (list initial limit step))
               ;; loop body
               (list
                `(lambda ()
                   (lambda-case
                    ;; no arguments
                    ((() #f #f #f () ())
                     ;; body
                     (begin
                       (set! (lexical ,named ,gs-named)
                             (lexical variable ,gs-variable))
                       ,(parameterize ((context 'numeric-for-loop))
                          (unparse-tree-il (compile body)))
                       (set! (lexical variable ,gs-variable)
                             (call (primitive +)
                                   (lexical variable ,gs-variable)
                                   (lexical step ,gs-step)))
                       ,while-condition)))))))
           ;; body
           (begin
             ;; if not (var and limit and step) then error() end
             (if (call (primitive not)
                        (if (lexical variable ,gs-variable)
                            (if (lexical limit ,gs-limit)
                                (if (lexical step ,gs-step)
                                    (const #t)
                                    (const #f))
                                (const #f))
                            (const #f)))
                 (call (@ (guile) error))
                 (void))
             ,while-condition
             )))))

    ((ast-table-literal src fields)
     (let* ((table (make-runtime-application src 'make-table '())))
       (if (not (null? fields))
           ;; if the table's fields are initialized inside of the
           ;; literal, we need to store it in a variable and initialize
           ;; its values
           (let* ((temp-name (gensym " table"))
                  (names (list temp-name))
                  (ref (make-lexical-ref src temp-name temp-name)))
             (make-let
              src
              names names
              (list table)
              (make-sequence
               src
               (append!
                (map
                 (lambda (x)
                   (let* ((key (compile (car x)))
                          (value (compile (cdr x))))
                     (make-runtime-application
                      src 'new-index!
                      (list (make-lexical-ref src temp-name temp-name)
                            key
                            value))))
                 fields)
                (list ref)))))
           ;; otherwise we can just return the fresh table
           table)))

    ((ast-unary-operation src operator right)
     ;; reduce simple negative numbers, like -5, to literals
     (if (and (eq? operator #\-) (ast-literal? right)
              (number? (ast-literal-exp right)))
         (make-const src (- (ast-literal-exp right)))
         (make-call
          src
          (case operator
            ((#\-) (ref-runtime src 'unm))
            ((#\#) (ref-runtime src 'len))
            ((not) (make-primitive-ref src 'not)))
          (list (compile right)))))


    ((ast-binary-operation src operator left right)
     (let ((left (compile left))
           (right (compile right)))
       (case operator
         ((#\+)      (make-runtime-application src 'add    (list left right)))
         ((#\-)      (make-runtime-application src 'sub    (list left right)))
         ((#\*)      (make-runtime-application src 'mul    (list left right)))
         ((#\/)      (make-runtime-application src 'div    (list left right)))
         ((#\^)      (make-runtime-application src 'pow    (list left right)))
         ((#\<)      (make-runtime-application src 'lt     (list left right)))
         ((#\>)      (make-runtime-application src 'lt     (list right left)))
         ((#:<=)     (make-runtime-application src 'le     (list left right)))
         ((#:>=)     (make-runtime-application src 'le     (list right left)))
         ((#:==)     (make-runtime-application src 'eq     (list left right)))
         ((#:~=)     (make-runtime-application src 'neq    (list left right)))
         ((#:concat) (make-runtime-application src 'concat (list left right)))
         ((#:or)
          (let ((tmp (gensym "or-tmp")))
            (make-let src '(or-tmp) (list tmp) (list left)
              (make-conditional src
                (make-lexical-ref src 'or-tmp tmp)
                (make-lexical-ref src 'or-tmp tmp)
                right))))
        ((#:and)
          (let ((tmp (gensym "and-tmp")))
            (make-let src '(and-tmp) (list tmp) (list left)
              (make-conditional src
                (make-lexical-ref src 'and-tmp tmp)
                right
                (make-lexical-ref src 'and-tmp tmp)))))
         (else (error #:COMPILE "unknown binary operator" operator)))))
    ((ast-variable-arguments src gensym)
     (make-call src
                       (make-primitive-ref src 'apply)
                       (list (make-primitive-ref src 'values)
                             (make-lexical-ref src '... gensym))))))

;; exported compiler function
(define (compile-tree-il exp env opts)
  (parameterize ((context #f))
    (values (compile exp) env env)))