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