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