source: trunk/abcl/src/org/armedbear/lisp/precompiler.lisp @ 12768

Last change on this file since 12768 was 12768, checked in by ehuelsmann, 13 years ago

Fix elimination of unused local functions:
macroexpand before scanning the body.

Found by: William Wadsworth (will wadsworth 10 at gmail com)

  • Property svn:eol-style set to native
  • Property svn:keywords set to Id
File size: 42.9 KB
Line 
1;;; precompiler.lisp
2;;;
3;;; Copyright (C) 2003-2008 Peter Graves <peter@armedbear.org>
4;;; $Id: precompiler.lisp 12768 2010-06-27 10:10:38Z ehuelsmann $
5;;;
6;;; This program is free software; you can redistribute it and/or
7;;; modify it under the terms of the GNU General Public License
8;;; as published by the Free Software Foundation; either version 2
9;;; of the License, or (at your option) any later version.
10;;;
11;;; This program is distributed in the hope that it will be useful,
12;;; but WITHOUT ANY WARRANTY; without even the implied warranty of
13;;; MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
14;;; GNU General Public License for more details.
15;;;
16;;; You should have received a copy of the GNU General Public License
17;;; along with this program; if not, write to the Free Software
18;;; Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA  02110-1301, USA.
19;;;
20;;; As a special exception, the copyright holders of this library give you
21;;; permission to link this library with independent modules to produce an
22;;; executable, regardless of the license terms of these independent
23;;; modules, and to copy and distribute the resulting executable under
24;;; terms of your choice, provided that you also meet, for each linked
25;;; independent module, the terms and conditions of the license of that
26;;; module.  An independent module is a module which is not derived from
27;;; or based on this library.  If you modify this library, you may extend
28;;; this exception to your version of the library, but you are not
29;;; obligated to do so.  If you do not wish to do so, delete this
30;;; exception statement from your version.
31
32(in-package "SYSTEM")
33
34
35(export '(process-optimization-declarations
36          inline-p notinline-p inline-expansion expand-inline
37          *defined-functions* *undefined-functions* note-name-defined))
38
39(declaim (ftype (function (t) t) process-optimization-declarations))
40(defun process-optimization-declarations (forms)
41  (dolist (form forms)
42    (unless (and (consp form) (eq (%car form) 'DECLARE))
43      (return))
44    (dolist (decl (%cdr form))
45      (case (car decl)
46        (OPTIMIZE
47         (dolist (spec (%cdr decl))
48           (let ((val 3)
49                 (quality spec))
50             (when (consp spec)
51               (setf quality (%car spec)
52                     val (cadr spec)))
53             (when (and (fixnump val)
54                        (<= 0 val 3))
55               (case quality
56                 (speed
57                  (setf *speed* val))
58                 (safety
59                  (setf *safety* val))
60                 (debug
61                  (setf *debug* val))
62                 (space
63                  (setf *space* val))
64                 (compilation-speed) ;; Ignored.
65                 (t
66                  (compiler-warn "Ignoring unknown optimization quality ~S in ~S." quality decl)))))))
67        ((INLINE NOTINLINE)
68         (dolist (symbol (%cdr decl))
69           (push (cons symbol (%car decl)) *inline-declarations*)))
70        (:explain
71         (dolist (spec (%cdr decl))
72           (let ((val t)
73                 (quality spec))
74             (when (consp spec)
75               (setf quality (%car spec))
76               (when (= (length spec) 2)
77                 (setf val (%cadr spec))))
78             (if val
79                 (pushnew quality *explain*)
80                 (setf *explain* (remove quality *explain*)))))))))
81  t)
82
83(declaim (ftype (function (t) t) inline-p))
84(defun inline-p (name)
85  (declare (optimize speed))
86  (let ((entry (assoc name *inline-declarations* :test #'equal)))
87    (if entry
88        (eq (cdr entry) 'INLINE)
89        (and (symbolp name) (eq (get name '%inline) 'INLINE)))))
90
91(declaim (ftype (function (t) t) notinline-p))
92(defun notinline-p (name)
93  (declare (optimize speed))
94  (let ((entry (assoc name *inline-declarations* :test #'equal)))
95    (if entry
96        (eq (cdr entry) 'NOTINLINE)
97        (and (symbolp name) (eq (get name '%inline) 'NOTINLINE)))))
98
99(defun expand-inline (form expansion)
100;;   (format t "expand-inline form = ~S~%" form)
101;;   (format t "expand-inline expansion = ~S~%" expansion)
102  (let* ((op (car form))
103         (proclaimed-ftype (proclaimed-ftype op))
104         (args (cdr form))
105         (vars (cadr expansion))
106         (varlist ())
107         new-form)
108;;     (format t "op = ~S proclaimed-ftype = ~S~%" op (proclaimed-ftype op))
109    (do ((vars vars (cdr vars))
110         (args args (cdr args)))
111        ((null vars))
112      (push (list (car vars) (car args)) varlist))
113    (setf new-form (list* 'LET (nreverse varlist)
114                          (copy-tree (cddr expansion))))
115    (when proclaimed-ftype
116      (let ((result-type (ftype-result-type proclaimed-ftype)))
117        (when (and result-type
118                   (neq result-type t)
119                   (neq result-type '*))
120          (setf new-form (list 'TRULY-THE result-type new-form)))))
121;;     (format t "expand-inline new form = ~S~%" new-form)
122    new-form))
123
124(define-compiler-macro assoc (&whole form &rest args)
125  (cond ((and (= (length args) 4)
126              (eq (third args) :test)
127              (or (equal (fourth args) '(quote eq))
128                  (equal (fourth args) '(function eq))))
129         `(assq ,(first args) ,(second args)))
130        ((= (length args) 2)
131         `(assql ,(first args) ,(second args)))
132        (t form)))
133
134(define-compiler-macro member (&whole form &rest args)
135  (let ((arg1 (first args))
136        (arg2 (second args)))
137    (case (length args)
138      (2
139       `(memql ,arg1 ,arg2))
140      (4
141       (let ((arg3 (third args))
142             (arg4 (fourth args)))
143         (cond ((and (eq arg3 :test)
144                     (or (equal arg4 '(quote eq))
145                         (equal arg4 '(function eq))))
146                `(memq ,arg1 ,arg2))
147               ((and (eq arg3 :test)
148                     (or (equal arg4 '(quote eql))
149                         (equal arg4 '(function eql))
150                         (equal arg4 '(quote char=))
151                         (equal arg4 '(function char=))))
152                `(memql ,arg1 ,arg2))
153               (t
154                form))))
155      (t
156       form))))
157
158(define-compiler-macro search (&whole form &rest args)
159  (if (= (length args) 2)
160      `(simple-search ,@args)
161      form))
162
163(define-compiler-macro identity (&whole form &rest args)
164  (if (= (length args) 1)
165      `(progn ,(car args))
166      form))
167
168(defun quoted-form-p (form)
169  (and (consp form) (eq (%car form) 'QUOTE) (= (length form) 2)))
170
171(define-compiler-macro eql (&whole form &rest args)
172  (let ((first (car args))
173        (second (cadr args)))
174    (if (or (and (quoted-form-p first) (symbolp (cadr first)))
175            (and (quoted-form-p second) (symbolp (cadr second))))
176        `(eq ,first ,second)
177        form)))
178
179(define-compiler-macro not (&whole form arg)
180  (if (atom arg)
181      form
182      (let ((op (case (car arg)
183                  (>= '<)
184                  (<  '>=)
185                  (<= '>)
186                  (>  '<=)
187                  (t  nil))))
188        (if (and op (= (length arg) 3))
189            (cons op (cdr arg))
190            form))))
191
192(defun predicate-for-type (type)
193  (cdr (assq type '((ARRAY             . arrayp)
194                    (ATOM              . atom)
195                    (BIT-VECTOR        . bit-vector-p)
196                    (CHARACTER         . characterp)
197                    (COMPLEX           . complexp)
198                    (CONS              . consp)
199                    (FIXNUM            . fixnump)
200                    (FLOAT             . floatp)
201                    (FUNCTION          . functionp)
202                    (HASH-TABLE        . hash-table-p)
203                    (INTEGER           . integerp)
204                    (LIST              . listp)
205                    (NULL              . null)
206                    (NUMBER            . numberp)
207                    (NUMBER            . numberp)
208                    (PACKAGE           . packagep)
209                    (RATIONAL          . rationalp)
210                    (REAL              . realp)
211                    (SIMPLE-BIT-VECTOR . simple-bit-vector-p)
212                    (SIMPLE-STRING     . simple-string-p)
213                    (SIMPLE-VECTOR     . simple-vector-p)
214                    (STREAM            . streamp)
215                    (STRING            . stringp)
216                    (SYMBOL            . symbolp)))))
217
218(define-compiler-macro typep (&whole form &rest args)
219  (if (= (length args) 2) ; no environment arg
220      (let* ((object (%car args))
221             (type-specifier (%cadr args))
222             (type (and (consp type-specifier)
223                        (eq (%car type-specifier) 'QUOTE)
224                        (%cadr type-specifier)))
225             (predicate (and type (predicate-for-type type))))
226        (if predicate
227            `(,predicate ,object)
228            `(%typep ,@args)))
229      form))
230
231(define-compiler-macro subtypep (&whole form &rest args)
232  (if (= (length args) 2)
233      `(%subtypep ,@args)
234      form))
235
236(define-compiler-macro funcall (&whole form
237                                &environment env &rest args)
238  (let ((callee (car args)))
239    (if (and (>= *speed* *debug*)
240             (consp callee)
241             (eq (%car callee) 'function)
242             (symbolp (cadr callee))
243             (not (special-operator-p (cadr callee)))
244             (not (macro-function (cadr callee) env))
245             (memq (symbol-package (cadr callee))
246                   (list (find-package "CL") (find-package "SYS"))))
247        `(,(cadr callee) ,@(cdr args))
248        form)))
249
250(define-compiler-macro byte (size position)
251  `(cons ,size ,position))
252
253(define-compiler-macro byte-size (bytespec)
254  `(car ,bytespec))
255
256(define-compiler-macro byte-position (bytespec)
257  `(cdr ,bytespec))
258
259(define-source-transform concatenate (&whole form result-type &rest sequences)
260  (if (equal result-type '(quote STRING))
261      `(sys::concatenate-to-string (list ,@sequences))
262      form))
263
264(define-source-transform ldb (&whole form bytespec integer)
265  (if (and (consp bytespec)
266           (eq (%car bytespec) 'byte)
267           (= (length bytespec) 3))
268      (let ((size (%cadr bytespec))
269            (position (%caddr bytespec)))
270        `(%ldb ,size ,position ,integer))
271      form))
272
273(define-source-transform find (&whole form item sequence &key from-end test test-not start end key)
274  (cond ((and (>= (length form) 3) (null start) (null end))
275         (cond ((and (stringp sequence)
276                     (null from-end)
277                     (member test '(#'eql #'char=) :test #'equal)
278                     (null test-not)
279                     (null key))
280                `(string-find ,item ,sequence))
281               (t
282                (let ((item-var (gensym))
283                      (seq-var (gensym)))
284                  `(let ((,item-var ,item)
285                         (,seq-var ,sequence))
286                     (if (listp ,seq-var)
287                         (list-find* ,item-var ,seq-var ,from-end ,test ,test-not 0 (length ,seq-var) ,key)
288                         (vector-find* ,item-var ,seq-var ,from-end ,test ,test-not 0 (length ,seq-var) ,key)))))))
289        (t
290         form)))
291
292(define-source-transform adjoin (&whole form &rest args)
293  (if (= (length args) 2)
294      `(adjoin-eql ,(first args) ,(second args))
295      form))
296
297(define-source-transform format (&whole form &rest args)
298  (if (stringp (second args))
299      `(format ,(pop args) (formatter ,(pop args)) ,@args)
300      form))
301
302(define-compiler-macro catch (&whole form tag &rest args)
303  (declare (ignore tag))
304  (if (and (null (cdr args))
305           (constantp (car args)))
306      (car args)
307      form))
308
309(define-compiler-macro string= (&whole form &rest args)
310  (if (= (length args) 2)
311      `(sys::%%string= ,@args)
312      form))
313
314(define-compiler-macro <= (&whole form &rest args)
315  (cond ((and (= (length args) 3)
316              (numberp (first args))
317              (numberp (third args))
318              (= (first args) (third args)))
319         `(= ,(second args) ,(first args)))
320        (t
321         form)))
322
323
324(in-package "PRECOMPILER")
325
326;; No source-transforms and inlining in precompile-function-call
327;; No macro expansion in precompile-dolist and precompile-dotimes
328;; No macro expansion in precompile-do/do*
329;; No macro expansion in precompile-defun
330;; Special precompilation in precompile-case and precompile-cond
331;; Special precompilation in precompile-when and precompile-unless
332;; No precompilation in precompile-nth-value
333;; Special precompilation in precompile-return
334;; Special precompilation in expand-macro
335;;
336;; if *in-jvm-compile* is false
337
338(defvar *in-jvm-compile* nil)
339(defvar *precompile-env* nil)
340
341
342(declaim (ftype (function (t) t) precompile1))
343(defun precompile1 (form)
344  (cond ((symbolp form)
345         (multiple-value-bind
346               (expansion expanded)
347             (expand-macro form)
348           (if expanded
349               (precompile1 expansion)
350               form)))
351        ((atom form)
352         form)
353        (t
354         (let ((op (%car form))
355               handler)
356           (when (symbolp op)
357             (cond ((setf handler (get op 'precompile-handler))
358                    (return-from precompile1 (funcall handler form)))
359                   ((macro-function op *precompile-env*)
360                    (return-from precompile1 (precompile1 (expand-macro form))))
361                   ((special-operator-p op)
362                    (error "PRECOMPILE1: unsupported special operator ~S." op))))
363           (precompile-function-call form)))))
364
365(defun precompile-identity (form)
366  (declare (optimize speed))
367  form)
368
369(declaim (ftype (function (t) cons) precompile-cons))
370(defun precompile-cons (form)
371  (cons (car form) (mapcar #'precompile1 (cdr form))))
372
373(declaim (ftype (function (t t) t) precompile-function-call))
374(defun precompile-function-call (form)
375  (let ((op (car form)))
376    (when (and (consp op) (eq (%car op) 'LAMBDA))
377      (return-from precompile-function-call
378                   (cons (precompile-lambda op)
379                         (mapcar #'precompile1 (cdr form)))))
380    (when (or (not *in-jvm-compile*) (notinline-p op))
381      (return-from precompile-function-call (precompile-cons form)))
382    (when (source-transform op)
383      (let ((new-form (expand-source-transform form)))
384        (when (neq new-form form)
385          (return-from precompile-function-call (precompile1 new-form)))))
386    (when *enable-inline-expansion*
387      (let ((expansion (inline-expansion op)))
388        (when expansion
389          (let ((explain *explain*))
390            (when (and explain (memq :calls explain))
391              (format t ";   inlining call to ~S~%" op)))
392          (return-from precompile-function-call (precompile1 (expand-inline form expansion))))))
393    (cons op (mapcar #'precompile1 (cdr form)))))
394
395(defun precompile-locally (form)
396  (let ((*inline-declarations* *inline-declarations*))
397    (process-optimization-declarations (cdr form))
398  (cons 'LOCALLY (mapcar #'precompile1 (cdr form)))))
399
400(defun precompile-block (form)
401  (let ((args (cdr form)))
402    (if (null (cdr args))
403        nil
404        (list* 'BLOCK (car args) (mapcar #'precompile1 (cdr args))))))
405
406(defun precompile-dolist (form)
407  (if *in-jvm-compile*
408      (precompile1 (macroexpand form *precompile-env*))
409      (cons 'DOLIST (cons (mapcar #'precompile1 (cadr form))
410                          (mapcar #'precompile1 (cddr form))))))
411
412(defun precompile-dotimes (form)
413  (if *in-jvm-compile*
414      (precompile1 (macroexpand form *precompile-env*))
415      (cons 'DOTIMES (cons (mapcar #'precompile1 (cadr form))
416                           (mapcar #'precompile1 (cddr form))))))
417
418(defun precompile-do/do*-vars (varlist)
419  (let ((result nil))
420    (dolist (varspec varlist)
421      (if (atom varspec)
422          (push varspec result)
423          (case (length varspec)
424            (1
425             (push (%car varspec) result))
426            (2
427             (let* ((var (%car varspec))
428                    (init-form (%cadr varspec)))
429               (unless (symbolp var)
430                 (error 'type-error))
431               (push (list var (precompile1 init-form))
432                     result)))
433            (3
434             (let* ((var (%car varspec))
435                    (init-form (%cadr varspec))
436                    (step-form (%caddr varspec)))
437               (unless (symbolp var)
438                 (error 'type-error))
439               (push (list var (precompile1 init-form) (precompile1 step-form))
440                     result))))))
441    (nreverse result)))
442
443(defun precompile-do/do*-end-form (end-form)
444  (let ((end-test-form (car end-form))
445        (result-forms (cdr end-form)))
446    (list* end-test-form (mapcar #'precompile1 result-forms))))
447
448(defun precompile-do/do* (form)
449  (if *in-jvm-compile*
450      (precompile1 (macroexpand form *precompile-env*))
451      (list* (car form)
452             (precompile-do/do*-vars (cadr form))
453             (precompile-do/do*-end-form (caddr form))
454             (mapcar #'precompile1 (cdddr form)))))
455
456(defun precompile-do-symbols (form)
457  (list* (car form) (cadr form) (mapcar #'precompile1 (cddr form))))
458
459(defun precompile-load-time-value (form)
460  form)
461
462(defun precompile-progn (form)
463  (let ((body (cdr form)))
464    (if (eql (length body) 1)
465        (let ((res (precompile1 (%car body))))
466          ;; If the result turns out to be a bare symbol, leave it wrapped
467          ;; with PROGN so it won't be mistaken for a tag in an enclosing
468          ;; TAGBODY.
469          (if (symbolp res)
470              (list 'progn res)
471              res))
472        (cons 'PROGN (mapcar #'precompile1 body)))))
473
474(defun precompile-threads-synchronized-on (form)
475  (cons 'threads:synchronized-on (mapcar #'precompile1 (cdr form))))
476
477(defun precompile-progv (form)
478  (if (< (length form) 3)
479      (error "Not enough arguments for ~S." 'progv)
480      (list* 'PROGV (mapcar #'precompile1 (%cdr form)))))
481
482(defun precompile-setf (form)
483  (let ((place (second form)))
484    (cond ((and (consp place)
485                (eq (%car place) 'VALUES))
486     (setf form
487     (list* 'SETF
488      (list* 'VALUES
489             (mapcar #'precompile1 (%cdr place)))
490      (cddr form)))
491     (precompile1 (expand-macro form)))
492    ((symbolp place)
493           (multiple-value-bind
494                 (expansion expanded)
495               (expand-macro place)
496             (if expanded
497                 (precompile1 (list* 'SETF expansion
498                                     (cddr form)))
499                 (precompile1 (expand-macro form)))))
500          (t
501           (precompile1 (expand-macro form))))))
502
503(defun precompile-setq (form)
504  (let* ((args (cdr form))
505         (len (length args)))
506    (when (oddp len)
507      (error 'simple-program-error
508             :format-control "Odd number of arguments to SETQ."))
509    (if (= len 2)
510        (let* ((sym (%car args))
511               (val (%cadr args)))
512          (multiple-value-bind
513                (expansion expanded)
514              (expand-macro sym)
515            (if expanded
516                (precompile1 (list 'SETF expansion val))
517                (list 'SETQ sym (precompile1 val)))))
518        (let ((result ()))
519          (loop
520            (when (null args)
521              (return))
522            (push (precompile-setq (list 'SETQ (car args) (cadr args))) result)
523            (setq args (cddr args)))
524          (setq result (nreverse result))
525          (push 'PROGN result)
526          result))))
527
528(defun precompile-psetf (form)
529  (setf form
530        (list* 'PSETF
531               (mapcar #'precompile1 (cdr form))))
532  (precompile1 (expand-macro form)))
533
534(defun precompile-psetq (form)
535  ;; Make sure all the vars are symbols.
536  (do* ((rest (cdr form) (cddr rest))
537        (var (car rest)))
538       ((null rest))
539    (unless (symbolp var)
540      (error 'simple-error
541             :format-control "~S is not a symbol."
542             :format-arguments (list var))))
543  ;; Delegate to PRECOMPILE-PSETF so symbol macros are handled correctly.
544  (precompile-psetf form))
545
546
547(defun precompile-lambda-list (form)
548  (let (new aux-tail)
549    (dolist (arg form (nreverse new))
550       (if (or (atom arg) (> 2 (length arg)))
551           (progn
552             (when (eq arg '&aux)
553               (setf aux-tail t))
554             (push arg new))
555          ;; must be a cons of more than 1 cell
556          (let ((new-arg (copy-list arg)))
557            (unless (<= 1 (length arg) (if aux-tail 2 3))
558              ;; the aux-vars have a maximum length of 2 conses
559              ;; optional and key vars may have 3
560              (error 'program-error
561                     :format-control
562                     "The ~A binding specification ~S is invalid."
563                     :format-arguments (list (if aux-tail "&AUX"
564                                                 "&OPTIONAL/&KEY") arg)))
565             (setf (second new-arg)
566                   (precompile1 (second arg)))
567             (push new-arg new))))))
568
569(defun extract-lambda-vars (lambda-list)
570  (let ((state :required)
571        vars)
572    (dolist (var/key lambda-list vars)
573      (cond
574        ((eq '&aux var/key)       (setf state :aux))
575        ((eq '&key var/key)       (setf state :key))
576        ((eq '&optional var/key)  (setf state :optional))
577        ((eq '&rest var/key)      (setf state :rest))
578        ((symbolp var/key)        (unless (eq var/key '&allow-other-keys)
579                                    (push var/key vars)))
580        ((and (consp var/key)
581              (member state '(:optional :key)))
582         (setf var/key (car var/key))
583         (when (and (consp var/key) (eq state :key))
584           (setf var/key (second var/key)))
585         (if (symbolp var/key)
586             (push var/key vars)
587             (error 'program-error
588                    :format-control
589                    "Unexpected ~A variable specifier ~A."
590                    :format-arguments (list state var/key))))
591        ((and (consp var/key) (eq state :aux))
592         (if (symbolp (car var/key))
593             (push (car var/key) vars)
594             (error 'program-error
595                    :format-control "Unexpected &AUX format for ~A."
596                    :format-arguments (list var/key))))
597        (t
598         (error 'program-error
599                :format-control "Unexpected lambda-list format: ~A."
600                :format-arguments (list lambda-list)))))))
601
602(defun precompile-lambda (form)
603  (let ((body (cddr form))
604        (precompiled-lambda-list
605           (precompile-lambda-list (cadr form)))
606        (*inline-declarations* *inline-declarations*)
607        (*precompile-env* (make-environment *precompile-env*)))
608    (process-optimization-declarations body)
609    (dolist (var (extract-lambda-vars precompiled-lambda-list))
610      (environment-add-symbol-binding *precompile-env* var nil))
611    (list* 'LAMBDA precompiled-lambda-list
612           (mapcar #'precompile1 body))))
613
614(defun precompile-named-lambda (form)
615  (let ((lambda-form (list* 'LAMBDA (caddr form) (cdddr form))))
616    (let ((body (cddr lambda-form))
617          (precompiled-lambda-list
618           (precompile-lambda-list (cadr lambda-form)))
619          (*inline-declarations* *inline-declarations*)
620          (*precompile-env* (make-environment *precompile-env*)))
621      (process-optimization-declarations body)
622      (dolist (var (extract-lambda-vars precompiled-lambda-list))
623        (environment-add-symbol-binding *precompile-env* var nil))
624      (list* 'NAMED-LAMBDA (cadr form) precompiled-lambda-list
625             (mapcar #'precompile1 body)))))
626
627(defun precompile-defun (form)
628  (if *in-jvm-compile*
629      (precompile1 (expand-macro form))
630      form))
631
632(defun precompile-macrolet (form)
633  (let ((*precompile-env* (make-environment *precompile-env*)))
634    (dolist (definition (cadr form))
635      (environment-add-macro-definition
636       *precompile-env*
637       (car definition)
638       (make-macro (car definition)
639                   (make-closure
640                    (make-expander-for-macrolet definition)
641                    NIL))))
642    (multiple-value-bind (body decls)
643        (parse-body (cddr form) nil)
644      `(locally ,@decls ,@(mapcar #'precompile1 body)))))
645
646(defun precompile-symbol-macrolet (form)
647  (let ((*precompile-env* (make-environment *precompile-env*))
648        (defs (cadr form)))
649    (dolist (def defs)
650      (let ((sym (car def))
651            (expansion (cadr def)))
652        (when (special-variable-p sym)
653          (error 'program-error
654                 :format-control
655                 "Attempt to bind the special variable ~S with SYMBOL-MACROLET."
656                 :format-arguments (list sym)))
657        (environment-add-symbol-binding *precompile-env*
658                                        sym
659                                        (sys::make-symbol-macro expansion))))
660    (multiple-value-bind (body decls)
661        (parse-body (cddr form) nil)
662      (when decls
663        (let ((specials ()))
664          (dolist (decl decls)
665            (when (eq (car decl) 'DECLARE)
666              (dolist (declspec (cdr decl))
667                (when (eq (car declspec) 'SPECIAL)
668                  (setf specials (append specials (cdr declspec)))))))
669          (when specials
670            (let ((syms (mapcar #'car (cadr form))))
671              (dolist (special specials)
672                (when (memq special syms)
673                  (error 'program-error
674                         :format-control
675                         "~S is a symbol-macro and may not be declared special."
676                         :format-arguments (list special))))))))
677      `(locally ,@decls ,@(mapcar #'precompile1 body)))))
678
679(defun precompile-the (form)
680  (list 'THE
681        (second form)
682        (precompile1 (third form))))
683
684(defun precompile-truly-the (form)
685  (list 'TRULY-THE
686        (second form)
687        (precompile1 (third form))))
688
689(defun precompile-let/let*-vars (vars)
690  (let ((result nil))
691    (dolist (var vars)
692      (cond ((consp var)
693             (unless (<= 1 (length var) 2)
694               (error 'program-error
695                       :format-control
696                       "The LET/LET* binding specification ~S is invalid."
697                       :format-arguments (list var)))
698             (let ((v (%car var))
699                   (expr (cadr var)))
700               (unless (symbolp v)
701                 (error 'simple-type-error
702                        :format-control "The variable ~S is not a symbol."
703                        :format-arguments (list v)))
704               (push (list v (precompile1 expr)) result)
705               (environment-add-symbol-binding *precompile-env* v nil)))
706               ;; any value will do: we just need to shadow any symbol macros
707            (t
708             (push var result)
709             (environment-add-symbol-binding *precompile-env* var nil))))
710    (nreverse result)))
711
712(defun precompile-let (form)
713  (let ((*precompile-env* (make-environment *precompile-env*)))
714    (list* 'LET
715           (precompile-let/let*-vars (cadr form))
716           (mapcar #'precompile1 (cddr form)))))
717
718;; (LET* ((X 1)) (LET* ((Y 2)) (LET* ((Z 3)) (+ X Y Z)))) =>
719;; (LET* ((X 1) (Y 2) (Z 3)) (+ X Y Z))
720(defun maybe-fold-let* (form)
721  (if (and (= (length form) 3)
722           (consp (%caddr form))
723           (eq (%car (%caddr form)) 'LET*))
724      (let ((third (maybe-fold-let* (%caddr form))))
725        (list* 'LET* (append (%cadr form) (cadr third)) (cddr third)))
726      form))
727
728(defun precompile-let* (form)
729  (setf form (maybe-fold-let* form))
730  (let ((*precompile-env* (make-environment *precompile-env*)))
731    (list* 'LET*
732           (precompile-let/let*-vars (cadr form))
733           (mapcar #'precompile1 (cddr form)))))
734
735(defun precompile-case (form)
736  (if *in-jvm-compile*
737      (precompile1 (macroexpand form *precompile-env*))
738      (let* ((keyform (cadr form))
739             (clauses (cddr form))
740             (result (list (precompile1 keyform))))
741        (dolist (clause clauses)
742          (push (precompile-case-clause clause) result))
743        (cons (car form) (nreverse result)))))
744
745(defun precompile-case-clause (clause)
746  (let ((keys (car clause))
747        (forms (cdr clause)))
748    (cons keys (mapcar #'precompile1 forms))))
749
750(defun precompile-cond (form)
751  (if *in-jvm-compile*
752      (precompile1 (macroexpand form *precompile-env*))
753      (let ((clauses (cdr form))
754            (result nil))
755        (dolist (clause clauses)
756          (push (precompile-cond-clause clause) result))
757        (cons 'COND (nreverse result)))))
758
759(defun precompile-cond-clause (clause)
760  (let ((test (car clause))
761        (forms (cdr clause)))
762    (cons (precompile1 test) (mapcar #'precompile1 forms))))
763
764(defun precompile-local-function-def (def)
765  (let ((name (car def))
766        (body (cddr def)))
767    ;; Macro names are shadowed by local functions.
768    (environment-add-function-definition *precompile-env* name body)
769    (cdr (precompile-named-lambda (list* 'NAMED-LAMBDA def)))))
770
771(defun precompile-local-functions (defs)
772  (let ((result nil))
773    (dolist (def defs (nreverse result))
774      (push (precompile-local-function-def def) result))))
775
776(defun find-use (name expression)
777  (cond ((atom expression)
778         nil)
779        ((eq (%car expression) name)
780         t)
781        ((consp name)
782         t) ;; FIXME Recognize use of SETF functions!
783        (t
784         (or (find-use name (%car expression))
785             (find-use name (%cdr expression))))))
786
787(defun precompile-flet/labels (form)
788  (let ((*precompile-env* (make-environment *precompile-env*))
789        (operator (car form))
790        (locals (cadr form))
791        ;; precompile (thus macro-expand) the body before inspecting it
792        ;; for the use of our locals and optimizing them away
793        (body (mapcar #'precompile1 (cddr form))))
794    (dolist (local locals)
795      (let* ((name (car local))
796             (used-p (find-use name body)))
797        (unless used-p
798          (when (eq operator 'LABELS)
799            (dolist (local locals)
800              (when (neq name (car local))
801                (when (find-use name (cddr local))
802                  (setf used-p t)
803                  (return))
804                ;; Scope of defined function names includes
805                ;; &OPTIONAL, &KEY and &AUX parameters
806                ;; (LABELS.7B, LABELS.7C and LABELS.7D).
807                (let ((vars (or
808                             (cdr (memq '&optional (cadr local)))
809                             (cdr (memq '&key (cadr local)))
810                             (cdr (memq '&aux (cadr local))))))
811                  (when (and vars (find-use name vars)
812                             (setf used-p t)
813                             (return))))))))
814        (unless used-p
815          (format t "; Note: deleting unused local function ~A ~S~%"
816                  operator name)
817          (let* ((new-locals (remove local locals :test 'eq))
818                 (new-form
819                  (if new-locals
820                      (list* operator new-locals body)
821                      (list* 'LOCALLY body))))
822            (return-from precompile-flet/labels (precompile1 new-form))))))
823    (list* (car form)
824           (precompile-local-functions locals)
825           body)))
826
827(defun precompile-function (form)
828  (if (and (consp (cadr form)) (eq (caadr form) 'LAMBDA))
829      (list 'FUNCTION (precompile-lambda (%cadr form)))
830      form))
831
832(defun precompile-if (form)
833  (let ((args (cdr form)))
834    (case (length args)
835      (2
836       (let ((test (precompile1 (%car args))))
837         (cond ((null test)
838                nil)
839               (;;(constantp test)
840                (eq test t)
841                (precompile1 (%cadr args)))
842               (t
843                (list 'IF
844                      test
845                      (precompile1 (%cadr args)))))))
846      (3
847       (let ((test (precompile1 (%car args))))
848         (cond ((null test)
849                (precompile1 (%caddr args)))
850               (;;(constantp test)
851                (eq test t)
852                (precompile1 (%cadr args)))
853               (t
854                (list 'IF
855                      test
856                      (precompile1 (%cadr args))
857                      (precompile1 (%caddr args)))))))
858      (t
859       (error "wrong number of arguments for IF")))))
860
861(defun precompile-when (form)
862  (if *in-jvm-compile*
863      (precompile1 (macroexpand form *precompile-env*))
864      (precompile-cons form)))
865
866(defun precompile-unless (form)
867  (if *in-jvm-compile*
868      (precompile1 (macroexpand form *precompile-env*))
869      (precompile-cons form)))
870
871;; MULTIPLE-VALUE-BIND is handled explicitly by the JVM compiler.
872(defun precompile-multiple-value-bind (form)
873  (let ((vars (cadr form))
874        (values-form (caddr form))
875        (body (cdddr form))
876        (*precompile-env* (make-environment *precompile-env*)))
877    (dolist (var vars)
878      (environment-add-symbol-binding *precompile-env* var nil))
879    (list* 'MULTIPLE-VALUE-BIND
880           vars
881           (precompile1 values-form)
882           (mapcar #'precompile1 body))))
883
884;; MULTIPLE-VALUE-LIST is handled explicitly by the JVM compiler.
885(defun precompile-multiple-value-list (form)
886  (list 'MULTIPLE-VALUE-LIST (precompile1 (cadr form))))
887
888(defun precompile-nth-value (form)
889  (if *in-jvm-compile*
890      (precompile1 (macroexpand form *precompile-env*))
891      form))
892
893(defun precompile-return (form)
894  (if *in-jvm-compile*
895      (precompile1 (macroexpand form *precompile-env*))
896      (list 'RETURN (precompile1 (cadr form)))))
897
898(defun precompile-return-from (form)
899  (list 'RETURN-FROM (cadr form) (precompile1 (caddr form))))
900
901(defun precompile-tagbody (form)
902  (do ((body (cdr form) (cdr body))
903       (result ()))
904      ((null body) (cons 'TAGBODY (nreverse result)))
905    (if (atom (car body))
906        (push (car body) result)
907        (push (let* ((first-form (car body))
908                     (expanded (precompile1 first-form)))
909                (if (and (symbolp expanded)
910                         (neq expanded first-form))
911                    ;; Workaround:
912                    ;;  Since our expansion/compilation order
913                    ;;   is out of sync with the definition of
914                    ;;   TAGBODY (which requires the compiler
915                    ;;   to look for tags before expanding),
916                    ;;   we need to disguise anything which might
917                    ;;   look like a tag. We do this by wrapping
918                    ;;   it in a PROGN form.
919                    (list 'PROGN expanded)
920                    expanded)) result))))
921
922(defun precompile-eval-when (form)
923  (list* 'EVAL-WHEN (cadr form) (mapcar #'precompile1 (cddr form))))
924
925(defun precompile-unwind-protect (form)
926  (list* 'UNWIND-PROTECT
927         (precompile1 (cadr form))
928         (mapcar #'precompile1 (cddr form))))
929
930;; EXPAND-MACRO is like MACROEXPAND, but EXPAND-MACRO quits if *IN-JVM-COMPILE*
931;; is false and a macro is encountered that is also implemented as a special
932;; operator, so interpreted code can use the special operator implementation.
933(defun expand-macro (form)
934  (let (exp)
935    (loop
936       (unless *in-jvm-compile*
937         (when (and (consp form)
938                    (symbolp (%car form))
939                    (special-operator-p (%car form)))
940           (return-from expand-macro (values form exp))))
941       (multiple-value-bind (result expanded)
942           (macroexpand-1 form *precompile-env*)
943         (unless expanded
944           (return-from expand-macro (values result exp)))
945         (setf form result
946               exp t)))))
947
948(declaim (ftype (function (t t) t) precompile-form))
949(defun precompile-form (form in-jvm-compile
950                        &optional precompile-env)
951  (let ((*in-jvm-compile* in-jvm-compile)
952        (*inline-declarations* *inline-declarations*)
953        (pre::*precompile-env* precompile-env))
954    (precompile1 form)))
955
956(defun install-handler (symbol &optional handler)
957  (declare (type symbol symbol))
958  (let ((handler (or handler
959                     (find-symbol (sys::%format nil "PRECOMPILE-~A"
960                                                (symbol-name symbol))
961                                  'precompiler))))
962    (unless (and handler (fboundp handler))
963      (error "No handler for ~S." (let ((*package* (find-package :keyword)))
964            (format nil "~S" symbol))))
965    (setf (get symbol 'precompile-handler) handler)))
966
967(defun install-handlers ()
968  (mapcar #'install-handler '(BLOCK
969                              CASE
970                              COND
971                              DOLIST
972                              DOTIMES
973                              EVAL-WHEN
974                              FUNCTION
975                              IF
976                              LAMBDA
977                              MACROLET
978                              MULTIPLE-VALUE-BIND
979                              MULTIPLE-VALUE-LIST
980                              NAMED-LAMBDA
981                              NTH-VALUE
982                              PROGN
983                              PROGV
984                              PSETF
985                              PSETQ
986                              RETURN
987                              RETURN-FROM
988                              SETF
989                              SETQ
990                              SYMBOL-MACROLET
991                              TAGBODY
992                              UNWIND-PROTECT
993                              UNLESS
994                              WHEN))
995
996  (dolist (pair '((ECASE                precompile-case)
997
998                  (AND                  precompile-cons)
999                  (OR                   precompile-cons)
1000
1001                  (CATCH                precompile-cons)
1002                  (MULTIPLE-VALUE-CALL  precompile-cons)
1003                  (MULTIPLE-VALUE-PROG1 precompile-cons)
1004
1005                  (DO                   precompile-do/do*)
1006                  (DO*                  precompile-do/do*)
1007
1008                  (LET                  precompile-let)
1009                  (LET*                 precompile-let*)
1010
1011                  (LOCALLY              precompile-locally)
1012
1013                  (FLET                 precompile-flet/labels)
1014                  (LABELS               precompile-flet/labels)
1015
1016                  (LOAD-TIME-VALUE      precompile-load-time-value)
1017
1018                  (DECLARE              precompile-identity)
1019                  (DEFUN                precompile-defun)
1020                  (GO                   precompile-identity)
1021                  (QUOTE                precompile-identity)
1022                  (THE                  precompile-the)
1023                  (THROW                precompile-cons)
1024                  (TRULY-THE            precompile-truly-the)
1025
1026                  (THREADS:SYNCHRONIZED-ON
1027                                        precompile-threads-synchronized-on)
1028     
1029      (JVM::WITH-INLINE-CODE precompile-identity)))
1030    (install-handler (first pair) (second pair))))
1031
1032(install-handlers)
1033
1034(export '(precompile-form))
1035
1036(in-package #:ext)
1037(defun macroexpand-all (form &optional env)
1038  (precompiler:precompile-form form t env))
1039
1040(in-package #:lisp)
1041
1042(defmacro compiler-let (bindings &body forms &environment env)
1043  (let ((bindings (mapcar #'(lambda (binding)
1044                              (if (atom binding) (list binding) binding))
1045                          bindings)))
1046    (progv (mapcar #'car bindings)
1047           (mapcar #'(lambda (binding)
1048                       (eval (cadr binding))) bindings)
1049      (macroexpand-all `(progn ,@forms) env))))
1050
1051(in-package #:system)
1052
1053(defun set-function-definition (name new old)
1054  (let ((*warn-on-redefinition* nil))
1055    (sys::%set-lambda-name new name)
1056    (sys:set-call-count new (sys:call-count old))
1057    (sys::%set-arglist new (sys::arglist old))
1058    (when (macro-function name)
1059      (setf new (make-macro name new)))
1060    (if (typep old 'standard-generic-function)
1061        (mop:set-funcallable-instance-function old new)
1062        (setf (fdefinition name) new))))
1063
1064(defun precompile (name &optional definition)
1065  (unless definition
1066    (setq definition (or (and (symbolp name) (macro-function name))
1067                         (fdefinition name))))
1068  (let ((expr definition)
1069        env result
1070        (pre::*precompile-env* nil))
1071    (when (functionp definition)
1072      (multiple-value-bind (form closure-p)
1073          (function-lambda-expression definition)
1074        (unless form
1075          (return-from precompile (values nil t t)))
1076        (setq env closure-p)
1077        (setq expr form)))
1078    (unless (and (consp expr) (eq (car expr) 'lambda))
1079      (format t "Unable to precompile ~S.~%" name)
1080      (return-from precompile (values nil t t)))
1081    (setf result
1082          (sys:make-closure (precompiler:precompile-form expr nil env) env))
1083    (when (and name (functionp result))
1084      (sys::set-function-definition name result definition))
1085    (values (or name result) nil nil)))
1086
1087(defun precompile-package (pkg &key verbose)
1088  (dolist (sym (package-symbols pkg))
1089    (when (fboundp sym)
1090      (unless (special-operator-p sym)
1091        (let ((f (fdefinition sym)))
1092          (unless (compiled-function-p f)
1093            (when verbose
1094              (format t "Precompiling ~S~%" sym)
1095              (finish-output))
1096            (precompile sym))))))
1097  t)
1098
1099(defun %compile (name definition)
1100  (if (and name (fboundp name) (%typep (symbol-function name) 'generic-function))
1101      (values name nil nil)
1102      (precompile name definition)))
1103
1104;; ;; Redefine EVAL to precompile its argument.
1105;; (defun eval (form)
1106;;   (%eval (precompile-form form nil)))
1107
1108;; ;; Redefine DEFMACRO to precompile the expansion function on the fly.
1109;; (defmacro defmacro (name lambda-list &rest body)
1110;;   (let* ((form (gensym "WHOLE-"))
1111;;          (env (gensym "ENVIRONMENT-")))
1112;;     (multiple-value-bind (body decls)
1113;;         (parse-defmacro lambda-list form body name 'defmacro :environment env)
1114;;       (let ((expander `(lambda (,form ,env) ,@decls (block ,name ,body))))
1115;;         `(progn
1116;;            (let ((macro (make-macro ',name
1117;;                                     (or (precompile nil ,expander) ,expander))))
1118;;              ,@(if (special-operator-p name)
1119;;                    `((put ',name 'macroexpand-macro macro))
1120;;                    `((fset ',name macro)))
1121;;              (%set-arglist macro ',lambda-list)
1122;;              ',name))))))
1123
1124;; Make an exception just this one time...
1125(when (get 'defmacro 'macroexpand-macro)
1126  (fset 'defmacro (get 'defmacro 'macroexpand-macro))
1127  (remprop 'defmacro 'macroexpand-macro))
1128
1129(defvar *defined-functions*)
1130
1131(defvar *undefined-functions*)
1132
1133(defun note-name-defined (name)
1134  (when (boundp '*defined-functions*)
1135    (push name *defined-functions*))
1136  (when (and (boundp '*undefined-functions*) (not (null *undefined-functions*)))
1137    (setf *undefined-functions* (remove name *undefined-functions*))))
1138
1139;; Redefine DEFUN to precompile the definition on the fly.
1140(defmacro defun (name lambda-list &body body &environment env)
1141  (note-name-defined name)
1142  (multiple-value-bind (body decls doc)
1143      (parse-body body)
1144    (let* ((block-name (fdefinition-block-name name))
1145           (lambda-expression
1146            `(named-lambda ,name ,lambda-list
1147                           ,@decls
1148                           ,@(when doc `(,doc))
1149                           (block ,block-name ,@body))))
1150      (cond ((and (boundp 'jvm::*file-compilation*)
1151                  ;; when JVM.lisp isn't loaded yet, this variable isn't bound
1152                  ;; meaning that we're not trying to compile to a file:
1153                  ;; Both COMPILE and COMPILE-FILE bind this variable.
1154                  ;; This function is also triggered by MACROEXPAND, though
1155                  jvm::*file-compilation*)
1156             `(fset ',name ,lambda-expression))
1157            (t
1158             (when (and env (empty-environment-p env))
1159               (setf env nil))
1160             (when (null env)
1161               (setf lambda-expression (precompiler:precompile-form lambda-expression nil)))
1162             `(progn
1163                (%defun ',name ,lambda-expression)
1164                ,@(when doc
1165                   `((%set-documentation ',name 'function ,doc)))))))))
1166
1167(export '(precompile))
1168
1169;;(provide "PRECOMPILER")
Note: See TracBrowser for help on using the repository browser.