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