sbcl-0.8.14.11:
[sbcl.git] / src / compiler / ir1tran-lambda.lisp
1 ;;;; This file contains code which does the translation of lambda
2 ;;;; forms from Lisp code to the first intermediate representation
3 ;;;; (IR1).
4
5 ;;;; This software is part of the SBCL system. See the README file for
6 ;;;; more information.
7 ;;;;
8 ;;;; This software is derived from the CMU CL system, which was
9 ;;;; written at Carnegie Mellon University and released into the
10 ;;;; public domain. The software is in the public domain and is
11 ;;;; provided with absolutely no warranty. See the COPYING and CREDITS
12 ;;;; files for more information.
13
14 (in-package "SB!C")
15
16 ;;;; LAMBDA hackery
17
18 ;;;; Note: Take a look at the compiler-overview.tex section on "Hairy
19 ;;;; function representation" before you seriously mess with this
20 ;;;; stuff.
21
22 ;;; Verify that the NAME is a legal name for a variable and return a
23 ;;; VAR structure for it, filling in info if it is globally special.
24 ;;; If it is losing, we punt with a COMPILER-ERROR. NAMES-SO-FAR is a
25 ;;; list of names which have previously been bound. If the NAME is in
26 ;;; this list, then we error out.
27 (declaim (ftype (sfunction (t list) lambda-var) varify-lambda-arg))
28 (defun varify-lambda-arg (name names-so-far)
29   (declare (inline member))
30   (unless (symbolp name)
31     (compiler-error "The lambda variable ~S is not a symbol." name))
32   (when (member name names-so-far :test #'eq)
33     (compiler-error "The variable ~S occurs more than once in the lambda list."
34                     name))
35   (let ((kind (info :variable :kind name)))
36     (when (or (keywordp name) (eq kind :constant))
37       (compiler-error "The name of the lambda variable ~S is already in use to name a constant."
38                       name))
39     (cond ((eq kind :special)
40            (let ((specvar (find-free-var name)))
41              (make-lambda-var :%source-name name
42                               :type (leaf-type specvar)
43                               :where-from (leaf-where-from specvar)
44                               :specvar specvar)))
45           (t
46            (make-lambda-var :%source-name name)))))
47
48 ;;; Make the default keyword for a &KEY arg, checking that the keyword
49 ;;; isn't already used by one of the VARS.
50 (declaim (ftype (sfunction (symbol list t) symbol) make-keyword-for-arg))
51 (defun make-keyword-for-arg (symbol vars keywordify)
52   (let ((key (if (and keywordify (not (keywordp symbol)))
53                  (keywordicate symbol)
54                  symbol)))
55     (dolist (var vars)
56       (let ((info (lambda-var-arg-info var)))
57         (when (and info
58                    (eq (arg-info-kind info) :keyword)
59                    (eq (arg-info-key info) key))
60           (compiler-error
61            "The keyword ~S appears more than once in the lambda list."
62            key))))
63     key))
64
65 ;;; Parse a lambda list into a list of VAR structures, stripping off
66 ;;; any &AUX bindings. Each arg name is checked for legality, and
67 ;;; duplicate names are checked for. If an arg is globally special,
68 ;;; the var is marked as :SPECIAL instead of :LEXICAL. &KEY,
69 ;;; &OPTIONAL and &REST args are annotated with an ARG-INFO structure
70 ;;; which contains the extra information. If we hit something losing,
71 ;;; we bug out with COMPILER-ERROR. These values are returned:
72 ;;;  1. a list of the var structures for each top level argument;
73 ;;;  2. a flag indicating whether &KEY was specified;
74 ;;;  3. a flag indicating whether other &KEY args are allowed;
75 ;;;  4. a list of the &AUX variables; and
76 ;;;  5. a list of the &AUX values.
77 (declaim (ftype (sfunction (list) (values list boolean boolean list list))
78                 make-lambda-vars))
79 (defun make-lambda-vars (list)
80   (multiple-value-bind (required optional restp rest keyp keys allowp auxp aux
81                         morep more-context more-count)
82       (parse-lambda-list list)
83     (declare (ignore auxp)) ; since we just iterate over AUX regardless
84     (collect ((vars)
85               (names-so-far)
86               (aux-vars)
87               (aux-vals))
88       (flet (;; PARSE-DEFAULT deals with defaults and supplied-p args
89              ;; for optionals and keywords args.
90              (parse-default (spec info)
91                (when (consp (cdr spec))
92                  (setf (arg-info-default info) (second spec))
93                  (when (consp (cddr spec))
94                    (let* ((supplied-p (third spec))
95                           (supplied-var (varify-lambda-arg supplied-p
96                                                            (names-so-far))))
97                      (setf (arg-info-supplied-p info) supplied-var)
98                      (names-so-far supplied-p)
99                      (when (> (length (the list spec)) 3)
100                        (compiler-error
101                         "The list ~S is too long to be an arg specifier."
102                         spec)))))))
103
104         (dolist (name required)
105           (let ((var (varify-lambda-arg name (names-so-far))))
106             (vars var)
107             (names-so-far name)))
108
109         (dolist (spec optional)
110           (if (atom spec)
111               (let ((var (varify-lambda-arg spec (names-so-far))))
112                 (setf (lambda-var-arg-info var)
113                       (make-arg-info :kind :optional))
114                 (vars var)
115                 (names-so-far spec))
116               (let* ((name (first spec))
117                      (var (varify-lambda-arg name (names-so-far)))
118                      (info (make-arg-info :kind :optional)))
119                 (setf (lambda-var-arg-info var) info)
120                 (vars var)
121                 (names-so-far name)
122                 (parse-default spec info))))
123
124         (when restp
125           (let ((var (varify-lambda-arg rest (names-so-far))))
126             (setf (lambda-var-arg-info var) (make-arg-info :kind :rest))
127             (vars var)
128             (names-so-far rest)))
129
130         (when morep
131           (let ((var (varify-lambda-arg more-context (names-so-far))))
132             (setf (lambda-var-arg-info var)
133                   (make-arg-info :kind :more-context))
134             (vars var)
135             (names-so-far more-context))
136           (let ((var (varify-lambda-arg more-count (names-so-far))))
137             (setf (lambda-var-arg-info var)
138                   (make-arg-info :kind :more-count))
139             (vars var)
140             (names-so-far more-count)))
141
142         (dolist (spec keys)
143           (cond
144            ((atom spec)
145             (let ((var (varify-lambda-arg spec (names-so-far))))
146               (setf (lambda-var-arg-info var)
147                     (make-arg-info :kind :keyword
148                                    :key (make-keyword-for-arg spec
149                                                               (vars)
150                                                               t)))
151               (vars var)
152               (names-so-far spec)))
153            ((atom (first spec))
154             (let* ((name (first spec))
155                    (var (varify-lambda-arg name (names-so-far)))
156                    (info (make-arg-info
157                           :kind :keyword
158                           :key (make-keyword-for-arg name (vars) t))))
159               (setf (lambda-var-arg-info var) info)
160               (vars var)
161               (names-so-far name)
162               (parse-default spec info)))
163            (t
164             (let ((head (first spec)))
165               (unless (proper-list-of-length-p head 2)
166                 (error "malformed &KEY argument specifier: ~S" spec))
167               (let* ((name (second head))
168                      (var (varify-lambda-arg name (names-so-far)))
169                      (info (make-arg-info
170                             :kind :keyword
171                             :key (make-keyword-for-arg (first head)
172                                                        (vars)
173                                                        nil))))
174                 (setf (lambda-var-arg-info var) info)
175                 (vars var)
176                 (names-so-far name)
177                 (parse-default spec info))))))
178
179         (dolist (spec aux)
180           (cond ((atom spec)
181                  (let ((var (varify-lambda-arg spec nil)))
182                    (aux-vars var)
183                    (aux-vals nil)
184                    (names-so-far spec)))
185                 (t
186                  (unless (proper-list-of-length-p spec 1 2)
187                    (compiler-error "malformed &AUX binding specifier: ~S"
188                                    spec))
189                  (let* ((name (first spec))
190                         (var (varify-lambda-arg name nil)))
191                    (aux-vars var)
192                    (aux-vals (second spec))
193                    (names-so-far name)))))
194
195         (values (vars) keyp allowp (aux-vars) (aux-vals))))))
196
197 ;;; This is similar to IR1-CONVERT-PROGN-BODY except that we
198 ;;; sequentially bind each AUX-VAR to the corresponding AUX-VAL before
199 ;;; converting the body. If there are no bindings, just convert the
200 ;;; body, otherwise do one binding and recurse on the rest.
201 ;;;
202 ;;; FIXME: This could and probably should be converted to use
203 ;;; SOURCE-NAME and DEBUG-NAME. But I (WHN) don't use &AUX bindings,
204 ;;; so I'm not motivated. Patches will be accepted...
205 (defun ir1-convert-aux-bindings (start next result body aux-vars aux-vals)
206   (declare (type ctran start next) (type (or lvar null) result)
207            (list body aux-vars aux-vals))
208   (if (null aux-vars)
209       (ir1-convert-progn-body start next result body)
210       (let ((ctran (make-ctran))
211             (fun-lvar (make-lvar))
212             (fun (ir1-convert-lambda-body body
213                                           (list (first aux-vars))
214                                           :aux-vars (rest aux-vars)
215                                           :aux-vals (rest aux-vals)
216                                           :debug-name (debug-namify
217                                                        "&AUX bindings " 
218                                                        aux-vars))))
219         (reference-leaf start ctran fun-lvar fun)
220         (ir1-convert-combination-args fun-lvar ctran next result
221                                       (list (first aux-vals)))))
222   (values))
223
224 ;;; This is similar to IR1-CONVERT-PROGN-BODY except that code to bind
225 ;;; the SPECVAR for each SVAR to the value of the variable is wrapped
226 ;;; around the body. If there are no special bindings, we just convert
227 ;;; the body, otherwise we do one special binding and recurse on the
228 ;;; rest.
229 ;;;
230 ;;; We make a cleanup and introduce it into the lexical
231 ;;; environment. If there are multiple special bindings, the cleanup
232 ;;; for the blocks will end up being the innermost one. We force NEXT
233 ;;; to start a block outside of this cleanup, causing cleanup code to
234 ;;; be emitted when the scope is exited.
235 (defun ir1-convert-special-bindings
236     (start next result body aux-vars aux-vals svars)
237   (declare (type ctran start next) (type (or lvar null) result)
238            (list body aux-vars aux-vals svars))
239   (cond
240    ((null svars)
241     (ir1-convert-aux-bindings start next result body aux-vars aux-vals))
242    (t
243     (ctran-starts-block next)
244     (let ((cleanup (make-cleanup :kind :special-bind))
245           (var (first svars))
246           (bind-ctran (make-ctran))
247           (cleanup-ctran (make-ctran)))
248       (ir1-convert start bind-ctran nil
249                    `(%special-bind ',(lambda-var-specvar var) ,var))
250       (setf (cleanup-mess-up cleanup) (ctran-use bind-ctran))
251       (let ((*lexenv* (make-lexenv :cleanup cleanup)))
252         (ir1-convert bind-ctran cleanup-ctran nil '(%cleanup-point))
253         (ir1-convert-special-bindings cleanup-ctran next result
254                                       body aux-vars aux-vals
255                                       (rest svars))))))
256   (values))
257
258 ;;; Create a lambda node out of some code, returning the result. The
259 ;;; bindings are specified by the list of VAR structures VARS. We deal
260 ;;; with adding the names to the LEXENV-VARS for the conversion. The
261 ;;; result is added to the NEW-FUNCTIONALS in the *CURRENT-COMPONENT*
262 ;;; and linked to the component head and tail.
263 ;;;
264 ;;; We detect special bindings here, replacing the original VAR in the
265 ;;; lambda list with a temporary variable. We then pass a list of the
266 ;;; special vars to IR1-CONVERT-SPECIAL-BINDINGS, which actually emits
267 ;;; the special binding code.
268 ;;;
269 ;;; We ignore any ARG-INFO in the VARS, trusting that someone else is
270 ;;; dealing with &NONSENSE, except for &REST vars with DYNAMIC-EXTENT.
271 ;;;
272 ;;; AUX-VARS is a list of VAR structures for variables that are to be
273 ;;; sequentially bound. Each AUX-VAL is a form that is to be evaluated
274 ;;; to get the initial value for the corresponding AUX-VAR.
275 (defun ir1-convert-lambda-body (body
276                                 vars
277                                 &key
278                                 aux-vars
279                                 aux-vals
280                                 (source-name '.anonymous.)
281                                 debug-name
282                                 (note-lexical-bindings t))
283   (declare (list body vars aux-vars aux-vals))
284
285   ;; We're about to try to put new blocks into *CURRENT-COMPONENT*.
286   (aver-live-component *current-component*)
287
288   (let* ((bind (make-bind))
289          (lambda (make-lambda :vars vars
290                   :bind bind
291                   :%source-name source-name
292                   :%debug-name debug-name))
293          (result-ctran (make-ctran))
294          (result-lvar (make-lvar)))
295
296     (awhen (lexenv-lambda *lexenv*)
297       (push lambda (lambda-children it))
298       (setf (lambda-parent lambda) it))
299
300     ;; just to check: This function should fail internal assertions if
301     ;; we didn't set up a valid debug name above.
302     ;;
303     ;; (In SBCL we try to make everything have a debug name, since we
304     ;; lack the omniscient perspective the original implementors used
305     ;; to decide which things didn't need one.)
306     (functional-debug-name lambda)
307
308     (setf (lambda-home lambda) lambda)
309     (collect ((svars)
310               (new-venv nil cons))
311
312       (dolist (var vars)
313         ;; As far as I can see, LAMBDA-VAR-HOME should never have
314         ;; been set before. Let's make sure. -- WHN 2001-09-29
315         (aver (not (lambda-var-home var)))
316         (setf (lambda-var-home var) lambda)
317         (let ((specvar (lambda-var-specvar var)))
318           (cond (specvar
319                  (svars var)
320                  (new-venv (cons (leaf-source-name specvar) specvar)))
321                 (t
322                  (when note-lexical-bindings
323                    (note-lexical-binding (leaf-source-name var)))
324                  (new-venv (cons (leaf-source-name var) var))))))
325
326       (let ((*lexenv* (make-lexenv :vars (new-venv)
327                                    :lambda lambda
328                                    :cleanup nil)))
329         (setf (bind-lambda bind) lambda)
330         (setf (node-lexenv bind) *lexenv*)
331
332         (let ((block (ctran-starts-block result-ctran)))
333           (let ((return (make-return :result result-lvar :lambda lambda))
334                 (tail-set (make-tail-set :funs (list lambda))))
335             (setf (lambda-tail-set lambda) tail-set)
336             (setf (lambda-return lambda) return)
337             (setf (lvar-dest result-lvar) return)
338             (link-node-to-previous-ctran return result-ctran)
339             (setf (block-last block) return))
340           (link-blocks block (component-tail *current-component*)))
341
342         (with-component-last-block (*current-component*
343                                     (ctran-block result-ctran))
344           (let ((prebind-ctran (make-ctran))
345                 (postbind-ctran (make-ctran)))
346             (ctran-starts-block prebind-ctran)
347             (link-node-to-previous-ctran bind prebind-ctran)
348             (use-ctran bind postbind-ctran)
349             (ir1-convert-special-bindings postbind-ctran result-ctran
350                                           result-lvar body
351                                           aux-vars aux-vals (svars))))))
352
353     (link-blocks (component-head *current-component*) (node-block bind))
354     (push lambda (component-new-functionals *current-component*))
355
356     lambda))
357
358 ;;; Entry point CLAMBDAs have a special kind
359 (defun register-entry-point (entry dispatcher)
360   (declare (type clambda entry)
361            (type optional-dispatch dispatcher))
362   (setf (functional-kind entry) :optional)
363   (setf (leaf-ever-used entry) t)
364   (setf (lambda-optional-dispatch entry) dispatcher)
365   entry)
366
367 ;;; Create the actual entry-point function for an optional entry
368 ;;; point. The lambda binds copies of each of the VARS, then calls FUN
369 ;;; with the argument VALS and the DEFAULTS. Presumably the VALS refer
370 ;;; to the VARS by name. The VALS are passed in the reverse order.
371 ;;;
372 ;;; If any of the copies of the vars are referenced more than once,
373 ;;; then we mark the corresponding var as EVER-USED to inhibit
374 ;;; "defined but not read" warnings for arguments that are only used
375 ;;; by default forms.
376 (defun convert-optional-entry (fun vars vals defaults)
377   (declare (type clambda fun) (list vars vals defaults))
378   (let* ((fvars (reverse vars))
379          (arg-vars (mapcar (lambda (var)
380                              (make-lambda-var
381                               :%source-name (leaf-source-name var)
382                               :type (leaf-type var)
383                               :where-from (leaf-where-from var)
384                               :specvar (lambda-var-specvar var)))
385                            fvars))
386          (fun (collect ((default-bindings)
387                         (default-vals))
388                 (dolist (default defaults)
389                   (if (constantp default)
390                       (default-vals default)
391                       (let ((var (gensym)))
392                         (default-bindings `(,var ,default))
393                         (default-vals var))))
394                 (ir1-convert-lambda-body `((let (,@(default-bindings))
395                                              (%funcall ,fun
396                                                        ,@(reverse vals)
397                                                        ,@(default-vals))))
398                                          arg-vars
399                                          :debug-name
400                                          (debug-namify "&OPTIONAL processor "
401                                                        (gensym))
402                                          :note-lexical-bindings nil))))
403     (mapc (lambda (var arg-var)
404             (when (cdr (leaf-refs arg-var))
405               (setf (leaf-ever-used var) t)))
406           fvars arg-vars)
407     fun))
408
409 ;;; This function deals with supplied-p vars in optional arguments. If
410 ;;; the there is no supplied-p arg, then we just call
411 ;;; IR1-CONVERT-HAIRY-ARGS on the remaining arguments, and generate a
412 ;;; optional entry that calls the result. If there is a supplied-p
413 ;;; var, then we add it into the default vars and throw a T into the
414 ;;; entry values. The resulting entry point function is returned.
415 (defun generate-optional-default-entry (res default-vars default-vals
416                                         entry-vars entry-vals
417                                         vars supplied-p-p body
418                                         aux-vars aux-vals
419                                         source-name debug-name
420                                         force)
421   (declare (type optional-dispatch res)
422            (list default-vars default-vals entry-vars entry-vals vars body
423                  aux-vars aux-vals))
424   (let* ((arg (first vars))
425          (arg-name (leaf-source-name arg))
426          (info (lambda-var-arg-info arg))
427          (default (arg-info-default info))
428          (supplied-p (arg-info-supplied-p info))
429          (force (or force
430                     (not (sb!xc:constantp (arg-info-default info)))))
431          (ep (if supplied-p
432                  (ir1-convert-hairy-args
433                   res
434                   (list* supplied-p arg default-vars)
435                   (list* (leaf-source-name supplied-p) arg-name default-vals)
436                   (cons arg entry-vars)
437                   (list* t arg-name entry-vals)
438                   (rest vars) t body aux-vars aux-vals
439                   source-name debug-name
440                   force)
441                  (ir1-convert-hairy-args
442                   res
443                   (cons arg default-vars)
444                   (cons arg-name default-vals)
445                   (cons arg entry-vars)
446                   (cons arg-name entry-vals)
447                   (rest vars) supplied-p-p body aux-vars aux-vals
448                   source-name debug-name
449                   force))))
450
451     ;; We want to delay converting the entry, but there exist
452     ;; problems: hidden references should not be established to
453     ;; lambdas of kind NIL should not have (otherwise the compiler
454     ;; might let-convert or delete them) and to variables.
455     (if (or force
456             supplied-p-p ; this entry will be of kind NIL
457             (and (lambda-p ep) (eq (lambda-kind ep) nil)))
458         (convert-optional-entry ep
459                                 default-vars default-vals
460                                 (if supplied-p
461                                     (list default nil)
462                                     (list default)))
463         (delay
464          (register-entry-point
465            (convert-optional-entry (force ep)
466                                    default-vars default-vals
467                                    (if supplied-p
468                                        (list default nil)
469                                        (list default)))
470            res)))))
471
472 ;;; Create the MORE-ENTRY function for the OPTIONAL-DISPATCH RES.
473 ;;; ENTRY-VARS and ENTRY-VALS describe the fixed arguments. REST is
474 ;;; the var for any &REST arg. KEYS is a list of the &KEY arg vars.
475 ;;;
476 ;;; The most interesting thing that we do is parse keywords. We create
477 ;;; a bunch of temporary variables to hold the result of the parse,
478 ;;; and then loop over the supplied arguments, setting the appropriate
479 ;;; temps for the supplied keyword. Note that it is significant that
480 ;;; we iterate over the keywords in reverse order --- this implements
481 ;;; the CL requirement that (when a keyword appears more than once)
482 ;;; the first value is used.
483 ;;;
484 ;;; If there is no supplied-p var, then we initialize the temp to the
485 ;;; default and just pass the temp into the main entry. Since
486 ;;; non-constant &KEY args are forcibly given a supplied-p var, we
487 ;;; know that the default is constant, and thus safe to evaluate out
488 ;;; of order.
489 ;;;
490 ;;; If there is a supplied-p var, then we create temps for both the
491 ;;; value and the supplied-p, and pass them into the main entry,
492 ;;; letting it worry about defaulting.
493 ;;;
494 ;;; We deal with :ALLOW-OTHER-KEYS by delaying unknown keyword errors
495 ;;; until we have scanned all the keywords.
496 (defun convert-more-entry (res entry-vars entry-vals rest morep keys)
497   (declare (type optional-dispatch res) (list entry-vars entry-vals keys))
498   (collect ((arg-vars)
499             (arg-vals (reverse entry-vals))
500             (temps)
501             (body))
502
503     (dolist (var (reverse entry-vars))
504       (arg-vars (make-lambda-var :%source-name (leaf-source-name var)
505                                  :type (leaf-type var)
506                                  :where-from (leaf-where-from var))))
507
508     (let* ((n-context (gensym "N-CONTEXT-"))
509            (context-temp (make-lambda-var :%source-name n-context))
510            (n-count (gensym "N-COUNT-"))
511            (count-temp (make-lambda-var :%source-name n-count
512                                         :type (specifier-type 'index))))
513
514       (arg-vars context-temp count-temp)
515
516       (when rest
517         (arg-vals `(%listify-rest-args
518                     ,n-context ,n-count)))
519       (when morep
520         (arg-vals n-context)
521         (arg-vals n-count))
522
523       (when (optional-dispatch-keyp res)
524         (let ((n-index (gensym "N-INDEX-"))
525               (n-key (gensym "N-KEY-"))
526               (n-value-temp (gensym "N-VALUE-TEMP-"))
527               (n-allowp (gensym "N-ALLOWP-"))
528               (n-losep (gensym "N-LOSEP-"))
529               (allowp (or (optional-dispatch-allowp res)
530                           (policy *lexenv* (zerop safety))))
531               (found-allow-p nil))
532
533           (temps `(,n-index (1- ,n-count)) n-key n-value-temp)
534           (body `(declare (fixnum ,n-index) (ignorable ,n-key ,n-value-temp)))
535
536           (collect ((tests))
537             (dolist (key keys)
538               (let* ((info (lambda-var-arg-info key))
539                      (default (arg-info-default info))
540                      (keyword (arg-info-key info))
541                      (supplied-p (arg-info-supplied-p info))
542                      (n-value (gensym "N-VALUE-"))
543                      (clause (cond (supplied-p
544                                     (let ((n-supplied (gensym "N-SUPPLIED-")))
545                                       (temps n-supplied)
546                                       (arg-vals n-value n-supplied)
547                                       `((eq ,n-key ',keyword)
548                                         (setq ,n-supplied t)
549                                         (setq ,n-value ,n-value-temp))))
550                                    (t
551                                     (arg-vals n-value)
552                                     `((eq ,n-key ',keyword)
553                                       (setq ,n-value ,n-value-temp))))))
554                 (when (and (not allowp) (eq keyword :allow-other-keys))
555                   (setq found-allow-p t)
556                   (setq clause
557                         (append clause `((setq ,n-allowp ,n-value-temp)))))
558
559                 (temps `(,n-value ,default))
560                 (tests clause)))
561
562             (unless allowp
563               (temps n-allowp n-losep)
564               (unless found-allow-p
565                 (tests `((eq ,n-key :allow-other-keys)
566                          (setq ,n-allowp ,n-value-temp))))
567               (tests `(t
568                        (setq ,n-losep (list ,n-key)))))
569
570             (body
571              `(when (oddp ,n-count)
572                 (%odd-key-args-error)))
573
574             (body
575              `(locally
576                 (declare (optimize (safety 0)))
577                 (loop
578                   (when (minusp ,n-index) (return))
579                   (setf ,n-value-temp (%more-arg ,n-context ,n-index))
580                   (decf ,n-index)
581                   (setq ,n-key (%more-arg ,n-context ,n-index))
582                   (decf ,n-index)
583                   (cond ,@(tests)))))
584
585             (unless allowp
586               (body `(when (and ,n-losep (not ,n-allowp))
587                        (%unknown-key-arg-error (car ,n-losep))))))))
588
589       (let ((ep (ir1-convert-lambda-body
590                  `((let ,(temps)
591                      ,@(body)
592                      (%funcall ,(optional-dispatch-main-entry res)
593                                ,@(arg-vals))))
594                  (arg-vars)
595                  :debug-name "&MORE processing"
596                  :note-lexical-bindings nil)))
597         (setf (optional-dispatch-more-entry res)
598               (register-entry-point ep res)))))
599
600   (values))
601
602 ;;; This is called by IR1-CONVERT-HAIRY-ARGS when we run into a &REST
603 ;;; or &KEY arg. The arguments are similar to that function, but we
604 ;;; split off any &REST arg and pass it in separately. REST is the
605 ;;; &REST arg var, or NIL if there is no &REST arg. KEYS is a list of
606 ;;; the &KEY argument vars.
607 ;;;
608 ;;; When there are &KEY arguments, we introduce temporary gensym
609 ;;; variables to hold the values while keyword defaulting is in
610 ;;; progress to get the required sequential binding semantics.
611 ;;;
612 ;;; This gets interesting mainly when there are &KEY arguments with
613 ;;; supplied-p vars or non-constant defaults. In either case, pass in
614 ;;; a supplied-p var. If the default is non-constant, we introduce an
615 ;;; IF in the main entry that tests the supplied-p var and decides
616 ;;; whether to evaluate the default or not. In this case, the real
617 ;;; incoming value is NIL, so we must union NULL with the declared
618 ;;; type when computing the type for the main entry's argument.
619 (defun ir1-convert-more (res default-vars default-vals entry-vars entry-vals
620                              rest more-context more-count keys supplied-p-p
621                              body aux-vars aux-vals
622                              source-name debug-name)
623   (declare (type optional-dispatch res)
624            (list default-vars default-vals entry-vars entry-vals keys body
625                  aux-vars aux-vals))
626   (collect ((main-vars (reverse default-vars))
627             (main-vals default-vals cons)
628             (bind-vars)
629             (bind-vals))
630     (when rest
631       (main-vars rest)
632       (main-vals '()))
633     (when more-context
634       (main-vars more-context)
635       (main-vals nil)
636       (main-vars more-count)
637       (main-vals 0))
638
639     (dolist (key keys)
640       (let* ((info (lambda-var-arg-info key))
641              (default (arg-info-default info))
642              (hairy-default (not (sb!xc:constantp default)))
643              (supplied-p (arg-info-supplied-p info))
644              (n-val (make-symbol (format nil
645                                          "~A-DEFAULTING-TEMP"
646                                          (leaf-source-name key))))
647              (key-type (leaf-type key))
648              (val-temp (make-lambda-var
649                         :%source-name n-val
650                         :type (if hairy-default
651                                   (type-union key-type (specifier-type 'null))
652                                   key-type))))
653         (main-vars val-temp)
654         (bind-vars key)
655         (cond ((or hairy-default supplied-p)
656                (let* ((n-supplied (gensym "N-SUPPLIED-"))
657                       (supplied-temp (make-lambda-var
658                                       :%source-name n-supplied)))
659                  (unless supplied-p
660                    (setf (arg-info-supplied-p info) supplied-temp))
661                  (when hairy-default
662                    (setf (arg-info-default info) nil))
663                  (main-vars supplied-temp)
664                  (cond (hairy-default
665                         (main-vals nil nil)
666                         (bind-vals `(if ,n-supplied ,n-val ,default)))
667                        (t
668                         (main-vals default nil)
669                         (bind-vals n-val)))
670                  (when supplied-p
671                    (bind-vars supplied-p)
672                    (bind-vals n-supplied))))
673               (t
674                (main-vals (arg-info-default info))
675                (bind-vals n-val)))))
676
677     (let* ((main-entry (ir1-convert-lambda-body
678                         body (main-vars)
679                         :aux-vars (append (bind-vars) aux-vars)
680                         :aux-vals (append (bind-vals) aux-vals)
681                         :debug-name (debug-namify
682                                      "varargs entry for " source-name debug-name)))
683            (last-entry (convert-optional-entry main-entry default-vars
684                                                (main-vals) ())))
685       (setf (optional-dispatch-main-entry res)
686             (register-entry-point main-entry res))
687       (convert-more-entry res entry-vars entry-vals rest more-context keys)
688
689       (push (register-entry-point
690              (if supplied-p-p
691                 (convert-optional-entry last-entry entry-vars entry-vals ())
692                 last-entry)
693              res)
694             (optional-dispatch-entry-points res))
695       last-entry)))
696
697 ;;; This function generates the entry point functions for the
698 ;;; OPTIONAL-DISPATCH RES. We accomplish this by recursion on the list
699 ;;; of arguments, analyzing the arglist on the way down and generating
700 ;;; entry points on the way up.
701 ;;;
702 ;;; DEFAULT-VARS is a reversed list of all the argument vars processed
703 ;;; so far, including supplied-p vars. DEFAULT-VALS is a list of the
704 ;;; names of the DEFAULT-VARS.
705 ;;;
706 ;;; ENTRY-VARS is a reversed list of processed argument vars,
707 ;;; excluding supplied-p vars. ENTRY-VALS is a list things that can be
708 ;;; evaluated to get the values for all the vars from the ENTRY-VARS.
709 ;;; It has the var name for each required or optional arg, and has T
710 ;;; for each supplied-p arg.
711 ;;;
712 ;;; VARS is a list of the LAMBDA-VAR structures for arguments that
713 ;;; haven't been processed yet. SUPPLIED-P-P is true if a supplied-p
714 ;;; argument has already been processed; only in this case are the
715 ;;; DEFAULT-XXX and ENTRY-XXX different.
716 ;;;
717 ;;; The result at each point is a lambda which should be called by the
718 ;;; above level to default the remaining arguments and evaluate the
719 ;;; body. We cause the body to be evaluated by converting it and
720 ;;; returning it as the result when the recursion bottoms out.
721 ;;;
722 ;;; Each level in the recursion also adds its entry point function to
723 ;;; the result OPTIONAL-DISPATCH. For most arguments, the defaulting
724 ;;; function and the entry point function will be the same, but when
725 ;;; SUPPLIED-P args are present they may be different.
726 ;;;
727 ;;; When we run into a &REST or &KEY arg, we punt out to
728 ;;; IR1-CONVERT-MORE, which finishes for us in this case.
729 (defun ir1-convert-hairy-args (res default-vars default-vals
730                                entry-vars entry-vals
731                                vars supplied-p-p body aux-vars
732                                aux-vals
733                                source-name debug-name
734                                force)
735   (declare (type optional-dispatch res)
736            (list default-vars default-vals entry-vars entry-vals vars body
737                  aux-vars aux-vals))
738   (cond ((not vars)
739          (if (optional-dispatch-keyp res)
740              ;; Handle &KEY with no keys...
741              (ir1-convert-more res default-vars default-vals
742                                entry-vars entry-vals
743                                nil nil nil vars supplied-p-p body aux-vars
744                                aux-vals source-name debug-name)
745              (let ((fun (ir1-convert-lambda-body
746                          body (reverse default-vars)
747                          :aux-vars aux-vars
748                          :aux-vals aux-vals
749                          :debug-name (debug-namify
750                                       "hairy arg processor for "
751                                       source-name
752                                       debug-name))))
753                (setf (optional-dispatch-main-entry res) fun)
754                (register-entry-point fun res)
755                (push (if supplied-p-p
756                          (register-entry-point
757                           (convert-optional-entry fun entry-vars entry-vals ())
758                           res)
759                           fun)
760                      (optional-dispatch-entry-points res))
761                fun)))
762         ((not (lambda-var-arg-info (first vars)))
763          (let* ((arg (first vars))
764                 (nvars (cons arg default-vars))
765                 (nvals (cons (leaf-source-name arg) default-vals)))
766            (ir1-convert-hairy-args res nvars nvals nvars nvals
767                                    (rest vars) nil body aux-vars aux-vals
768                                    source-name debug-name
769                                    nil)))
770         (t
771          (let* ((arg (first vars))
772                 (info (lambda-var-arg-info arg))
773                 (kind (arg-info-kind info)))
774            (ecase kind
775              (:optional
776               (let ((ep (generate-optional-default-entry
777                          res default-vars default-vals
778                          entry-vars entry-vals vars supplied-p-p body
779                          aux-vars aux-vals
780                          source-name debug-name
781                          force)))
782                 ;; See GENERATE-OPTIONAL-DEFAULT-ENTRY.
783                 (push (if (lambda-p ep)
784                           (register-entry-point
785                            (if supplied-p-p
786                                (convert-optional-entry ep entry-vars entry-vals ())
787                                ep)
788                            res)
789                           (progn (aver (not supplied-p-p))
790                                  ep))
791                       (optional-dispatch-entry-points res))
792                 ep))
793              (:rest
794               (ir1-convert-more res default-vars default-vals
795                                 entry-vars entry-vals
796                                 arg nil nil (rest vars) supplied-p-p body
797                                 aux-vars aux-vals
798                                 source-name debug-name))
799              (:more-context
800               (ir1-convert-more res default-vars default-vals
801                                 entry-vars entry-vals
802                                 nil arg (second vars) (cddr vars) supplied-p-p
803                                 body aux-vars aux-vals
804                                 source-name debug-name))
805              (:keyword
806               (ir1-convert-more res default-vars default-vals
807                                 entry-vars entry-vals
808                                 nil nil nil vars supplied-p-p body aux-vars
809                                 aux-vals source-name debug-name)))))))
810
811 ;;; This function deals with the case where we have to make an
812 ;;; OPTIONAL-DISPATCH to represent a LAMBDA. We cons up the result and
813 ;;; call IR1-CONVERT-HAIRY-ARGS to do the work. When it is done, we
814 ;;; figure out the MIN-ARGS and MAX-ARGS.
815 (defun ir1-convert-hairy-lambda (body vars keyp allowp aux-vars aux-vals
816                                       &key
817                                       (source-name '.anonymous.)
818                                       (debug-name (debug-namify
819                                                    "OPTIONAL-DISPATCH "
820                                                    vars)))
821   (declare (list body vars aux-vars aux-vals))
822   (let ((res (make-optional-dispatch :arglist vars
823                                      :allowp allowp
824                                      :keyp keyp
825                                      :%source-name source-name
826                                      :%debug-name debug-name
827                                      :plist `(:ir1-environment
828                                               (,*lexenv*
829                                                ,*current-path*))))
830         (min (or (position-if #'lambda-var-arg-info vars) (length vars))))
831     (aver-live-component *current-component*)
832     (push res (component-new-functionals *current-component*))
833     (ir1-convert-hairy-args res () () () () vars nil body aux-vars aux-vals
834                             source-name debug-name nil)
835     (setf (optional-dispatch-min-args res) min)
836     (setf (optional-dispatch-max-args res)
837           (+ (1- (length (optional-dispatch-entry-points res))) min))
838
839     res))
840
841 ;;; Convert a LAMBDA form into a LAMBDA leaf or an OPTIONAL-DISPATCH leaf.
842 (defun ir1-convert-lambda (form &key (source-name '.anonymous.)
843                            debug-name
844                            allow-debug-catch-tag)
845
846   (unless (consp form)
847     (compiler-error "A ~S was found when expecting a lambda expression:~%  ~S"
848                     (type-of form)
849                     form))
850   (unless (eq (car form) 'lambda)
851     (compiler-error "~S was expected but ~S was found:~%  ~S"
852                     'lambda
853                     (car form)
854                     form))
855   (unless (and (consp (cdr form)) (listp (cadr form)))
856     (compiler-error
857      "The lambda expression has a missing or non-list lambda list:~%  ~S"
858      form))
859
860   (let ((*allow-debug-catch-tag* (and *allow-debug-catch-tag* allow-debug-catch-tag)))
861     (multiple-value-bind (vars keyp allow-other-keys aux-vars aux-vals)
862         (make-lambda-vars (cadr form))
863       (multiple-value-bind (forms decls) (parse-body (cddr form))
864         (binding* (((*lexenv* result-type)
865                     (process-decls decls (append aux-vars vars) nil))
866                    (forms (if (and *allow-debug-catch-tag*
867                                    (policy *lexenv* (>= insert-debug-catch 2)))
868                               `((catch (make-symbol "SB-DEBUG-CATCH-TAG")
869                                   ,@forms))
870                               forms))
871                    (forms (if (eq result-type *wild-type*)
872                               forms
873                               `((the ,result-type (progn ,@forms)))))
874                    (res (if (or (find-if #'lambda-var-arg-info vars) keyp)
875                             (ir1-convert-hairy-lambda forms vars keyp
876                                                       allow-other-keys
877                                                       aux-vars aux-vals
878                                                       :source-name source-name
879                                                       :debug-name debug-name)
880                             (ir1-convert-lambda-body forms vars
881                                                      :aux-vars aux-vars
882                                                      :aux-vals aux-vals
883                                                      :source-name source-name
884                                                      :debug-name debug-name))))
885           (setf (functional-inline-expansion res) form)
886           (setf (functional-arg-documentation res) (cadr form))
887           res)))))
888
889 ;;; helper for LAMBDA-like things, to massage them into a form
890 ;;; suitable for IR1-CONVERT-LAMBDA.
891 ;;;
892 ;;; KLUDGE: We cons up a &REST list here, maybe for no particularly
893 ;;; good reason.  It's probably lost in the noise of all the other
894 ;;; consing, but it's still inelegant.  And we force our called
895 ;;; functions to do full runtime keyword parsing, ugh.  -- CSR,
896 ;;; 2003-01-25
897 (defun ir1-convert-lambdalike (thing &rest args
898                                &key (source-name '.anonymous.)
899                                debug-name allow-debug-catch-tag)
900   (declare (ignorable source-name debug-name allow-debug-catch-tag))
901   (ecase (car thing)
902     ((lambda) (apply #'ir1-convert-lambda thing args))
903     ((instance-lambda)
904      (let ((res (apply #'ir1-convert-lambda
905                        `(lambda ,@(cdr thing)) args)))
906        (setf (getf (functional-plist res) :fin-function) t)
907        res))
908     ((named-lambda)
909      (let ((name (cadr thing)))
910        (if (legal-fun-name-p name)
911            (let ((defined-fun-res (get-defined-fun name))
912                  (res (apply #'ir1-convert-lambda `(lambda ,@(cddr thing))
913                              :source-name name
914                              :debug-name nil
915                              args)))
916              (assert-global-function-definition-type name res)
917              (setf (defined-fun-functional defined-fun-res)
918                    res)
919              (unless (eq (defined-fun-inlinep defined-fun-res) :notinline)
920                (substitute-leaf-if
921                 (lambda (ref)
922                   (policy ref (> recognize-self-calls 0)))
923                 res defined-fun-res))
924              res)
925            (apply #'ir1-convert-lambda `(lambda ,@(cddr thing))
926                   :debug-name name args))))
927     ((lambda-with-lexenv) (apply #'ir1-convert-inline-lambda thing args))))
928 \f
929 ;;;; defining global functions
930
931 ;;; Convert FUN as a lambda in the null environment, but use the
932 ;;; current compilation policy. Note that FUN may be a
933 ;;; LAMBDA-WITH-LEXENV, so we may have to augment the environment to
934 ;;; reflect the state at the definition site.
935 (defun ir1-convert-inline-lambda (fun &key
936                                       (source-name '.anonymous.)
937                                       debug-name
938                                       allow-debug-catch-tag)
939   (declare (ignore allow-debug-catch-tag))
940   (destructuring-bind (decls macros symbol-macros &rest body)
941                       (if (eq (car fun) 'lambda-with-lexenv)
942                           (cdr fun)
943                           `(() () () . ,(cdr fun)))
944     (let ((*lexenv* (make-lexenv
945                      :default (process-decls decls nil nil
946                                              (make-null-lexenv))
947                      :vars (copy-list symbol-macros)
948                      :funs (mapcar (lambda (x)
949                                      `(,(car x) .
950                                        (macro . ,(coerce (cdr x) 'function))))
951                                    macros)
952                      :policy (lexenv-policy *lexenv*))))
953       (ir1-convert-lambda `(lambda ,@body)
954                           :source-name source-name
955                           :debug-name debug-name
956                           :allow-debug-catch-tag nil))))
957
958 ;;; Get a DEFINED-FUN object for a function we are about to define. If
959 ;;; the function has been forward referenced, then substitute for the
960 ;;; previous references.
961 (defun get-defined-fun (name)
962   (proclaim-as-fun-name name)
963   (let ((found (find-free-fun name "shouldn't happen! (defined-fun)")))
964     (note-name-defined name :function)
965     (cond ((not (defined-fun-p found))
966            (aver (not (info :function :inlinep name)))
967            (let* ((where-from (leaf-where-from found))
968                   (res (make-defined-fun
969                         :%source-name name
970                         :where-from (if (eq where-from :declared)
971                                         :declared :defined)
972                         :type (leaf-type found))))
973              (substitute-leaf res found)
974              (setf (gethash name *free-funs*) res)))
975           ;; If *FREE-FUNS* has a previously converted definition
976           ;; for this name, then blow it away and try again.
977           ((defined-fun-functional found)
978            (remhash name *free-funs*)
979            (get-defined-fun name))
980           (t found))))
981
982 ;;; Check a new global function definition for consistency with
983 ;;; previous declaration or definition, and assert argument/result
984 ;;; types if appropriate. This assertion is suppressed by the
985 ;;; EXPLICIT-CHECK attribute, which is specified on functions that
986 ;;; check their argument types as a consequence of type dispatching.
987 ;;; This avoids redundant checks such as NUMBERP on the args to +, etc.
988 (defun assert-new-definition (var fun)
989   (let ((type (leaf-type var))
990         (for-real (eq (leaf-where-from var) :declared))
991         (info (info :function :info (leaf-source-name var))))
992     (assert-definition-type
993      fun type
994      ;; KLUDGE: Common Lisp is such a dynamic language that in general
995      ;; all we can do here in general is issue a STYLE-WARNING. It
996      ;; would be nice to issue a full WARNING in the special case of
997      ;; of type mismatches within a compilation unit (as in section
998      ;; 3.2.2.3 of the spec) but at least as of sbcl-0.6.11, we don't
999      ;; keep track of whether the mismatched data came from the same
1000      ;; compilation unit, so we can't do that. -- WHN 2001-02-11
1001      :lossage-fun #'compiler-style-warn
1002      :unwinnage-fun (cond (info #'compiler-style-warn)
1003                           (for-real #'compiler-notify)
1004                           (t nil))
1005      :really-assert
1006      (and for-real
1007           (not (and info
1008                     (ir1-attributep (fun-info-attributes info)
1009                                     explicit-check))))
1010      :where (if for-real
1011                 "previous declaration"
1012                 "previous definition"))))
1013
1014 ;;; Convert a lambda doing all the basic stuff we would do if we were
1015 ;;; converting a DEFUN. In the old CMU CL system, this was used both
1016 ;;; by the %DEFUN translator and for global inline expansion, but
1017 ;;; since sbcl-0.pre7.something %DEFUN does things differently.
1018 ;;; FIXME: And now it's probably worth rethinking whether this
1019 ;;; function is a good idea.
1020 ;;;
1021 ;;; Unless a :INLINE function, we temporarily clobber the inline
1022 ;;; expansion. This prevents recursive inline expansion of
1023 ;;; opportunistic pseudo-inlines.
1024 (defun ir1-convert-lambda-for-defun (lambda var expansion converter)
1025   (declare (cons lambda) (function converter) (type defined-fun var))
1026   (let ((var-expansion (defined-fun-inline-expansion var)))
1027     (unless (eq (defined-fun-inlinep var) :inline)
1028       (setf (defined-fun-inline-expansion var) nil))
1029     (let* ((name (leaf-source-name var))
1030            (fun (funcall converter lambda
1031                          :source-name name))
1032            (fun-info (info :function :info name)))
1033       (setf (functional-inlinep fun) (defined-fun-inlinep var))
1034       (assert-new-definition var fun)
1035       (setf (defined-fun-inline-expansion var) var-expansion)
1036       ;; If definitely not an interpreter stub, then substitute for
1037       ;; any old references.
1038       (unless (or (eq (defined-fun-inlinep var) :notinline)
1039                   (not *block-compile*)
1040                   (and fun-info
1041                        (or (fun-info-transforms fun-info)
1042                            (fun-info-templates fun-info)
1043                            (fun-info-ir2-convert fun-info))))
1044         (substitute-leaf fun var)
1045         ;; If in a simple environment, then we can allow backward
1046         ;; references to this function from following top level forms.
1047         (when expansion (setf (defined-fun-functional var) fun)))
1048       fun)))
1049
1050 ;;; the even-at-compile-time part of DEFUN
1051 ;;;
1052 ;;; The INLINE-EXPANSION is a LAMBDA-WITH-LEXENV, or NIL if there is
1053 ;;; no inline expansion.
1054 (defun %compiler-defun (name lambda-with-lexenv compile-toplevel)
1055
1056   (let ((defined-fun nil)) ; will be set below if we're in the compiler
1057
1058     (when compile-toplevel
1059       ;; better be in the compiler
1060       (aver (boundp '*lexenv*)) 
1061       (when sb!xc:*compile-print*
1062         (compiler-mumble "~&; recognizing DEFUN ~S~%" name))
1063       (remhash name *free-funs*)
1064       (setf defined-fun (get-defined-fun name))
1065
1066       (aver (fasl-output-p *compile-object*))
1067       (if (member name *fun-names-in-this-file* :test #'equal)
1068           (warn 'duplicate-definition :name name)
1069           (push name *fun-names-in-this-file*)))
1070
1071     (become-defined-fun-name name)
1072     
1073     (cond (lambda-with-lexenv
1074            (setf (info :function :inline-expansion-designator name)
1075                  lambda-with-lexenv)
1076            (when defined-fun
1077              (setf (defined-fun-inline-expansion defined-fun)
1078                    lambda-with-lexenv)))
1079           (t
1080            (clear-info :function :inline-expansion-designator name)))
1081
1082     ;; old CMU CL comment:
1083     ;;   If there is a type from a previous definition, blast it,
1084     ;;   since it is obsolete.
1085     (when (and defined-fun
1086                (eq (leaf-where-from defined-fun) :defined))
1087       (setf (leaf-type defined-fun)
1088             ;; FIXME: If this is a block compilation thing, shouldn't
1089             ;; we be setting the type to the full derived type for the
1090             ;; definition, instead of this most general function type?
1091             (specifier-type 'function))))
1092
1093   (values))
1094
1095 \f
1096 ;;; Entry point utilities
1097
1098 ;;; Return a function for the Nth entry point.
1099 (defun optional-dispatch-entry-point-fun (dispatcher n)
1100   (declare (type optional-dispatch dispatcher)
1101            (type unsigned-byte n))
1102   (let* ((env (getf (optional-dispatch-plist dispatcher) :ir1-environment))
1103          (*lexenv* (first env))
1104          (*current-path* (second env)))
1105     (force (nth n (optional-dispatch-entry-points dispatcher)))))