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