lisp-build.lisp 42.6 KB
Newer Older
1
2
3
;;;; -------------------------------------------------------------------------
;;;; Support to build (compile and load) Lisp files

4
(uiop/package:define-package :uiop/lisp-build
5
  (:nicknames :asdf/lisp-build) ;; OBSOLETE, used by slime/contrib/swank-asdf.lisp
6
7
  (:use :uiop/common-lisp :uiop/package :uiop/utility
   :uiop/os :uiop/pathname :uiop/filesystem :uiop/stream :uiop/image)
8
  (:export
9
   ;; Variables
10
   #:*compile-file-warnings-behaviour* #:*compile-file-failure-behaviour*
11
   #:*output-translation-function*
12
   #:*optimization-settings* #:*previous-optimization-settings*
13
   #:*base-build-directory*
14
15
16
   #:compile-condition #:compile-file-error #:compile-warned-error #:compile-failed-error
   #:compile-warned-warning #:compile-failed-warning
   #:check-lisp-compile-results #:check-lisp-compile-warnings
17
18
   #:*uninteresting-conditions* #:*usual-uninteresting-conditions*
   #:*uninteresting-compiler-conditions* #:*uninteresting-loader-conditions*
19
20
   ;; Types
   #+sbcl #:sb-grovel-unknown-constant-condition
21
   ;; Functions & Macros
22
   #:get-optimization-settings #:proclaim-optimization-settings #:with-optimization-settings
23
24
   #:call-with-muffled-compiler-conditions #:with-muffled-compiler-conditions
   #:call-with-muffled-loader-conditions #:with-muffled-loader-conditions
25
   #:reify-simple-sexp #:unreify-simple-sexp
26
   #:reify-deferred-warnings #:unreify-deferred-warnings
27
   #:reset-deferred-warnings #:save-deferred-warnings #:check-deferred-warnings
28
   #:with-saved-deferred-warnings #:warnings-file-p #:warnings-file-type #:*warnings-file-type*
29
   #:enable-deferred-warnings-check #:disable-deferred-warnings-check
30
31
   #:current-lisp-file-pathname #:load-pathname
   #:lispize-pathname #:compile-file-type #:call-around-hook
32
   #:compile-file* #:compile-file-pathname* #:*compile-check*
33
   #:load* #:load-from-string #:combine-fasls)
34
  (:intern #:defaults #:failure-p #:warnings-p #:s #:y #:body))
35
(in-package :uiop/lisp-build)
36

37
38
39
40
(with-upgradability ()
  (defvar *compile-file-warnings-behaviour*
    (or #+clisp :ignore :warn)
    "How should ASDF react if it encounters a warning when compiling a file?
41
42
Valid values are :error, :warn, and :ignore.")

43
44
45
  (defvar *compile-file-failure-behaviour*
    (or #+(or mkcl sbcl) :error #+clisp :ignore :warn)
    "How should ASDF react if it encounters a failure (per the ANSI spec of COMPILE-FILE)
46
47
when compiling a file, which includes any non-style-warning warning.
Valid values are :error, :warn, and :ignore.
48
Note that ASDF ALWAYS raises an error if it fails to create an output file when compiling.")
49

50
51
52
53
54
  (defvar *base-build-directory* nil
    "When set to a non-null value, it should be an absolute directory pathname,
which will serve as the *DEFAULT-PATHNAME-DEFAULTS* around a COMPILE-FILE,
what more while the input-file is shortened if possible to ENOUGH-PATHNAME relative to it.
This can help you produce more deterministic output for FASLs."))
55
56

;;; Optimization settings
57
(with-upgradability ()
58
59
60
61
  (defvar *optimization-settings* nil
    "Optimization settings to be used by PROCLAIM-OPTIMIZATION-SETTINGS")
  (defvar *previous-optimization-settings* nil
    "Optimization settings saved by PROCLAIM-OPTIMIZATION-SETTINGS")
62
63
  (defparameter +optimization-variables+
    ;; TODO: allegro genera corman mcl
64
65
    (or #+(or abcl xcl) '(system::*speed* system::*space* system::*safety* system::*debug*)
        #+clisp '() ;; system::*optimize* is a constant hash-table! (with non-constant contents)
66
67
        #+clozure '(ccl::*nx-speed* ccl::*nx-space* ccl::*nx-safety*
                    ccl::*nx-debug* ccl::*nx-cspeed*)
68
        #+(or cmucl scl) '(c::*default-cookie*)
69
        #+clasp nil
Elias Pipping's avatar
Elias Pipping committed
70
        #+ecl (unless (use-ecl-byte-compiler-p) '(c::*speed* c::*space* c::*safety* c::*debug*))
71
72
73
74
        #+gcl '(compiler::*speed* compiler::*space* compiler::*compiler-new-safety* compiler::*debug*)
        #+lispworks '(compiler::*optimization-level*)
        #+mkcl '(si::*speed* si::*space* si::*safety* si::*debug*)
        #+sbcl '(sb-c::*policy*)))
75
76
  (defun get-optimization-settings ()
    "Get current compiler optimization settings, ready to PROCLAIM again"
77
    #-(or abcl allegro clasp clisp clozure cmucl ecl lispworks mkcl sbcl scl xcl)
78
79
    (warn "~S does not support ~S. Please help me fix that."
          'get-optimization-settings (implementation-type))
80
81
    #+clasp (cleavir-env:optimize (cleavir-env:optimize-info CLASP-CLEAVIR:*CLASP-ENV*))
    #+(or abcl allegro clisp clozure cmucl ecl lispworks mkcl sbcl scl xcl)
82
    (let ((settings '(speed space safety debug compilation-speed #+(or cmucl scl) c::brevity)))
83
84
85
86
      #.`(loop #+(or allegro clozure)
               ,@'(:with info = #+allegro (sys:declaration-information 'optimize)
                   #+clozure (ccl:declaration-information 'optimize nil))
               :for x :in settings
Francois-Rene Rideau's avatar
Francois-Rene Rideau committed
87
               ,@(or #+(or abcl clasp ecl gcl mkcl xcl) '(:for v :in +optimization-variables+))
88
89
               :for y = (or #+(or allegro clozure) (second (assoc x info)) ; normalize order
                            #+clisp (gethash x system::*optimize* 1)
90
                            #+(or abcl ecl mkcl xcl) (symbol-value v)
91
                            #+(or cmucl scl) (slot-value c::*default-cookie*
92
93
                                                       (case x (compilation-speed 'c::cspeed)
                                                             (otherwise x)))
94
                            #+lispworks (slot-value compiler::*optimization-level* x)
95
                            #+sbcl (sb-c::policy-quality sb-c::*policy* x))
96
97
98
99
100
101
               :when y :collect (list x y))))
  (defun proclaim-optimization-settings ()
    "Proclaim the optimization settings in *OPTIMIZATION-SETTINGS*"
    (proclaim `(optimize ,@*optimization-settings*))
    (let ((settings (get-optimization-settings)))
      (unless (equal *previous-optimization-settings* settings)
102
103
        (setf *previous-optimization-settings* settings))))
  (defmacro with-optimization-settings ((&optional (settings *optimization-settings*)) &body body)
104
105
106
107
108
    #+(or allegro clasp clisp)
    (let ((previous-settings (gensym "PREVIOUS-SETTINGS"))
          (reset-settings (gensym "RESET-SETTINGS")))
      `(let* ((,previous-settings (get-optimization-settings))
              (,reset-settings #+clasp (reverse ,previous-settings) #-clasp ,previous-settings))
109
110
         ,@(when settings `((proclaim `(optimize ,@,settings))))
         (unwind-protect (progn ,@body)
111
112
           (proclaim `(optimize ,@,reset-settings)))))
    #-(or allegro clasp clisp)
113
114
115
    `(let ,(loop :for v :in +optimization-variables+ :collect `(,v ,v))
       ,@(when settings `((proclaim `(optimize ,@,settings))))
       ,@body)))
116
117
118


;;; Condition control
119
120
121
122
(with-upgradability ()
  #+sbcl
  (progn
    (defun sb-grovel-unknown-constant-condition-p (c)
123
      "Detect SB-GROVEL unknown-constant conditions on older versions of SBCL"
124
125
126
127
128
129
130
131
      (and (typep c 'sb-int:simple-style-warning)
           (string-enclosed-p
            "Couldn't grovel for "
            (simple-condition-format-control c)
            " (unknown to the C compiler).")))
    (deftype sb-grovel-unknown-constant-condition ()
      '(and style-warning (satisfies sb-grovel-unknown-constant-condition-p))))

132
  (defvar *usual-uninteresting-conditions*
133
134
    (append
     ;;#+clozure '(ccl:compiler-warning)
135
     #+cmucl '("Deleting unreachable code.")
136
137
     #+lispworks '("~S being redefined in ~A (previously in ~A)."
                   "~S defined more than once in ~A.") ;; lispworks gets confused by eval-when.
138
139
140
141
     #+sbcl
     '(sb-c::simple-compiler-note
       "&OPTIONAL and &KEY found in the same lambda list: ~S"
       #+sb-eval sb-kernel:lexical-environment-too-complex
142
       sb-kernel:undefined-alien-style-warning
143
       sb-grovel-unknown-constant-condition ; defined above.
144
       sb-ext:implicit-generic-function-warning ;; Controversial.
145
146
       sb-int:package-at-variance
       sb-kernel:uninteresting-redefinition
147
148
149
150
151
152
       ;; BEWARE: the below four are controversial to include here.
       sb-kernel:redefinition-with-defun
       sb-kernel:redefinition-with-defgeneric
       sb-kernel:redefinition-with-defmethod
       sb-kernel::redefinition-with-defmacro) ; not exported by old SBCLs
     '("No generic function ~S present when encountering macroexpansion of defmethod. Assuming it will be an instance of standard-generic-function.")) ;; from closer2mop
153
154
155
    "A suggested value to which to set or bind *uninteresting-conditions*.")

  (defvar *uninteresting-conditions* '()
156
157
158
    "Conditions that may be skipped while compiling or loading Lisp code.")
  (defvar *uninteresting-compiler-conditions* '()
    "Additional conditions that may be skipped while compiling Lisp code.")
159
160
161
162
163
  (defvar *uninteresting-loader-conditions*
    (append
     '("Overwriting already existing readtable ~S." ;; from named-readtables
       #(#:finalizers-off-warning :asdf-finalizers)) ;; from asdf-finalizers
     #+clisp '(clos::simple-gf-replacing-method-warning))
164
    "Additional conditions that may be skipped while loading Lisp code."))
165
166

;;;; ----- Filtering conditions while building -----
167
168
(with-upgradability ()
  (defun call-with-muffled-compiler-conditions (thunk)
169
    "Call given THUNK in a context where uninteresting conditions and compiler conditions are muffled"
170
    (call-with-muffled-conditions
171
     thunk (append *uninteresting-conditions* *uninteresting-compiler-conditions*)))
172
  (defmacro with-muffled-compiler-conditions ((&optional) &body body)
173
    "Trivial syntax for CALL-WITH-MUFFLED-COMPILER-CONDITIONS"
174
175
    `(call-with-muffled-compiler-conditions #'(lambda () ,@body)))
  (defun call-with-muffled-loader-conditions (thunk)
176
    "Call given THUNK in a context where uninteresting conditions and loader conditions are muffled"
177
    (call-with-muffled-conditions
178
     thunk (append *uninteresting-conditions* *uninteresting-loader-conditions*)))
179
  (defmacro with-muffled-loader-conditions ((&optional) &body body)
180
    "Trivial syntax for CALL-WITH-MUFFLED-LOADER-CONDITIONS"
181
    `(call-with-muffled-loader-conditions #'(lambda () ,@body))))
182

183

184
;;;; Handle warnings and failures
185
186
187
188
189
190
191
192
193
(with-upgradability ()
  (define-condition compile-condition (condition)
    ((context-format
      :initform nil :reader compile-condition-context-format :initarg :context-format)
     (context-arguments
      :initform nil :reader compile-condition-context-arguments :initarg :context-arguments)
     (description
      :initform nil :reader compile-condition-description :initarg :description))
    (:report (lambda (c s)
194
195
196
197
               (format s (compatfmt "~@<~A~@[ while ~?~]~@:>")
                       (or (compile-condition-description c) (type-of c))
                       (compile-condition-context-format c)
                       (compile-condition-context-arguments c)))))
198
199
200
201
202
203
204
205
  (define-condition compile-file-error (compile-condition error) ())
  (define-condition compile-warned-warning (compile-condition warning) ())
  (define-condition compile-warned-error (compile-condition error) ())
  (define-condition compile-failed-warning (compile-condition warning) ())
  (define-condition compile-failed-error (compile-condition error) ())

  (defun check-lisp-compile-warnings (warnings-p failure-p
                                                  &optional context-format context-arguments)
206
207
    "Given the warnings or failures as resulted from COMPILE-FILE or checking deferred warnings,
raise an error or warning as appropriate"
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
    (when failure-p
      (case *compile-file-failure-behaviour*
        (:warn (warn 'compile-failed-warning
                     :description "Lisp compilation failed"
                     :context-format context-format
                     :context-arguments context-arguments))
        (:error (error 'compile-failed-error
                       :description "Lisp compilation failed"
                       :context-format context-format
                       :context-arguments context-arguments))
        (:ignore nil)))
    (when warnings-p
      (case *compile-file-warnings-behaviour*
        (:warn (warn 'compile-warned-warning
                     :description "Lisp compilation had style-warnings"
                     :context-format context-format
                     :context-arguments context-arguments))
        (:error (error 'compile-warned-error
                       :description "Lisp compilation had style-warnings"
                       :context-format context-format
                       :context-arguments context-arguments))
        (:ignore nil))))

  (defun check-lisp-compile-results (output warnings-p failure-p
                                             &optional context-format context-arguments)
233
    "Given the results of COMPILE-FILE, raise an error or warning as appropriate"
234
235
236
    (unless output
      (error 'compile-file-error :context-format context-format :context-arguments context-arguments))
    (check-lisp-compile-warnings warnings-p failure-p context-format context-arguments)))
237
238


239
;;;; Deferred-warnings treatment, originally implemented by Douglas Katzman.
240
241
242
243
244
245
;;;
;;; To support an implementation, three functions must be implemented:
;;; reify-deferred-warnings unreify-deferred-warnings reset-deferred-warnings
;;; See their respective docstrings.
(with-upgradability ()
  (defun reify-simple-sexp (sexp)
246
247
    "Given a simple SEXP, return a representation of it as a portable SEXP.
Simple means made of symbols, numbers, characters, simple-strings, pathnames, cons cells."
248
249
250
    (etypecase sexp
      (symbol (reify-symbol sexp))
      ((or number character simple-string pathname) sexp)
251
252
      (cons (cons (reify-simple-sexp (car sexp)) (reify-simple-sexp (cdr sexp))))
      (simple-vector (vector (mapcar 'reify-simple-sexp (coerce sexp 'list))))))
253

254
  (defun unreify-simple-sexp (sexp)
255
    "Given the portable output of REIFY-SIMPLE-SEXP, return the simple SEXP it represents"
256
257
258
    (etypecase sexp
      ((or symbol number character simple-string pathname) sexp)
      (cons (cons (unreify-simple-sexp (car sexp)) (unreify-simple-sexp (cdr sexp))))
259
260
      ((simple-vector 2) (unreify-symbol sexp))
      ((simple-vector 1) (coerce (mapcar 'unreify-simple-sexp (aref sexp 0)) 'vector))))
261
262
263
264
265
266
267

  #+clozure
  (progn
    (defun reify-source-note (source-note)
      (when source-note
        (with-accessors ((source ccl::source-note-source) (filename ccl:source-note-filename)
                         (start-pos ccl:source-note-start-pos) (end-pos ccl:source-note-end-pos)) source-note
268
269
270
          (declare (ignorable source))
          (list :filename filename :start-pos start-pos :end-pos end-pos
                #|:source (reify-source-note source)|#))))
271
272
273
274
275
    (defun unreify-source-note (source-note)
      (when source-note
        (destructuring-bind (&key filename start-pos end-pos source) source-note
          (ccl::make-source-note :filename filename :start-pos start-pos :end-pos end-pos
                                 :source (unreify-source-note source)))))
276
277
278
279
280
281
282
283
284
    (defun unsymbolify-function-name (name)
      (if-let (setfed (gethash name ccl::%setf-function-name-inverses%))
        `(setf ,setfed)
        name))
    (defun symbolify-function-name (name)
      (if (and (consp name) (eq (first name) 'setf))
          (let ((setfed (second name)))
            (gethash setfed ccl::%setf-function-names%))
          name))
285
    (defun reify-function-name (function-name)
286
      (let ((name (or (first function-name) ;; defun: extract the name
287
288
289
                      (let ((sec (second function-name)))
                        (or (and (atom sec) sec) ; scoped method: drop scope
                            (first sec)))))) ; method: keep gf name, drop method specializers
290
        (list name)))
291
    (defun unreify-function-name (function-name)
292
      function-name)
293
294
295
296
297
298
    (defun nullify-non-literals (sexp)
      (typecase sexp
        ((or number character simple-string symbol pathname) sexp)
        (cons (cons (nullify-non-literals (car sexp))
                    (nullify-non-literals (cdr sexp))))
        (t nil)))
299
300
301
302
303
    (defun reify-deferred-warning (deferred-warning)
      (with-accessors ((warning-type ccl::compiler-warning-warning-type)
                       (args ccl::compiler-warning-args)
                       (source-note ccl:compiler-warning-source-note)
                       (function-name ccl:compiler-warning-function-name)) deferred-warning
304
        (list :warning-type warning-type :function-name (reify-function-name function-name)
305
              :source-note (reify-source-note source-note)
306
307
308
309
              :args (destructuring-bind (fun &rest more)
                        args
                      (cons (unsymbolify-function-name fun)
                            (nullify-non-literals more))))))
310
311
312
313
314
    (defun unreify-deferred-warning (reified-deferred-warning)
      (destructuring-bind (&key warning-type function-name source-note args)
          reified-deferred-warning
        (make-condition (or (cdr (ccl::assq warning-type ccl::*compiler-whining-conditions*))
                            'ccl::compiler-warning)
315
                        :function-name (unreify-function-name function-name)
316
317
                        :source-note (unreify-source-note source-note)
                        :warning-type warning-type
318
319
                        :args (destructuring-bind (fun . more) args
                                (cons (symbolify-function-name fun) more))))))
320
  #+(or cmucl scl)
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
  (defun reify-undefined-warning (warning)
    ;; Extracting undefined-warnings from the compilation-unit
    ;; To be passed through the above reify/unreify link, it must be a "simple-sexp"
    (list*
     (c::undefined-warning-kind warning)
     (c::undefined-warning-name warning)
     (c::undefined-warning-count warning)
     (mapcar
      #'(lambda (frob)
          ;; the lexenv slot can be ignored for reporting purposes
          `(:enclosing-source ,(c::compiler-error-context-enclosing-source frob)
            :source ,(c::compiler-error-context-source frob)
            :original-source ,(c::compiler-error-context-original-source frob)
            :context ,(c::compiler-error-context-context frob)
            :file-name ,(c::compiler-error-context-file-name frob) ; a pathname
            :file-position ,(c::compiler-error-context-file-position frob) ; an integer
            :original-source-path ,(c::compiler-error-context-original-source-path frob)))
      (c::undefined-warning-warnings warning))))

340
341
342
343
344
345
346
347
  #+sbcl
  (defun reify-undefined-warning (warning)
    ;; Extracting undefined-warnings from the compilation-unit
    ;; To be passed through the above reify/unreify link, it must be a "simple-sexp"
    (list*
     (sb-c::undefined-warning-kind warning)
     (sb-c::undefined-warning-name warning)
     (sb-c::undefined-warning-count warning)
348
349
350
351
     ;; the COMPILER-ERROR-CONTEXT struct has changed in SBCL, which means how we
     ;; handle deferred warnings must change... TODO: when enough time has
     ;; gone by, just assume all versions of SBCL are adequately
     ;; up-to-date, and cut this material.[2018/05/30:rpg]
352
353
354
     (mapcar
      #'(lambda (frob)
          ;; the lexenv slot can be ignored for reporting purposes
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
          `(
            #- #.(uiop/utility:symbol-test-to-feature-expression '#:compiler-error-context-%source '#:sb-c)
            ,@`(:enclosing-source
                ,(sb-c::compiler-error-context-enclosing-source frob)
                :source
                ,(sb-c::compiler-error-context-source frob)
                :original-source
                ,(sb-c::compiler-error-context-original-source frob))
            #+ #.(uiop/utility:symbol-test-to-feature-expression '#:compiler-error-context-%source '#:sb-c)
            ,@ `(:%enclosing-source
                 ,(sb-c::compiler-error-context-enclosing-source frob)
                 :%source
                 ,(sb-c::compiler-error-context-source frob)
                 :original-form
                 ,(sb-c::compiler-error-context-original-form frob))
370
371
372
373
374
375
376
377
            :context ,(sb-c::compiler-error-context-context frob)
            :file-name ,(sb-c::compiler-error-context-file-name frob) ; a pathname
            :file-position ,(sb-c::compiler-error-context-file-position frob) ; an integer
            :original-source-path ,(sb-c::compiler-error-context-original-source-path frob)))
      (sb-c::undefined-warning-warnings warning))))

  (defun reify-deferred-warnings ()
    "return a portable S-expression, portably readable and writeable in any Common Lisp implementation
378
379
using READ within a WITH-SAFE-IO-SYNTAX, that represents the warnings currently deferred by
WITH-COMPILATION-UNIT. One of three functions required for deferred-warnings support in ASDF."
380
    #+allegro
381
    (list :functions-defined excl::.functions-defined.
382
          :functions-called excl::.functions-called.)
383
384
385
386
387
    #+clozure
    (mapcar 'reify-deferred-warning
            (if-let (dw ccl::*outstanding-deferred-warnings*)
              (let ((mdw (ccl::ensure-merged-deferred-warnings dw)))
                (ccl::deferred-warnings.warnings mdw))))
388
    #+(or cmucl scl)
389
390
391
392
393
394
395
396
397
398
399
    (when lisp::*in-compilation-unit*
      ;; Try to send nothing through the pipe if nothing needs to be accumulated
      `(,@(when c::*undefined-warnings*
            `((c::*undefined-warnings*
               ,@(mapcar #'reify-undefined-warning c::*undefined-warnings*))))
        ,@(loop :for what :in '(c::*compiler-error-count*
                                c::*compiler-warning-count*
                                c::*compiler-note-count*)
                :for value = (symbol-value what)
                :when (plusp value)
                  :collect `(,what . ,value))))
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
    #+sbcl
    (when sb-c::*in-compilation-unit*
      ;; Try to send nothing through the pipe if nothing needs to be accumulated
      `(,@(when sb-c::*undefined-warnings*
            `((sb-c::*undefined-warnings*
               ,@(mapcar #'reify-undefined-warning sb-c::*undefined-warnings*))))
        ,@(loop :for what :in '(sb-c::*aborted-compilation-unit-count*
                                sb-c::*compiler-error-count*
                                sb-c::*compiler-warning-count*
                                sb-c::*compiler-style-warning-count*
                                sb-c::*compiler-note-count*)
                :for value = (symbol-value what)
                :when (plusp value)
                  :collect `(,what . ,value)))))

  (defun unreify-deferred-warnings (reified-deferred-warnings)
    "given a S-expression created by REIFY-DEFERRED-WARNINGS, reinstantiate the corresponding
417
418
419
420
deferred warnings as to be handled at the end of the current WITH-COMPILATION-UNIT.
Handle any warning that has been resolved already,
such as an undefined function that has been defined since.
One of three functions required for deferred-warnings support in ASDF."
421
    (declare (ignorable reified-deferred-warnings))
422
423
    #+allegro
    (destructuring-bind (&key functions-defined functions-called)
424
        reified-deferred-warnings
425
426
427
428
      (setf excl::.functions-defined.
            (append functions-defined excl::.functions-defined.)
            excl::.functions-called.
            (append functions-called excl::.functions-called.)))
429
430
431
432
433
    #+clozure
    (let ((dw (or ccl::*outstanding-deferred-warnings*
                  (setf ccl::*outstanding-deferred-warnings* (ccl::%defer-warnings t)))))
      (appendf (ccl::deferred-warnings.warnings dw)
               (mapcar 'unreify-deferred-warning reified-deferred-warnings)))
434
    #+(or cmucl scl)
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
    (dolist (item reified-deferred-warnings)
      ;; Each item is (symbol . adjustment) where the adjustment depends on the symbol.
      ;; For *undefined-warnings*, the adjustment is a list of initargs.
      ;; For everything else, it's an integer.
      (destructuring-bind (symbol . adjustment) item
        (case symbol
          ((c::*undefined-warnings*)
           (setf c::*undefined-warnings*
                 (nconc (mapcan
                         #'(lambda (stuff)
                             (destructuring-bind (kind name count . rest) stuff
                               (unless (case kind (:function (fboundp name)))
                                 (list
                                  (c::make-undefined-warning
                                   :name name
                                   :kind kind
                                   :count count
                                   :warnings
                                   (mapcar #'(lambda (x)
                                               (apply #'c::make-compiler-error-context x))
                                           rest))))))
                         adjustment)
                        c::*undefined-warnings*)))
          (otherwise
           (set symbol (+ (symbol-value symbol) adjustment))))))
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
    #+sbcl
    (dolist (item reified-deferred-warnings)
      ;; Each item is (symbol . adjustment) where the adjustment depends on the symbol.
      ;; For *undefined-warnings*, the adjustment is a list of initargs.
      ;; For everything else, it's an integer.
      (destructuring-bind (symbol . adjustment) item
        (case symbol
          ((sb-c::*undefined-warnings*)
           (setf sb-c::*undefined-warnings*
                 (nconc (mapcan
                         #'(lambda (stuff)
                             (destructuring-bind (kind name count . rest) stuff
                               (unless (case kind (:function (fboundp name)))
                                 (list
                                  (sb-c::make-undefined-warning
                                   :name name
                                   :kind kind
                                   :count count
                                   :warnings
                                   (mapcar #'(lambda (x)
                                               (apply #'sb-c::make-compiler-error-context x))
                                           rest))))))
                         adjustment)
                        sb-c::*undefined-warnings*)))
          (otherwise
           (set symbol (+ (symbol-value symbol) adjustment)))))))

  (defun reset-deferred-warnings ()
    "Reset the set of deferred warnings to be handled at the end of the current WITH-COMPILATION-UNIT.
489
One of three functions required for deferred-warnings support in ASDF."
490
491
492
    #+allegro
    (setf excl::.functions-defined. nil
          excl::.functions-called. nil)
493
494
495
496
    #+clozure
    (if-let (dw ccl::*outstanding-deferred-warnings*)
      (let ((mdw (ccl::ensure-merged-deferred-warnings dw)))
        (setf (ccl::deferred-warnings.warnings mdw) nil)))
497
    #+(or cmucl scl)
498
499
500
501
502
    (when lisp::*in-compilation-unit*
      (setf c::*undefined-warnings* nil
            c::*compiler-error-count* 0
            c::*compiler-warning-count* 0
            c::*compiler-note-count* 0))
503
504
505
506
507
508
509
510
511
512
513
    #+sbcl
    (when sb-c::*in-compilation-unit*
      (setf sb-c::*undefined-warnings* nil
            sb-c::*aborted-compilation-unit-count* 0
            sb-c::*compiler-error-count* 0
            sb-c::*compiler-warning-count* 0
            sb-c::*compiler-style-warning-count* 0
            sb-c::*compiler-note-count* 0)))

  (defun save-deferred-warnings (warnings-file)
    "Save forward reference conditions so they may be issued at a latter time,
514
possibly in a different process."
515
516
517
    (with-open-file (s warnings-file :direction :output :if-exists :supersede
                       :element-type *default-stream-element-type*
                       :external-format *utf-8-external-format*)
518
      (with-safe-io-syntax ()
519
520
        (let ((*read-eval* t))
          (write (reify-deferred-warnings) :stream s :pretty t :readably t))
521
522
523
        (terpri s))))

  (defun warnings-file-type (&optional implementation-type)
524
525
    "The pathname type for warnings files on given IMPLEMENTATION-TYPE,
where NIL designates the current one"
526
    (case (or implementation-type *implementation-type*)
527
528
      ((:acl :allegro) "allegro-warnings")
      ;;((:clisp) "clisp-warnings")
529
530
531
532
      ((:cmu :cmucl) "cmucl-warnings")
      ((:sbcl) "sbcl-warnings")
      ((:clozure :ccl) "ccl-warnings")
      ((:scl) "scl-warnings")))
533

534
  (defvar *warnings-file-type* nil
535
    "Pathname type for warnings files, or NIL if disabled")
536

537
  (defun enable-deferred-warnings-check ()
538
    "Enable the saving of deferred warnings"
539
540
541
    (setf *warnings-file-type* (warnings-file-type)))

  (defun disable-deferred-warnings-check ()
542
    "Disable the saving of deferred warnings"
543
544
    (setf *warnings-file-type* nil))

545
  (defun warnings-file-p (file &optional implementation-type)
546
547
    "Is FILE a saved warnings file for the given IMPLEMENTATION-TYPE?
If that given type is NIL, use the currently configured *WARNINGS-FILE-TYPE* instead."
548
549
550
551
552
553
    (if-let (type (if implementation-type
                      (warnings-file-type implementation-type)
                      *warnings-file-type*))
      (equal (pathname-type file) type)))

  (defun check-deferred-warnings (files &optional context-format context-arguments)
554
    "Given a list of FILES containing deferred warnings saved by CALL-WITH-SAVED-DEFERRED-WARNINGS,
555
re-intern and raise any warnings that are still meaningful."
556
557
558
559
560
561
562
563
564
565
566
567
    (let ((file-errors nil)
          (failure-p nil)
          (warnings-p nil))
      (handler-bind
          ((warning #'(lambda (c)
                        (setf warnings-p t)
                        (unless (typep c 'style-warning)
                          (setf failure-p t)))))
        (with-compilation-unit (:override t)
          (reset-deferred-warnings)
          (dolist (file files)
            (unreify-deferred-warnings
568
569
570
571
             (handler-case
                 (with-safe-io-syntax ()
                   (let ((*read-eval* t))
                     (read-file-form file)))
572
               (error (c)
573
                 ;;(delete-file-if-exists file) ;; deleting forces rebuild but prevents debugging
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
                 (push c file-errors)
                 nil))))))
      (dolist (error file-errors) (error error))
      (check-lisp-compile-warnings
       (or failure-p warnings-p) failure-p context-format context-arguments)))

  #|
  Mini-guide to adding support for deferred warnings on an implementation.

  First, look at what such a warning looks like:

  (describe
  (handler-case
  (and (eval '(lambda () (some-undefined-function))) nil)
  (t (c) c)))

  Then you can grep for the condition type in your compiler sources
  and see how to catch those that have been deferred,
  and/or read, clear and restore the deferred list.

  Also look at
  (macroexpand-1 '(with-compilation-unit () foo))
  |#

598
  (defun call-with-saved-deferred-warnings (thunk warnings-file &key source-namestring)
599
600
601
    "If WARNINGS-FILE is not nil, record the deferred-warnings around a call to THUNK
and save those warnings to the given file for latter use,
possibly in a different process. Otherwise just call THUNK."
602
    (declare (ignorable source-namestring))
603
    (if warnings-file
604
        (with-compilation-unit (:override t #+sbcl :source-namestring #+sbcl source-namestring)
605
606
607
          (unwind-protect
               (let (#+sbcl (sb-c::*undefined-warnings* nil))
                 (multiple-value-prog1
608
                     (funcall thunk)
609
610
611
612
                   (save-deferred-warnings warnings-file)))
            (reset-deferred-warnings)))
        (funcall thunk)))

613
  (defmacro with-saved-deferred-warnings ((warnings-file &key source-namestring) &body body)
614
    "Trivial syntax for CALL-WITH-SAVED-DEFERRED-WARNINGS"
615
616
    `(call-with-saved-deferred-warnings
      #'(lambda () ,@body) ,warnings-file :source-namestring ,source-namestring)))
617
618
619


;;; from ASDF
620
621
(with-upgradability ()
  (defun current-lisp-file-pathname ()
622
    "Portably return the PATHNAME of the current Lisp source file being compiled or loaded"
623
624
625
    (or *compile-file-pathname* *load-pathname*))

  (defun load-pathname ()
626
    "Portably return the LOAD-PATHNAME of the current source file or fasl"
627
    *load-pathname*) ;; magic no longer needed for GCL.
628
629

  (defun lispize-pathname (input-file)
630
    "From a INPUT-FILE pathname, return a corresponding .lisp source pathname"
631
632
633
634
635
    (make-pathname :type "lisp" :defaults input-file))

  (defun compile-file-type (&rest keys)
    "pathname TYPE for lisp FASt Loading files"
    (declare (ignorable keys))
Francois-Rene Rideau's avatar
Francois-Rene Rideau committed
636
637
    #-(or clasp ecl mkcl) (load-time-value (pathname-type (compile-file-pathname "foo.lisp")))
    #+(or clasp ecl mkcl) (pathname-type (apply 'compile-file-pathname "foo" keys)))
638
639

  (defun call-around-hook (hook function)
640
    "Call a HOOK around the execution of FUNCTION"
641
642
643
    (call-function (or hook 'funcall) function))

  (defun compile-file-pathname* (input-file &rest keys &key output-file &allow-other-keys)
644
    "Variant of COMPILE-FILE-PATHNAME that works well with COMPILE-FILE*"
645
    (let* ((keys
646
             (remove-plist-keys `(#+(or (and allegro (not (version>= 8 2)))) :external-format
647
648
649
650
651
652
653
654
655
656
                                    ,@(unless output-file '(:output-file))) keys)))
      (if (absolute-pathname-p output-file)
          ;; what cfp should be doing, w/ mp* instead of mp
          (let* ((type (pathname-type (apply 'compile-file-type keys)))
                 (defaults (make-pathname
                            :type type :defaults (merge-pathnames* input-file))))
            (merge-pathnames* output-file defaults))
          (funcall *output-translation-function*
                   (apply 'compile-file-pathname input-file keys)))))

657
658
659
  (defvar *compile-check* nil
    "A hook for user-defined compile-time invariants")

660
  (defun* (compile-file*) (input-file &rest keys
661
                                      &key (compile-check *compile-check*) output-file warnings-file
Francois-Rene Rideau's avatar
Francois-Rene Rideau committed
662
                                      #+clisp lib-file #+(or clasp ecl mkcl) object-file #+sbcl emit-cfasl
663
664
                                      &allow-other-keys)
    "This function provides a portable wrapper around COMPILE-FILE.
665
666
It ensures that the OUTPUT-FILE value is only returned and
the file only actually created if the compilation was successful,
667
668
even though your implementation may not do that. It also checks an optional
user-provided consistency function COMPILE-CHECK to determine success;
669
670
671
672
673
674
it will call this function if not NIL at the end of the compilation
with the arguments sent to COMPILE-FILE*, except with :OUTPUT-FILE TMP-FILE
where TMP-FILE is the name of a temporary output-file.
It also checks two flags (with legacy british spelling from ASDF1),
*COMPILE-FILE-FAILURE-BEHAVIOUR* and *COMPILE-FILE-WARNINGS-BEHAVIOUR*
with appropriate implementation-dependent defaults,
675
676
and if a failure (respectively warnings) are reported by COMPILE-FILE,
it will consider that an error unless the respective behaviour flag
677
is one of :SUCCESS :WARN :IGNORE.
678
If WARNINGS-FILE is defined, deferred warnings are saved to that file.
679
680
681
On ECL or MKCL, it creates both the linkable object and loadable fasl files.
On implementations that erroneously do not recognize standard keyword arguments,
it will filter them appropriately."
682
683
684
685
686
    #+(or clasp ecl)
    (when (and object-file (equal (compile-file-type) (pathname object-file)))
      (format t "Whoa, some funky ASDF upgrade switched ~S calling convention for ~S and ~S~%"
              'compile-file* output-file object-file)
      (rotatef output-file object-file))
687
    (let* ((keywords (remove-plist-keys
688
                      `(:output-file :compile-check :warnings-file
Francois-Rene Rideau's avatar
Francois-Rene Rideau committed
689
                                     #+clisp :lib-file #+(or clasp ecl mkcl) :object-file) keys))
690
           (output-file
691
692
             (or output-file
                 (apply 'compile-file-pathname* input-file :output-file output-file keywords)))
693
           (physical-output-file (physicalize-pathname output-file))
Francois-Rene Rideau's avatar
Francois-Rene Rideau committed
694
           #+(or clasp ecl)
695
           (object-file
696
697
698
699
             (unless (use-ecl-byte-compiler-p)
               (or object-file
                   #+ecl (compile-file-pathname output-file :type :object)
                   #+clasp (compile-file-pathname output-file :output-type :object))))
700
701
           #+mkcl
           (object-file
702
703
704
705
706
             (or object-file
                 (compile-file-pathname output-file :fasl-p nil)))
           (tmp-file (tmpize-pathname physical-output-file))
           #+clasp
           (tmp-object-file (compile-file-pathname tmp-file :output-type :object))
707
708
709
           #+sbcl
           (cfasl-file (etypecase emit-cfasl
                         (null nil)
710
                         ((eql t) (make-pathname :type "cfasl" :defaults physical-output-file))
711
712
713
714
                         (string (parse-namestring emit-cfasl))
                         (pathname emit-cfasl)))
           #+sbcl
           (tmp-cfasl (when cfasl-file (make-pathname :type "cfasl" :defaults tmp-file)))
715
716
717
           #+clisp
           (tmp-lib (make-pathname :type "lib" :defaults tmp-file)))
      (multiple-value-bind (output-truename warnings-p failure-p)
718
719
720
          (with-enough-pathname (input-file :defaults *base-build-directory*)
            (with-saved-deferred-warnings (warnings-file :source-namestring (namestring input-file))
              (with-muffled-compiler-conditions ()
Francois-Rene Rideau's avatar
Francois-Rene Rideau committed
721
                (or #-(or clasp ecl mkcl)
722
723
724
725
                    (let (#+genera (si:*common-lisp-syntax-is-ansi-common-lisp* t))
                      (apply 'compile-file input-file :output-file tmp-file
                             #+sbcl (if emit-cfasl (list* :emit-cfasl tmp-cfasl keywords) keywords)
                             #-sbcl keywords))
726
                    #+ecl (apply 'compile-file input-file :output-file
727
728
729
                                (if object-file
                                    (list* object-file :system-p t keywords)
                                    (list* tmp-file keywords)))
Francois-Rene Rideau's avatar
Francois-Rene Rideau committed
730
                    #+clasp (apply 'compile-file input-file :output-file
731
732
733
                                  (if object-file
                                      (list* tmp-object-file :output-type :object #|:system-p t|# keywords)
                                      (list* tmp-file keywords)))
734
735
                    #+mkcl (apply 'compile-file input-file
                                  :output-file object-file :fasl-p nil keywords)))))
736
737
738
739
740
741
742
        (cond
          ((and output-truename
                (flet ((check-flag (flag behaviour)
                         (or (not flag) (member behaviour '(:success :warn :ignore)))))
                  (and (check-flag failure-p *compile-file-failure-behaviour*)
                       (check-flag warnings-p *compile-file-warnings-behaviour*)))
                (progn
Francois-Rene Rideau's avatar
Francois-Rene Rideau committed
743
744
                  #+(or clasp ecl mkcl)
                  (when (and #+(or clasp ecl) object-file)
745
                    (setf output-truename
746
                          (compiler::build-fasl tmp-file
747
                           #+(or clasp ecl) :lisp-files #+mkcl :lisp-object-files (list #+clasp tmp-object-file #-clasp object-file))))
748
                  (or (not compile-check)
749
                      (apply compile-check input-file
750
                             :output-file output-truename
751
                             keywords))))
752
           (delete-file-if-exists physical-output-file)
753
           (when output-truename
754
755
756
757
758
759
             ;; see CLISP bug 677
             #+clisp
             (progn
               (setf tmp-lib (make-pathname :type "lib" :defaults output-truename))
               (unless lib-file (setf lib-file (make-pathname :type "lib" :defaults physical-output-file)))
               (rename-file-overwriting-target tmp-lib lib-file))
760
             #+sbcl (when cfasl-file (rename-file-overwriting-target tmp-cfasl cfasl-file))
761
762
             #+clasp
             (progn
763
               ;;; the following 4 rename-file-overwriting-target better be atomic, but we can't implement this right now
764
               #+:target-os-darwin
765
766
               (let ((temp-dwarf (pathname (strcat (namestring output-truename) ".dwarf")))
                     (target-dwarf (pathname (strcat (namestring physical-output-file) ".dwarf"))))
767
768
                 (when (probe-file temp-dwarf)
                   (rename-file-overwriting-target temp-dwarf target-dwarf)))
769
770
771
772
               ;;; need to rename the bc or ll file as well or test-bundle.script fails
               (rename-file-overwriting-target
                (compile-file-pathname tmp-file :output-type :bitcode)
                (compile-file-pathname physical-output-file :output-type :bitcode))
773
               (rename-file-overwriting-target tmp-object-file object-file))
774
775
             (rename-file-overwriting-target output-truename physical-output-file)
             (setf output-truename (truename physical-output-file)))
Francois-Rene Rideau's avatar
Francois-Rene Rideau committed
776
           #+clasp (delete-file-if-exists tmp-file)
777
778
           #+clisp (progn (delete-file-if-exists tmp-file) ;; this one works around clisp BUG 677
                          (delete-file-if-exists tmp-lib))) ;; this one is "normal" defensive cleanup
779
780
          (t ;; error or failed check
           (delete-file-if-exists output-truename)
781
782
           #+clisp (delete-file-if-exists tmp-lib)
           #+sbcl (delete-file-if-exists tmp-cfasl)
783
784
785
786
           (setf output-truename nil)))
        (values output-truename warnings-p failure-p))))

  (defun load* (x &rest keys &key &allow-other-keys)
787
    "Portable wrapper around LOAD that properly handles loading from a stream."
788
    (with-muffled-loader-conditions ()
789
790
791
792
793
794
795
796
797
798
799
800
801
802
      (let (#+genera (si:*common-lisp-syntax-is-ansi-common-lisp* t))
        (etypecase x
          ((or pathname string #-(or allegro clozure genera) stream #+clozure file-stream)
           (apply 'load x keys))
          ;; Genera can't load from a string-input-stream
          ;; ClozureCL 1.6 can only load from file input stream
          ;; Allegro 5, I don't remember but it must have been broken when I tested.
          #+(or allegro clozure genera)
          (stream ;; make do this way
           (let ((*package* *package*)
                 (*readtable* *readtable*)
                 (*load-pathname* nil)
                 (*load-truename* nil))
             (eval-input x)))))))
803
804
805
806

  (defun load-from-string (string)
    "Portably read and evaluate forms from a STRING."
    (with-input-from-string (s string) (load* s))))
807
808

;;; Links FASLs together
809
810
(with-upgradability ()
  (defun combine-fasls (inputs output)
811
    "Combine a list of FASLs INPUTS into a single FASL OUTPUT"
812
    #-(or abcl allegro clisp clozure cmucl lispworks sbcl scl xcl)
813
    (not-implemented-error 'combine-fasls "~%inputs: ~S~%output: ~S" inputs output)
814
    #+abcl (funcall 'sys::concatenate-fasls inputs output) ; requires ABCL 1.2.0
815
    #+(or allegro clisp cmucl sbcl scl xcl) (concatenate-files inputs output)
816
    #+clozure (ccl:fasl-concatenate output inputs :if-exists :supersede)
817
818
819
820
821
822
823
824
    #+lispworks
    (let (fasls)
      (unwind-protect
           (progn
             (loop :for i :in inputs
                   :for n :from 1
                   :for f = (add-pathname-suffix
                             output (format nil "-FASL~D" n))
825
826
                   :do (copy-file i f)
                       (push f fasls))
827
828
829
830
831
832
             (ignore-errors (lispworks:delete-system :fasls-to-concatenate))
             (eval `(scm:defsystem :fasls-to-concatenate
                      (:default-pathname ,(pathname-directory-pathname output))
                      :members
                      ,(loop :for f :in (reverse fasls)
                             :collect `(,(namestring f) :load-only t))))
833
             (scm:concatenate-system output :fasls-to-concatenate :force t))
834
835
        (loop :for f :in fasls :do (ignore-errors (delete-file f)))
        (ignore-errors (lispworks:delete-system :fasls-to-concatenate))))))