source: trunk/abcl/src/org/armedbear/lisp/compile-file.lisp @ 11811

Last change on this file since 11811 was 11811, checked in by ehuelsmann, 14 years ago

Add documentation as to why we do what we were doing.

  • Property svn:eol-style set to native
  • Property svn:keywords set to Id
File size: 24.8 KB
Line 
1;;; compile-file.lisp
2;;;
3;;; Copyright (C) 2004-2006 Peter Graves
4;;; $Id: compile-file.lisp 11811 2009-05-01 20:43:46Z 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., 59 Temple Place - Suite 330, Boston, MA  02111-1307, 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(require '#:jvm)
35
36(defvar *fbound-names*)
37
38(defvar *class-number*)
39
40(defvar *output-file-pathname*)
41
42(declaim (ftype (function (t) t) compute-classfile-name))
43(defun compute-classfile-name (n &optional (output-file-pathname
44                                            *output-file-pathname*))
45  "Computes the name of the class file associated with number `n'."
46  (let ((name
47         (%format nil "~A-~D"
48                  (substitute #\_ #\.
49                              (pathname-name output-file-pathname)) n)))
50    (namestring (merge-pathnames (make-pathname :name name :type "cls")
51                                 output-file-pathname))))
52
53(declaim (ftype (function () t) next-classfile-name))
54(defun next-classfile-name ()
55  (compute-classfile-name (incf *class-number*)))
56
57(defmacro report-error (&rest forms)
58  `(handler-case (progn ,@forms)
59     (compiler-unsupported-feature-error (condition)
60       (fresh-line)
61       (%format t "; UNSUPPORTED-FEATURE: ~A~%" condition)
62       (values nil condition))))
63
64;; Dummy function. Should never be called.
65(defun dummy (&rest ignored)
66  (declare (ignore ignored))
67  (assert nil))
68
69(declaim (ftype (function (t) t) verify-load))
70(defun verify-load (classfile)
71  (and classfile
72       (let ((*load-truename* *output-file-pathname*))
73         (report-error
74          (load-compiled-function classfile)))))
75
76(declaim (ftype (function (t stream) t) process-defconstant))
77(defun process-defconstant (form stream)
78  ;; "If a DEFCONSTANT form appears as a top level form, the compiler
79  ;; must recognize that [the] name names a constant variable. An
80  ;; implementation may choose to evaluate the value-form at compile
81  ;; time, load time, or both. Therefore, users must ensure that the
82  ;; initial-value can be evaluated at compile time (regardless of
83  ;; whether or not references to name appear in the file) and that
84  ;; it always evaluates to the same value."
85  (eval form)
86  (cond ((structure-object-p (third form))
87         (multiple-value-bind (creation-form initialization-form)
88             (make-load-form (third form))
89           (dump-form (list 'DEFCONSTANT (second form) creation-form) stream)))
90        (t
91         (dump-form form stream)))
92  (%stream-terpri stream))
93
94(declaim (ftype (function (t) t) note-toplevel-form))
95(defun note-toplevel-form (form)
96  (when *compile-print*
97    (fresh-line)
98    (princ "; ")
99    (let ((*print-length* 2)
100          (*print-level* 2)
101          (*print-pretty* nil))
102      (prin1 form))
103    (terpri)))
104
105(declaim (ftype (function (t stream t) t) process-toplevel-form))
106(defun process-toplevel-form (form stream compile-time-too)
107  (cond ((atom form)
108         (when compile-time-too
109           (eval form)))
110        (t
111         (let ((operator (%car form)))
112           (case operator
113             (MACROLET
114              (process-toplevel-macrolet form stream compile-time-too)
115              (return-from process-toplevel-form))
116             ((IN-PACKAGE DEFPACKAGE)
117              (note-toplevel-form form)
118              (setf form (precompile-form form nil))
119              (eval form)
120              ;; Force package prefix to be used when dumping form.
121              (let ((*package* +keyword-package+))
122                (dump-form form stream))
123              (%stream-terpri stream)
124              (return-from process-toplevel-form))
125             ((DEFVAR DEFPARAMETER)
126              (note-toplevel-form form)
127              (if compile-time-too
128                  (eval form)
129                  ;; "If a DEFVAR or DEFPARAMETER form appears as a top level form,
130                  ;; the compiler must recognize that the name has been proclaimed
131                  ;; special. However, it must neither evaluate the initial-value
132                  ;; form nor assign the dynamic variable named NAME at compile
133                  ;; time."
134                  (let ((name (second form)))
135                    (%defvar name))))
136             (DEFCONSTANT
137              (note-toplevel-form form)
138              (process-defconstant form stream)
139              (return-from process-toplevel-form))
140             (DEFUN
141              (note-toplevel-form form)
142              (let* ((name (second form))
143                     (block-name (fdefinition-block-name name))
144                     (lambda-list (third form))
145                     (body (nthcdr 3 form))
146                     (*speed* *speed*)
147                     (*space* *space*)
148                     (*safety* *safety*)
149                     (*debug* *debug*))
150                (multiple-value-bind (body decls doc)
151                    (parse-body body)
152                  (let* ((expr `(lambda ,lambda-list ,@decls (block ,block-name ,@body)))
153                         (classfile-name (next-classfile-name))
154                         (classfile (report-error
155                                     (jvm:compile-defun name expr nil classfile-name)))
156                         (compiled-function (verify-load classfile)))
157                    (cond (compiled-function
158                           (setf form
159                                 `(fset ',name
160                                        (load-compiled-function ,(file-namestring classfile))
161                                        ,*source-position*
162                                        ',lambda-list
163                                        ,doc))
164                           (when compile-time-too
165                             (fset name compiled-function)))
166                          (t
167                           ;; FIXME This should be a warning or error of some sort...
168                           (format *error-output* "; Unable to compile function ~A~%" name)
169                           (let ((precompiled-function (precompile-form expr nil)))
170                             (setf form
171                                   `(fset ',name
172                                          ,precompiled-function
173                                          ,*source-position*
174                                          ',lambda-list
175                                          ,doc)))
176                           (when compile-time-too
177                             (eval form)))))
178                  (when (and (symbolp name) (eq (get name '%inline) 'INLINE))
179                    ;; FIXME Need to support SETF functions too!
180                    (setf (inline-expansion name)
181                          (jvm::generate-inline-expansion block-name lambda-list body))
182                    (dump-form `(setf (inline-expansion ',name) ',(inline-expansion name))
183                               stream)
184                    (%stream-terpri stream)))
185                (push name jvm::*functions-defined-in-current-file*)
186                (note-name-defined name)
187                ;; If NAME is not fbound, provide a dummy definition so that
188                ;; getSymbolFunctionOrDie() will succeed when we try to verify that
189                ;; functions defined later in the same file can be loaded correctly.
190                (unless (fboundp name)
191                  (setf (fdefinition name) #'dummy)
192                  (push name *fbound-names*))))
193             ((DEFGENERIC DEFMETHOD)
194              (note-toplevel-form form)
195              (note-name-defined (second form))
196              (let ((*compile-print* nil))
197                (process-toplevel-form (macroexpand-1 form *compile-file-environment*)
198                                       stream compile-time-too))
199              (return-from process-toplevel-form))
200             (DEFMACRO
201              (note-toplevel-form form)
202              (let ((name (second form)))
203                (eval form)
204                (let* ((expr (function-lambda-expression (macro-function name)))
205                       (classfile-name (next-classfile-name))
206                       (classfile
207                        (ignore-errors
208                         (jvm:compile-defun nil expr nil classfile-name))))
209                  (if (verify-load classfile)
210                      (progn
211                        (setf form
212                              (if (special-operator-p name)
213                                  `(put ',name 'macroexpand-macro
214                                        (make-macro ',name
215                                                    (load-compiled-function
216                                                     ,(file-namestring classfile))))
217                                  `(fset ',name
218                                         (make-macro ',name
219                                                     (load-compiled-function
220                                                      ,(file-namestring classfile)))
221                                         ,*source-position*
222                                         ',(third form)))))
223                      ;; FIXME error or warning
224                      (format *error-output* "; Unable to compile macro ~A~%" name)))))
225             (DEFTYPE
226              (note-toplevel-form form)
227              (eval form))
228             (EVAL-WHEN
229              (multiple-value-bind (ct lt e)
230                  (parse-eval-when-situations (cadr form))
231                (let ((new-compile-time-too (or ct
232                                                (and compile-time-too e)))
233                      (body (cddr form)))
234                  (cond (lt
235                         (process-toplevel-progn body stream new-compile-time-too))
236                        (new-compile-time-too
237                         (eval `(progn ,@body)))))
238                (return-from process-toplevel-form)))
239             (LOCALLY
240              ;; FIXME Need to handle special declarations too!
241              (let ((*speed* *speed*)
242                    (*safety* *safety*)
243                    (*debug* *debug*)
244                    (*space* *space*)
245                    (*inline-declarations* *inline-declarations*))
246                (multiple-value-bind (forms decls)
247                    (parse-body (cdr form) nil)
248                  (process-optimization-declarations decls)
249                  (process-toplevel-progn forms stream compile-time-too)
250                  (return-from process-toplevel-form))))
251             (PROGN
252              (process-toplevel-progn (cdr form) stream compile-time-too)
253              (return-from process-toplevel-form))
254             (DECLARE
255              (compiler-style-warn "Misplaced declaration: ~S" form))
256             (t
257              (when (and (symbolp operator)
258                         (macro-function operator *compile-file-environment*))
259                (note-toplevel-form form)
260                ;; Note that we want MACROEXPAND-1 and not MACROEXPAND here, in
261                ;; case the form being expanded expands into something that needs
262                ;; special handling by PROCESS-TOPLEVEL-FORM (e.g. DEFMACRO).
263                (let ((*compile-print* nil))
264                  (process-toplevel-form (macroexpand-1 form *compile-file-environment*)
265                                         stream compile-time-too))
266                (return-from process-toplevel-form))
267
268              (cond ((eq operator 'QUOTE)
269;;                      (setf form (precompile-form form nil))
270                     (when compile-time-too
271                       (eval form))
272                     (return-from process-toplevel-form)
273                     )
274                    ((eq operator 'PUT)
275                     (setf form (precompile-form form nil)))
276                    ((eq operator 'COMPILER-DEFSTRUCT)
277                     (setf form (precompile-form form nil)))
278                    ((eq operator 'PROCLAIM)
279                     (setf form (precompile-form form nil)))
280                    ((and (memq operator '(EXPORT REQUIRE PROVIDE SHADOW))
281                          (or (keywordp (second form))
282                              (and (listp (second form))
283                                   (eq (first (second form)) 'QUOTE))))
284                     (setf form (precompile-form form nil)))
285                    ((eq operator 'IMPORT)
286                     (setf form (precompile-form form nil))
287                     ;; Make sure package prefix is printed when symbols are imported.
288                     (let ((*package* +keyword-package+))
289                       (dump-form form stream))
290                     (%stream-terpri stream)
291                     (when compile-time-too
292                       (eval form))
293                     (return-from process-toplevel-form))
294                    ((and (eq operator '%SET-FDEFINITION)
295                          (eq (car (second form)) 'QUOTE)
296                          (consp (third form))
297                          (eq (%car (third form)) 'FUNCTION)
298                          (symbolp (cadr (third form))))
299                     (setf form (precompile-form form nil)))
300;;                     ((memq operator '(LET LET*))
301;;                      (let ((body (cddr form)))
302;;                        (if (dolist (subform body nil)
303;;                              (when (and (consp subform) (eq (%car subform) 'DEFUN))
304;;                                (return t)))
305;;                            (setf form (convert-toplevel-form form))
306;;                            (setf form (precompile-form form nil)))))
307                    ((eq operator 'mop::ensure-method)
308                     (setf form (convert-ensure-method form)))
309                    ((and (symbolp operator)
310                          (not (special-operator-p operator))
311                          (null (cdr form)))
312                     (setf form (precompile-form form nil)))
313                    (t
314;;                      (setf form (precompile-form form nil))
315                     (note-toplevel-form form)
316                     (let ((new-form (convert-toplevel-form form)))
317                       ;; The converted form depends on the loader
318                       ;; but since we don't own the loader here,
319                       ;; we'll dump the converted form and eval
320                       ;; the original one (which won't depend on the loader
321                       ;; because it doesn't contain a compiled function)
322                       (when (consp new-form)
323                         (dump-form new-form stream)
324                         (%stream-terpri stream)))
325                     (when compile-time-too
326                       (eval form))
327                     (return-from process-toplevel-form)
328                     )))))))
329  (when (consp form)
330    (dump-form form stream)
331    (%stream-terpri stream))
332  (when compile-time-too
333    (eval form)))
334
335(declaim (ftype (function (t) t) convert-ensure-method))
336(defun convert-ensure-method (form)
337  (c-e-m-1 form :function)
338  (c-e-m-1 form :fast-function)
339  (precompile-form form nil))
340
341(declaim (ftype (function (t t) t) c-e-m-1))
342(defun c-e-m-1 (form key)
343  (let* ((tail (cddr form))
344         (function-form (getf tail key)))
345    (when (and function-form (consp function-form)
346               (eq (%car function-form) 'FUNCTION))
347      (let ((lambda-expression (cadr function-form)))
348        (let* ((*speed* *speed*)
349               (*space* *space*)
350               (*safety* *safety*)
351               (*debug* *debug*))
352          (let* ((classfile-name (next-classfile-name))
353                 (classfile (report-error
354                             (jvm:compile-defun nil lambda-expression nil classfile-name)))
355                 (compiled-function (verify-load classfile)))
356            (cond (compiled-function
357                   (setf (getf tail key)
358                         `(load-compiled-function ,(file-namestring classfile))))
359                  (t
360                   ;; FIXME This should be a warning or error of some sort...
361                   (format *error-output* "; Unable to compile method~%")))))))))
362
363(declaim (ftype (function (t) t) convert-toplevel-form))
364(defun convert-toplevel-form (form)
365  (let* ((expr `(lambda () ,form))
366         (classfile-name (next-classfile-name))
367         (classfile (report-error (jvm:compile-defun nil expr nil classfile-name)))
368         (compiled-function (verify-load classfile)))
369    (setf form
370          (if compiled-function
371              `(funcall (load-compiled-function ,(file-namestring classfile)))
372              (precompile-form form nil)))))
373
374
375(defun process-toplevel-macrolet (form stream compile-time-too)
376  (let ((*compile-file-environment* (make-environment *compile-file-environment*)))
377    (dolist (definition (cadr form))
378      (environment-add-macro-definition *compile-file-environment*
379                                        (car definition)
380                                        (make-macro (car definition)
381                                                    (make-expander-for-macrolet definition))))
382    (dolist (body-form (cddr form))
383      (process-toplevel-form body-form stream compile-time-too))))
384
385(declaim (ftype (function (t stream t) t) process-toplevel-progn))
386(defun process-toplevel-progn (forms stream compile-time-too)
387  (dolist (form forms)
388    (process-toplevel-form form stream compile-time-too)))
389
390;;; Adapted from SBCL.
391;;; Parse an EVAL-WHEN situations list, returning three flags,
392;;; (VALUES COMPILE-TOPLEVEL LOAD-TOPLEVEL EXECUTE), indicating
393;;; the types of situations present in the list.
394(defun parse-eval-when-situations (situations)
395  (when (or (not (listp situations))
396      (set-difference situations
397          '(:compile-toplevel
398            compile
399            :load-toplevel
400            load
401            :execute
402            eval)))
403    (error "Bad EVAL-WHEN situation list: ~S." situations))
404  (values (intersection '(:compile-toplevel compile) situations)
405    (intersection '(:load-toplevel load) situations)
406    (intersection '(:execute eval) situations)))
407
408(defun compile-file (input-file
409                     &key
410                     output-file
411                     ((:verbose *compile-verbose*) *compile-verbose*)
412                     ((:print *compile-print*) *compile-print*)
413                     external-format)
414  (declare (ignore external-format)) ; FIXME
415  (unless (or (and (probe-file input-file) (not (file-directory-p input-file)))
416              (pathname-type input-file))
417    (let ((pathname (merge-pathnames (make-pathname :type "lisp") input-file)))
418      (when (probe-file pathname)
419        (setf input-file pathname))))
420  (setf output-file (if output-file
421                        (merge-pathnames output-file *default-pathname-defaults*)
422                        (compile-file-pathname input-file)))
423  (let* ((*output-file-pathname* output-file)
424         (type (pathname-type output-file))
425         (temp-file (merge-pathnames (make-pathname :type (concatenate 'string type "-tmp"))
426                                     output-file))
427         (warnings-p nil)
428         (failure-p nil))
429    (with-open-file (in input-file :direction :input)
430      (let* ((*compile-file-pathname* (pathname in))
431             (*compile-file-truename* (truename in))
432             (*source* *compile-file-truename*)
433             (*class-number* 0)
434             (namestring (namestring *compile-file-truename*))
435             (start (get-internal-real-time))
436             elapsed)
437        (when *compile-verbose*
438          (format t "; Compiling ~A ...~%" namestring))
439        (with-compilation-unit ()
440          (with-open-file (out temp-file :direction :output :if-exists :supersede)
441            (let ((*readtable* *readtable*)
442                  (*read-default-float-format* *read-default-float-format*)
443                  (*read-base* *read-base*)
444                  (*package* *package*)
445                  (*speed* *speed*)
446                  (*space* *space*)
447                  (*safety* *safety*)
448                  (*debug* *debug*)
449                  (*explain* *explain*)
450                  (jvm::*functions-defined-in-current-file* '())
451                  (*fbound-names* '())
452                  (*fasl-anonymous-package* (%make-package)))
453              (jvm::with-file-compilation
454                (write "; -*- Mode: Lisp -*-" :escape nil :stream out)
455                (%stream-terpri out)
456                (let ((*package* (find-package '#:cl)))
457                  (write (list 'init-fasl :version *fasl-version*) :stream out)
458                  (%stream-terpri out)
459                  (write (list 'setq '*source* *compile-file-truename*) :stream out)
460                  (%stream-terpri out))
461                (handler-bind ((style-warning #'(lambda (c)
462                                                  (declare (ignore c))
463                                                  (setf warnings-p t)
464                                                  nil))
465                               ((or warning
466                                    compiler-error) #'(lambda (c)
467                                                        (declare (ignore c))
468                                                        (setf warnings-p t
469                                                              failure-p t)
470                                                        nil)))
471                  (loop
472                     (let* ((*source-position* (file-position in))
473                            (jvm::*source-line-number* (stream-line-number in))
474                            (form (read in nil in))
475                            (*compiler-error-context* form))
476                       (when (eq form in)
477                         (return))
478                       (process-toplevel-form form out nil))))
479                (dolist (name *fbound-names*)
480                  (fmakunbound name))))))
481        (rename-file temp-file output-file)
482
483        (when *compile-file-zip*
484          (let* ((type ;; Don't use ".zip", it'll result in an extension
485                       ;;  with a dot, which is rejected by NAMESTRING
486                  (%format nil "~A~A" (pathname-type output-file) "-zip"))
487                 (zipfile (namestring
488                           (merge-pathnames (make-pathname :type type)
489                                            output-file)))
490                 (pathnames ()))
491            (dotimes (i *class-number*)
492              (let* ((pathname (compute-classfile-name (1+ i))))
493                (when (probe-file pathname)
494                  (push pathname pathnames))))
495            (setf pathnames (nreverse pathnames))
496            (let ((load-file (merge-pathnames (make-pathname :type "_")
497                                              output-file)))
498              (rename-file output-file load-file)
499              (push load-file pathnames))
500            (zip zipfile pathnames)
501            (dolist (pathname pathnames)
502              (let ((truename (probe-file pathname)))
503                (when truename
504                  (delete-file truename))))
505            (rename-file zipfile output-file)))
506
507        (setf elapsed (/ (- (get-internal-real-time) start) 1000.0))
508        (when *compile-verbose*
509          (format t "~&; Wrote ~A (~A seconds)~%" (namestring output-file) elapsed))))
510    (values (truename output-file) warnings-p failure-p)))
511
512(defun compile-file-if-needed (input-file &rest allargs &key force-compile
513                               &allow-other-keys)
514  (setf input-file (truename input-file))
515  (cond (force-compile
516         (remf allargs :force-compile)
517         (apply 'compile-file input-file allargs))
518        (t
519         (let* ((source-write-time (file-write-date input-file))
520                (output-file       (or (getf allargs :output-file)
521                                       (compile-file-pathname input-file)))
522                (target-write-time (and (probe-file output-file)
523                                        (file-write-date output-file))))
524           (if (or (null target-write-time)
525                   (<= target-write-time source-write-time))
526               (apply 'compile-file input-file allargs)
527               output-file)))))
528
529(provide 'compile-file)
Note: See TracBrowser for help on using the repository browser.