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