b8a9ddd39497c6541705fabe7cd6fc42542bbfae
[sbcl.git] / src / code / defboot.lisp
1 ;;;; bootstrapping fundamental machinery (e.g. DEFUN, DEFCONSTANT,
2 ;;;; DEFVAR) from special forms and primitive functions
3 ;;;;
4 ;;;; KLUDGE: The bootstrapping aspect of this is now obsolete. It was
5 ;;;; originally intended that this file file would be loaded into a
6 ;;;; Lisp image which had Common Lisp primitives defined, and DEFMACRO
7 ;;;; defined, and little else. Since then that approach has been
8 ;;;; dropped and this file has been modified somewhat to make it work
9 ;;;; more cleanly when used to predefine macros at
10 ;;;; build-the-cross-compiler time.
11
12 ;;;; This software is part of the SBCL system. See the README file for
13 ;;;; more information.
14 ;;;;
15 ;;;; This software is derived from the CMU CL system, which was
16 ;;;; written at Carnegie Mellon University and released into the
17 ;;;; public domain. The software is in the public domain and is
18 ;;;; provided with absolutely no warranty. See the COPYING and CREDITS
19 ;;;; files for more information.
20
21 (in-package "SB!IMPL")
22 \f
23 ;;;; IN-PACKAGE
24
25 (defmacro-mundanely in-package (package-designator)
26   `(eval-when (:compile-toplevel :load-toplevel :execute)
27      (setq *package* (find-undeleted-package-or-lose ',package-designator))))
28 \f
29 ;;;; MULTIPLE-VALUE-FOO
30
31 (defun list-of-symbols-p (x)
32   (and (listp x)
33        (every #'symbolp x)))
34
35 (defmacro-mundanely multiple-value-bind (vars value-form &body body)
36   (if (list-of-symbols-p vars)
37     ;; It's unclear why it would be important to special-case the LENGTH=1 case
38     ;; at this level, but the CMU CL code did it, so.. -- WHN 19990411
39     (if (= (length vars) 1)
40       `(let ((,(car vars) ,value-form))
41          ,@body)
42       (let ((ignore (gensym)))
43         `(multiple-value-call #'(lambda (&optional ,@vars &rest ,ignore)
44                                   (declare (ignore ,ignore))
45                                   ,@body)
46                               ,value-form)))
47     (error "Vars is not a list of symbols: ~S" vars)))
48
49 (defmacro-mundanely multiple-value-setq (vars value-form)
50   (cond ((null vars)
51          ;; The ANSI spec says that the primary value of VALUE-FORM must be
52          ;; returned. The general-case-handling code below doesn't do this
53          ;; correctly in the special case when there are no vars bound, so we
54          ;; handle this special case separately here.
55          (let ((g (gensym)))
56            `(multiple-value-bind (,g) ,value-form
57               ,g)))
58         ((list-of-symbols-p vars)
59          (let ((temps (make-gensym-list (length vars))))
60            `(multiple-value-bind ,temps ,value-form
61               ,@(mapcar #'(lambda (var temp)
62                             `(setq ,var ,temp))
63                         vars temps)
64               ,(car temps))))
65         (t (error "Vars is not a list of symbols: ~S" vars))))
66
67 (defmacro-mundanely multiple-value-list (value-form)
68   `(multiple-value-call #'list ,value-form))
69 \f
70 ;;;; various conditional constructs
71
72 ;;; COND defined in terms of IF
73 (defmacro-mundanely cond (&rest clauses)
74   (if (endp clauses)
75     nil
76     (let ((clause (first clauses)))
77       (if (atom clause)
78         (error "Cond clause is not a list: ~S" clause)
79         (let ((test (first clause))
80               (forms (rest clause)))
81           (if (endp forms)
82             (let ((n-result (gensym)))
83               `(let ((,n-result ,test))
84                  (if ,n-result
85                    ,n-result
86                    (cond ,@(rest clauses)))))
87             `(if ,test
88                (progn ,@forms)
89                (cond ,@(rest clauses)))))))))
90
91 ;;; other things defined in terms of COND
92 (defmacro-mundanely when (test &body forms)
93   #!+sb-doc
94   "If the first argument is true, the rest of the forms are
95   evaluated as a PROGN."
96   `(cond (,test nil ,@forms)))
97 (defmacro-mundanely unless (test &body forms)
98   #!+sb-doc
99   "If the first argument is not true, the rest of the forms are
100   evaluated as a PROGN."
101   `(cond ((not ,test) nil ,@forms)))
102 (defmacro-mundanely and (&rest forms)
103   (cond ((endp forms) t)
104         ((endp (rest forms)) (first forms))
105         (t
106          `(if ,(first forms)
107               (and ,@(rest forms))
108               nil))))
109 (defmacro-mundanely or (&rest forms)
110   (cond ((endp forms) nil)
111         ((endp (rest forms)) (first forms))
112         (t
113          (let ((n-result (gensym)))
114            `(let ((,n-result ,(first forms)))
115               (if ,n-result
116                   ,n-result
117                   (or ,@(rest forms))))))))
118 \f
119 ;;;; various sequencing constructs
120
121 (defmacro-mundanely prog (varlist &body body-decls)
122   (multiple-value-bind (body decls) (parse-body body-decls nil)
123     `(block nil
124        (let ,varlist
125          ,@decls
126          (tagbody ,@body)))))
127
128 (defmacro-mundanely prog* (varlist &body body-decls)
129   (multiple-value-bind (body decls) (parse-body body-decls nil)
130     `(block nil
131        (let* ,varlist
132          ,@decls
133          (tagbody ,@body)))))
134
135 (defmacro-mundanely prog1 (result &body body)
136   (let ((n-result (gensym)))
137     `(let ((,n-result ,result))
138        ,@body
139        ,n-result)))
140
141 (defmacro-mundanely prog2 (form1 result &body body)
142   `(prog1 (progn ,form1 ,result) ,@body))
143 \f
144 ;;;; DEFUN
145
146 ;;; Should we save the inline expansion of the function named NAME?
147 (defun inline-fun-name-p (name)
148   (or
149    ;; the normal reason for saving the inline expansion
150    (info :function :inlinep name)
151    ;; another reason for saving the inline expansion: If the
152    ;; ANSI-recommended idiom
153    ;;   (DECLAIM (INLINE FOO))
154    ;;   (DEFUN FOO ..)
155    ;;   (DECLAIM (NOTINLINE FOO))
156    ;; has been used, and then we later do another
157    ;;   (DEFUN FOO ..)
158    ;; without a preceding
159    ;;   (DECLAIM (INLINE FOO))
160    ;; what should we do with the old inline expansion when we see the
161    ;; new DEFUN? Overwriting it with the new definition seems like
162    ;; the only unsurprising choice.
163    (info :function :inline-expansion-designator name)))
164
165 ;;; Now that we have the definition of MULTIPLE-VALUE-BIND, we can
166 ;;; make a reasonably readable definition of DEFUN.
167 (defmacro-mundanely defun (&environment env name args &body body)
168   "Define a function at top level."
169   #+sb-xc-host
170   (unless (symbol-package (fun-name-block-name name))
171     (warn "DEFUN of uninterned symbol ~S (tricky for GENESIS)" name))
172   (multiple-value-bind (forms decls doc) (parse-body body)
173     (let* ((lambda `(lambda ,args
174                       ,@decls
175                       (block ,(fun-name-block-name name)
176                         ,@forms)))
177            (inline-lambda
178             (cond (;; Does the user not even want to inline?
179                    (not (inline-fun-name-p name))
180                    nil)
181                   (;; Does inlining look too hairy to handle?
182                    (not (sb!c:lambda-independent-of-lexenv-p lambda env))
183                    (sb!c:maybe-compiler-note
184                     "lexical environment too hairy, can't inline DEFUN ~S"
185                     name)
186                    nil)
187                   (t
188                    ;; FIXME: The only reason that we return
189                    ;; LAMBDA-WITH-LEXENV instead of returning bare
190                    ;; LAMBDA is to avoid modifying downstream code
191                    ;; which expects LAMBDA-WITH-LEXENV. But the code
192                    ;; here is the only code which feeds into the
193                    ;; downstream code, and the generality of the
194                    ;; interface is no longer used, so it'd make sense
195                    ;; to simplify the interface instead of using the
196                    ;; old general LAMBDA-WITH-LEXENV interface in this
197                    ;; simplified way.
198                    `(sb!c:lambda-with-lexenv
199                      nil nil nil ; i.e. no DECLS, no MACROS, no SYMMACS
200                      ,@(rest lambda))))))
201       `(progn
202
203          ;; In cross-compilation of toplevel DEFUNs, we arrange
204          ;; for the LAMBDA to be statically linked by GENESIS.
205          #+sb-xc-host
206          (cold-fset ,name ,lambda)
207
208          (eval-when (:compile-toplevel :load-toplevel :execute)
209            (sb!c:%compiler-defun ',name ',inline-lambda))
210
211          (%defun ',name
212                  ;; In normal compilation (not for cold load) this is
213                  ;; where the compiled LAMBDA first appears. In
214                  ;; cross-compilation, we manipulate the
215                  ;; previously-statically-linked LAMBDA here.
216                  #-sb-xc-host ,lambda
217                  #+sb-xc-host (fdefinition ',name)
218                  ,doc)))))
219 #-sb-xc-host
220 (defun %defun (name def doc)
221   (declare (type function def))
222   (declare (type (or null simple-string doc)))
223   (aver (legal-fun-name-p name))
224   (when (fboundp name)
225     (/show0 "redefining NAME in %DEFUN")
226     (style-warn "redefining ~S in DEFUN" name))
227   (setf (sb!xc:fdefinition name) def)
228   (when doc
229     ;; FIXME: This should use shared SETF-name-parsing logic.
230     (if (and (consp name) (eq (first name) 'setf))
231         (setf (fdocumentation (second name) 'setf) doc)
232         (setf (fdocumentation (the symbol name) 'function) doc)))
233   name)
234 \f
235 ;;;; DEFVAR and DEFPARAMETER
236
237 (defmacro-mundanely defvar (var &optional (val nil valp) (doc nil docp))
238   #!+sb-doc
239   "Define a global variable at top level. Declare the variable
240   SPECIAL and, optionally, initialize it. If the variable already has a
241   value, the old value is not clobbered. The third argument is an optional
242   documentation string for the variable."
243   `(progn
244      (declaim (special ,var))
245      ,@(when valp
246          `((unless (boundp ',var)
247              (setq ,var ,val))))
248      ,@(when docp
249          `((funcall #'(setf fdocumentation) ',doc ',var 'variable)))
250      ',var))
251
252 (defmacro-mundanely defparameter (var val &optional (doc nil docp))
253   #!+sb-doc
254   "Define a parameter that is not normally changed by the program,
255   but that may be changed without causing an error. Declare the
256   variable special and sets its value to VAL, overwriting any
257   previous value. The third argument is an optional documentation
258   string for the parameter."
259   `(progn
260      (declaim (special ,var))
261      (setq ,var ,val)
262      ,@(when docp
263          ;; FIXME: The various FUNCALL #'(SETF FDOCUMENTATION) and
264          ;; other FUNCALL #'(SETF FOO) forms in the code should
265          ;; unbogobootstrapized back to ordinary SETF forms.
266          `((funcall #'(setf fdocumentation) ',doc ',var 'variable)))
267      ',var))
268 \f
269 ;;;; iteration constructs
270
271 ;;; (These macros are defined in terms of a function DO-DO-BODY which
272 ;;; is also used by SB!INT:DO-ANONYMOUS. Since these macros should not
273 ;;; be loaded on the cross-compilation host, but SB!INT:DO-ANONYMOUS
274 ;;; and DO-DO-BODY should be, these macros can't conveniently be in
275 ;;; the same file as DO-DO-BODY.)
276 (defmacro-mundanely do (varlist endlist &body body)
277   #!+sb-doc
278   "DO ({(Var [Init] [Step])}*) (Test Exit-Form*) Declaration* Form*
279   Iteration construct. Each Var is initialized in parallel to the value of the
280   specified Init form. On subsequent iterations, the Vars are assigned the
281   value of the Step form (if any) in parallel. The Test is evaluated before
282   each evaluation of the body Forms. When the Test is true, the Exit-Forms
283   are evaluated as a PROGN, with the result being the value of the DO. A block
284   named NIL is established around the entire expansion, allowing RETURN to be
285   used as an alternate exit mechanism."
286   (do-do-body varlist endlist body 'let 'psetq 'do nil))
287 (defmacro-mundanely do* (varlist endlist &body body)
288   #!+sb-doc
289   "DO* ({(Var [Init] [Step])}*) (Test Exit-Form*) Declaration* Form*
290   Iteration construct. Each Var is initialized sequentially (like LET*) to the
291   value of the specified Init form. On subsequent iterations, the Vars are
292   sequentially assigned the value of the Step form (if any). The Test is
293   evaluated before each evaluation of the body Forms. When the Test is true,
294   the Exit-Forms are evaluated as a PROGN, with the result being the value
295   of the DO. A block named NIL is established around the entire expansion,
296   allowing RETURN to be used as an laternate exit mechanism."
297   (do-do-body varlist endlist body 'let* 'setq 'do* nil))
298
299 ;;; DOTIMES and DOLIST could be defined more concisely using
300 ;;; destructuring macro lambda lists or DESTRUCTURING-BIND, but then
301 ;;; it'd be tricky to use them before those things were defined.
302 ;;; They're used enough times before destructuring mechanisms are
303 ;;; defined that it looks as though it's worth just implementing them
304 ;;; ASAP, at the cost of being unable to use the standard
305 ;;; destructuring mechanisms.
306 (defmacro-mundanely dotimes (var-count-result &body body)
307   (multiple-value-bind ; to roll our own destructuring
308       (var count result)
309       (apply (lambda (var count &optional (result nil))
310                (values var count result))
311              var-count-result)
312     (cond ((numberp count)
313            `(do ((,var 0 (1+ ,var)))
314                 ((>= ,var ,count) ,result)
315               (declare (type unsigned-byte ,var))
316               ,@body))
317           (t (let ((v1 (gensym)))
318                `(do ((,var 0 (1+ ,var)) (,v1 ,count))
319                     ((>= ,var ,v1) ,result)
320                   (declare (type unsigned-byte ,var))
321                   ,@body))))))
322 (defmacro-mundanely dolist (var-list-result &body body)
323   (multiple-value-bind ; to roll our own destructuring
324       (var list result)
325       (apply (lambda (var list &optional (result nil))
326                (values var list result))
327              var-list-result)
328     ;; We repeatedly bind the var instead of setting it so that we
329     ;; never have to give the var an arbitrary value such as NIL
330     ;; (which might conflict with a declaration). If there is a result
331     ;; form, we introduce a gratuitous binding of the variable to NIL
332     ;; without the declarations, then evaluate the result form in that
333     ;; environment. We spuriously reference the gratuitous variable,
334     ;; since since we don't want to use IGNORABLE on what might be a
335     ;; special var.
336     (let ((n-list (gensym)))
337       `(do ((,n-list ,list (cdr ,n-list)))
338            ((endp ,n-list)
339             ,@(if result
340                 `((let ((,var nil))
341                     ,var
342                     ,result))
343                 '(nil)))
344          (let ((,var (car ,n-list)))
345            ,@body)))))
346 \f
347 ;;;; miscellaneous
348
349 (defmacro-mundanely return (&optional (value nil))
350   `(return-from nil ,value))
351
352 (defmacro-mundanely psetq (&rest pairs)
353   #!+sb-doc
354   "SETQ {var value}*
355    Set the variables to the values, like SETQ, except that assignments
356    happen in parallel, i.e. no assignments take place until all the
357    forms have been evaluated."
358   ;; (This macro is used in the definition of DO, so we can't use DO in the
359   ;; definition of this macro without getting into confusing bootstrap issues.)
360   (prog ((lets nil)
361          (setqs nil)
362          (pairs pairs))
363     :again
364     (when (atom (cdr pairs))
365       (return `(let ,(nreverse lets)
366                  (setq ,@(nreverse setqs))
367                  nil)))
368     (let ((gen (gensym)))
369       (setq lets (cons `(,gen ,(cadr pairs)) lets)
370             setqs (list* gen (car pairs) setqs)
371             pairs (cddr pairs)))
372     (go :again)))
373
374 (defmacro-mundanely lambda (&whole whole args &body body)
375   (declare (ignore args body))
376   `#',whole)