0.pre7.114:
[sbcl.git] / src / compiler / ir1tran.lisp
1 ;;;; This file contains code which does the translation from Lisp code
2 ;;;; to the first intermediate representation (IR1).
3
4 ;;;; This software is part of the SBCL system. See the README file for
5 ;;;; more information.
6 ;;;;
7 ;;;; This software is derived from the CMU CL system, which was
8 ;;;; written at Carnegie Mellon University and released into the
9 ;;;; public domain. The software is in the public domain and is
10 ;;;; provided with absolutely no warranty. See the COPYING and CREDITS
11 ;;;; files for more information.
12
13 (in-package "SB!C")
14
15 (declaim (special *compiler-error-bailout*))
16
17 ;;; *SOURCE-PATHS* is a hashtable from source code forms to the path
18 ;;; taken through the source to reach the form. This provides a way to
19 ;;; keep track of the location of original source forms, even when
20 ;;; macroexpansions and other arbitary permutations of the code
21 ;;; happen. This table is initialized by calling FIND-SOURCE-PATHS on
22 ;;; the original source.
23 (declaim (hash-table *source-paths*))
24 (defvar *source-paths*)
25
26 ;;; *CURRENT-COMPONENT* is the COMPONENT structure which we link
27 ;;; blocks into as we generate them. This just serves to glue the
28 ;;; emitted blocks together until local call analysis and flow graph
29 ;;; canonicalization figure out what is really going on. We need to
30 ;;; keep track of all the blocks generated so that we can delete them
31 ;;; if they turn out to be unreachable.
32 ;;;
33 ;;; FIXME: It's confusing having one variable named *CURRENT-COMPONENT*
34 ;;; and another named *COMPONENT-BEING-COMPILED*. (In CMU CL they
35 ;;; were called *CURRENT-COMPONENT* and *COMPILE-COMPONENT* respectively,
36 ;;; which also confusing.)
37 (declaim (type (or component null) *current-component*))
38 (defvar *current-component*)
39
40 ;;; *CURRENT-PATH* is the source path of the form we are currently
41 ;;; translating. See NODE-SOURCE-PATH in the NODE structure.
42 (declaim (list *current-path*))
43 (defvar *current-path*)
44
45 (defvar *derive-function-types* nil
46   "Should the compiler assume that function types will never change,
47   so that it can use type information inferred from current definitions
48   to optimize code which uses those definitions? Setting this true
49   gives non-ANSI, early-CMU-CL behavior. It can be useful for improving
50   the efficiency of stable code.")
51 \f
52 ;;;; namespace management utilities
53
54 ;;; Return a GLOBAL-VAR structure usable for referencing the global
55 ;;; function NAME.
56 (defun find-free-really-function (name)
57   (unless (info :function :kind name)
58     (setf (info :function :kind name) :function)
59     (setf (info :function :where-from name) :assumed))
60
61   (let ((where (info :function :where-from name)))
62     (when (and (eq where :assumed)
63                ;; In the ordinary target Lisp, it's silly to report
64                ;; undefinedness when the function is defined in the
65                ;; running Lisp. But at cross-compile time, the current
66                ;; definedness of a function is irrelevant to the
67                ;; definedness at runtime, which is what matters.
68                #-sb-xc-host (not (fboundp name)))
69       (note-undefined-reference name :function))
70     (make-global-var :kind :global-function
71                      :%source-name name
72                      :type (if (or *derive-function-types*
73                                    (eq where :declared))
74                                (info :function :type name)
75                                (specifier-type 'function))
76                      :where-from where)))
77
78 ;;; Return a SLOT-ACCESSOR structure usable for referencing the slot
79 ;;; accessor NAME. CLASS is the structure class.
80 (defun find-structure-slot-accessor (class name)
81   (declare (type sb!xc:class class))
82   (let* ((info (layout-info
83                 (or (info :type :compiler-layout (sb!xc:class-name class))
84                     (class-layout class))))
85          (accessor-name (if (listp name) (cadr name) name))
86          (slot (find accessor-name (dd-slots info)
87                      :key #'sb!kernel:dsd-accessor-name))
88          (type (dd-name info))
89          (slot-type (dsd-type slot)))
90     (unless slot
91       (error "can't find slot ~S" type))
92     (make-slot-accessor
93      :%source-name name
94      :type (specifier-type
95             (if (listp name)
96                 `(function (,slot-type ,type) ,slot-type)
97                 `(function (,type) ,slot-type)))
98      :for class
99      :slot slot)))
100
101 ;;; If NAME is already entered in *FREE-FUNCTIONS*, then return the
102 ;;; value. Otherwise, make a new GLOBAL-VAR using information from the
103 ;;; global environment and enter it in *FREE-FUNCTIONS*. If NAME names
104 ;;; a macro or special form, then we error out using the supplied
105 ;;; context which indicates what we were trying to do that demanded a
106 ;;; function.
107 (defun find-free-function (name context)
108   (declare (string context))
109   (declare (values global-var))
110   (or (gethash name *free-functions*)
111       (ecase (info :function :kind name)
112         ;; FIXME: The :MACRO and :SPECIAL-FORM cases could be merged.
113         (:macro
114          (compiler-error "The macro name ~S was found ~A." name context))
115         (:special-form
116          (compiler-error "The special form name ~S was found ~A."
117                          name
118                          context))
119         ((:function nil)
120          (check-fun-name name)
121          (note-if-setf-function-and-macro name)
122          (let ((expansion (fun-name-inline-expansion name))
123                (inlinep (info :function :inlinep name)))
124            (setf (gethash name *free-functions*)
125                  (if (or expansion inlinep)
126                      (make-defined-fun
127                       :%source-name name
128                       :inline-expansion expansion
129                       :inlinep inlinep
130                       :where-from (info :function :where-from name)
131                       :type (info :function :type name))
132                      (find-free-really-function name))))))))
133
134 ;;; Return the LEAF structure for the lexically apparent function
135 ;;; definition of NAME.
136 (declaim (ftype (function (t string) leaf) find-lexically-apparent-function))
137 (defun find-lexically-apparent-function (name context)
138   (let ((var (lexenv-find name functions :test #'equal)))
139     (cond (var
140            (unless (leaf-p var)
141              (aver (and (consp var) (eq (car var) 'macro)))
142              (compiler-error "found macro name ~S ~A" name context))
143            var)
144           (t
145            (find-free-function name context)))))
146
147 ;;; Return the LEAF node for a global variable reference to NAME. If
148 ;;; NAME is already entered in *FREE-VARIABLES*, then we just return
149 ;;; the corresponding value. Otherwise, we make a new leaf using
150 ;;; information from the global environment and enter it in
151 ;;; *FREE-VARIABLES*. If the variable is unknown, then we emit a
152 ;;; warning.
153 (defun find-free-variable (name)
154   (declare (values (or leaf heap-alien-info)))
155   (unless (symbolp name)
156     (compiler-error "Variable name is not a symbol: ~S." name))
157   (or (gethash name *free-variables*)
158       (let ((kind (info :variable :kind name))
159             (type (info :variable :type name))
160             (where-from (info :variable :where-from name)))
161         (when (and (eq where-from :assumed) (eq kind :global))
162           (note-undefined-reference name :variable))
163         (setf (gethash name *free-variables*)
164               (case kind
165                 (:alien
166                  (info :variable :alien-info name))
167                 (:constant
168                  (let ((value (info :variable :constant-value name)))
169                    (make-constant :value value
170                                   :%source-name name
171                                   :type (ctype-of value)
172                                   :where-from where-from)))
173                 (t
174                  (make-global-var :kind kind
175                                   :%source-name name
176                                   :type type
177                                   :where-from where-from)))))))
178 \f
179 ;;; Grovel over CONSTANT checking for any sub-parts that need to be
180 ;;; processed with MAKE-LOAD-FORM. We have to be careful, because
181 ;;; CONSTANT might be circular. We also check that the constant (and
182 ;;; any subparts) are dumpable at all.
183 (eval-when (:compile-toplevel :load-toplevel :execute)
184   ;; The EVAL-WHEN is necessary for #.(1+ LIST-TO-HASH-TABLE-THRESHOLD) 
185   ;; below. -- AL 20010227
186   (defconstant list-to-hash-table-threshold 32))
187 (defun maybe-emit-make-load-forms (constant)
188   (let ((things-processed nil)
189         (count 0))
190     ;; FIXME: Does this LIST-or-HASH-TABLE messiness give much benefit?
191     (declare (type (or list hash-table) things-processed)
192              (type (integer 0 #.(1+ list-to-hash-table-threshold)) count)
193              (inline member))
194     (labels ((grovel (value)
195                ;; Unless VALUE is an object which which obviously
196                ;; can't contain other objects
197                (unless (typep value
198                               '(or #-sb-xc-host unboxed-array
199                                    symbol
200                                    number
201                                    character
202                                    string))
203                  (etypecase things-processed
204                    (list
205                     (when (member value things-processed :test #'eq)
206                       (return-from grovel nil))
207                     (push value things-processed)
208                     (incf count)
209                     (when (> count list-to-hash-table-threshold)
210                       (let ((things things-processed))
211                         (setf things-processed
212                               (make-hash-table :test 'eq))
213                         (dolist (thing things)
214                           (setf (gethash thing things-processed) t)))))
215                    (hash-table
216                     (when (gethash value things-processed)
217                       (return-from grovel nil))
218                     (setf (gethash value things-processed) t)))
219                  (typecase value
220                    (cons
221                     (grovel (car value))
222                     (grovel (cdr value)))
223                    (simple-vector
224                     (dotimes (i (length value))
225                       (grovel (svref value i))))
226                    ((vector t)
227                     (dotimes (i (length value))
228                       (grovel (aref value i))))
229                    ((simple-array t)
230                     ;; Even though the (ARRAY T) branch does the exact
231                     ;; same thing as this branch we do this separately
232                     ;; so that the compiler can use faster versions of
233                     ;; array-total-size and row-major-aref.
234                     (dotimes (i (array-total-size value))
235                       (grovel (row-major-aref value i))))
236                    ((array t)
237                     (dotimes (i (array-total-size value))
238                       (grovel (row-major-aref value i))))
239                    (;; In the target SBCL, we can dump any instance,
240                     ;; but in the cross-compilation host,
241                     ;; %INSTANCE-FOO functions don't work on general
242                     ;; instances, only on STRUCTURE!OBJECTs.
243                     #+sb-xc-host structure!object
244                     #-sb-xc-host instance
245                     (when (emit-make-load-form value)
246                       (dotimes (i (%instance-length value))
247                         (grovel (%instance-ref value i)))))
248                    (t
249                     (compiler-error
250                      "Objects of type ~S can't be dumped into fasl files."
251                      (type-of value)))))))
252       (grovel constant)))
253   (values))
254 \f
255 ;;;; some flow-graph hacking utilities
256
257 ;;; This function sets up the back link between the node and the
258 ;;; continuation which continues at it.
259 (defun link-node-to-previous-continuation (node cont)
260   (declare (type node node) (type continuation cont))
261   (aver (not (continuation-next cont)))
262   (setf (continuation-next cont) node)
263   (setf (node-prev node) cont))
264
265 ;;; This function is used to set the continuation for a node, and thus
266 ;;; determine what receives the value and what is evaluated next. If
267 ;;; the continuation has no block, then we make it be in the block
268 ;;; that the node is in. If the continuation heads its block, we end
269 ;;; our block and link it to that block. If the continuation is not
270 ;;; currently used, then we set the DERIVED-TYPE for the continuation
271 ;;; to that of the node, so that a little type propagation gets done.
272 ;;;
273 ;;; We also deal with a bit of THE's semantics here: we weaken the
274 ;;; assertion on CONT to be no stronger than the assertion on CONT in
275 ;;; our scope. See the IR1-CONVERT method for THE.
276 #!-sb-fluid (declaim (inline use-continuation))
277 (defun use-continuation (node cont)
278   (declare (type node node) (type continuation cont))
279   (let ((node-block (continuation-block (node-prev node))))
280     (case (continuation-kind cont)
281       (:unused
282        (setf (continuation-block cont) node-block)
283        (setf (continuation-kind cont) :inside-block)
284        (setf (continuation-use cont) node)
285        (setf (node-cont node) cont))
286       (t
287        (%use-continuation node cont)))))
288 (defun %use-continuation (node cont)
289   (declare (type node node) (type continuation cont) (inline member))
290   (let ((block (continuation-block cont))
291         (node-block (continuation-block (node-prev node))))
292     (aver (eq (continuation-kind cont) :block-start))
293     (when (block-last node-block)
294       (error "~S has already ended." node-block))
295     (setf (block-last node-block) node)
296     (when (block-succ node-block)
297       (error "~S already has successors." node-block))
298     (setf (block-succ node-block) (list block))
299     (when (memq node-block (block-pred block))
300       (error "~S is already a predecessor of ~S." node-block block))
301     (push node-block (block-pred block))
302     (add-continuation-use node cont)
303     (unless (eq (continuation-asserted-type cont) *wild-type*)
304       (let ((new (values-type-union (continuation-asserted-type cont)
305                                     (or (lexenv-find cont type-restrictions)
306                                         *wild-type*))))
307         (when (type/= new (continuation-asserted-type cont))
308           (setf (continuation-asserted-type cont) new)
309           (reoptimize-continuation cont))))))
310 \f
311 ;;;; exported functions
312
313 ;;; This function takes a form and the top level form number for that
314 ;;; form, and returns a lambda representing the translation of that
315 ;;; form in the current global environment. The returned lambda is a
316 ;;; top level lambda that can be called to cause evaluation of the
317 ;;; forms. This lambda is in the initial component. If FOR-VALUE is T,
318 ;;; then the value of the form is returned from the function,
319 ;;; otherwise NIL is returned.
320 ;;;
321 ;;; This function may have arbitrary effects on the global environment
322 ;;; due to processing of EVAL-WHENs. All syntax error checking is
323 ;;; done, with erroneous forms being replaced by a proxy which signals
324 ;;; an error if it is evaluated. Warnings about possibly inconsistent
325 ;;; or illegal changes to the global environment will also be given.
326 ;;;
327 ;;; We make the initial component and convert the form in a PROGN (and
328 ;;; an optional NIL tacked on the end.) We then return the lambda. We
329 ;;; bind all of our state variables here, rather than relying on the
330 ;;; global value (if any) so that IR1 conversion will be reentrant.
331 ;;; This is necessary for EVAL-WHEN processing, etc.
332 ;;;
333 ;;; The hashtables used to hold global namespace info must be
334 ;;; reallocated elsewhere. Note also that *LEXENV* is not bound, so
335 ;;; that local macro definitions can be introduced by enclosing code.
336 (defun ir1-toplevel (form path for-value)
337   (declare (list path))
338   (let* ((*current-path* path)
339          (component (make-empty-component))
340          (*current-component* component))
341     (setf (component-name component) "initial component")
342     (setf (component-kind component) :initial)
343     (let* ((forms (if for-value `(,form) `(,form nil)))
344            (res (ir1-convert-lambda-body
345                  forms ()
346                  :debug-name (debug-namify "top level form ~S" form))))
347       (setf (functional-entry-fun res) res
348             (functional-arg-documentation res) ()
349             (functional-kind res) :toplevel)
350       res)))
351
352 ;;; *CURRENT-FORM-NUMBER* is used in FIND-SOURCE-PATHS to compute the
353 ;;; form number to associate with a source path. This should be bound
354 ;;; to an initial value of 0 before the processing of each truly
355 ;;; top level form.
356 (declaim (type index *current-form-number*))
357 (defvar *current-form-number*)
358
359 ;;; This function is called on freshly read forms to record the
360 ;;; initial location of each form (and subform.) Form is the form to
361 ;;; find the paths in, and TLF-NUM is the top level form number of the
362 ;;; truly top level form.
363 ;;;
364 ;;; This gets a bit interesting when the source code is circular. This
365 ;;; can (reasonably?) happen in the case of circular list constants.
366 (defun find-source-paths (form tlf-num)
367   (declare (type index tlf-num))
368   (let ((*current-form-number* 0))
369     (sub-find-source-paths form (list tlf-num)))
370   (values))
371 (defun sub-find-source-paths (form path)
372   (unless (gethash form *source-paths*)
373     (setf (gethash form *source-paths*)
374           (list* 'original-source-start *current-form-number* path))
375     (incf *current-form-number*)
376     (let ((pos 0)
377           (subform form)
378           (trail form))
379       (declare (fixnum pos))
380       (macrolet ((frob ()
381                    '(progn
382                       (when (atom subform) (return))
383                       (let ((fm (car subform)))
384                         (when (consp fm)
385                           (sub-find-source-paths fm (cons pos path)))
386                         (incf pos))
387                       (setq subform (cdr subform))
388                       (when (eq subform trail) (return)))))
389         (loop
390           (frob)
391           (frob)
392           (setq trail (cdr trail)))))))
393 \f
394 ;;;; IR1-CONVERT, macroexpansion and special form dispatching
395
396 (macrolet (;; Bind *COMPILER-ERROR-BAILOUT* to a function that throws
397            ;; out of the body and converts a proxy form instead.
398            (ir1-error-bailout ((start
399                                 cont
400                                 form
401                                 &optional
402                                 (proxy ``(error "execution of a form compiled with errors:~% ~S"
403                                                 ',,form)))
404                                &body body)
405                               (let ((skip (gensym "SKIP")))
406                                 `(block ,skip
407                                    (catch 'ir1-error-abort
408                                      (let ((*compiler-error-bailout*
409                                             (lambda ()
410                                               (throw 'ir1-error-abort nil))))
411                                        ,@body
412                                        (return-from ,skip nil)))
413                                    (ir1-convert ,start ,cont ,proxy)))))
414
415   ;; Translate FORM into IR1. The code is inserted as the NEXT of the
416   ;; continuation START. CONT is the continuation which receives the
417   ;; value of the FORM to be translated. The translators call this
418   ;; function recursively to translate their subnodes.
419   ;;
420   ;; As a special hack to make life easier in the compiler, a LEAF
421   ;; IR1-converts into a reference to that LEAF structure. This allows
422   ;; the creation using backquote of forms that contain leaf
423   ;; references, without having to introduce dummy names into the
424   ;; namespace.
425   (declaim (ftype (function (continuation continuation t) (values)) ir1-convert))
426   (defun ir1-convert (start cont form)
427     (ir1-error-bailout (start cont form)
428       (let ((*current-path* (or (gethash form *source-paths*)
429                                 (cons form *current-path*))))
430         (if (atom form)
431             (cond ((and (symbolp form) (not (keywordp form)))
432                    (ir1-convert-variable start cont form))
433                   ((leaf-p form)
434                    (reference-leaf start cont form))
435                   (t
436                    (reference-constant start cont form)))
437             (let ((opname (car form)))
438               (cond ((symbolp opname)
439                      (let ((lexical-def (lexenv-find opname functions)))
440                        (typecase lexical-def
441                          (null (ir1-convert-global-functoid start cont form))
442                          (functional
443                           (ir1-convert-local-combination start
444                                                          cont
445                                                          form
446                                                          lexical-def))
447                          (global-var
448                           (ir1-convert-srctran start cont lexical-def form))
449                          (t
450                           (aver (and (consp lexical-def)
451                                      (eq (car lexical-def) 'macro)))
452                           (ir1-convert start cont
453                                        (careful-expand-macro (cdr lexical-def)
454                                                              form))))))
455                     ((or (atom opname) (not (eq (car opname) 'lambda)))
456                      (compiler-error "illegal function call"))
457                     (t
458                      ;; implicitly #'(LAMBDA ..) because the LAMBDA
459                      ;; expression is the CAR of an executed form
460                      (ir1-convert-combination start
461                                               cont
462                                               form
463                                               (ir1-convert-lambda
464                                                opname
465                                                :debug-name (debug-namify
466                                                             "LAMBDA CAR ~S"
467                                                             opname)))))))))
468     (values))
469
470   ;; Generate a reference to a manifest constant, creating a new leaf
471   ;; if necessary. If we are producing a fasl file, make sure that
472   ;; MAKE-LOAD-FORM gets used on any parts of the constant that it
473   ;; needs to be.
474   (defun reference-constant (start cont value)
475     (declare (type continuation start cont)
476              (inline find-constant))
477     (ir1-error-bailout
478      (start cont value '(error "attempt to reference undumpable constant"))
479      (when (producing-fasl-file)
480        (maybe-emit-make-load-forms value))
481      (let* ((leaf (find-constant value))
482             (res (make-ref (leaf-type leaf) leaf)))
483        (push res (leaf-refs leaf))
484        (link-node-to-previous-continuation res start)
485        (use-continuation res cont)))
486     (values)))
487
488 ;;; Add FUN to the COMPONENT-REANALYZE-FUNS. FUN is returned.
489 (defun maybe-reanalyze-fun (fun)
490   (declare (type functional fun))
491   (when (typep fun '(or optional-dispatch clambda))
492     (pushnew fun (component-reanalyze-funs *current-component*)))
493   fun)
494
495 ;;; Generate a REF node for LEAF, frobbing the LEAF structure as
496 ;;; needed. If LEAF represents a defined function which has already
497 ;;; been converted, and is not :NOTINLINE, then reference the
498 ;;; functional instead.
499 (defun reference-leaf (start cont leaf)
500   (declare (type continuation start cont) (type leaf leaf))
501   (let* ((leaf (or (and (defined-fun-p leaf)
502                         (not (eq (defined-fun-inlinep leaf)
503                                  :notinline))
504                         (let ((fun (defined-fun-functional leaf)))
505                           (when (and fun (not (functional-kind fun)))
506                             (maybe-reanalyze-fun fun))))
507                    leaf))
508          (res (make-ref (or (lexenv-find leaf type-restrictions)
509                             (leaf-type leaf))
510                         leaf)))
511     (push res (leaf-refs leaf))
512     (setf (leaf-ever-used leaf) t)
513     (link-node-to-previous-continuation res start)
514     (use-continuation res cont)))
515
516 ;;; Convert a reference to a symbolic constant or variable. If the
517 ;;; symbol is entered in the LEXENV-VARIABLES we use that definition,
518 ;;; otherwise we find the current global definition. This is also
519 ;;; where we pick off symbol macro and alien variable references.
520 (defun ir1-convert-variable (start cont name)
521   (declare (type continuation start cont) (symbol name))
522   (let ((var (or (lexenv-find name variables) (find-free-variable name))))
523     (etypecase var
524       (leaf
525        (when (lambda-var-p var)
526          (let ((home (continuation-home-lambda-or-null start)))
527            (when home
528              (pushnew var (lambda-calls-or-closes home))))
529          (when (lambda-var-ignorep var)
530            ;; (ANSI's specification for the IGNORE declaration requires
531            ;; that this be a STYLE-WARNING, not a full WARNING.)
532            (compiler-style-warning "reading an ignored variable: ~S" name)))
533        (reference-leaf start cont var))
534       (cons
535        (aver (eq (car var) 'MACRO))
536        (ir1-convert start cont (cdr var)))
537       (heap-alien-info
538        (ir1-convert start cont `(%heap-alien ',var)))))
539   (values))
540
541 ;;; Convert anything that looks like a special form, global function
542 ;;; or macro call.
543 (defun ir1-convert-global-functoid (start cont form)
544   (declare (type continuation start cont) (list form))
545   (let* ((fun (first form))
546          (translator (info :function :ir1-convert fun))
547          (cmacro (info :function :compiler-macro-function fun)))
548     (cond (translator (funcall translator start cont form))
549           ((and cmacro
550                 (not (eq (info :function :inlinep fun)
551                          :notinline)))
552            (let ((res (careful-expand-macro cmacro form)))
553              (if (eq res form)
554                  (ir1-convert-global-functoid-no-cmacro start cont form fun)
555                  (ir1-convert start cont res))))
556           (t
557            (ir1-convert-global-functoid-no-cmacro start cont form fun)))))
558
559 ;;; Handle the case of where the call was not a compiler macro, or was
560 ;;; a compiler macro and passed.
561 (defun ir1-convert-global-functoid-no-cmacro (start cont form fun)
562   (declare (type continuation start cont) (list form))
563   ;; FIXME: Couldn't all the INFO calls here be converted into
564   ;; standard CL functions, like MACRO-FUNCTION or something?
565   ;; And what happens with lexically-defined (MACROLET) macros
566   ;; here, anyway?
567   (ecase (info :function :kind fun)
568     (:macro
569      (ir1-convert start
570                   cont
571                   (careful-expand-macro (info :function :macro-function fun)
572                                         form)))
573     ((nil :function)
574      (ir1-convert-srctran start
575                           cont
576                           (find-free-function fun
577                                               "shouldn't happen! (no-cmacro)")
578                           form))))
579
580 (defun muffle-warning-or-die ()
581   (muffle-warning)
582   (error "internal error -- no MUFFLE-WARNING restart"))
583
584 ;;; Expand FORM using the macro whose MACRO-FUNCTION is FUN, trapping
585 ;;; errors which occur during the macroexpansion.
586 (defun careful-expand-macro (fun form)
587   (let (;; a hint I (WHN) wish I'd known earlier
588         (hint "(hint: For more precise location, try *BREAK-ON-SIGNALS*.)"))
589     (flet (;; Return a string to use as a prefix in error reporting,
590            ;; telling something about which form caused the problem.
591            (wherestring ()
592              (let ((*print-pretty* nil)
593                    ;; We rely on the printer to abbreviate FORM. 
594                    (*print-length* 3)
595                    (*print-level* 1))
596                (format
597                 nil
598                 #-sb-xc-host "(in macroexpansion of ~S)"
599                 ;; longer message to avoid ambiguity "Was it the xc host
600                 ;; or the cross-compiler which encountered the problem?"
601                 #+sb-xc-host "(in cross-compiler macroexpansion of ~S)"
602                 form))))
603       (handler-bind (;; When cross-compiling, we can get style warnings
604                      ;; about e.g. undefined functions. An unhandled
605                      ;; CL:STYLE-WARNING (as opposed to a
606                      ;; SB!C::COMPILER-NOTE) would cause FAILURE-P to be
607                      ;; set on the return from #'SB!XC:COMPILE-FILE, which
608                      ;; would falsely indicate an error sufficiently
609                      ;; serious that we should stop the build process. To
610                      ;; avoid this, we translate CL:STYLE-WARNING
611                      ;; conditions from the host Common Lisp into
612                      ;; cross-compiler SB!C::COMPILER-NOTE calls. (It
613                      ;; might be cleaner to just make Python use
614                      ;; CL:STYLE-WARNING internally, so that the
615                      ;; significance of any host Common Lisp
616                      ;; CL:STYLE-WARNINGs is understood automatically. But
617                      ;; for now I'm not motivated to do this. -- WHN
618                      ;; 19990412)
619                      (style-warning (lambda (c)
620                                       (compiler-note "~@<~A~:@_~A~:@_~A~:>"
621                                                      (wherestring) hint c)
622                                       (muffle-warning-or-die)))
623                      ;; KLUDGE: CMU CL in its wisdom (version 2.4.6 for
624                      ;; Debian Linux, anyway) raises a CL:WARNING
625                      ;; condition (not a CL:STYLE-WARNING) for undefined
626                      ;; symbols when converting interpreted functions,
627                      ;; causing COMPILE-FILE to think the file has a real
628                      ;; problem, causing COMPILE-FILE to return FAILURE-P
629                      ;; set (not just WARNINGS-P set). Since undefined
630                      ;; symbol warnings are often harmless forward
631                      ;; references, and since it'd be inordinately painful
632                      ;; to try to eliminate all such forward references,
633                      ;; these warnings are basically unavoidable. Thus, we
634                      ;; need to coerce the system to work through them,
635                      ;; and this code does so, by crudely suppressing all
636                      ;; warnings in cross-compilation macroexpansion. --
637                      ;; WHN 19990412
638                      #+cmu
639                      (warning (lambda (c)
640                                 (compiler-note
641                                  "~@<~A~:@_~
642                                   ~A~:@_~
643                                   ~@<(KLUDGE: That was a non-STYLE WARNING. ~
644                                   Ordinarily that would cause compilation to ~
645                                   fail. However, since we're running under ~
646                                   CMU CL, and since CMU CL emits non-STYLE ~
647                                   warnings for safe, hard-to-fix things (e.g. ~
648                                   references to not-yet-defined functions) ~
649                                   we're going to have to ignore it and ~
650                                   proceed anyway. Hopefully we're not ~
651                                   ignoring anything  horrible here..)~:@>~:>"
652                                  (wherestring)
653                                  c)
654                                 (muffle-warning-or-die)))
655                      (error (lambda (c)
656                               (compiler-error "~@<~A~:@_~A~@:_~A~:>"
657                                               (wherestring) hint c))))
658         (funcall sb!xc:*macroexpand-hook* fun form *lexenv*)))))
659 \f
660 ;;;; conversion utilities
661
662 ;;; Convert a bunch of forms, discarding all the values except the
663 ;;; last. If there aren't any forms, then translate a NIL.
664 (declaim (ftype (function (continuation continuation list) (values))
665                 ir1-convert-progn-body))
666 (defun ir1-convert-progn-body (start cont body)
667   (if (endp body)
668       (reference-constant start cont nil)
669       (let ((this-start start)
670             (forms body))
671         (loop
672           (let ((form (car forms)))
673             (when (endp (cdr forms))
674               (ir1-convert this-start cont form)
675               (return))
676             (let ((this-cont (make-continuation)))
677               (ir1-convert this-start this-cont form)
678               (setq this-start this-cont
679                     forms (cdr forms)))))))
680   (values))
681 \f
682 ;;;; converting combinations
683
684 ;;; Convert a function call where the function (i.e. the FUN argument)
685 ;;; is a LEAF. We return the COMBINATION node so that the caller can
686 ;;; poke at it if it wants to.
687 (declaim (ftype (function (continuation continuation list leaf) combination)
688                 ir1-convert-combination))
689 (defun ir1-convert-combination (start cont form fun)
690   (let ((fun-cont (make-continuation)))
691     (reference-leaf start fun-cont fun)
692     (ir1-convert-combination-args fun-cont cont (cdr form))))
693
694 ;;; Convert the arguments to a call and make the COMBINATION node.
695 ;;; FUN-CONT is the continuation which yields the function to call.
696 ;;; FORM is the source for the call. ARGS is the list of arguments for
697 ;;; the call, which defaults to the cdr of source. We return the
698 ;;; COMBINATION node.
699 (defun ir1-convert-combination-args (fun-cont cont args)
700   (declare (type continuation fun-cont cont) (list args))
701   (let ((node (make-combination fun-cont)))
702     (setf (continuation-dest fun-cont) node)
703     (assert-continuation-type fun-cont
704                               (specifier-type '(or function symbol)))
705     (collect ((arg-conts))
706       (let ((this-start fun-cont))
707         (dolist (arg args)
708           (let ((this-cont (make-continuation node)))
709             (ir1-convert this-start this-cont arg)
710             (setq this-start this-cont)
711             (arg-conts this-cont)))
712         (link-node-to-previous-continuation node this-start)
713         (use-continuation node cont)
714         (setf (combination-args node) (arg-conts))))
715     node))
716
717 ;;; Convert a call to a global function. If not :NOTINLINE, then we do
718 ;;; source transforms and try out any inline expansion. If there is no
719 ;;; expansion, but is :INLINE, then give an efficiency note (unless a
720 ;;; known function which will quite possibly be open-coded.) Next, we
721 ;;; go to ok-combination conversion.
722 (defun ir1-convert-srctran (start cont var form)
723   (declare (type continuation start cont) (type global-var var))
724   (let ((inlinep (when (defined-fun-p var)
725                    (defined-fun-inlinep var))))
726     (if (eq inlinep :notinline)
727         (ir1-convert-combination start cont form var)
728         (let ((transform (info :function
729                                :source-transform
730                                (leaf-source-name var))))
731           (if transform
732               (multiple-value-bind (result pass) (funcall transform form)
733                 (if pass
734                     (ir1-convert-maybe-predicate start cont form var)
735                     (ir1-convert start cont result)))
736               (ir1-convert-maybe-predicate start cont form var))))))
737
738 ;;; If the function has the PREDICATE attribute, and the CONT's DEST
739 ;;; isn't an IF, then we convert (IF <form> T NIL), ensuring that a
740 ;;; predicate always appears in a conditional context.
741 ;;;
742 ;;; If the function isn't a predicate, then we call
743 ;;; IR1-CONVERT-COMBINATION-CHECKING-TYPE.
744 (defun ir1-convert-maybe-predicate (start cont form var)
745   (declare (type continuation start cont) (list form) (type global-var var))
746   (let ((info (info :function :info (leaf-source-name var))))
747     (if (and info
748              (ir1-attributep (function-info-attributes info) predicate)
749              (not (if-p (continuation-dest cont))))
750         (ir1-convert start cont `(if ,form t nil))
751         (ir1-convert-combination-checking-type start cont form var))))
752
753 ;;; Actually really convert a global function call that we are allowed
754 ;;; to early-bind.
755 ;;;
756 ;;; If we know the function type of the function, then we check the
757 ;;; call for syntactic legality with respect to the declared function
758 ;;; type. If it is impossible to determine whether the call is correct
759 ;;; due to non-constant keywords, then we give up, marking the call as
760 ;;; :FULL to inhibit further error messages. We return true when the
761 ;;; call is legal.
762 ;;;
763 ;;; If the call is legal, we also propagate type assertions from the
764 ;;; function type to the arg and result continuations. We do this now
765 ;;; so that IR1 optimize doesn't have to redundantly do the check
766 ;;; later so that it can do the type propagation.
767 (defun ir1-convert-combination-checking-type (start cont form var)
768   (declare (type continuation start cont) (list form) (type leaf var))
769   (let* ((node (ir1-convert-combination start cont form var))
770          (fun-cont (basic-combination-fun node))
771          (type (leaf-type var)))
772     (when (validate-call-type node type t)
773       (setf (continuation-%derived-type fun-cont) type)
774       (setf (continuation-reoptimize fun-cont) nil)
775       (setf (continuation-%type-check fun-cont) nil)))
776   (values))
777
778 ;;; Convert a call to a local function. If the function has already
779 ;;; been LET converted, then throw FUN to LOCAL-CALL-LOSSAGE. This
780 ;;; should only happen when we are converting inline expansions for
781 ;;; local functions during optimization.
782 (defun ir1-convert-local-combination (start cont form fun)
783   (if (functional-kind fun)
784       (throw 'local-call-lossage fun)
785       (ir1-convert-combination start cont form
786                                (maybe-reanalyze-fun fun))))
787 \f
788 ;;;; PROCESS-DECLS
789
790 ;;; Given a list of LAMBDA-VARs and a variable name, return the
791 ;;; LAMBDA-VAR for that name, or NIL if it isn't found. We return the
792 ;;; *last* variable with that name, since LET* bindings may be
793 ;;; duplicated, and declarations always apply to the last.
794 (declaim (ftype (function (list symbol) (or lambda-var list))
795                 find-in-bindings))
796 (defun find-in-bindings (vars name)
797   (let ((found nil))
798     (dolist (var vars)
799       (cond ((leaf-p var)
800              (when (eq (leaf-source-name var) name)
801                (setq found var))
802              (let ((info (lambda-var-arg-info var)))
803                (when info
804                  (let ((supplied-p (arg-info-supplied-p info)))
805                    (when (and supplied-p
806                               (eq (leaf-source-name supplied-p) name))
807                      (setq found supplied-p))))))
808             ((and (consp var) (eq (car var) name))
809              (setf found (cdr var)))))
810     found))
811
812 ;;; Called by Process-Decls to deal with a variable type declaration.
813 ;;; If a lambda-var being bound, we intersect the type with the vars
814 ;;; type, otherwise we add a type-restriction on the var. If a symbol
815 ;;; macro, we just wrap a THE around the expansion.
816 (defun process-type-decl (decl res vars)
817   (declare (list decl vars) (type lexenv res))
818   (let ((type (specifier-type (first decl))))
819     (collect ((restr nil cons)
820               (new-vars nil cons))
821       (dolist (var-name (rest decl))
822         (let* ((bound-var (find-in-bindings vars var-name))
823                (var (or bound-var
824                         (lexenv-find var-name variables)
825                         (find-free-variable var-name))))
826           (etypecase var
827             (leaf
828              (let* ((old-type (or (lexenv-find var type-restrictions)
829                                   (leaf-type var)))
830                     (int (if (or (fun-type-p type)
831                                  (fun-type-p old-type))
832                              type
833                              (type-approx-intersection2 old-type type))))
834                (cond ((eq int *empty-type*)
835                       (unless (policy *lexenv* (= inhibit-warnings 3))
836                         (compiler-warning
837                          "The type declarations ~S and ~S for ~S conflict."
838                          (type-specifier old-type) (type-specifier type)
839                          var-name)))
840                      (bound-var (setf (leaf-type bound-var) int))
841                      (t
842                       (restr (cons var int))))))
843             (cons
844              ;; FIXME: non-ANSI weirdness
845              (aver (eq (car var) 'MACRO))
846              (new-vars `(,var-name . (MACRO . (the ,(first decl)
847                                                    ,(cdr var))))))
848             (heap-alien-info
849              (compiler-error
850               "~S is an alien variable, so its type can't be declared."
851               var-name)))))
852
853       (if (or (restr) (new-vars))
854           (make-lexenv :default res
855                        :type-restrictions (restr)
856                        :variables (new-vars))
857           res))))
858
859 ;;; This is somewhat similar to PROCESS-TYPE-DECL, but handles
860 ;;; declarations for function variables. In addition to allowing
861 ;;; declarations for functions being bound, we must also deal with
862 ;;; declarations that constrain the type of lexically apparent
863 ;;; functions.
864 (defun process-ftype-decl (spec res names fvars)
865   (declare (list spec names fvars) (type lexenv res))
866   (let ((type (specifier-type spec)))
867     (collect ((res nil cons))
868       (dolist (name names)
869         (let ((found (find name fvars
870                            :key #'leaf-source-name
871                            :test #'equal)))
872           (cond
873            (found
874             (setf (leaf-type found) type)
875             (assert-definition-type found type
876                                     :warning-function #'compiler-note
877                                     :where "FTYPE declaration"))
878            (t
879             (res (cons (find-lexically-apparent-function
880                         name "in a function type declaration")
881                        type))))))
882       (if (res)
883           (make-lexenv :default res :type-restrictions (res))
884           res))))
885
886 ;;; Process a special declaration, returning a new LEXENV. A non-bound
887 ;;; special declaration is instantiated by throwing a special variable
888 ;;; into the variables.
889 (defun process-special-decl (spec res vars)
890   (declare (list spec vars) (type lexenv res))
891   (collect ((new-venv nil cons))
892     (dolist (name (cdr spec))
893       (let ((var (find-in-bindings vars name)))
894         (etypecase var
895           (cons
896            (aver (eq (car var) 'MACRO))
897            (compiler-error
898             "~S is a symbol-macro and thus can't be declared special."
899             name))
900           (lambda-var
901            (when (lambda-var-ignorep var)
902              ;; ANSI's definition for "Declaration IGNORE, IGNORABLE"
903              ;; requires that this be a STYLE-WARNING, not a full WARNING.
904              (compiler-style-warning
905               "The ignored variable ~S is being declared special."
906               name))
907            (setf (lambda-var-specvar var)
908                  (specvar-for-binding name)))
909           (null
910            (unless (assoc name (new-venv) :test #'eq)
911              (new-venv (cons name (specvar-for-binding name))))))))
912     (if (new-venv)
913         (make-lexenv :default res :variables (new-venv))
914         res)))
915
916 ;;; Return a DEFINED-FUN which copies a GLOBAL-VAR but for its INLINEP.
917 (defun make-new-inlinep (var inlinep)
918   (declare (type global-var var) (type inlinep inlinep))
919   (let ((res (make-defined-fun
920               :%source-name (leaf-source-name var)
921               :where-from (leaf-where-from var)
922               :type (leaf-type var)
923               :inlinep inlinep)))
924     (when (defined-fun-p var)
925       (setf (defined-fun-inline-expansion res)
926             (defined-fun-inline-expansion var))
927       (setf (defined-fun-functional res)
928             (defined-fun-functional var)))
929     res))
930
931 ;;; Parse an inline/notinline declaration. If it's a local function we're
932 ;;; defining, set its INLINEP. If a global function, add a new FENV entry.
933 (defun process-inline-decl (spec res fvars)
934   (let ((sense (cdr (assoc (first spec) *inlinep-translations* :test #'eq)))
935         (new-fenv ()))
936     (dolist (name (rest spec))
937       (let ((fvar (find name fvars
938                         :key #'leaf-source-name
939                         :test #'equal)))
940         (if fvar
941             (setf (functional-inlinep fvar) sense)
942             (let ((found
943                    (find-lexically-apparent-function
944                     name "in an inline or notinline declaration")))
945               (etypecase found
946                 (functional
947                  (when (policy *lexenv* (>= speed inhibit-warnings))
948                    (compiler-note "ignoring ~A declaration not at ~
949                                    definition of local function:~%  ~S"
950                                   sense name)))
951                 (global-var
952                  (push (cons name (make-new-inlinep found sense))
953                        new-fenv)))))))
954
955     (if new-fenv
956         (make-lexenv :default res :functions new-fenv)
957         res)))
958
959 ;;; Like FIND-IN-BINDINGS, but looks for #'foo in the fvars.
960 (defun find-in-bindings-or-fbindings (name vars fvars)
961   (declare (list vars fvars))
962   (if (consp name)
963       (destructuring-bind (wot fn-name) name
964         (unless (eq wot 'function)
965           (compiler-error "The function or variable name ~S is unrecognizable."
966                           name))
967         (find fn-name fvars :key #'leaf-source-name :test #'equal))
968       (find-in-bindings vars name)))
969
970 ;;; Process an ignore/ignorable declaration, checking for various losing
971 ;;; conditions.
972 (defun process-ignore-decl (spec vars fvars)
973   (declare (list spec vars fvars))
974   (dolist (name (rest spec))
975     (let ((var (find-in-bindings-or-fbindings name vars fvars)))
976       (cond
977        ((not var)
978         ;; ANSI's definition for "Declaration IGNORE, IGNORABLE"
979         ;; requires that this be a STYLE-WARNING, not a full WARNING.
980         (compiler-style-warning "declaring unknown variable ~S to be ignored"
981                                 name))
982        ;; FIXME: This special case looks like non-ANSI weirdness.
983        ((and (consp var) (consp (cdr var)) (eq (cadr var) 'macro))
984         ;; Just ignore the IGNORE decl.
985         )
986        ((functional-p var)
987         (setf (leaf-ever-used var) t))
988        ((lambda-var-specvar var)
989         ;; ANSI's definition for "Declaration IGNORE, IGNORABLE"
990         ;; requires that this be a STYLE-WARNING, not a full WARNING.
991         (compiler-style-warning "declaring special variable ~S to be ignored"
992                                 name))
993        ((eq (first spec) 'ignorable)
994         (setf (leaf-ever-used var) t))
995        (t
996         (setf (lambda-var-ignorep var) t)))))
997   (values))
998
999 ;;; FIXME: This is non-ANSI, so the default should be T, or it should
1000 ;;; go away, I think.
1001 (defvar *suppress-values-declaration* nil
1002   #!+sb-doc
1003   "If true, processing of the VALUES declaration is inhibited.")
1004
1005 ;;; Process a single declaration spec, augmenting the specified LEXENV
1006 ;;; RES and returning it as a result. VARS and FVARS are as described in
1007 ;;; PROCESS-DECLS.
1008 (defun process-1-decl (raw-spec res vars fvars cont)
1009   (declare (type list raw-spec vars fvars))
1010   (declare (type lexenv res))
1011   (declare (type continuation cont))
1012   (let ((spec (canonized-decl-spec raw-spec)))
1013     (case (first spec)
1014       (special (process-special-decl spec res vars))
1015       (ftype
1016        (unless (cdr spec)
1017          (compiler-error "No type specified in FTYPE declaration: ~S" spec))
1018        (process-ftype-decl (second spec) res (cddr spec) fvars))
1019       ((inline notinline maybe-inline)
1020        (process-inline-decl spec res fvars))
1021       ((ignore ignorable)
1022        (process-ignore-decl spec vars fvars)
1023        res)
1024       (optimize
1025        (make-lexenv
1026         :default res
1027         :policy (process-optimize-decl spec (lexenv-policy res))))
1028       (type
1029        (process-type-decl (cdr spec) res vars))
1030       (values
1031        (if *suppress-values-declaration*
1032            res
1033            (let ((types (cdr spec)))
1034              (do-the-stuff (if (eql (length types) 1)
1035                                (car types)
1036                                `(values ,@types))
1037                            cont res 'values))))
1038       (dynamic-extent
1039        (when (policy *lexenv* (> speed inhibit-warnings))
1040          (compiler-note
1041           "compiler limitation:~
1042            ~%  There's no special support for DYNAMIC-EXTENT (so it's ignored)."))
1043        res)
1044       (t
1045        (unless (info :declaration :recognized (first spec))
1046          (compiler-warning "unrecognized declaration ~S" raw-spec))
1047        res))))
1048
1049 ;;; Use a list of DECLARE forms to annotate the lists of LAMBDA-VAR
1050 ;;; and FUNCTIONAL structures which are being bound. In addition to
1051 ;;; filling in slots in the leaf structures, we return a new LEXENV
1052 ;;; which reflects pervasive special and function type declarations,
1053 ;;; (NOT)INLINE declarations and OPTIMIZE declarations. CONT is the
1054 ;;; continuation affected by VALUES declarations.
1055 ;;;
1056 ;;; This is also called in main.lisp when PROCESS-FORM handles a use
1057 ;;; of LOCALLY.
1058 (defun process-decls (decls vars fvars cont &optional (env *lexenv*))
1059   (declare (list decls vars fvars) (type continuation cont))
1060   (dolist (decl decls)
1061     (dolist (spec (rest decl))
1062       (unless (consp spec)
1063         (compiler-error "malformed declaration specifier ~S in ~S"
1064                         spec
1065                         decl))
1066       (setq env (process-1-decl spec env vars fvars cont))))
1067   env)
1068
1069 ;;; Return the SPECVAR for NAME to use when we see a local SPECIAL
1070 ;;; declaration. If there is a global variable of that name, then
1071 ;;; check that it isn't a constant and return it. Otherwise, create an
1072 ;;; anonymous GLOBAL-VAR.
1073 (defun specvar-for-binding (name)
1074   (cond ((not (eq (info :variable :where-from name) :assumed))
1075          (let ((found (find-free-variable name)))
1076            (when (heap-alien-info-p found)
1077              (compiler-error
1078               "~S is an alien variable and so can't be declared special."
1079               name))
1080            (unless (global-var-p found)
1081              (compiler-error
1082               "~S is a constant and so can't be declared special."
1083               name))
1084            found))
1085         (t
1086          (make-global-var :kind :special
1087                           :%source-name name
1088                           :where-from :declared))))
1089 \f
1090 ;;;; LAMBDA hackery
1091
1092 ;;;; Note: Take a look at the compiler-overview.tex section on "Hairy
1093 ;;;; function representation" before you seriously mess with this
1094 ;;;; stuff.
1095
1096 ;;; Verify that a thing is a legal name for a variable and return a
1097 ;;; Var structure for it, filling in info if it is globally special.
1098 ;;; If it is losing, we punt with a Compiler-Error. Names-So-Far is an
1099 ;;; alist of names which have previously been bound. If the name is in
1100 ;;; this list, then we error out.
1101 (declaim (ftype (function (t list) lambda-var) varify-lambda-arg))
1102 (defun varify-lambda-arg (name names-so-far)
1103   (declare (inline member))
1104   (unless (symbolp name)
1105     (compiler-error "The lambda-variable ~S is not a symbol." name))
1106   (when (member name names-so-far :test #'eq)
1107     (compiler-error "The variable ~S occurs more than once in the lambda-list."
1108                     name))
1109   (let ((kind (info :variable :kind name)))
1110     (when (or (keywordp name) (eq kind :constant))
1111       (compiler-error "The name of the lambda-variable ~S is a constant."
1112                       name))
1113     (cond ((eq kind :special)
1114            (let ((specvar (find-free-variable name)))
1115              (make-lambda-var :%source-name name
1116                               :type (leaf-type specvar)
1117                               :where-from (leaf-where-from specvar)
1118                               :specvar specvar)))
1119           (t
1120            (note-lexical-binding name)
1121            (make-lambda-var :%source-name name)))))
1122
1123 ;;; Make the default keyword for a &KEY arg, checking that the keyword
1124 ;;; isn't already used by one of the VARS. We also check that the
1125 ;;; keyword isn't the magical :ALLOW-OTHER-KEYS.
1126 (declaim (ftype (function (symbol list t) keyword) make-keyword-for-arg))
1127 (defun make-keyword-for-arg (symbol vars keywordify)
1128   (let ((key (if (and keywordify (not (keywordp symbol)))
1129                  (keywordicate symbol)
1130                  symbol)))
1131     (when (eq key :allow-other-keys)
1132       (compiler-error "No &KEY arg can be called :ALLOW-OTHER-KEYS."))
1133     (dolist (var vars)
1134       (let ((info (lambda-var-arg-info var)))
1135         (when (and info
1136                    (eq (arg-info-kind info) :keyword)
1137                    (eq (arg-info-key info) key))
1138           (compiler-error
1139            "The keyword ~S appears more than once in the lambda-list."
1140            key))))
1141     key))
1142
1143 ;;; Parse a lambda list into a list of VAR structures, stripping off
1144 ;;; any &AUX bindings. Each arg name is checked for legality, and
1145 ;;; duplicate names are checked for. If an arg is globally special,
1146 ;;; the var is marked as :SPECIAL instead of :LEXICAL. &KEY,
1147 ;;; &OPTIONAL and &REST args are annotated with an ARG-INFO structure
1148 ;;; which contains the extra information. If we hit something losing,
1149 ;;; we bug out with COMPILER-ERROR. These values are returned:
1150 ;;;  1. a list of the var structures for each top level argument;
1151 ;;;  2. a flag indicating whether &KEY was specified;
1152 ;;;  3. a flag indicating whether other &KEY args are allowed;
1153 ;;;  4. a list of the &AUX variables; and
1154 ;;;  5. a list of the &AUX values.
1155 (declaim (ftype (function (list) (values list boolean boolean list list))
1156                 make-lambda-vars))
1157 (defun make-lambda-vars (list)
1158   (multiple-value-bind (required optional restp rest keyp keys allowp aux
1159                         morep more-context more-count)
1160       (parse-lambda-list list)
1161     (collect ((vars)
1162               (names-so-far)
1163               (aux-vars)
1164               (aux-vals))
1165       (flet (;; PARSE-DEFAULT deals with defaults and supplied-p args
1166              ;; for optionals and keywords args.
1167              (parse-default (spec info)
1168                (when (consp (cdr spec))
1169                  (setf (arg-info-default info) (second spec))
1170                  (when (consp (cddr spec))
1171                    (let* ((supplied-p (third spec))
1172                           (supplied-var (varify-lambda-arg supplied-p
1173                                                            (names-so-far))))
1174                      (setf (arg-info-supplied-p info) supplied-var)
1175                      (names-so-far supplied-p)
1176                      (when (> (length (the list spec)) 3)
1177                        (compiler-error
1178                         "The list ~S is too long to be an arg specifier."
1179                         spec)))))))
1180         
1181         (dolist (name required)
1182           (let ((var (varify-lambda-arg name (names-so-far))))
1183             (vars var)
1184             (names-so-far name)))
1185         
1186         (dolist (spec optional)
1187           (if (atom spec)
1188               (let ((var (varify-lambda-arg spec (names-so-far))))
1189                 (setf (lambda-var-arg-info var) (make-arg-info :kind :optional))
1190                 (vars var)
1191                 (names-so-far spec))
1192               (let* ((name (first spec))
1193                      (var (varify-lambda-arg name (names-so-far)))
1194                      (info (make-arg-info :kind :optional)))
1195                 (setf (lambda-var-arg-info var) info)
1196                 (vars var)
1197                 (names-so-far name)
1198                 (parse-default spec info))))
1199         
1200         (when restp
1201           (let ((var (varify-lambda-arg rest (names-so-far))))
1202             (setf (lambda-var-arg-info var) (make-arg-info :kind :rest))
1203             (vars var)
1204             (names-so-far rest)))
1205
1206         (when morep
1207           (let ((var (varify-lambda-arg more-context (names-so-far))))
1208             (setf (lambda-var-arg-info var)
1209                   (make-arg-info :kind :more-context))
1210             (vars var)
1211             (names-so-far more-context))
1212           (let ((var (varify-lambda-arg more-count (names-so-far))))
1213             (setf (lambda-var-arg-info var)
1214                   (make-arg-info :kind :more-count))
1215             (vars var)
1216             (names-so-far more-count)))
1217         
1218         (dolist (spec keys)
1219           (cond
1220            ((atom spec)
1221             (let ((var (varify-lambda-arg spec (names-so-far))))
1222               (setf (lambda-var-arg-info var)
1223                     (make-arg-info :kind :keyword
1224                                    :key (make-keyword-for-arg spec
1225                                                               (vars)
1226                                                               t)))
1227               (vars var)
1228               (names-so-far spec)))
1229            ((atom (first spec))
1230             (let* ((name (first spec))
1231                    (var (varify-lambda-arg name (names-so-far)))
1232                    (info (make-arg-info
1233                           :kind :keyword
1234                           :key (make-keyword-for-arg name (vars) t))))
1235               (setf (lambda-var-arg-info var) info)
1236               (vars var)
1237               (names-so-far name)
1238               (parse-default spec info)))
1239            (t
1240             (let ((head (first spec)))
1241               (unless (proper-list-of-length-p head 2)
1242                 (error "malformed &KEY argument specifier: ~S" spec))
1243               (let* ((name (second head))
1244                      (var (varify-lambda-arg name (names-so-far)))
1245                      (info (make-arg-info
1246                             :kind :keyword
1247                             :key (make-keyword-for-arg (first head)
1248                                                        (vars)
1249                                                        nil))))
1250                 (setf (lambda-var-arg-info var) info)
1251                 (vars var)
1252                 (names-so-far name)
1253                 (parse-default spec info))))))
1254         
1255         (dolist (spec aux)
1256           (cond ((atom spec)
1257                  (let ((var (varify-lambda-arg spec nil)))
1258                    (aux-vars var)
1259                    (aux-vals nil)
1260                    (names-so-far spec)))
1261                 (t
1262                  (unless (proper-list-of-length-p spec 1 2)
1263                    (compiler-error "malformed &AUX binding specifier: ~S"
1264                                    spec))
1265                  (let* ((name (first spec))
1266                         (var (varify-lambda-arg name nil)))
1267                    (aux-vars var)
1268                    (aux-vals (second spec))
1269                    (names-so-far name)))))
1270
1271         (values (vars) keyp allowp (aux-vars) (aux-vals))))))
1272
1273 ;;; This is similar to IR1-CONVERT-PROGN-BODY except that we
1274 ;;; sequentially bind each AUX-VAR to the corresponding AUX-VAL before
1275 ;;; converting the body. If there are no bindings, just convert the
1276 ;;; body, otherwise do one binding and recurse on the rest.
1277 ;;;
1278 ;;; FIXME: This could and probably should be converted to use
1279 ;;; SOURCE-NAME and DEBUG-NAME. But I (WHN) don't use &AUX bindings,
1280 ;;; so I'm not motivated. Patches will be accepted...
1281 (defun ir1-convert-aux-bindings (start cont body aux-vars aux-vals)
1282   (declare (type continuation start cont) (list body aux-vars aux-vals))
1283   (if (null aux-vars)
1284       (ir1-convert-progn-body start cont body)
1285       (let ((fun-cont (make-continuation))
1286             (fun (ir1-convert-lambda-body body
1287                                           (list (first aux-vars))
1288                                           :aux-vars (rest aux-vars)
1289                                           :aux-vals (rest aux-vals)
1290                                           :debug-name (debug-namify
1291                                                        "&AUX bindings ~S"
1292                                                        aux-vars))))
1293         (reference-leaf start fun-cont fun)
1294         (ir1-convert-combination-args fun-cont cont
1295                                       (list (first aux-vals)))))
1296   (values))
1297
1298 ;;; This is similar to IR1-CONVERT-PROGN-BODY except that code to bind
1299 ;;; the SPECVAR for each SVAR to the value of the variable is wrapped
1300 ;;; around the body. If there are no special bindings, we just convert
1301 ;;; the body, otherwise we do one special binding and recurse on the
1302 ;;; rest.
1303 ;;;
1304 ;;; We make a cleanup and introduce it into the lexical environment.
1305 ;;; If there are multiple special bindings, the cleanup for the blocks
1306 ;;; will end up being the innermost one. We force CONT to start a
1307 ;;; block outside of this cleanup, causing cleanup code to be emitted
1308 ;;; when the scope is exited.
1309 (defun ir1-convert-special-bindings (start cont body aux-vars aux-vals svars)
1310   (declare (type continuation start cont)
1311            (list body aux-vars aux-vals svars))
1312   (cond
1313    ((null svars)
1314     (ir1-convert-aux-bindings start cont body aux-vars aux-vals))
1315    (t
1316     (continuation-starts-block cont)
1317     (let ((cleanup (make-cleanup :kind :special-bind))
1318           (var (first svars))
1319           (next-cont (make-continuation))
1320           (nnext-cont (make-continuation)))
1321       (ir1-convert start next-cont
1322                    `(%special-bind ',(lambda-var-specvar var) ,var))
1323       (setf (cleanup-mess-up cleanup) (continuation-use next-cont))
1324       (let ((*lexenv* (make-lexenv :cleanup cleanup)))
1325         (ir1-convert next-cont nnext-cont '(%cleanup-point))
1326         (ir1-convert-special-bindings nnext-cont cont body aux-vars aux-vals
1327                                       (rest svars))))))
1328   (values))
1329
1330 ;;; Create a lambda node out of some code, returning the result. The
1331 ;;; bindings are specified by the list of VAR structures VARS. We deal
1332 ;;; with adding the names to the LEXENV-VARIABLES for the conversion.
1333 ;;; The result is added to the NEW-FUNS in the *CURRENT-COMPONENT* and
1334 ;;; linked to the component head and tail.
1335 ;;;
1336 ;;; We detect special bindings here, replacing the original VAR in the
1337 ;;; lambda list with a temporary variable. We then pass a list of the
1338 ;;; special vars to IR1-CONVERT-SPECIAL-BINDINGS, which actually emits
1339 ;;; the special binding code.
1340 ;;;
1341 ;;; We ignore any ARG-INFO in the VARS, trusting that someone else is
1342 ;;; dealing with &nonsense.
1343 ;;;
1344 ;;; AUX-VARS is a list of VAR structures for variables that are to be
1345 ;;; sequentially bound. Each AUX-VAL is a form that is to be evaluated
1346 ;;; to get the initial value for the corresponding AUX-VAR. 
1347 (defun ir1-convert-lambda-body (body
1348                                 vars
1349                                 &key
1350                                 aux-vars
1351                                 aux-vals
1352                                 result
1353                                 (source-name '.anonymous.)
1354                                 debug-name)
1355   (declare (list body vars aux-vars aux-vals)
1356            (type (or continuation null) result))
1357   (let* ((bind (make-bind))
1358          (lambda (make-lambda :vars vars
1359                               :bind bind
1360                               :%source-name source-name
1361                               :%debug-name debug-name))
1362          (result (or result (make-continuation))))
1363
1364     ;; just to check: This function should fail internal assertions if
1365     ;; we didn't set up a valid debug name above.
1366     ;;
1367     ;; (In SBCL we try to make everything have a debug name, since we
1368     ;; lack the omniscient perspective the original implementors used
1369     ;; to decide which things didn't need one.)
1370     (functional-debug-name lambda)
1371
1372     (setf (lambda-home lambda) lambda)
1373     (collect ((svars)
1374               (new-venv nil cons))
1375
1376       (dolist (var vars)
1377         ;; As far as I can see, LAMBDA-VAR-HOME should never have
1378         ;; been set before. Let's make sure. -- WHN 2001-09-29
1379         (aver (null (lambda-var-home var)))
1380         (setf (lambda-var-home var) lambda)
1381         (let ((specvar (lambda-var-specvar var)))
1382           (cond (specvar
1383                  (svars var)
1384                  (new-venv (cons (leaf-source-name specvar) specvar)))
1385                 (t
1386                  (note-lexical-binding (leaf-source-name var))
1387                  (new-venv (cons (leaf-source-name var) var))))))
1388
1389       (let ((*lexenv* (make-lexenv :variables (new-venv)
1390                                    :lambda lambda
1391                                    :cleanup nil)))
1392         (setf (bind-lambda bind) lambda)
1393         (setf (node-lexenv bind) *lexenv*)
1394         
1395         (let ((cont1 (make-continuation))
1396               (cont2 (make-continuation)))
1397           (continuation-starts-block cont1)
1398           (link-node-to-previous-continuation bind cont1)
1399           (use-continuation bind cont2)
1400           (ir1-convert-special-bindings cont2 result body aux-vars aux-vals
1401                                         (svars)))
1402
1403         (let ((block (continuation-block result)))
1404           (when block
1405             (let ((return (make-return :result result :lambda lambda))
1406                   (tail-set (make-tail-set :funs (list lambda)))
1407                   (dummy (make-continuation)))
1408               (setf (lambda-tail-set lambda) tail-set)
1409               (setf (lambda-return lambda) return)
1410               (setf (continuation-dest result) return)
1411               (setf (block-last block) return)
1412               (link-node-to-previous-continuation return result)
1413               (use-continuation return dummy))
1414             (link-blocks block (component-tail *current-component*))))))
1415
1416     (link-blocks (component-head *current-component*) (node-block bind))
1417     (push lambda (component-new-funs *current-component*))
1418     lambda))
1419
1420 ;;; Create the actual entry-point function for an optional entry
1421 ;;; point. The lambda binds copies of each of the VARS, then calls FUN
1422 ;;; with the argument VALS and the DEFAULTS. Presumably the VALS refer
1423 ;;; to the VARS by name. The VALS are passed in in reverse order.
1424 ;;;
1425 ;;; If any of the copies of the vars are referenced more than once,
1426 ;;; then we mark the corresponding var as EVER-USED to inhibit
1427 ;;; "defined but not read" warnings for arguments that are only used
1428 ;;; by default forms.
1429 (defun convert-optional-entry (fun vars vals defaults)
1430   (declare (type clambda fun) (list vars vals defaults))
1431   (let* ((fvars (reverse vars))
1432          (arg-vars (mapcar (lambda (var)
1433                              (unless (lambda-var-specvar var)
1434                                (note-lexical-binding (leaf-source-name var)))
1435                              (make-lambda-var
1436                               :%source-name (leaf-source-name var)
1437                               :type (leaf-type var)
1438                               :where-from (leaf-where-from var)
1439                               :specvar (lambda-var-specvar var)))
1440                            fvars))
1441          (fun (ir1-convert-lambda-body `((%funcall ,fun
1442                                                    ,@(reverse vals)
1443                                                    ,@defaults))
1444                                        arg-vars
1445                                        :debug-name "&OPTIONAL processor")))
1446     (mapc (lambda (var arg-var)
1447             (when (cdr (leaf-refs arg-var))
1448               (setf (leaf-ever-used var) t)))
1449           fvars arg-vars)
1450     fun))
1451
1452 ;;; This function deals with supplied-p vars in optional arguments. If
1453 ;;; the there is no supplied-p arg, then we just call
1454 ;;; IR1-CONVERT-HAIRY-ARGS on the remaining arguments, and generate a
1455 ;;; optional entry that calls the result. If there is a supplied-p
1456 ;;; var, then we add it into the default vars and throw a T into the
1457 ;;; entry values. The resulting entry point function is returned.
1458 (defun generate-optional-default-entry (res default-vars default-vals
1459                                             entry-vars entry-vals
1460                                             vars supplied-p-p body
1461                                             aux-vars aux-vals cont
1462                                             source-name debug-name)
1463   (declare (type optional-dispatch res)
1464            (list default-vars default-vals entry-vars entry-vals vars body
1465                  aux-vars aux-vals)
1466            (type (or continuation null) cont))
1467   (let* ((arg (first vars))
1468          (arg-name (leaf-source-name arg))
1469          (info (lambda-var-arg-info arg))
1470          (supplied-p (arg-info-supplied-p info))
1471          (ep (if supplied-p
1472                  (ir1-convert-hairy-args
1473                   res
1474                   (list* supplied-p arg default-vars)
1475                   (list* (leaf-source-name supplied-p) arg-name default-vals)
1476                   (cons arg entry-vars)
1477                   (list* t arg-name entry-vals)
1478                   (rest vars) t body aux-vars aux-vals cont
1479                   source-name debug-name)
1480                  (ir1-convert-hairy-args
1481                   res
1482                   (cons arg default-vars)
1483                   (cons arg-name default-vals)
1484                   (cons arg entry-vars)
1485                   (cons arg-name entry-vals)
1486                   (rest vars) supplied-p-p body aux-vars aux-vals cont
1487                   source-name debug-name))))
1488
1489     (convert-optional-entry ep default-vars default-vals
1490                             (if supplied-p
1491                                 (list (arg-info-default info) nil)
1492                                 (list (arg-info-default info))))))
1493
1494 ;;; Create the MORE-ENTRY function for the OPTIONAL-DISPATCH RES.
1495 ;;; ENTRY-VARS and ENTRY-VALS describe the fixed arguments. REST is
1496 ;;; the var for any &REST arg. KEYS is a list of the &KEY arg vars.
1497 ;;;
1498 ;;; The most interesting thing that we do is parse keywords. We create
1499 ;;; a bunch of temporary variables to hold the result of the parse,
1500 ;;; and then loop over the supplied arguments, setting the appropriate
1501 ;;; temps for the supplied keyword. Note that it is significant that
1502 ;;; we iterate over the keywords in reverse order --- this implements
1503 ;;; the CL requirement that (when a keyword appears more than once)
1504 ;;; the first value is used.
1505 ;;;
1506 ;;; If there is no supplied-p var, then we initialize the temp to the
1507 ;;; default and just pass the temp into the main entry. Since
1508 ;;; non-constant &KEY args are forcibly given a supplied-p var, we
1509 ;;; know that the default is constant, and thus safe to evaluate out
1510 ;;; of order.
1511 ;;;
1512 ;;; If there is a supplied-p var, then we create temps for both the
1513 ;;; value and the supplied-p, and pass them into the main entry,
1514 ;;; letting it worry about defaulting.
1515 ;;;
1516 ;;; We deal with :ALLOW-OTHER-KEYS by delaying unknown keyword errors
1517 ;;; until we have scanned all the keywords.
1518 (defun convert-more-entry (res entry-vars entry-vals rest morep keys)
1519   (declare (type optional-dispatch res) (list entry-vars entry-vals keys))
1520   (collect ((arg-vars)
1521             (arg-vals (reverse entry-vals))
1522             (temps)
1523             (body))
1524
1525     (dolist (var (reverse entry-vars))
1526       (arg-vars (make-lambda-var :%source-name (leaf-source-name var)
1527                                  :type (leaf-type var)
1528                                  :where-from (leaf-where-from var))))
1529
1530     (let* ((n-context (gensym "N-CONTEXT-"))
1531            (context-temp (make-lambda-var :%source-name n-context))
1532            (n-count (gensym "N-COUNT-"))
1533            (count-temp (make-lambda-var :%source-name n-count
1534                                         :type (specifier-type 'index))))
1535
1536       (arg-vars context-temp count-temp)
1537
1538       (when rest
1539         (arg-vals `(%listify-rest-args ,n-context ,n-count)))
1540       (when morep
1541         (arg-vals n-context)
1542         (arg-vals n-count))
1543
1544       (when (optional-dispatch-keyp res)
1545         (let ((n-index (gensym "N-INDEX-"))
1546               (n-key (gensym "N-KEY-"))
1547               (n-value-temp (gensym "N-VALUE-TEMP-"))
1548               (n-allowp (gensym "N-ALLOWP-"))
1549               (n-losep (gensym "N-LOSEP-"))
1550               (allowp (or (optional-dispatch-allowp res)
1551                           (policy *lexenv* (zerop safety)))))
1552
1553           (temps `(,n-index (1- ,n-count)) n-key n-value-temp)
1554           (body `(declare (fixnum ,n-index) (ignorable ,n-key ,n-value-temp)))
1555
1556           (collect ((tests))
1557             (dolist (key keys)
1558               (let* ((info (lambda-var-arg-info key))
1559                      (default (arg-info-default info))
1560                      (keyword (arg-info-key info))
1561                      (supplied-p (arg-info-supplied-p info))
1562                      (n-value (gensym "N-VALUE-")))
1563                 (temps `(,n-value ,default))
1564                 (cond (supplied-p
1565                        (let ((n-supplied (gensym "N-SUPPLIED-")))
1566                          (temps n-supplied)
1567                          (arg-vals n-value n-supplied)
1568                          (tests `((eq ,n-key ',keyword)
1569                                   (setq ,n-supplied t)
1570                                   (setq ,n-value ,n-value-temp)))))
1571                       (t
1572                        (arg-vals n-value)
1573                        (tests `((eq ,n-key ',keyword)
1574                                 (setq ,n-value ,n-value-temp)))))))
1575
1576             (unless allowp
1577               (temps n-allowp n-losep)
1578               (tests `((eq ,n-key :allow-other-keys)
1579                        (setq ,n-allowp ,n-value-temp)))
1580               (tests `(t
1581                        (setq ,n-losep ,n-key))))
1582
1583             (body
1584              `(when (oddp ,n-count)
1585                 (%odd-key-arguments-error)))
1586
1587             (body
1588              `(locally
1589                 (declare (optimize (safety 0)))
1590                 (loop
1591                   (when (minusp ,n-index) (return))
1592                   (setf ,n-value-temp (%more-arg ,n-context ,n-index))
1593                   (decf ,n-index)
1594                   (setq ,n-key (%more-arg ,n-context ,n-index))
1595                   (decf ,n-index)
1596                   (cond ,@(tests)))))
1597
1598             (unless allowp
1599               (body `(when (and ,n-losep (not ,n-allowp))
1600                        (%unknown-key-argument-error ,n-losep)))))))
1601
1602       (let ((ep (ir1-convert-lambda-body
1603                  `((let ,(temps)
1604                      ,@(body)
1605                      (%funcall ,(optional-dispatch-main-entry res)
1606                                . ,(arg-vals)))) ; FIXME: What is the '.'? ,@?
1607                  (arg-vars)
1608                  :debug-name (debug-namify "~S processing" '&more))))
1609         (setf (optional-dispatch-more-entry res) ep))))
1610
1611   (values))
1612
1613 ;;; This is called by IR1-CONVERT-HAIRY-ARGS when we run into a &REST
1614 ;;; or &KEY arg. The arguments are similar to that function, but we
1615 ;;; split off any &REST arg and pass it in separately. REST is the
1616 ;;; &REST arg var, or NIL if there is no &REST arg. KEYS is a list of
1617 ;;; the &KEY argument vars.
1618 ;;;
1619 ;;; When there are &KEY arguments, we introduce temporary gensym
1620 ;;; variables to hold the values while keyword defaulting is in
1621 ;;; progress to get the required sequential binding semantics.
1622 ;;;
1623 ;;; This gets interesting mainly when there are &KEY arguments with
1624 ;;; supplied-p vars or non-constant defaults. In either case, pass in
1625 ;;; a supplied-p var. If the default is non-constant, we introduce an
1626 ;;; IF in the main entry that tests the supplied-p var and decides
1627 ;;; whether to evaluate the default or not. In this case, the real
1628 ;;; incoming value is NIL, so we must union NULL with the declared
1629 ;;; type when computing the type for the main entry's argument.
1630 (defun ir1-convert-more (res default-vars default-vals entry-vars entry-vals
1631                              rest more-context more-count keys supplied-p-p
1632                              body aux-vars aux-vals cont
1633                              source-name debug-name)
1634   (declare (type optional-dispatch res)
1635            (list default-vars default-vals entry-vars entry-vals keys body
1636                  aux-vars aux-vals)
1637            (type (or continuation null) cont))
1638   (collect ((main-vars (reverse default-vars))
1639             (main-vals default-vals cons)
1640             (bind-vars)
1641             (bind-vals))
1642     (when rest
1643       (main-vars rest)
1644       (main-vals '()))
1645     (when more-context
1646       (main-vars more-context)
1647       (main-vals nil)
1648       (main-vars more-count)
1649       (main-vals 0))
1650
1651     (dolist (key keys)
1652       (let* ((info (lambda-var-arg-info key))
1653              (default (arg-info-default info))
1654              (hairy-default (not (sb!xc:constantp default)))
1655              (supplied-p (arg-info-supplied-p info))
1656              (n-val (make-symbol (format nil
1657                                          "~A-DEFAULTING-TEMP"
1658                                          (leaf-source-name key))))
1659              (key-type (leaf-type key))
1660              (val-temp (make-lambda-var
1661                         :%source-name n-val
1662                         :type (if hairy-default
1663                                   (type-union key-type (specifier-type 'null))
1664                                   key-type))))
1665         (main-vars val-temp)
1666         (bind-vars key)
1667         (cond ((or hairy-default supplied-p)
1668                (let* ((n-supplied (gensym "N-SUPPLIED-"))
1669                       (supplied-temp (make-lambda-var
1670                                       :%source-name n-supplied)))
1671                  (unless supplied-p
1672                    (setf (arg-info-supplied-p info) supplied-temp))
1673                  (when hairy-default
1674                    (setf (arg-info-default info) nil))
1675                  (main-vars supplied-temp)
1676                  (cond (hairy-default
1677                         (main-vals nil nil)
1678                         (bind-vals `(if ,n-supplied ,n-val ,default)))
1679                        (t
1680                         (main-vals default nil)
1681                         (bind-vals n-val)))
1682                  (when supplied-p
1683                    (bind-vars supplied-p)
1684                    (bind-vals n-supplied))))
1685               (t
1686                (main-vals (arg-info-default info))
1687                (bind-vals n-val)))))
1688
1689     (let* ((main-entry (ir1-convert-lambda-body
1690                         body (main-vars)
1691                         :aux-vars (append (bind-vars) aux-vars)
1692                         :aux-vals (append (bind-vals) aux-vals)
1693                         :result cont
1694                         :debug-name (debug-namify "~S processor for ~A"
1695                                                   '&more
1696                                                   (as-debug-name source-name
1697                                                                  debug-name))))
1698            (last-entry (convert-optional-entry main-entry default-vars
1699                                                (main-vals) ())))
1700       (setf (optional-dispatch-main-entry res) main-entry)
1701       (convert-more-entry res entry-vars entry-vals rest more-context keys)
1702
1703       (push (if supplied-p-p
1704                 (convert-optional-entry last-entry entry-vars entry-vals ())
1705                 last-entry)
1706             (optional-dispatch-entry-points res))
1707       last-entry)))
1708
1709 ;;; This function generates the entry point functions for the
1710 ;;; OPTIONAL-DISPATCH RES. We accomplish this by recursion on the list
1711 ;;; of arguments, analyzing the arglist on the way down and generating
1712 ;;; entry points on the way up.
1713 ;;;
1714 ;;; DEFAULT-VARS is a reversed list of all the argument vars processed
1715 ;;; so far, including supplied-p vars. DEFAULT-VALS is a list of the
1716 ;;; names of the DEFAULT-VARS.
1717 ;;;
1718 ;;; ENTRY-VARS is a reversed list of processed argument vars,
1719 ;;; excluding supplied-p vars. ENTRY-VALS is a list things that can be
1720 ;;; evaluated to get the values for all the vars from the ENTRY-VARS.
1721 ;;; It has the var name for each required or optional arg, and has T
1722 ;;; for each supplied-p arg.
1723 ;;;
1724 ;;; VARS is a list of the LAMBDA-VAR structures for arguments that
1725 ;;; haven't been processed yet. SUPPLIED-P-P is true if a supplied-p
1726 ;;; argument has already been processed; only in this case are the
1727 ;;; DEFAULT-XXX and ENTRY-XXX different.
1728 ;;;
1729 ;;; The result at each point is a lambda which should be called by the
1730 ;;; above level to default the remaining arguments and evaluate the
1731 ;;; body. We cause the body to be evaluated by converting it and
1732 ;;; returning it as the result when the recursion bottoms out.
1733 ;;;
1734 ;;; Each level in the recursion also adds its entry point function to
1735 ;;; the result OPTIONAL-DISPATCH. For most arguments, the defaulting
1736 ;;; function and the entry point function will be the same, but when
1737 ;;; SUPPLIED-P args are present they may be different.
1738 ;;;
1739 ;;; When we run into a &REST or &KEY arg, we punt out to
1740 ;;; IR1-CONVERT-MORE, which finishes for us in this case.
1741 (defun ir1-convert-hairy-args (res default-vars default-vals
1742                                    entry-vars entry-vals
1743                                    vars supplied-p-p body aux-vars
1744                                    aux-vals cont
1745                                    source-name debug-name)
1746   (declare (type optional-dispatch res)
1747            (list default-vars default-vals entry-vars entry-vals vars body
1748                  aux-vars aux-vals)
1749            (type (or continuation null) cont))
1750   (cond ((not vars)
1751          (if (optional-dispatch-keyp res)
1752              ;; Handle &KEY with no keys...
1753              (ir1-convert-more res default-vars default-vals
1754                                entry-vars entry-vals
1755                                nil nil nil vars supplied-p-p body aux-vars
1756                                aux-vals cont source-name debug-name)
1757              (let ((fun (ir1-convert-lambda-body
1758                          body (reverse default-vars)
1759                          :aux-vars aux-vars
1760                          :aux-vals aux-vals
1761                          :result cont
1762                          :debug-name (debug-namify
1763                                       "hairy arg processor for ~A"
1764                                       (as-debug-name source-name
1765                                                      debug-name)))))
1766                (setf (optional-dispatch-main-entry res) fun)
1767                (push (if supplied-p-p
1768                          (convert-optional-entry fun entry-vars entry-vals ())
1769                          fun)
1770                      (optional-dispatch-entry-points res))
1771                fun)))
1772         ((not (lambda-var-arg-info (first vars)))
1773          (let* ((arg (first vars))
1774                 (nvars (cons arg default-vars))
1775                 (nvals (cons (leaf-source-name arg) default-vals)))
1776            (ir1-convert-hairy-args res nvars nvals nvars nvals
1777                                    (rest vars) nil body aux-vars aux-vals
1778                                    cont
1779                                    source-name debug-name)))
1780         (t
1781          (let* ((arg (first vars))
1782                 (info (lambda-var-arg-info arg))
1783                 (kind (arg-info-kind info)))
1784            (ecase kind
1785              (:optional
1786               (let ((ep (generate-optional-default-entry
1787                          res default-vars default-vals
1788                          entry-vars entry-vals vars supplied-p-p body
1789                          aux-vars aux-vals cont
1790                          source-name debug-name)))
1791                 (push (if supplied-p-p
1792                           (convert-optional-entry ep entry-vars entry-vals ())
1793                           ep)
1794                       (optional-dispatch-entry-points res))
1795                 ep))
1796              (:rest
1797               (ir1-convert-more res default-vars default-vals
1798                                 entry-vars entry-vals
1799                                 arg nil nil (rest vars) supplied-p-p body
1800                                 aux-vars aux-vals cont
1801                                 source-name debug-name))
1802              (:more-context
1803               (ir1-convert-more res default-vars default-vals
1804                                 entry-vars entry-vals
1805                                 nil arg (second vars) (cddr vars) supplied-p-p
1806                                 body aux-vars aux-vals cont
1807                                 source-name debug-name))
1808              (:keyword
1809               (ir1-convert-more res default-vars default-vals
1810                                 entry-vars entry-vals
1811                                 nil nil nil vars supplied-p-p body aux-vars
1812                                 aux-vals cont source-name debug-name)))))))
1813
1814 ;;; This function deals with the case where we have to make an
1815 ;;; OPTIONAL-DISPATCH to represent a LAMBDA. We cons up the result and
1816 ;;; call IR1-CONVERT-HAIRY-ARGS to do the work. When it is done, we
1817 ;;; figure out the MIN-ARGS and MAX-ARGS.
1818 (defun ir1-convert-hairy-lambda (body vars keyp allowp aux-vars aux-vals cont
1819                                       &key
1820                                       (source-name '.anonymous.)
1821                                       (debug-name (debug-namify
1822                                                    "OPTIONAL-DISPATCH ~S"
1823                                                    vars)))
1824   (declare (list body vars aux-vars aux-vals) (type continuation cont))
1825   (let ((res (make-optional-dispatch :arglist vars
1826                                      :allowp allowp
1827                                      :keyp keyp
1828                                      :%source-name source-name
1829                                      :%debug-name debug-name))
1830         (min (or (position-if #'lambda-var-arg-info vars) (length vars))))
1831     (push res (component-new-funs *current-component*))
1832     (ir1-convert-hairy-args res () () () () vars nil body aux-vars aux-vals
1833                             cont source-name debug-name)
1834     (setf (optional-dispatch-min-args res) min)
1835     (setf (optional-dispatch-max-args res)
1836           (+ (1- (length (optional-dispatch-entry-points res))) min))
1837
1838     (flet ((frob (ep)
1839              (when ep
1840                (setf (functional-kind ep) :optional)
1841                (setf (leaf-ever-used ep) t)
1842                (setf (lambda-optional-dispatch ep) res))))
1843       (dolist (ep (optional-dispatch-entry-points res)) (frob ep))
1844       (frob (optional-dispatch-more-entry res))
1845       (frob (optional-dispatch-main-entry res)))
1846
1847     res))
1848
1849 ;;; Convert a LAMBDA form into a LAMBDA leaf or an OPTIONAL-DISPATCH leaf.
1850 (defun ir1-convert-lambda (form &key (source-name '.anonymous.) debug-name)
1851   (unless (consp form)
1852     (compiler-error "A ~S was found when expecting a lambda expression:~%  ~S"
1853                     (type-of form)
1854                     form))
1855   (unless (eq (car form) 'lambda)
1856     (compiler-error "~S was expected but ~S was found:~%  ~S"
1857                     'lambda
1858                     (car form)
1859                     form))
1860   (unless (and (consp (cdr form)) (listp (cadr form)))
1861     (compiler-error
1862      "The lambda expression has a missing or non-list lambda list:~%  ~S"
1863      form))
1864
1865   (multiple-value-bind (vars keyp allow-other-keys aux-vars aux-vals)
1866       (make-lambda-vars (cadr form))
1867     (multiple-value-bind (forms decls) (sb!sys:parse-body (cddr form))
1868       (let* ((result-cont (make-continuation))
1869              (*lexenv* (process-decls decls
1870                                       (append aux-vars vars)
1871                                       nil result-cont))
1872              (res (if (or (find-if #'lambda-var-arg-info vars) keyp)
1873                       (ir1-convert-hairy-lambda forms vars keyp
1874                                                 allow-other-keys
1875                                                 aux-vars aux-vals result-cont
1876                                                 :source-name source-name
1877                                                 :debug-name debug-name)
1878                       (ir1-convert-lambda-body forms vars
1879                                                :aux-vars aux-vars
1880                                                :aux-vals aux-vals
1881                                                :result result-cont
1882                                                :source-name source-name
1883                                                :debug-name debug-name))))
1884         (setf (functional-inline-expansion res) form)
1885         (setf (functional-arg-documentation res) (cadr form))
1886         res))))
1887 \f
1888 ;;;; defining global functions
1889
1890 ;;; Convert FUN as a lambda in the null environment, but use the
1891 ;;; current compilation policy. Note that FUN may be a
1892 ;;; LAMBDA-WITH-LEXENV, so we may have to augment the environment to
1893 ;;; reflect the state at the definition site.
1894 (defun ir1-convert-inline-lambda (fun &key
1895                                       (source-name '.anonymous.)
1896                                       debug-name)
1897   (destructuring-bind (decls macros symbol-macros &rest body)
1898                       (if (eq (car fun) 'lambda-with-lexenv)
1899                           (cdr fun)
1900                           `(() () () . ,(cdr fun)))
1901     (let ((*lexenv* (make-lexenv
1902                      :default (process-decls decls nil nil
1903                                              (make-continuation)
1904                                              (make-null-lexenv))
1905                      :variables (copy-list symbol-macros)
1906                      :functions
1907                      (mapcar (lambda (x)
1908                                `(,(car x) .
1909                                  (macro . ,(coerce (cdr x) 'function))))
1910                              macros)
1911                      :policy (lexenv-policy *lexenv*))))
1912       (ir1-convert-lambda `(lambda ,@body)
1913                           :source-name source-name
1914                           :debug-name debug-name))))
1915
1916 ;;; Get a DEFINED-FUN object for a function we are about to
1917 ;;; define. If the function has been forward referenced, then
1918 ;;; substitute for the previous references.
1919 (defun get-defined-fun (name)
1920   (proclaim-as-fun-name name)
1921   (let ((found (find-free-function name "shouldn't happen! (defined-fun)")))
1922     (note-name-defined name :function)
1923     (cond ((not (defined-fun-p found))
1924            (aver (not (info :function :inlinep name)))
1925            (let* ((where-from (leaf-where-from found))
1926                   (res (make-defined-fun
1927                         :%source-name name
1928                         :where-from (if (eq where-from :declared)
1929                                         :declared :defined)
1930                         :type (leaf-type found))))
1931              (substitute-leaf res found)
1932              (setf (gethash name *free-functions*) res)))
1933           ;; If *FREE-FUNCTIONS* has a previously converted definition
1934           ;; for this name, then blow it away and try again.
1935           ((defined-fun-functional found)
1936            (remhash name *free-functions*)
1937            (get-defined-fun name))
1938           (t found))))
1939
1940 ;;; Check a new global function definition for consistency with
1941 ;;; previous declaration or definition, and assert argument/result
1942 ;;; types if appropriate. This assertion is suppressed by the
1943 ;;; EXPLICIT-CHECK attribute, which is specified on functions that
1944 ;;; check their argument types as a consequence of type dispatching.
1945 ;;; This avoids redundant checks such as NUMBERP on the args to +, etc.
1946 (defun assert-new-definition (var fun)
1947   (let ((type (leaf-type var))
1948         (for-real (eq (leaf-where-from var) :declared))
1949         (info (info :function :info (leaf-source-name var))))
1950     (assert-definition-type
1951      fun type
1952      ;; KLUDGE: Common Lisp is such a dynamic language that in general
1953      ;; all we can do here in general is issue a STYLE-WARNING. It
1954      ;; would be nice to issue a full WARNING in the special case of
1955      ;; of type mismatches within a compilation unit (as in section
1956      ;; 3.2.2.3 of the spec) but at least as of sbcl-0.6.11, we don't
1957      ;; keep track of whether the mismatched data came from the same
1958      ;; compilation unit, so we can't do that. -- WHN 2001-02-11
1959      :error-function #'compiler-style-warning
1960      :warning-function (cond (info #'compiler-style-warning)
1961                              (for-real #'compiler-note)
1962                              (t nil))
1963      :really-assert
1964      (and for-real
1965           (not (and info
1966                     (ir1-attributep (function-info-attributes info)
1967                                     explicit-check))))
1968      :where (if for-real
1969                 "previous declaration"
1970                 "previous definition"))))
1971
1972 ;;; Convert a lambda doing all the basic stuff we would do if we were
1973 ;;; converting a DEFUN. In the old CMU CL system, this was used both
1974 ;;; by the %DEFUN translator and for global inline expansion, but
1975 ;;; since sbcl-0.pre7.something %DEFUN does things differently.
1976 ;;; FIXME: And now it's probably worth rethinking whether this
1977 ;;; function is a good idea.
1978 ;;;
1979 ;;; Unless a :INLINE function, we temporarily clobber the inline
1980 ;;; expansion. This prevents recursive inline expansion of
1981 ;;; opportunistic pseudo-inlines.
1982 (defun ir1-convert-lambda-for-defun (lambda var expansion converter)
1983   (declare (cons lambda) (function converter) (type defined-fun var))
1984   (let ((var-expansion (defined-fun-inline-expansion var)))
1985     (unless (eq (defined-fun-inlinep var) :inline)
1986       (setf (defined-fun-inline-expansion var) nil))
1987     (let* ((name (leaf-source-name var))
1988            (fun (funcall converter lambda :source-name name))
1989            (function-info (info :function :info name)))
1990       (setf (functional-inlinep fun) (defined-fun-inlinep var))
1991       (assert-new-definition var fun)
1992       (setf (defined-fun-inline-expansion var) var-expansion)
1993       ;; If definitely not an interpreter stub, then substitute for any
1994       ;; old references.
1995       (unless (or (eq (defined-fun-inlinep var) :notinline)
1996                   (not *block-compile*)
1997                   (and function-info
1998                        (or (function-info-transforms function-info)
1999                            (function-info-templates function-info)
2000                            (function-info-ir2-convert function-info))))
2001         (substitute-leaf fun var)
2002         ;; If in a simple environment, then we can allow backward
2003         ;; references to this function from following top level forms.
2004         (when expansion (setf (defined-fun-functional var) fun)))
2005       fun)))
2006
2007 ;;; the even-at-compile-time part of DEFUN
2008 ;;;
2009 ;;; The INLINE-EXPANSION is a LAMBDA-WITH-LEXENV, or NIL if there is
2010 ;;; no inline expansion.
2011 (defun %compiler-defun (name lambda-with-lexenv)
2012
2013   (let ((defined-fun nil)) ; will be set below if we're in the compiler
2014     
2015     (when (boundp '*lexenv*) ; when in the compiler
2016       (when sb!xc:*compile-print*
2017         (compiler-mumble "~&; recognizing DEFUN ~S~%" name))
2018       (remhash name *free-functions*)
2019       (setf defined-fun (get-defined-fun name)))
2020
2021     (become-defined-fun-name name)
2022
2023     (cond (lambda-with-lexenv
2024            (setf (info :function :inline-expansion-designator name)
2025                  lambda-with-lexenv)
2026            (when defined-fun 
2027              (setf (defined-fun-inline-expansion defined-fun)
2028                    lambda-with-lexenv)))
2029           (t
2030            (clear-info :function :inline-expansion-designator name)))
2031
2032     ;; old CMU CL comment:
2033     ;;   If there is a type from a previous definition, blast it,
2034     ;;   since it is obsolete.
2035     (when (and defined-fun
2036                (eq (leaf-where-from defined-fun) :defined))
2037       (setf (leaf-type defined-fun)
2038             ;; FIXME: If this is a block compilation thing, shouldn't
2039             ;; we be setting the type to the full derived type for the
2040             ;; definition, instead of this most general function type?
2041             (specifier-type 'function))))
2042
2043   (values))