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