0.8.17.4: Stricter lambda list parsing
[sbcl.git] / src / compiler / main.lisp
1 ;;;; the top level interfaces to the compiler, plus some other
2 ;;;; compiler-related stuff (e.g. CL:CALL-ARGUMENTS-LIMIT) which
3 ;;;; doesn't obviously belong anywhere else
4
5 ;;;; This software is part of the SBCL system. See the README file for
6 ;;;; more information.
7 ;;;;
8 ;;;; This software is derived from the CMU CL system, which was
9 ;;;; written at Carnegie Mellon University and released into the
10 ;;;; public domain. The software is in the public domain and is
11 ;;;; provided with absolutely no warranty. See the COPYING and CREDITS
12 ;;;; files for more information.
13
14 (in-package "SB!C")
15
16 ;;; FIXME: Doesn't this belong somewhere else, like early-c.lisp?
17 (declaim (special *constants* *free-vars* *component-being-compiled*
18                   *code-vector* *next-location* *result-fixups*
19                   *free-funs* *source-paths*
20                   *seen-blocks* *seen-funs* *list-conflicts-table*
21                   *continuation-number* *continuation-numbers*
22                   *number-continuations* *tn-id* *tn-ids* *id-tns*
23                   *label-ids* *label-id* *id-labels*
24                   *undefined-warnings* *compiler-error-count*
25                   *compiler-warning-count* *compiler-style-warning-count*
26                   *compiler-note-count*
27                   *compiler-error-bailout*
28                   #!+sb-show *compiler-trace-output*
29                   *last-source-context* *last-original-source*
30                   *last-source-form* *last-format-string* *last-format-args*
31                   *last-message-count* *lexenv* *fun-names-in-this-file*
32                   *allow-instrumenting*))
33
34 ;;; Whether call of a function which cannot be defined causes a full
35 ;;; warning.
36 (defvar *flame-on-necessarily-undefined-function* nil)
37
38 (defvar *check-consistency* nil)
39 (defvar *all-components*)
40
41 ;;; Set to NIL to disable loop analysis for register allocation. 
42 (defvar *loop-analyze* t)
43
44 ;;; Bind this to a stream to capture various internal debugging output.
45 (defvar *compiler-trace-output* nil)
46
47 ;;; The current block compilation state. These are initialized to the
48 ;;; :BLOCK-COMPILE and :ENTRY-POINTS arguments that COMPILE-FILE was
49 ;;; called with.
50 ;;;
51 ;;; *BLOCK-COMPILE-ARG* holds the original value of the :BLOCK-COMPILE
52 ;;; argument, which overrides any internal declarations.
53 (defvar *block-compile*)
54 (defvar *block-compile-arg*)
55 (declaim (type (member nil t :specified) *block-compile* *block-compile-arg*))
56 (defvar *entry-points*)
57 (declaim (list *entry-points*))
58
59 ;;; When block compiling, used by PROCESS-FORM to accumulate top level
60 ;;; lambdas resulting from compiling subforms. (In reverse order.)
61 (defvar *toplevel-lambdas*)
62 (declaim (list *toplevel-lambdas*))
63
64 (defvar sb!xc:*compile-verbose* t
65   #!+sb-doc
66   "The default for the :VERBOSE argument to COMPILE-FILE.")
67 (defvar sb!xc:*compile-print* t
68   #!+sb-doc
69   "The default for the :PRINT argument to COMPILE-FILE.")
70 (defvar *compile-progress* nil
71   #!+sb-doc
72   "When this is true, the compiler prints to *ERROR-OUTPUT* progress
73   information about the phases of compilation of each function. (This
74   is useful mainly in large block compilations.)")
75
76 (defvar sb!xc:*compile-file-pathname* nil
77   #!+sb-doc
78   "The defaulted pathname of the file currently being compiled, or NIL if not
79   compiling.")
80 (defvar sb!xc:*compile-file-truename* nil
81   #!+sb-doc
82   "The TRUENAME of the file currently being compiled, or NIL if not
83   compiling.")
84
85 (declaim (type (or pathname null)
86                sb!xc:*compile-file-pathname*
87                sb!xc:*compile-file-truename*))
88
89 ;;; the SOURCE-INFO structure for the current compilation. This is
90 ;;; null globally to indicate that we aren't currently in any
91 ;;; identifiable compilation.
92 (defvar *source-info* nil)
93
94 ;;; This is true if we are within a WITH-COMPILATION-UNIT form (which
95 ;;; normally causes nested uses to be no-ops).
96 (defvar *in-compilation-unit* nil)
97
98 ;;; Count of the number of compilation units dynamically enclosed by
99 ;;; the current active WITH-COMPILATION-UNIT that were unwound out of.
100 (defvar *aborted-compilation-unit-count*)
101
102 ;;; Mumble conditional on *COMPILE-PROGRESS*.
103 (defun maybe-mumble (&rest foo)
104   (when *compile-progress*
105     (compiler-mumble "~&")
106     (pprint-logical-block (*error-output* nil :per-line-prefix "; ")
107        (apply #'compiler-mumble foo))))
108
109 (deftype object () '(or fasl-output core-object null))
110
111 (defvar *compile-object* nil)
112 (declaim (type object *compile-object*))
113 \f
114 ;;;; WITH-COMPILATION-UNIT and WITH-COMPILATION-VALUES
115
116 (defmacro sb!xc:with-compilation-unit (options &body body)
117   #!+sb-doc
118   "WITH-COMPILATION-UNIT ({Key Value}*) Form*
119   This form affects compilations that take place within its dynamic extent. It
120   is intended to be wrapped around the compilation of all files in the same
121   system. These keywords are defined:
122     :OVERRIDE Boolean-Form
123         One of the effects of this form is to delay undefined warnings
124         until the end of the form, instead of giving them at the end of each
125         compilation. If OVERRIDE is NIL (the default), then the outermost
126         WITH-COMPILATION-UNIT form grabs the undefined warnings. Specifying
127         OVERRIDE true causes that form to grab any enclosed warnings, even if
128         it is enclosed by another WITH-COMPILATION-UNIT."
129   `(%with-compilation-unit (lambda () ,@body) ,@options))
130
131 (defun %with-compilation-unit (fn &key override)
132   (declare (type function fn))
133   (let ((succeeded-p nil))
134     (if (and *in-compilation-unit* (not override))
135         ;; Inside another WITH-COMPILATION-UNIT, a WITH-COMPILATION-UNIT is
136         ;; ordinarily (unless OVERRIDE) basically a no-op.
137         (unwind-protect
138              (multiple-value-prog1 (funcall fn) (setf succeeded-p t))
139           (unless succeeded-p
140             (incf *aborted-compilation-unit-count*)))
141         (let ((*aborted-compilation-unit-count* 0)
142               (*compiler-error-count* 0)
143               (*compiler-warning-count* 0)
144               (*compiler-style-warning-count* 0)
145               (*compiler-note-count* 0)
146               (*undefined-warnings* nil)
147               (*in-compilation-unit* t))
148           (sb!thread:with-recursive-lock (*big-compiler-lock*)
149             (handler-bind ((parse-unknown-type
150                             (lambda (c)
151                               (note-undefined-reference
152                                (parse-unknown-type-specifier c)
153                                :type))))
154               (unwind-protect
155                    (multiple-value-prog1 (funcall fn) (setf succeeded-p t))
156                 (unless succeeded-p
157                   (incf *aborted-compilation-unit-count*))
158                 (summarize-compilation-unit (not succeeded-p)))))))))
159
160 ;;; Is FUN-NAME something that no conforming program can rely on
161 ;;; defining as a function?
162 (defun fun-name-reserved-by-ansi-p (fun-name)
163   (eq (symbol-package (fun-name-block-name fun-name))
164       *cl-package*))
165
166 ;;; This is to be called at the end of a compilation unit. It signals
167 ;;; any residual warnings about unknown stuff, then prints the total
168 ;;; error counts. ABORT-P should be true when the compilation unit was
169 ;;; aborted by throwing out. ABORT-COUNT is the number of dynamically
170 ;;; enclosed nested compilation units that were aborted.
171 (defun summarize-compilation-unit (abort-p)
172   (unless abort-p
173     (handler-bind ((style-warning #'compiler-style-warning-handler)
174                    (warning #'compiler-warning-handler))
175
176       (let ((undefs (sort *undefined-warnings* #'string<
177                           :key (lambda (x)
178                                  (let ((x (undefined-warning-name x)))
179                                    (if (symbolp x)
180                                        (symbol-name x)
181                                        (prin1-to-string x)))))))
182         (dolist (undef undefs)
183           (let ((name (undefined-warning-name undef))
184                 (kind (undefined-warning-kind undef))
185                 (warnings (undefined-warning-warnings undef))
186                 (undefined-warning-count (undefined-warning-count undef)))
187             (dolist (*compiler-error-context* warnings)
188               (if #-sb-xc-host (and (eq kind :function)
189                                     (fun-name-reserved-by-ansi-p name)
190                                     *flame-on-necessarily-undefined-function*)
191                   #+sb-xc-host nil
192                   (case name
193                     ((declare)
194                      (compiler-warn
195                       "~@<There is no function named ~S. References to ~S in ~
196                        some contexts (like starts of blocks) have special ~
197                        meaning, but here it would have to be a function, ~
198                        and that shouldn't be right.~:@>"
199                       name name))
200                     (t
201                      (compiler-warn
202                       "~@<The ~(~A~) ~S is undefined, and its name is ~
203                        reserved by ANSI CL so that even if it were ~
204                        defined later, the code doing so would not be ~
205                        portable.~:@>"
206                       kind name)))
207                   (if (eq kind :variable)
208                       (compiler-warn "undefined ~(~A~): ~S" kind name)
209                       (compiler-style-warn "undefined ~(~A~): ~S" kind name))))
210             (let ((warn-count (length warnings)))
211               (when (and warnings (> undefined-warning-count warn-count))
212                 (let ((more (- undefined-warning-count warn-count)))
213                   (if (eq kind :variable)
214                       (compiler-warn
215                        "~W more use~:P of undefined ~(~A~) ~S"
216                        more kind name)
217                       (compiler-style-warn
218                        "~W more use~:P of undefined ~(~A~) ~S"
219                        more kind name)))))))
220
221         (dolist (kind '(:variable :function :type))
222           (let ((summary (mapcar #'undefined-warning-name
223                                  (remove kind undefs :test #'neq
224                                          :key #'undefined-warning-kind))))
225             (when summary
226               (if (eq kind :variable)
227                   (compiler-warn
228                    "~:[This ~(~A~) is~;These ~(~A~)s are~] undefined:~
229                     ~%  ~{~<~%  ~1:;~S~>~^ ~}"
230                    (cdr summary) kind summary)
231                   (compiler-style-warn
232                    "~:[This ~(~A~) is~;These ~(~A~)s are~] undefined:~
233                    ~%  ~{~<~%  ~1:;~S~>~^ ~}"
234                    (cdr summary) kind summary))))))))
235
236   (unless (and (not abort-p)
237                (zerop *aborted-compilation-unit-count*)
238                (zerop *compiler-error-count*)
239                (zerop *compiler-warning-count*)
240                (zerop *compiler-style-warning-count*)
241                (zerop *compiler-note-count*))
242     (format *error-output* "~&")
243     (pprint-logical-block (*error-output* nil :per-line-prefix "; ")
244       (compiler-mumble "compilation unit ~:[finished~;aborted~]~
245                        ~[~:;~:*~&  caught ~W fatal ERROR condition~:P~]~
246                        ~[~:;~:*~&  caught ~W ERROR condition~:P~]~
247                        ~[~:;~:*~&  caught ~W WARNING condition~:P~]~
248                        ~[~:;~:*~&  caught ~W STYLE-WARNING condition~:P~]~
249                        ~[~:;~:*~&  printed ~W note~:P~]"
250                        abort-p
251                        *aborted-compilation-unit-count*
252                        *compiler-error-count*
253                        *compiler-warning-count*
254                        *compiler-style-warning-count*
255                        *compiler-note-count*)))
256   (format *error-output* "~&"))
257
258 ;;; Evaluate BODY, then return (VALUES BODY-VALUE WARNINGS-P
259 ;;; FAILURE-P), where BODY-VALUE is the first value of the body, and
260 ;;; WARNINGS-P and FAILURE-P are as in CL:COMPILE or CL:COMPILE-FILE.
261 ;;; This also wraps up WITH-IR1-NAMESPACE functionality.
262 (defmacro with-compilation-values (&body body)
263   `(with-ir1-namespace
264     (let ((*warnings-p* nil)
265           (*failure-p* nil))
266       (values (progn ,@body)
267               *warnings-p*
268               *failure-p*))))
269 \f
270 ;;;; component compilation
271
272 (defparameter *max-optimize-iterations* 3 ; ARB
273   #!+sb-doc
274   "The upper limit on the number of times that we will consecutively do IR1
275   optimization that doesn't introduce any new code. A finite limit is
276   necessary, since type inference may take arbitrarily long to converge.")
277
278 (defevent ir1-optimize-until-done "IR1-OPTIMIZE-UNTIL-DONE called")
279 (defevent ir1-optimize-maxed-out "hit *MAX-OPTIMIZE-ITERATIONS* limit")
280
281 ;;; Repeatedly optimize COMPONENT until no further optimizations can
282 ;;; be found or we hit our iteration limit. When we hit the limit, we
283 ;;; clear the component and block REOPTIMIZE flags to discourage the
284 ;;; next optimization attempt from pounding on the same code.
285 (defun ir1-optimize-until-done (component)
286   (declare (type component component))
287   (maybe-mumble "opt")
288   (event ir1-optimize-until-done)
289   (let ((count 0)
290         (cleared-reanalyze nil)
291         (fastp nil))
292     (loop
293       (when (component-reanalyze component)
294         (setq count 0)
295         (setq cleared-reanalyze t)
296         (setf (component-reanalyze component) nil))
297       (setf (component-reoptimize component) nil)
298       (ir1-optimize component fastp)
299       (cond ((component-reoptimize component)
300              (incf count)
301              (when (and (>= count *max-optimize-iterations*)
302                         (not (component-reanalyze component))
303                         (eq (component-reoptimize component) :maybe))
304                (maybe-mumble "*")
305                (cond ((retry-delayed-ir1-transforms :optimize)
306                       (maybe-mumble "+")
307                       (setq count 0))
308                      (t
309                       (event ir1-optimize-maxed-out)
310                       (setf (component-reoptimize component) nil)
311                       (do-blocks (block component)
312                         (setf (block-reoptimize block) nil))
313                       (return)))))
314             ((retry-delayed-ir1-transforms :optimize)
315              (setf count 0)
316              (maybe-mumble "+"))
317             (t
318              (maybe-mumble " ")
319              (return)))
320       (setq fastp (>= count *max-optimize-iterations*))
321       (maybe-mumble (if fastp "-" ".")))
322     (when cleared-reanalyze
323       (setf (component-reanalyze component) t)))
324   (values))
325
326 (defparameter *constraint-propagate* t)
327
328 ;;; KLUDGE: This was bumped from 5 to 10 in a DTC patch ported by MNA
329 ;;; from CMU CL into sbcl-0.6.11.44, the same one which allowed IR1
330 ;;; transforms to be delayed. Either DTC or MNA or both didn't explain
331 ;;; why, and I don't know what the rationale was. -- WHN 2001-04-28
332 ;;;
333 ;;; FIXME: It would be good to document why it's important to have a
334 ;;; large value here, and what the drawbacks of an excessively large
335 ;;; value are; and it might also be good to make it depend on
336 ;;; optimization policy.
337 (defparameter *reoptimize-after-type-check-max* 10)
338
339 (defevent reoptimize-maxed-out
340   "*REOPTIMIZE-AFTER-TYPE-CHECK-MAX* exceeded.")
341
342 ;;; Iterate doing FIND-DFO until no new dead code is discovered.
343 (defun dfo-as-needed (component)
344   (declare (type component component))
345   (when (component-reanalyze component)
346     (maybe-mumble "DFO")
347     (loop
348       (find-dfo component)
349       (unless (component-reanalyze component)
350         (maybe-mumble " ")
351         (return))
352       (maybe-mumble ".")))
353   (values))
354
355 ;;; Do all the IR1 phases for a non-top-level component.
356 (defun ir1-phases (component)
357   (declare (type component component))
358   (aver-live-component component)
359   (let ((*constraint-number* 0)
360         (loop-count 1)
361         (*delayed-ir1-transforms* nil))
362     (declare (special *constraint-number* *delayed-ir1-transforms*))
363     (loop
364       (ir1-optimize-until-done component)
365       (when (or (component-new-functionals component)
366                 (component-reanalyze-functionals component))
367         (maybe-mumble "locall ")
368         (locall-analyze-component component))
369       (dfo-as-needed component)
370       (when *constraint-propagate*
371         (maybe-mumble "constraint ")
372         (constraint-propagate component))
373       (when (retry-delayed-ir1-transforms :constraint)
374         (maybe-mumble "Rtran "))
375       (flet ((want-reoptimization-p ()
376                (or (component-reoptimize component)
377                    (component-reanalyze component)
378                    (component-new-functionals component)
379                    (component-reanalyze-functionals component))))
380         (unless (and (want-reoptimization-p)
381                      ;; We delay the generation of type checks until
382                      ;; the type constraints have had time to
383                      ;; propagate, else the compiler can confuse itself.
384                      (< loop-count (- *reoptimize-after-type-check-max* 4)))
385           (maybe-mumble "type ")
386           (generate-type-checks component)
387           (unless (want-reoptimization-p)
388             (return))))
389       (when (>= loop-count *reoptimize-after-type-check-max*)
390         (maybe-mumble "[reoptimize limit]")
391         (event reoptimize-maxed-out)
392         (return))
393       (incf loop-count)))
394
395   (ir1-finalize component)
396   (values))
397
398 (defun %compile-component (component)
399   (let ((*code-segment* nil)
400         (*elsewhere* nil))
401     (maybe-mumble "GTN ")
402     (gtn-analyze component)
403     (maybe-mumble "LTN ")
404     (ltn-analyze component)
405     (dfo-as-needed component)
406     (maybe-mumble "control ")
407     (control-analyze component #'make-ir2-block)
408
409     (when (or (ir2-component-values-receivers (component-info component))
410               (component-dx-lvars component))
411       (maybe-mumble "stack ")
412       (stack-analyze component)
413       ;; Assign BLOCK-NUMBER for any cleanup blocks introduced by
414       ;; stack analysis. There shouldn't be any unreachable code after
415       ;; control, so this won't delete anything.
416       (dfo-as-needed component))
417
418     (unwind-protect
419         (progn
420           (maybe-mumble "IR2tran ")
421           (init-assembler)
422           (entry-analyze component)
423           (ir2-convert component)
424
425           (when (policy *lexenv* (>= speed compilation-speed))
426             (maybe-mumble "copy ")
427             (copy-propagate component))
428
429           (select-representations component)
430
431           (when *check-consistency*
432             (maybe-mumble "check2 ")
433             (check-ir2-consistency component))
434
435           (delete-unreferenced-tns component)
436
437           (maybe-mumble "life ")
438           (lifetime-analyze component)
439
440           (when *compile-progress*
441             (compiler-mumble "") ; Sync before doing more output.
442             (pre-pack-tn-stats component *error-output*))
443
444           (when *check-consistency*
445             (maybe-mumble "check-life ")
446             (check-life-consistency component))
447
448           (maybe-mumble "pack ")
449           (pack component)
450
451           (when *check-consistency*
452             (maybe-mumble "check-pack ")
453             (check-pack-consistency component))
454
455           (when *compiler-trace-output*
456             (describe-component component *compiler-trace-output*)
457             (describe-ir2-component component *compiler-trace-output*))
458
459           (maybe-mumble "code ")
460           (multiple-value-bind (code-length trace-table fixup-notes)
461               (generate-code component)
462
463             #-sb-xc-host
464             (when *compiler-trace-output*
465               (format *compiler-trace-output*
466                       "~|~%disassembly of code for ~S~2%" component)
467               (sb!disassem:disassemble-assem-segment *code-segment*
468                                                      *compiler-trace-output*))
469
470             (etypecase *compile-object*
471               (fasl-output
472                (maybe-mumble "fasl")
473                (fasl-dump-component component
474                                     *code-segment*
475                                     code-length
476                                     trace-table
477                                     fixup-notes
478                                     *compile-object*))
479               (core-object
480                (maybe-mumble "core")
481                (make-core-component component
482                                     *code-segment*
483                                     code-length
484                                     trace-table
485                                     fixup-notes
486                                     *compile-object*))
487               (null))))))
488
489   ;; We're done, so don't bother keeping anything around.
490   (setf (component-info component) :dead)
491
492   (values))
493
494 ;;; Delete components with no external entry points before we try to
495 ;;; generate code. Unreachable closures can cause IR2 conversion to
496 ;;; puke on itself, since it is the reference to the closure which
497 ;;; normally causes the components to be combined.
498 (defun delete-if-no-entries (component)
499   (dolist (fun (component-lambdas component) (delete-component component))
500     (when (functional-has-external-references-p fun)
501       (return))
502     (case (functional-kind fun)
503       (:toplevel (return))
504       (:external
505        (unless (every (lambda (ref)
506                         (eq (node-component ref) component))
507                       (leaf-refs fun))
508          (return))))))
509
510 (defun compile-component (component)
511
512   ;; miscellaneous sanity checks
513   ;;
514   ;; FIXME: These are basically pretty wimpy compared to the checks done
515   ;; by the old CHECK-IR1-CONSISTENCY code. It would be really nice to
516   ;; make those internal consistency checks work again and use them.
517   (aver-live-component component)
518   (do-blocks (block component)
519     (aver (eql (block-component block) component)))
520   (dolist (lambda (component-lambdas component))
521     ;; sanity check to prevent weirdness from propagating insidiously as
522     ;; far from its root cause as it did in bug 138: Make sure that
523     ;; thing-to-COMPONENT links are consistent.
524     (aver (eql (lambda-component lambda) component))
525     (aver (eql (node-component (lambda-bind lambda)) component)))
526
527   (let* ((*component-being-compiled* component))
528     (when sb!xc:*compile-print*
529       (compiler-mumble "~&; compiling ~A: " (component-name component)))
530
531     (ir1-phases component)
532
533     (when *loop-analyze*
534       (dfo-as-needed component)
535       (find-dominators component)
536       (loop-analyze component))
537
538     #|
539     (when (and *loop-analyze* *compiler-trace-output*)
540       (labels ((print-blocks (block)
541                  (format *compiler-trace-output* "    ~A~%" block)
542                  (when (block-loop-next block)
543                    (print-blocks (block-loop-next block))))
544                (print-loop (loop)
545                  (format *compiler-trace-output* "loop=~A~%" loop)
546                  (print-blocks (loop-blocks loop))
547                  (dolist (l (loop-inferiors loop))
548                    (print-loop l))))
549         (print-loop (component-outer-loop component))))
550     |#
551     
552     ;; FIXME: What is MAYBE-MUMBLE for? Do we need it any more?
553     (maybe-mumble "env ")
554     (physenv-analyze component)
555     (dfo-as-needed component)
556
557     (delete-if-no-entries component)
558
559     (unless (eq (block-next (component-head component))
560                 (component-tail component))
561       (%compile-component component)))
562
563   (clear-constant-info)
564
565   (when sb!xc:*compile-print*
566     (compiler-mumble "~&"))
567
568   (values))
569 \f
570 ;;;; clearing global data structures
571 ;;;;
572 ;;;; FIXME: Is it possible to get rid of this stuff, getting rid of
573 ;;;; global data structures entirely when possible and consing up the
574 ;;;; others from scratch instead of clearing and reusing them?
575
576 ;;; Clear the INFO in constants in the *FREE-VARS*, etc. In
577 ;;; addition to allowing stuff to be reclaimed, this is required for
578 ;;; correct assignment of constant offsets, since we need to assign a
579 ;;; new offset for each component. We don't clear the FUNCTIONAL-INFO
580 ;;; slots, since they are used to keep track of functions across
581 ;;; component boundaries.
582 (defun clear-constant-info ()
583   (maphash (lambda (k v)
584              (declare (ignore k))
585              (setf (leaf-info v) nil))
586            *constants*)
587   (maphash (lambda (k v)
588              (declare (ignore k))
589              (when (constant-p v)
590                (setf (leaf-info v) nil)))
591            *free-vars*)
592   (values))
593
594 ;;; Blow away the REFS for all global variables, and let COMPONENT
595 ;;; be recycled.
596 (defun clear-ir1-info (component)
597   (declare (type component component))
598   (labels ((blast (x)
599              (maphash (lambda (k v)
600                         (declare (ignore k))
601                         (when (leaf-p v)
602                           (setf (leaf-refs v)
603                                 (delete-if #'here-p (leaf-refs v)))
604                           (when (basic-var-p v)
605                             (setf (basic-var-sets v)
606                                   (delete-if #'here-p (basic-var-sets v))))))
607                       x))
608            (here-p (x)
609              (eq (node-component x) component)))
610     (blast *free-vars*)
611     (blast *free-funs*)
612     (blast *constants*))
613   (values))
614
615 ;;; Clear global variables used by the compiler.
616 ;;;
617 ;;; FIXME: It seems kinda nasty and unmaintainable to have to do this,
618 ;;; and it adds overhead even when people aren't using the compiler.
619 ;;; Perhaps we could make these global vars unbound except when
620 ;;; actually in use, so that this function could go away.
621 (defun clear-stuff (&optional (debug-too t))
622
623   ;; Clear global tables.
624   (when (boundp '*free-funs*)
625     (clrhash *free-funs*)
626     (clrhash *free-vars*)
627     (clrhash *constants*))
628
629   ;; Clear debug counters and tables.
630   (clrhash *seen-blocks*)
631   (clrhash *seen-funs*)
632   (clrhash *list-conflicts-table*)
633
634   (when debug-too
635     (clrhash *continuation-numbers*)
636     (clrhash *number-continuations*)
637     (setq *continuation-number* 0)
638     (clrhash *tn-ids*)
639     (clrhash *id-tns*)
640     (setq *tn-id* 0)
641     (clrhash *label-ids*)
642     (clrhash *id-labels*)
643     (setq *label-id* 0))
644
645   ;; (Note: The CMU CL code used to set CL::*GENSYM-COUNTER* to zero here.
646   ;; Superficially, this seemed harmful -- the user could reasonably be
647   ;; surprised if *GENSYM-COUNTER* turned back to zero when something was
648   ;; compiled. A closer inspection showed that this actually turned out to be
649   ;; harmless in practice, because CLEAR-STUFF was only called from within
650   ;; forms which bound CL::*GENSYM-COUNTER* to zero. However, this means that
651   ;; even though zeroing CL::*GENSYM-COUNTER* here turned out to be harmless in
652   ;; practice, it was also useless in practice. So we don't do it any more.)
653
654   (values))
655 \f
656 ;;;; trace output
657
658 ;;; Print out some useful info about COMPONENT to STREAM.
659 (defun describe-component (component *standard-output*)
660   (declare (type component component))
661   (format t "~|~%;;;; component: ~S~2%" (component-name component))
662   (print-all-blocks component)
663   (values))
664
665 (defun describe-ir2-component (component *standard-output*)
666   (format t "~%~|~%;;;; IR2 component: ~S~2%" (component-name component))
667   (format t "entries:~%")
668   (dolist (entry (ir2-component-entries (component-info component)))
669     (format t "~4TL~D: ~S~:[~; [closure]~]~%"
670             (label-id (entry-info-offset entry))
671             (entry-info-name entry)
672             (entry-info-closure-p entry)))
673   (terpri)
674   (pre-pack-tn-stats component *standard-output*)
675   (terpri)
676   (print-ir2-blocks component)
677   (terpri)
678   (values))
679 \f
680 ;;;; file reading
681 ;;;;
682 ;;;; When reading from a file, we have to keep track of some source
683 ;;;; information. We also exploit our ability to back up for printing
684 ;;;; the error context and for recovering from errors.
685 ;;;;
686 ;;;; The interface we provide to this stuff is the stream-oid
687 ;;;; SOURCE-INFO structure. The bookkeeping is done as a side effect
688 ;;;; of getting the next source form.
689
690 ;;; A FILE-INFO structure holds all the source information for a
691 ;;; given file.
692 (def!struct (file-info (:copier nil))
693   ;; If a file, the truename of the corresponding source file. If from
694   ;; a Lisp form, :LISP. If from a stream, :STREAM.
695   (name (missing-arg) :type (or pathname (member :lisp :stream)))
696   ;; the defaulted, but not necessarily absolute file name (i.e. prior
697   ;; to TRUENAME call.) Null if not a file. This is used to set
698   ;; *COMPILE-FILE-PATHNAME*, and if absolute, is dumped in the
699   ;; debug-info.
700   (untruename nil :type (or pathname null))
701   ;; the file's write date (if relevant)
702   (write-date nil :type (or unsigned-byte null))
703   ;; the source path root number of the first form in this file (i.e.
704   ;; the total number of forms converted previously in this
705   ;; compilation)
706   (source-root 0 :type unsigned-byte)
707   ;; parallel vectors containing the forms read out of the file and
708   ;; the file positions that reading of each form started at (i.e. the
709   ;; end of the previous form)
710   (forms (make-array 10 :fill-pointer 0 :adjustable t) :type (vector t))
711   (positions (make-array 10 :fill-pointer 0 :adjustable t) :type (vector t)))
712
713 ;;; The SOURCE-INFO structure provides a handle on all the source
714 ;;; information for an entire compilation.
715 (def!struct (source-info
716              #-no-ansi-print-object
717              (:print-object (lambda (s stream)
718                               (print-unreadable-object (s stream :type t))))
719              (:copier nil))
720   ;; the UT that compilation started at
721   (start-time (get-universal-time) :type unsigned-byte)
722   ;; the FILE-INFO structure for this compilation
723   (file-info nil :type (or file-info null))
724   ;; the stream that we are using to read the FILE-INFO, or NIL if
725   ;; no stream has been opened yet
726   (stream nil :type (or stream null)))
727
728 ;;; Given a pathname, return a SOURCE-INFO structure.
729 (defun make-file-source-info (file)
730   (let ((file-info (make-file-info :name (truename file)
731                                    :untruename file
732                                    :write-date (file-write-date file))))
733
734     (make-source-info :file-info file-info)))
735
736 ;;; Return a SOURCE-INFO to describe the incremental compilation of FORM. 
737 (defun make-lisp-source-info (form)
738   (make-source-info :start-time (get-universal-time)
739                     :file-info (make-file-info :name :lisp
740                                                :forms (vector form)
741                                                :positions '#(0))))
742
743 ;;; Return a SOURCE-INFO which will read from STREAM.
744 (defun make-stream-source-info (stream)
745   (let ((file-info (make-file-info :name :stream)))
746     (make-source-info :file-info file-info
747                       :stream stream)))
748
749 ;;; Return a form read from STREAM; or for EOF use the trick,
750 ;;; popularized by Kent Pitman, of returning STREAM itself. If an
751 ;;; error happens, then convert it to standard abort-the-compilation
752 ;;; error condition (possibly recording some extra location
753 ;;; information).
754 (defun read-for-compile-file (stream position)
755   (handler-case (read stream nil stream)
756     (reader-error (condition)
757      (error 'input-error-in-compile-file
758             :condition condition
759             ;; We don't need to supply :POSITION here because
760             ;; READER-ERRORs already know their position in the file.
761             ))
762     ;; ANSI, in its wisdom, says that READ should return END-OF-FILE
763     ;; (and that this is not a READER-ERROR) when it encounters end of
764     ;; file in the middle of something it's trying to read.
765     (end-of-file (condition)
766      (error 'input-error-in-compile-file
767             :condition condition
768             ;; We need to supply :POSITION here because the END-OF-FILE
769             ;; condition doesn't carry the position that the user
770             ;; probably cares about, where the failed READ began.
771             :position position))))
772
773 ;;; If STREAM is present, return it, otherwise open a stream to the
774 ;;; current file. There must be a current file.
775 ;;;
776 ;;; FIXME: This is probably an unnecessarily roundabout way to do
777 ;;; things now that we process a single file in COMPILE-FILE (unlike
778 ;;; the old CMU CL code, which accepted multiple files). Also, the old
779 ;;; comment said
780 ;;;   When we open a new file, we also reset *PACKAGE* and policy.
781 ;;;   This gives the effect of rebinding around each file.
782 ;;; which doesn't seem to be true now. Check to make sure that if
783 ;;; such rebinding is necessary, it's still done somewhere.
784 (defun get-source-stream (info)
785   (declare (type source-info info))
786   (or (source-info-stream info)
787       (let* ((file-info (source-info-file-info info))
788              (name (file-info-name file-info)))
789         (setf sb!xc:*compile-file-truename* name
790               sb!xc:*compile-file-pathname* (file-info-untruename file-info)
791               (source-info-stream info) (open name :direction :input)))))
792
793 ;;; Close the stream in INFO if it is open.
794 (defun close-source-info (info)
795   (declare (type source-info info))
796   (let ((stream (source-info-stream info)))
797     (when stream (close stream)))
798   (setf (source-info-stream info) nil)
799   (values))
800
801 ;;; Read and compile the source file.
802 (defun sub-sub-compile-file (info)
803   (let* ((file-info (source-info-file-info info))
804          (stream (get-source-stream info)))
805     (loop
806      (let* ((pos (file-position stream))
807             (form (read-for-compile-file stream pos)))
808        (if (eq form stream) ; i.e., if EOF
809            (return)
810            (let* ((forms (file-info-forms file-info))
811                   (current-idx (+ (fill-pointer forms)
812                                   (file-info-source-root file-info))))
813              (vector-push-extend form forms)
814              (vector-push-extend pos (file-info-positions file-info))
815              (find-source-paths form current-idx)
816              (process-toplevel-form form
817                                     `(original-source-start 0 ,current-idx)
818                                     nil)))))))
819
820 ;;; Return the INDEX'th source form read from INFO and the position
821 ;;; where it was read.
822 (defun find-source-root (index info)
823   (declare (type index index) (type source-info info))
824   (let ((file-info (source-info-file-info info)))
825     (values (aref (file-info-forms file-info) index)
826             (aref (file-info-positions file-info) index))))
827 \f
828 ;;;; processing of top level forms
829
830 ;;; This is called by top level form processing when we are ready to
831 ;;; actually compile something. If *BLOCK-COMPILE* is T, then we still
832 ;;; convert the form, but delay compilation, pushing the result on
833 ;;; *TOPLEVEL-LAMBDAS* instead.
834 (defun convert-and-maybe-compile (form path)
835   (declare (list path))
836   (let* ((*lexenv* (make-lexenv :policy *policy*
837                                 :handled-conditions *handled-conditions*
838                                 :disabled-package-locks *disabled-package-locks*))
839          (tll (ir1-toplevel form path nil)))
840     (cond ((eq *block-compile* t) (push tll *toplevel-lambdas*))
841           (t (compile-toplevel (list tll) nil)))))
842
843 ;;; Macroexpand FORM in the current environment with an error handler.
844 ;;; We only expand one level, so that we retain all the intervening
845 ;;; forms in the source path.
846 (defun preprocessor-macroexpand-1 (form)
847   (handler-case (sb!xc:macroexpand-1 form *lexenv*)
848     (error (condition)
849       (signal condition)
850       (compiler-error "(during macroexpansion of ~A)~%~A"
851                       (let ((*print-level* 1)
852                             (*print-length* 2))
853                         (format nil "~S" form))
854                       condition))))
855
856 ;;; Process a PROGN-like portion of a top level form. FORMS is a list of
857 ;;; the forms, and PATH is the source path of the FORM they came out of.
858 ;;; COMPILE-TIME-TOO is as in ANSI "3.2.3.1 Processing of Top Level Forms".
859 (defun process-toplevel-progn (forms path compile-time-too)
860   (declare (list forms) (list path))
861   (dolist (form forms)
862     (process-toplevel-form form path compile-time-too)))
863
864 ;;; Process a top level use of LOCALLY, or anything else (e.g.
865 ;;; MACROLET) at top level which has declarations and ordinary forms.
866 ;;; We parse declarations and then recursively process the body.
867 (defun process-toplevel-locally (body path compile-time-too &key vars funs)
868   (declare (list path))
869   (multiple-value-bind (forms decls)
870       (parse-body body :doc-string-allowed nil :toplevel t)
871     (let* ((*lexenv* (process-decls decls vars funs))
872            ;; FIXME: VALUES declaration
873            ;;
874            ;; Binding *POLICY* is pretty much of a hack, since it
875            ;; causes LOCALLY to "capture" enclosed proclamations. It
876            ;; is necessary because CONVERT-AND-MAYBE-COMPILE uses the
877            ;; value of *POLICY* as the policy. The need for this hack
878            ;; is due to the quirk that there is no way to represent in
879            ;; a POLICY that an optimize quality came from the default.
880            ;;
881            ;; FIXME: Ideally, something should be done so that DECLAIM
882            ;; inside LOCALLY works OK. Failing that, at least we could
883            ;; issue a warning instead of silently screwing up.
884            (*policy* (lexenv-policy *lexenv*))
885            ;; This is probably also a hack
886            (*handled-conditions* (lexenv-handled-conditions *lexenv*))
887            ;; ditto
888            (*disabled-package-locks* (lexenv-disabled-package-locks *lexenv*)))
889       (process-toplevel-progn forms path compile-time-too))))
890
891 ;;; Parse an EVAL-WHEN situations list, returning three flags,
892 ;;; (VALUES COMPILE-TOPLEVEL LOAD-TOPLEVEL EXECUTE), indicating
893 ;;; the types of situations present in the list.
894 (defun parse-eval-when-situations (situations)
895   (when (or (not (listp situations))
896             (set-difference situations
897                             '(:compile-toplevel
898                               compile
899                               :load-toplevel
900                               load
901                               :execute
902                               eval)))
903     (compiler-error "bad EVAL-WHEN situation list: ~S" situations))
904   (let ((deprecated-names (intersection situations '(compile load eval))))
905     (when deprecated-names
906       (style-warn "using deprecated EVAL-WHEN situation names~{ ~S~}"
907                   deprecated-names)))
908   (values (intersection '(:compile-toplevel compile)
909                         situations)
910           (intersection '(:load-toplevel load) situations)
911           (intersection '(:execute eval) situations)))
912
913
914 ;;; utilities for extracting COMPONENTs of FUNCTIONALs
915 (defun functional-components (f)
916   (declare (type functional f))
917   (etypecase f
918     (clambda (list (lambda-component f)))
919     (optional-dispatch (let ((result nil))
920                          (flet ((maybe-frob (maybe-clambda)
921                                   (when (and maybe-clambda
922                                              (promise-ready-p maybe-clambda))
923                                     (pushnew (lambda-component
924                                               (force maybe-clambda))
925                                              result))))
926                            (map nil #'maybe-frob (optional-dispatch-entry-points f))
927                            (maybe-frob (optional-dispatch-more-entry f))
928                            (maybe-frob (optional-dispatch-main-entry f)))
929                          result))))
930
931 (defun make-functional-from-toplevel-lambda (definition
932                                              &key
933                                              name
934                                              (path
935                                               ;; I'd thought NIL should
936                                               ;; work, but it doesn't.
937                                               ;; -- WHN 2001-09-20
938                                               (missing-arg)))
939   (let* ((*current-path* path)
940          (component (make-empty-component))
941          (*current-component* component))
942     (setf (component-name component)
943           (debug-namify "~S initial component" name))
944     (setf (component-kind component) :initial)
945     (let* ((locall-fun (let ((*allow-instrumenting* t))
946                          (ir1-convert-lambdalike
947                           definition
948                           :debug-name (debug-namify "top level local call "
949                                                     name))))
950            (fun (ir1-convert-lambda (make-xep-lambda-expression locall-fun)
951                                     :source-name (or name '.anonymous.)
952                                     :debug-name (unless name
953                                                   "top level form"))))
954       (when name
955         (assert-global-function-definition-type name locall-fun))
956       (setf (functional-entry-fun fun) locall-fun
957             (functional-kind fun) :external
958             (functional-has-external-references-p fun) t)
959       fun)))
960
961 ;;; Compile LAMBDA-EXPRESSION into *COMPILE-OBJECT*, returning a
962 ;;; description of the result.
963 ;;;   * If *COMPILE-OBJECT* is a CORE-OBJECT, then write the function
964 ;;;     into core and return the compiled FUNCTION value.
965 ;;;   * If *COMPILE-OBJECT* is a fasl file, then write the function
966 ;;;     into the fasl file and return a dump handle.
967 ;;;
968 ;;; If NAME is provided, then we try to use it as the name of the
969 ;;; function for debugging/diagnostic information.
970 (defun %compile (lambda-expression
971                  *compile-object*
972                  &key
973                  name
974                  (path
975                   ;; This magical idiom seems to be the appropriate
976                   ;; path for compiling standalone LAMBDAs, judging
977                   ;; from the CMU CL code and experiment, so it's a
978                   ;; nice default for things where we don't have a
979                   ;; real source path (as in e.g. inside CL:COMPILE).
980                   '(original-source-start 0 0)))
981   (when name
982     (legal-fun-name-or-type-error name))
983   (let* (
984          (*lexenv* (make-lexenv :policy *policy*
985                                 :handled-conditions *handled-conditions*
986                                 :disabled-package-locks *disabled-package-locks*))
987          (fun (make-functional-from-toplevel-lambda lambda-expression
988                                                     :name name
989                                                     :path path)))
990
991     ;; FIXME: The compile-it code from here on is sort of a
992     ;; twisted version of the code in COMPILE-TOPLEVEL. It'd be
993     ;; better to find a way to share the code there; or
994     ;; alternatively, to use this code to replace the code there.
995     ;; (The second alternative might be pretty easy if we used
996     ;; the :LOCALL-ONLY option to IR1-FOR-LAMBDA. Then maybe the
997     ;; whole FUNCTIONAL-KIND=:TOPLEVEL case could go away..)
998
999     (locall-analyze-clambdas-until-done (list fun))
1000     
1001     (multiple-value-bind (components-from-dfo top-components hairy-top)
1002         (find-initial-dfo (list fun))
1003
1004       (let ((*all-components* (append components-from-dfo top-components)))
1005         ;; FIXME: This is more monkey see monkey do based on CMU CL
1006         ;; code. If anyone figures out why to only prescan HAIRY-TOP
1007         ;; and TOP-COMPONENTS here, instead of *ALL-COMPONENTS* or
1008         ;; some other combination of results from FIND-INITIAL-VALUES,
1009         ;; it'd be good to explain it.
1010         (mapc #'preallocate-physenvs-for-toplevelish-lambdas hairy-top)
1011         (mapc #'preallocate-physenvs-for-toplevelish-lambdas top-components)
1012         (dolist (component-from-dfo components-from-dfo)
1013           (compile-component component-from-dfo)
1014           (replace-toplevel-xeps component-from-dfo)))
1015
1016       (let ((entry-table (etypecase *compile-object*
1017                            (fasl-output (fasl-output-entry-table
1018                                          *compile-object*))
1019                            (core-object (core-object-entry-table
1020                                          *compile-object*)))))
1021         (multiple-value-bind (result found-p)
1022             (gethash (leaf-info fun) entry-table)
1023           (aver found-p)
1024           (prog1 
1025               result
1026             ;; KLUDGE: This code duplicates some other code in this
1027             ;; file. In the great reorganzation, the flow of program
1028             ;; logic changed from the original CMUCL model, and that
1029             ;; path (as of sbcl-0.7.5 in SUB-COMPILE-FILE) was no
1030             ;; longer followed for CORE-OBJECTS, leading to BUG
1031             ;; 156. This place is transparently not the right one for
1032             ;; this code, but I don't have a clear enough overview of
1033             ;; the compiler to know how to rearrange it all so that
1034             ;; this operation fits in nicely, and it was blocking
1035             ;; reimplementation of (DECLAIM (INLINE FOO)) (MACROLET
1036             ;; ((..)) (DEFUN FOO ...))
1037             ;;
1038             ;; FIXME: This KLUDGE doesn't solve all the problem in an
1039             ;; ideal way, as (1) definitions typed in at the REPL
1040             ;; without an INLINE declaration will give a NULL
1041             ;; FUNCTION-LAMBDA-EXPRESSION (allowable, but not ideal)
1042             ;; and (2) INLINE declarations will yield a
1043             ;; FUNCTION-LAMBDA-EXPRESSION headed by
1044             ;; SB-C:LAMBDA-WITH-LEXENV, even for null LEXENV.  -- CSR,
1045             ;; 2002-07-02
1046             ;;
1047             ;; (2) is probably fairly easy to fix -- it is, after all,
1048             ;; a matter of list manipulation (or possibly of teaching
1049             ;; CL:FUNCTION about SB-C:LAMBDA-WITH-LEXENV).  (1) is
1050             ;; significantly harder, as the association between
1051             ;; function object and source is a tricky one.
1052             ;;
1053             ;; FUNCTION-LAMBDA-EXPRESSION "works" (i.e. returns a
1054             ;; non-NULL list) when the function in question has been
1055             ;; compiled by (COMPILE <x> '(LAMBDA ...)); it does not
1056             ;; work when it has been compiled as part of the top-level
1057             ;; EVAL strategy of compiling everything inside (LAMBDA ()
1058             ;; ...).  -- CSR, 2002-11-02
1059             (when (core-object-p *compile-object*)
1060               (fix-core-source-info *source-info* *compile-object* result))
1061
1062             (mapc #'clear-ir1-info components-from-dfo)
1063             (clear-stuff)))))))
1064
1065 (defun process-toplevel-cold-fset (name lambda-expression path)
1066   (unless (producing-fasl-file)
1067     (error "can't COLD-FSET except in a fasl file"))
1068   (legal-fun-name-or-type-error name)
1069   (fasl-dump-cold-fset name
1070                        (%compile lambda-expression
1071                                  *compile-object*
1072                                  :name name
1073                                  :path path)
1074                        *compile-object*)
1075   (values))
1076
1077 ;;; Process a top level FORM with the specified source PATH.
1078 ;;;  * If this is a magic top level form, then do stuff.
1079 ;;;  * If this is a macro, then expand it.
1080 ;;;  * Otherwise, just compile it.
1081 ;;;
1082 ;;; COMPILE-TIME-TOO is as defined in ANSI
1083 ;;; "3.2.3.1 Processing of Top Level Forms".
1084 (defun process-toplevel-form (form path compile-time-too)
1085
1086   (declare (list path))
1087
1088   (catch 'process-toplevel-form-error-abort
1089     (let* ((path (or (gethash form *source-paths*) (cons form path)))
1090            (*compiler-error-bailout*
1091             (lambda (&optional condition)
1092               (convert-and-maybe-compile
1093                (make-compiler-error-form condition form)
1094                path)
1095               (throw 'process-toplevel-form-error-abort nil))))
1096
1097       (flet ((default-processor (form)
1098                ;; When we're cross-compiling, consider: what should we
1099                ;; do when we hit e.g.
1100                ;;   (EVAL-WHEN (:COMPILE-TOPLEVEL)
1101                ;;     (DEFUN FOO (X) (+ 7 X)))?
1102                ;; DEFUN has a macro definition in the cross-compiler,
1103                ;; and a different macro definition in the target
1104                ;; compiler. The only sensible thing is to use the
1105                ;; target compiler's macro definition, since the
1106                ;; cross-compiler's macro is in general into target
1107                ;; functions which can't meaningfully be executed at
1108                ;; cross-compilation time. So make sure we do the EVAL
1109                ;; here, before we macroexpand.
1110                ;;
1111                ;; Then things get even dicier with something like
1112                ;;   (DEFCONSTANT-EQX SB!XC:LAMBDA-LIST-KEYWORDS ..)
1113                ;; where we have to make sure that we don't uncross
1114                ;; the SB!XC: prefix before we do EVAL, because otherwise
1115                ;; we'd be trying to redefine the cross-compilation host's
1116                ;; constants.
1117                ;;
1118                ;; (Isn't it fun to cross-compile Common Lisp?:-)
1119                #+sb-xc-host
1120                (progn
1121                  (when compile-time-too
1122                    (eval form)) ; letting xc host EVAL do its own macroexpansion
1123                  (let* (;; (We uncross the operator name because things
1124                         ;; like SB!XC:DEFCONSTANT and SB!XC:DEFTYPE
1125                         ;; should be equivalent to their CL: counterparts
1126                         ;; when being compiled as target code. We leave
1127                         ;; the rest of the form uncrossed because macros
1128                         ;; might yet expand into EVAL-WHEN stuff, and
1129                         ;; things inside EVAL-WHEN can't be uncrossed
1130                         ;; until after we've EVALed them in the
1131                         ;; cross-compilation host.)
1132                         (slightly-uncrossed (cons (uncross (first form))
1133                                                   (rest form)))
1134                         (expanded (preprocessor-macroexpand-1
1135                                    slightly-uncrossed)))
1136                    (if (eq expanded slightly-uncrossed)
1137                        ;; (Now that we're no longer processing toplevel
1138                        ;; forms, and hence no longer need to worry about
1139                        ;; EVAL-WHEN, we can uncross everything.)
1140                        (convert-and-maybe-compile expanded path)
1141                        ;; (We have to demote COMPILE-TIME-TOO to NIL
1142                        ;; here, no matter what it was before, since
1143                        ;; otherwise we'd tend to EVAL subforms more than
1144                        ;; once, because of WHEN COMPILE-TIME-TOO form
1145                        ;; above.)
1146                        (process-toplevel-form expanded path nil))))
1147                ;; When we're not cross-compiling, we only need to
1148                ;; macroexpand once, so we can follow the 1-thru-6
1149                ;; sequence of steps in ANSI's "3.2.3.1 Processing of
1150                ;; Top Level Forms".
1151                #-sb-xc-host
1152                (let ((expanded (preprocessor-macroexpand-1 form)))
1153                  (cond ((eq expanded form)
1154                         (when compile-time-too
1155                           (eval-in-lexenv form *lexenv*))
1156                         (convert-and-maybe-compile form path))
1157                        (t
1158                         (process-toplevel-form expanded
1159                                                path
1160                                                compile-time-too))))))
1161         (if (atom form)
1162             #+sb-xc-host
1163             ;; (There are no xc EVAL-WHEN issues in the ATOM case until
1164             ;; (1) SBCL gets smart enough to handle global
1165             ;; DEFINE-SYMBOL-MACRO or SYMBOL-MACROLET and (2) SBCL
1166             ;; implementors start using symbol macros in a way which
1167             ;; interacts with SB-XC/CL distinction.)
1168             (convert-and-maybe-compile form path)
1169             #-sb-xc-host
1170             (default-processor form)
1171             (flet ((need-at-least-one-arg (form)
1172                      (unless (cdr form)
1173                        (compiler-error "~S form is too short: ~S"
1174                                        (car form)
1175                                        form))))
1176               (case (car form)
1177                 ;; In the cross-compiler, top level COLD-FSET arranges
1178                 ;; for static linking at cold init time.
1179                 #+sb-xc-host
1180                 ((cold-fset)
1181                  (aver (not compile-time-too))
1182                  (destructuring-bind (cold-fset fun-name lambda-expression) form
1183                    (declare (ignore cold-fset))
1184                    (process-toplevel-cold-fset fun-name
1185                                                lambda-expression
1186                                                path)))
1187                 ((eval-when macrolet symbol-macrolet);things w/ 1 arg before body
1188                  (need-at-least-one-arg form)
1189                  (destructuring-bind (special-operator magic &rest body) form
1190                    (ecase special-operator
1191                      ((eval-when)
1192                       ;; CT, LT, and E here are as in Figure 3-7 of ANSI
1193                       ;; "3.2.3.1 Processing of Top Level Forms".
1194                       (multiple-value-bind (ct lt e)
1195                           (parse-eval-when-situations magic)
1196                         (let ((new-compile-time-too (or ct
1197                                                         (and compile-time-too
1198                                                              e))))
1199                           (cond (lt (process-toplevel-progn
1200                                      body path new-compile-time-too))
1201                                 (new-compile-time-too (eval-in-lexenv
1202                                                        `(progn ,@body)
1203                                                        *lexenv*))))))
1204                      ((macrolet)
1205                       (funcall-in-macrolet-lexenv
1206                        magic
1207                        (lambda (&key funs prepend)
1208                          (declare (ignore funs))
1209                          (aver (null prepend))
1210                          (process-toplevel-locally body
1211                                                    path
1212                                                    compile-time-too))
1213                        :compile))
1214                      ((symbol-macrolet)
1215                       (funcall-in-symbol-macrolet-lexenv
1216                        magic
1217                        (lambda (&key vars prepend)
1218                          (aver (null prepend))
1219                          (process-toplevel-locally body
1220                                                    path
1221                                                    compile-time-too
1222                                                    :vars vars))
1223                        :compile)))))
1224                 ((locally)
1225                  (process-toplevel-locally (rest form) path compile-time-too))
1226                 ((progn)
1227                  (process-toplevel-progn (rest form) path compile-time-too))
1228                 (t (default-processor form))))))))
1229
1230   (values))
1231 \f
1232 ;;;; load time value support
1233 ;;;;
1234 ;;;; (See EMIT-MAKE-LOAD-FORM.)
1235
1236 ;;; Return T if we are currently producing a fasl file and hence
1237 ;;; constants need to be dumped carefully.
1238 (defun producing-fasl-file ()
1239   (fasl-output-p *compile-object*))
1240
1241 ;;; Compile FORM and arrange for it to be called at load-time. Return
1242 ;;; the dumper handle and our best guess at the type of the object.
1243 (defun compile-load-time-value (form)
1244   (let ((lambda (compile-load-time-stuff form t)))
1245     (values
1246      (fasl-dump-load-time-value-lambda lambda *compile-object*)
1247      (let ((type (leaf-type lambda)))
1248        (if (fun-type-p type)
1249            (single-value-type (fun-type-returns type))
1250            *wild-type*)))))
1251
1252 ;;; Compile the FORMS and arrange for them to be called (for effect,
1253 ;;; not value) at load time.
1254 (defun compile-make-load-form-init-forms (forms)
1255   (let ((lambda (compile-load-time-stuff `(progn ,@forms) nil)))
1256     (fasl-dump-toplevel-lambda-call lambda *compile-object*)))
1257
1258 ;;; Do the actual work of COMPILE-LOAD-TIME-VALUE or
1259 ;;; COMPILE-MAKE-LOAD-FORM-INIT-FORMS.
1260 (defun compile-load-time-stuff (form for-value)
1261   (with-ir1-namespace
1262    (let* ((*lexenv* (make-null-lexenv))
1263           (lambda (ir1-toplevel form *current-path* for-value)))
1264      (compile-toplevel (list lambda) t)
1265      lambda)))
1266
1267 ;;; This is called by COMPILE-TOPLEVEL when it was passed T for
1268 ;;; LOAD-TIME-VALUE-P (which happens in COMPILE-LOAD-TIME-STUFF). We
1269 ;;; don't try to combine this component with anything else and frob
1270 ;;; the name. If not in a :TOPLEVEL component, then don't bother
1271 ;;; compiling, because it was merged with a run-time component.
1272 (defun compile-load-time-value-lambda (lambdas)
1273   (aver (null (cdr lambdas)))
1274   (let* ((lambda (car lambdas))
1275          (component (lambda-component lambda)))
1276     (when (eql (component-kind component) :toplevel)
1277       (setf (component-name component) (leaf-debug-name lambda))
1278       (compile-component component)
1279       (clear-ir1-info component))))
1280 \f
1281 ;;;; COMPILE-FILE
1282
1283 (defun object-call-toplevel-lambda (tll)
1284   (declare (type functional tll))
1285   (let ((object *compile-object*))
1286     (etypecase object
1287       (fasl-output (fasl-dump-toplevel-lambda-call tll object))
1288       (core-object (core-call-toplevel-lambda      tll object))
1289       (null))))
1290
1291 ;;; Smash LAMBDAS into a single component, compile it, and arrange for
1292 ;;; the resulting function to be called.
1293 (defun sub-compile-toplevel-lambdas (lambdas)
1294   (declare (list lambdas))
1295   (when lambdas
1296     (multiple-value-bind (component tll) (merge-toplevel-lambdas lambdas)
1297       (compile-component component)
1298       (clear-ir1-info component)
1299       (object-call-toplevel-lambda tll)))
1300   (values))
1301
1302 ;;; Compile top level code and call the top level lambdas. We pick off
1303 ;;; top level lambdas in non-top-level components here, calling
1304 ;;; SUB-c-t-l-l on each subsequence of normal top level lambdas.
1305 (defun compile-toplevel-lambdas (lambdas)
1306   (declare (list lambdas))
1307   (let ((len (length lambdas)))
1308     (flet ((loser (start)
1309              (or (position-if (lambda (x)
1310                                 (not (eq (component-kind
1311                                           (node-component (lambda-bind x)))
1312                                          :toplevel)))
1313                               lambdas
1314                               ;; this used to read ":start start", but
1315                               ;; start can be greater than len, which
1316                               ;; is an error according to ANSI - CSR,
1317                               ;; 2002-04-25
1318                               :start (min start len))
1319                  len)))
1320       (do* ((start 0 (1+ loser))
1321             (loser (loser start) (loser start)))
1322            ((>= start len))
1323         (sub-compile-toplevel-lambdas (subseq lambdas start loser))
1324         (unless (= loser len)
1325           (object-call-toplevel-lambda (elt lambdas loser))))))
1326   (values))
1327
1328 ;;; Compile LAMBDAS (a list of CLAMBDAs for top level forms) into the
1329 ;;; object file. 
1330 ;;;
1331 ;;; LOAD-TIME-VALUE-P seems to control whether it's MAKE-LOAD-FORM and
1332 ;;; COMPILE-LOAD-TIME-VALUE stuff. -- WHN 20000201
1333 (defun compile-toplevel (lambdas load-time-value-p)
1334   (declare (list lambdas))
1335
1336   (maybe-mumble "locall ")
1337   (locall-analyze-clambdas-until-done lambdas)
1338
1339   (maybe-mumble "IDFO ")
1340   (multiple-value-bind (components top-components hairy-top)
1341       (find-initial-dfo lambdas)
1342     (let ((*all-components* (append components top-components)))
1343       (when *check-consistency*
1344         (maybe-mumble "[check]~%")
1345         (check-ir1-consistency *all-components*))
1346
1347       (dolist (component (append hairy-top top-components))
1348         (pre-physenv-analyze-toplevel component))
1349
1350       (dolist (component components)
1351         (compile-component component)
1352         (replace-toplevel-xeps component))
1353         
1354       (when *check-consistency*
1355         (maybe-mumble "[check]~%")
1356         (check-ir1-consistency *all-components*))
1357         
1358       (if load-time-value-p
1359           (compile-load-time-value-lambda lambdas)
1360           (compile-toplevel-lambdas lambdas))
1361
1362       (mapc #'clear-ir1-info components)
1363       (clear-stuff)))
1364   (values))
1365
1366 ;;; Actually compile any stuff that has been queued up for block
1367 ;;; compilation.
1368 (defun finish-block-compilation ()
1369   (when *block-compile*
1370     (when *toplevel-lambdas*
1371       (compile-toplevel (nreverse *toplevel-lambdas*) nil)
1372       (setq *toplevel-lambdas* ()))
1373     (setq *block-compile* nil)
1374     (setq *entry-points* nil)))
1375
1376 (defun handle-condition-p (condition)
1377   (let ((lexenv
1378          (etypecase *compiler-error-context*
1379            (node
1380             (node-lexenv *compiler-error-context*))
1381            (compiler-error-context
1382             (let ((lexenv (compiler-error-context-lexenv
1383                            *compiler-error-context*)))
1384               (aver lexenv)
1385               lexenv))
1386            (null *lexenv*))))
1387     (let ((muffles (lexenv-handled-conditions lexenv)))
1388       (if (null muffles) ; common case
1389           nil
1390           (dolist (muffle muffles nil)
1391             (destructuring-bind (typespec . restart-name) muffle
1392               (when (and (typep condition typespec)
1393                          (find-restart restart-name condition))
1394                 (return t))))))))
1395
1396 (defun handle-condition-handler (condition)
1397   (let ((lexenv
1398          (etypecase *compiler-error-context*
1399            (node
1400             (node-lexenv *compiler-error-context*))
1401            (compiler-error-context
1402             (let ((lexenv (compiler-error-context-lexenv
1403                            *compiler-error-context*)))
1404               (aver lexenv)
1405               lexenv))
1406            (null *lexenv*))))
1407     (let ((muffles (lexenv-handled-conditions lexenv)))
1408       (aver muffles)
1409       (dolist (muffle muffles (bug "fell through"))
1410         (destructuring-bind (typespec . restart-name) muffle
1411           (when (typep condition typespec)
1412             (awhen (find-restart restart-name condition)
1413               (invoke-restart it))))))))
1414
1415 ;;; Read all forms from INFO and compile them, with output to OBJECT.
1416 ;;; Return (VALUES NIL WARNINGS-P FAILURE-P).
1417 (defun sub-compile-file (info)
1418   (declare (type source-info info))
1419   (let ((*package* (sane-package))
1420         (*readtable* *readtable*)
1421         (sb!xc:*compile-file-pathname* nil) ; really bound in
1422         (sb!xc:*compile-file-truename* nil) ; SUB-SUB-COMPILE-FILE
1423
1424         (*policy* *policy*)
1425         (*handled-conditions* *handled-conditions*)
1426         (*disabled-package-locks* *disabled-package-locks*)
1427         (*lexenv* (make-null-lexenv))
1428         (*block-compile* *block-compile-arg*)
1429         (*source-info* info)
1430         (*toplevel-lambdas* ())
1431         (*fun-names-in-this-file* ())
1432         (*allow-instrumenting* nil)
1433         (*compiler-error-bailout*
1434          (lambda ()
1435            (compiler-mumble "~2&; fatal error, aborting compilation~%")
1436            (return-from sub-compile-file (values nil t t))))
1437         (*current-path* nil)
1438         (*last-source-context* nil)
1439         (*last-original-source* nil)
1440         (*last-source-form* nil)
1441         (*last-format-string* nil)
1442         (*last-format-args* nil)
1443         (*last-message-count* 0)
1444         ;; FIXME: Do we need this rebinding here? It's a literal
1445         ;; translation of the old CMU CL rebinding to
1446         ;; (OR *BACKEND-INFO-ENVIRONMENT* *INFO-ENVIRONMENT*),
1447         ;; and it's not obvious whether the rebinding to itself is
1448         ;; needed that SBCL doesn't need *BACKEND-INFO-ENVIRONMENT*.
1449         (*info-environment* *info-environment*)
1450         (*gensym-counter* 0))
1451     (handler-case
1452         (handler-bind (((satisfies handle-condition-p) #'handle-condition-handler))
1453           (with-compilation-values
1454               (sb!xc:with-compilation-unit ()
1455                 (clear-stuff)
1456                 
1457                 (sub-sub-compile-file info)
1458                 
1459                 (finish-block-compilation)
1460                 (let ((object *compile-object*))
1461                   (etypecase object
1462                     (fasl-output (fasl-dump-source-info info object))
1463                     (core-object (fix-core-source-info info object))
1464                     (null)))
1465                 nil)))
1466       ;; Some errors are sufficiently bewildering that we just fail
1467       ;; immediately, without trying to recover and compile more of
1468       ;; the input file.
1469       (fatal-compiler-error (condition)
1470        (signal condition)
1471        (format *error-output*
1472                "~@<compilation aborted because of fatal error: ~2I~_~A~:>"
1473                condition)
1474        (values nil t t)))))
1475
1476 ;;; Return a pathname for the named file. The file must exist.
1477 (defun verify-source-file (pathname-designator)
1478   (let* ((pathname (pathname pathname-designator))
1479          (default-host (make-pathname :host (pathname-host pathname))))
1480     (flet ((try-with-type (path type error-p)
1481              (let ((new (merge-pathnames
1482                          path (make-pathname :type type
1483                                              :defaults default-host))))
1484                (if (probe-file new)
1485                    new
1486                    (and error-p (truename new))))))
1487       (cond ((typep pathname 'logical-pathname)
1488              (try-with-type pathname "LISP" t))
1489             ((probe-file pathname) pathname)
1490             ((try-with-type pathname "lisp"  nil))
1491             ((try-with-type pathname "lisp"  t))))))
1492
1493 (defun elapsed-time-to-string (tsec)
1494   (multiple-value-bind (tmin sec) (truncate tsec 60)
1495     (multiple-value-bind (thr min) (truncate tmin 60)
1496       (format nil "~D:~2,'0D:~2,'0D" thr min sec))))
1497
1498 ;;; Print some junk at the beginning and end of compilation.
1499 (defun start-error-output (source-info)
1500   (declare (type source-info source-info))
1501   (let ((file-info (source-info-file-info source-info)))
1502     (compiler-mumble "~&; compiling file ~S (written ~A):~%"
1503                      (namestring (file-info-name file-info))
1504                      (sb!int:format-universal-time nil
1505                                                    (file-info-write-date
1506                                                     file-info)
1507                                                    :style :government
1508                                                    :print-weekday nil
1509                                                    :print-timezone nil)))
1510   (values))
1511 (defun finish-error-output (source-info won)
1512   (declare (type source-info source-info))
1513   (compiler-mumble "~&; compilation ~:[aborted after~;finished in~] ~A~&"
1514                    won
1515                    (elapsed-time-to-string
1516                     (- (get-universal-time)
1517                        (source-info-start-time source-info))))
1518   (values))
1519
1520 ;;; Open some files and call SUB-COMPILE-FILE. If something unwinds
1521 ;;; out of the compile, then abort the writing of the output file, so
1522 ;;; that we don't overwrite it with known garbage.
1523 (defun sb!xc:compile-file
1524     (input-file
1525      &key
1526
1527      ;; ANSI options
1528      (output-file (cfp-output-file-default input-file))
1529      ;; FIXME: ANSI doesn't seem to say anything about
1530      ;; *COMPILE-VERBOSE* and *COMPILE-PRINT* being rebound by this
1531      ;; function..
1532      ((:verbose sb!xc:*compile-verbose*) sb!xc:*compile-verbose*)
1533      ((:print sb!xc:*compile-print*) sb!xc:*compile-print*)
1534      (external-format :default)
1535
1536      ;; extensions
1537      (trace-file nil) 
1538      ((:block-compile *block-compile-arg*) nil))
1539
1540   #!+sb-doc
1541   "Compile INPUT-FILE, producing a corresponding fasl file and returning
1542    its filename. Besides the ANSI &KEY arguments :OUTPUT-FILE, :VERBOSE,
1543    :PRINT, and :EXTERNAL-FORMAT,the following extensions are supported:
1544      :TRACE-FILE
1545         If given, internal data structures are dumped to the specified
1546         file, or if a value of T is given, to a file of *.trace type
1547         derived from the input file name.
1548    Also, as a workaround for vaguely-non-ANSI behavior, the :BLOCK-COMPILE
1549    argument is quasi-supported, to determine whether multiple
1550    functions are compiled together as a unit, resolving function
1551    references at compile time. NIL means that global function names
1552    are never resolved at compilation time. Currently NIL is the
1553    default behavior, because although section 3.2.2.3, \"Semantic
1554    Constraints\", of the ANSI spec allows this behavior under all
1555    circumstances, the compiler's runtime scales badly when it
1556    tries to do this for large files. If/when this performance
1557    problem is fixed, the block compilation default behavior will
1558    probably be made dependent on the SPEED and COMPILATION-SPEED
1559    optimization values, and the :BLOCK-COMPILE argument will probably
1560    become deprecated."
1561
1562   (unless (eq external-format :default)
1563     (error "Non-:DEFAULT EXTERNAL-FORMAT values are not supported."))
1564   (let* ((fasl-output nil)
1565          (output-file-name nil)
1566          (compile-won nil)
1567          (warnings-p nil)
1568          (failure-p t) ; T in case error keeps this from being set later
1569          (input-pathname (verify-source-file input-file))
1570          (source-info (make-file-source-info input-pathname))
1571          (*compiler-trace-output* nil)) ; might be modified below
1572
1573     (unwind-protect
1574         (progn
1575           (when output-file
1576             (setq output-file-name
1577                   (sb!xc:compile-file-pathname input-file
1578                                                :output-file output-file))
1579             (setq fasl-output
1580                   (open-fasl-output output-file-name
1581                                     (namestring input-pathname))))
1582           (when trace-file
1583             (let* ((default-trace-file-pathname
1584                      (make-pathname :type "trace" :defaults input-pathname))
1585                    (trace-file-pathname
1586                     (if (eql trace-file t)
1587                         default-trace-file-pathname
1588                         (merge-pathnames trace-file
1589                                          default-trace-file-pathname))))
1590               (setf *compiler-trace-output*
1591                     (open trace-file-pathname
1592                           :if-exists :supersede
1593                           :direction :output))))
1594
1595           (when sb!xc:*compile-verbose*
1596             (start-error-output source-info))
1597           (let ((*compile-object* fasl-output)
1598                 dummy)
1599             (multiple-value-setq (dummy warnings-p failure-p)
1600               (sub-compile-file source-info)))
1601           (setq compile-won t))
1602
1603       (close-source-info source-info)
1604
1605       (when fasl-output
1606         (close-fasl-output fasl-output (not compile-won))
1607         (setq output-file-name
1608               (pathname (fasl-output-stream fasl-output)))
1609         (when (and compile-won sb!xc:*compile-verbose*)
1610           (compiler-mumble "~2&; ~A written~%" (namestring output-file-name))))
1611
1612       (when sb!xc:*compile-verbose*
1613         (finish-error-output source-info compile-won))
1614
1615       (when *compiler-trace-output*
1616         (close *compiler-trace-output*)))
1617
1618     (values (if output-file
1619                 ;; Hack around filesystem race condition...
1620                 (or (probe-file output-file-name) output-file-name)
1621                 nil)
1622             warnings-p
1623             failure-p)))
1624 \f
1625 ;;; a helper function for COMPILE-FILE-PATHNAME: the default for
1626 ;;; the OUTPUT-FILE argument
1627 ;;;
1628 ;;; ANSI: The defaults for the OUTPUT-FILE are taken from the pathname
1629 ;;; that results from merging the INPUT-FILE with the value of
1630 ;;; *DEFAULT-PATHNAME-DEFAULTS*, except that the type component should
1631 ;;; default to the appropriate implementation-defined default type for
1632 ;;; compiled files.
1633 (defun cfp-output-file-default (input-file)
1634   (let* ((defaults (merge-pathnames input-file *default-pathname-defaults*))
1635          (retyped (make-pathname :type *fasl-file-type* :defaults defaults)))
1636     retyped))
1637         
1638 ;;; KLUDGE: Part of the ANSI spec for this seems contradictory:
1639 ;;;   If INPUT-FILE is a logical pathname and OUTPUT-FILE is unsupplied,
1640 ;;;   the result is a logical pathname. If INPUT-FILE is a logical
1641 ;;;   pathname, it is translated into a physical pathname as if by
1642 ;;;   calling TRANSLATE-LOGICAL-PATHNAME.
1643 ;;; So I haven't really tried to make this precisely ANSI-compatible
1644 ;;; at the level of e.g. whether it returns logical pathname or a
1645 ;;; physical pathname. Patches to make it more correct are welcome.
1646 ;;; -- WHN 2000-12-09
1647 (defun sb!xc:compile-file-pathname (input-file
1648                                     &key
1649                                     (output-file (cfp-output-file-default
1650                                                   input-file))
1651                                     &allow-other-keys)
1652   #!+sb-doc
1653   "Return a pathname describing what file COMPILE-FILE would write to given
1654    these arguments."
1655   (merge-pathnames output-file (merge-pathnames input-file)))
1656 \f
1657 ;;;; MAKE-LOAD-FORM stuff
1658
1659 ;;; The entry point for MAKE-LOAD-FORM support. When IR1 conversion
1660 ;;; finds a constant structure, it invokes this to arrange for proper
1661 ;;; dumping. If it turns out that the constant has already been
1662 ;;; dumped, then we don't need to do anything.
1663 ;;;
1664 ;;; If the constant hasn't been dumped, then we check to see whether
1665 ;;; we are in the process of creating it. We detect this by
1666 ;;; maintaining the special *CONSTANTS-BEING-CREATED* as a list of all
1667 ;;; the constants we are in the process of creating. Actually, each
1668 ;;; entry is a list of the constant and any init forms that need to be
1669 ;;; processed on behalf of that constant.
1670 ;;;
1671 ;;; It's not necessarily an error for this to happen. If we are
1672 ;;; processing the init form for some object that showed up *after*
1673 ;;; the original reference to this constant, then we just need to
1674 ;;; defer the processing of that init form. To detect this, we
1675 ;;; maintain *CONSTANTS-CREATED-SINCE-LAST-INIT* as a list of the
1676 ;;; constants created since the last time we started processing an
1677 ;;; init form. If the constant passed to emit-make-load-form shows up
1678 ;;; in this list, then there is a circular chain through creation
1679 ;;; forms, which is an error.
1680 ;;;
1681 ;;; If there is some intervening init form, then we blow out of
1682 ;;; processing it by throwing to the tag PENDING-INIT. The value we
1683 ;;; throw is the entry from *CONSTANTS-BEING-CREATED*. This is so the
1684 ;;; offending init form can be tacked onto the init forms for the
1685 ;;; circular object.
1686 ;;;
1687 ;;; If the constant doesn't show up in *CONSTANTS-BEING-CREATED*, then
1688 ;;; we have to create it. We call MAKE-LOAD-FORM and check to see
1689 ;;; whether the creation form is the magic value
1690 ;;; :SB-JUST-DUMP-IT-NORMALLY. If it is, then we don't do anything. The
1691 ;;; dumper will eventually get its hands on the object and use the
1692 ;;; normal structure dumping noise on it.
1693 ;;;
1694 ;;; Otherwise, we bind *CONSTANTS-BEING-CREATED* and
1695 ;;; *CONSTANTS-CREATED-SINCE- LAST-INIT* and compile the creation form
1696 ;;; much the way LOAD-TIME-VALUE does. When this finishes, we tell the
1697 ;;; dumper to use that result instead whenever it sees this constant.
1698 ;;;
1699 ;;; Now we try to compile the init form. We bind
1700 ;;; *CONSTANTS-CREATED-SINCE-LAST-INIT* to NIL and compile the init
1701 ;;; form (and any init forms that were added because of circularity
1702 ;;; detection). If this works, great. If not, we add the init forms to
1703 ;;; the init forms for the object that caused the problems and let it
1704 ;;; deal with it.
1705 (defvar *constants-being-created* nil)
1706 (defvar *constants-created-since-last-init* nil)
1707 ;;; FIXME: Shouldn't these^ variables be unbound outside LET forms?
1708 (defun emit-make-load-form (constant)
1709   (aver (fasl-output-p *compile-object*))
1710   (unless (or (fasl-constant-already-dumped-p constant *compile-object*)
1711               ;; KLUDGE: This special hack is because I was too lazy
1712               ;; to rework DEF!STRUCT so that the MAKE-LOAD-FORM
1713               ;; function of LAYOUT returns nontrivial forms when
1714               ;; building the cross-compiler but :IGNORE-IT when
1715               ;; cross-compiling or running under the target Lisp. --
1716               ;; WHN 19990914
1717               #+sb-xc-host (typep constant 'layout))
1718     (let ((circular-ref (assoc constant *constants-being-created* :test #'eq)))
1719       (when circular-ref
1720         (when (find constant *constants-created-since-last-init* :test #'eq)
1721           (throw constant t))
1722         (throw 'pending-init circular-ref)))
1723     (multiple-value-bind (creation-form init-form)
1724         (handler-case
1725             (sb!xc:make-load-form constant (make-null-lexenv))
1726           (error (condition)
1727             (compiler-error condition)))
1728       (case creation-form
1729         (:sb-just-dump-it-normally
1730          (fasl-validate-structure constant *compile-object*)
1731          t)
1732         (:ignore-it
1733          nil)
1734         (t
1735          (when (fasl-constant-already-dumped-p constant *compile-object*)
1736            (return-from emit-make-load-form nil))
1737          (let* ((name (let ((*print-level* 1) (*print-length* 2))
1738                         (with-output-to-string (stream)
1739                           (write constant :stream stream))))
1740                 (info (if init-form
1741                           (list constant name init-form)
1742                           (list constant))))
1743            (let ((*constants-being-created*
1744                   (cons info *constants-being-created*))
1745                  (*constants-created-since-last-init*
1746                   (cons constant *constants-created-since-last-init*)))
1747              (when
1748                  (catch constant
1749                    (fasl-note-handle-for-constant
1750                     constant
1751                     (compile-load-time-value
1752                      creation-form)
1753                     *compile-object*)
1754                    nil)
1755                (compiler-error "circular references in creation form for ~S"
1756                                constant)))
1757            (when (cdr info)
1758              (let* ((*constants-created-since-last-init* nil)
1759                     (circular-ref
1760                      (catch 'pending-init
1761                        (loop for (name form) on (cdr info) by #'cddr
1762                          collect name into names
1763                          collect form into forms
1764                          finally (compile-make-load-form-init-forms forms))
1765                        nil)))
1766                (when circular-ref
1767                  (setf (cdr circular-ref)
1768                        (append (cdr circular-ref) (cdr info))))))))))))
1769
1770 \f
1771 ;;;; Host compile time definitions
1772 #+sb-xc-host
1773 (defun compile-in-lexenv (name lambda lexenv)
1774   (declare (ignore lexenv))
1775   (compile name lambda))
1776
1777 #+sb-xc-host
1778 (defun eval-in-lexenv (form lexenv)
1779   (declare (ignore lexenv))
1780   (eval form))