0.8.0.6:
[sbcl.git] / src / pcl / walk.lisp
1 ;;;; a simple code walker
2 ;;;;
3 ;;;; The code which implements the macroexpansion environment
4 ;;;; manipulation mechanisms is in the first part of the file, the
5 ;;;; real walker follows it.
6
7 ;;;; This software is part of the SBCL system. See the README file for
8 ;;;; more information.
9
10 ;;;; This software is derived from software originally released by Xerox
11 ;;;; Corporation. Copyright and release statements follow. Later modifications
12 ;;;; to the software are in the public domain and are provided with
13 ;;;; absolutely no warranty. See the COPYING and CREDITS files for more
14 ;;;; information.
15
16 ;;;; copyright information from original PCL sources:
17 ;;;;
18 ;;;; Copyright (c) 1985, 1986, 1987, 1988, 1989, 1990 Xerox Corporation.
19 ;;;; All rights reserved.
20 ;;;;
21 ;;;; Use and copying of this software and preparation of derivative works based
22 ;;;; upon this software are permitted. Any distribution of this software or
23 ;;;; derivative works must comply with all applicable United States export
24 ;;;; control laws.
25 ;;;;
26 ;;;; This software is made available AS IS, and Xerox Corporation makes no
27 ;;;; warranty about the software, its performance or its conformity to any
28 ;;;; specification.
29
30 (in-package "SB!WALKER")
31 \f
32 ;;;; forward references
33
34 (defvar *key-to-walker-environment*)
35 \f
36 ;;;; environment hacking stuff, necessarily SBCL-specific
37
38 ;;; Here in the original PCL were implementations of the
39 ;;; implementation-specific environment hacking functions for each of
40 ;;; the implementations this walker had been ported to. This
41 ;;; functionality was originally factored out in order to make PCL
42 ;;; portable from one Common Lisp to another. As of 19981107, that
43 ;;; portability was fairly stale and (because of the scarcity of CLTL1
44 ;;; implementations and the strong interdependence of the rest of ANSI
45 ;;; Common Lisp on the CLOS system) fairly irrelevant. It was fairly
46 ;;; thoroughly put out of its misery by WHN in his quest to clean up
47 ;;; the system enough that it can be built from scratch using any ANSI
48 ;;; Common Lisp.
49 ;;;
50 ;;; This code just hacks 'macroexpansion environments'. That is, it is
51 ;;; only concerned with the function binding of symbols in the
52 ;;; environment. The walker needs to be able to tell if the symbol
53 ;;; names a lexical macro or function, and it needs to be able to
54 ;;; build environments which contain lexical macro or function
55 ;;; bindings. It must be able, when walking a MACROLET, FLET or LABELS
56 ;;; form to construct an environment which reflects the bindings
57 ;;; created by that form. Note that the environment created does NOT
58 ;;; have to be sufficient to evaluate the body, merely to walk its
59 ;;; body. This means that definitions do not have to be supplied for
60 ;;; lexical functions, only the fact that that function is bound is
61 ;;; important. For macros, the macroexpansion function must be
62 ;;; supplied.
63 ;;;
64 ;;; This code is organized in a way that lets it work in
65 ;;; implementations that stack cons their environments. That is
66 ;;; reflected in the fact that the only operation that lets a user
67 ;;; build a new environment is a WITH-BODY macro which executes its
68 ;;; body with the specified symbol bound to the new environment. No
69 ;;; code in this walker or in PCL will hold a pointer to these
70 ;;; environments after the body returns. Other user code is free to do
71 ;;; so in implementations where it works, but that code is not
72 ;;; considered portable.
73 ;;;
74 ;;; There are 3 environment hacking tools. One macro,
75 ;;; WITH-AUGMENTED-ENVIRONMENT, which is used to create new
76 ;;; environments, and two functions, ENVIRONMENT-FUNCTION and
77 ;;; ENVIRONMENT-MACRO, which are used to access the bindings of
78 ;;; existing environments
79
80 ;;; In SBCL, as in CMU CL before it, the environment is represented
81 ;;; with a structure that holds alists for the functional things,
82 ;;; variables, blocks, etc. Except for SYMBOL-MACROLET, only the
83 ;;; SB!C::LEXENV-FUNS slot is relevant. It holds: Alist (Name . What),
84 ;;; where What is either a functional (a local function) or a list
85 ;;; (MACRO . <function>) (a local macro, with the specifier expander.)
86 ;;; Note that Name may be a (SETF <name>) function. Accessors are
87 ;;; defined below, eg (ENV-WALK-FUNCTION ENV).
88 ;;;
89 ;;; If WITH-AUGMENTED-ENVIRONMENT is called from WALKER-ENVIRONMENT-BIND
90 ;;; this code hides the WALKER version of an environment
91 ;;; inside the SB!C::LEXENV structure.
92 ;;;
93 ;;; In CMUCL (and former SBCL), This used to be a list of lists of form
94 ;;; (<gensym-name> MACRO . #<interpreted-function>) in the :functions slot
95 ;;; in a C::LEXENV.
96 ;;; This form was accepted by the compiler, but this was a crude hack,
97 ;;; because the <interpreted-function> was used as a structure to hold the
98 ;;; bits of interest, {function, form, declarations, lexical-variables},
99 ;;; a list, which was not really an interpreted function.
100 ;;; Instead this list was COERCEd to a #<FUNCTION ...>!
101 ;;;
102 ;;; Instead, we now use a special sort of "function"-type for that
103 ;;; information, because the functions slot in SB!C::LEXENV is
104 ;;; supposed to have a list of <Name MACRO . #<function> elements.
105 ;;; So, now we hide our bits of interest in the walker-info slot in
106 ;;; our new BOGO-FUN.
107 ;;;
108 ;;; MACROEXPAND-1 and SB!INT:EVAL-IN-LEXENV are the only SBCL
109 ;;; functions that get called with the constructed environment
110 ;;; argument.
111
112 (/show "walk.lisp 108")
113
114 (defmacro with-augmented-environment
115     ((new-env old-env &key functions macros) &body body)
116   `(let ((,new-env (with-augmented-environment-internal ,old-env
117                                                         ,functions
118                                                         ,macros)))
119      ,@body))
120
121 ;;; a unique tag to show that we're the intended caller of BOGO-FUN
122 (defvar *bogo-fun-magic-tag*
123   '(:bogo-fun-magic-tag))
124
125 ;;; The interface of BOGO-FUNs (previously implemented as
126 ;;; FUNCALLABLE-INSTANCEs) is just these two operations, so we can do
127 ;;; them with ordinary closures.
128 ;;;
129 ;;; KLUDGE: BOGO-FUNs are sorta weird, and MNA and I have both hacked
130 ;;; on this code without quite figuring out what they're for. (He
131 ;;; changed them to work after some changes in the IR1 interpreter
132 ;;; made functions not be built lazily, and I changed them so that
133 ;;; they don't need FUNCALLABLE-INSTANCE stuff, so that the F-I stuff
134 ;;; can become less general.) There may be further simplifications or
135 ;;; clarifications which could be done. -- WHN 2001-10-19
136 (defun walker-info-to-bogo-fun (walker-info)
137   (lambda (magic-tag &rest rest)
138     (aver (not rest)) ; else someone is using me in an unexpected way
139     (aver (eql magic-tag *bogo-fun-magic-tag*)) ; else ditto
140     walker-info))
141 (defun bogo-fun-to-walker-info (bogo-fun)
142   (declare (type function bogo-fun))
143   (funcall bogo-fun *bogo-fun-magic-tag*))
144
145 (defun with-augmented-environment-internal (env funs macros)
146   ;; Note: In order to record the correct function definition, we
147   ;; would have to create an interpreted closure, but the
148   ;; WITH-NEW-DEFINITION macro down below makes no distinction between
149   ;; FLET and LABELS, so we have no idea what to use for the
150   ;; environment. So we just blow it off, 'cause anything real we do
151   ;; would be wrong. But we still have to make an entry so we can tell
152   ;; functions from macros.
153   (let ((lexenv (sb!kernel::coerce-to-lexenv env)))
154     (sb!c::make-lexenv
155      :default lexenv
156      :funs (append (mapcar (lambda (f)
157                              (cons (car f)
158                                    (sb!c::make-functional :lexenv lexenv)))
159                            funs)
160                    (mapcar (lambda (m)
161                              (list* (car m)
162                                     'sb!c::macro
163                                     (if (eq (car m)
164                                             *key-to-walker-environment*)
165                                         (walker-info-to-bogo-fun (cadr m))
166                                         (coerce (cadr m) 'function))))
167                            macros)))))
168
169 (defun environment-function (env fn)
170   (when env
171     (let ((entry (assoc fn (sb!c::lexenv-funs env) :test #'equal)))
172       (and entry
173            (sb!c::functional-p (cdr entry))
174            (cdr entry)))))
175
176 (defun environment-macro (env macro)
177   (when env
178     (let ((entry (assoc macro (sb!c::lexenv-funs env) :test #'eq)))
179       (and entry
180            (eq (cadr entry) 'sb!c::macro)
181            (if (eq macro *key-to-walker-environment*)
182                (values (bogo-fun-to-walker-info (cddr entry)))
183                (values (function-lambda-expression (cddr entry))))))))
184 \f
185 ;;;; other environment hacking, not so SBCL-specific as the
186 ;;;; environment hacking in the previous section
187
188 (defmacro with-new-definition-in-environment
189           ((new-env old-env macrolet/flet/labels-form) &body body)
190   (let ((functions (make-symbol "Functions"))
191         (macros (make-symbol "Macros")))
192     `(let ((,functions ())
193            (,macros ()))
194        (ecase (car ,macrolet/flet/labels-form)
195          ((flet labels)
196           (dolist (fn (cadr ,macrolet/flet/labels-form))
197             (push fn ,functions)))
198          ((macrolet)
199           (dolist (mac (cadr ,macrolet/flet/labels-form))
200             (push (list (car mac)
201                         (convert-macro-to-lambda (cadr mac)
202                                                  (cddr mac)
203                                                  ,old-env
204                                                  (string (car mac))))
205                   ,macros))))
206        (with-augmented-environment
207               (,new-env ,old-env :functions ,functions :macros ,macros)
208          ,@body))))
209
210 (defun convert-macro-to-lambda (llist body env &optional (name "dummy macro"))
211   (let ((gensym (make-symbol name)))
212     (eval-in-lexenv `(defmacro ,gensym ,llist ,@body)
213                     (sb!c::make-restricted-lexenv env))
214     (macro-function gensym)))
215 \f
216 ;;;; the actual walker
217
218 ;;; As the walker walks over the code, it communicates information to
219 ;;; itself about the walk. This information includes the walk
220 ;;; function, variable bindings, declarations in effect etc. This
221 ;;; information is inherently lexical, so the walker passes it around
222 ;;; in the actual environment the walker passes to macroexpansion
223 ;;; functions. This is what makes the NESTED-WALK-FORM facility work
224 ;;; properly.
225 (defmacro walker-environment-bind ((var env &rest key-args)
226                                       &body body)
227   `(with-augmented-environment
228      (,var ,env :macros (walker-environment-bind-1 ,env ,.key-args))
229      .,body))
230
231 (defvar *key-to-walker-environment* (gensym))
232
233 (defun env-lock (env)
234   (environment-macro env *key-to-walker-environment*))
235
236 (defun walker-environment-bind-1 (env &key (walk-function nil wfnp)
237                                            (walk-form nil wfop)
238                                            (declarations nil decp)
239                                            (lexical-variables nil lexp))
240   (let ((lock (environment-macro env *key-to-walker-environment*)))
241     (list
242       (list *key-to-walker-environment*
243             (list (if wfnp walk-function     (car lock))
244                   (if wfop walk-form         (cadr lock))
245                   (if decp declarations      (caddr lock))
246                   (if lexp lexical-variables (cadddr lock)))))))
247
248 (defun env-walk-function (env)
249   (car (env-lock env)))
250
251 (defun env-walk-form (env)
252   (cadr (env-lock env)))
253
254 (defun env-declarations (env)
255   (caddr (env-lock env)))
256
257 (defun env-lexical-variables (env)
258   (cadddr (env-lock env)))
259
260 (defun note-declaration (declaration env)
261   (push declaration (caddr (env-lock env))))
262
263 (defun note-lexical-binding (thing env)
264   (push (list thing :lexical-var) (cadddr (env-lock env))))
265
266 (defun var-lexical-p (var env)
267   (let ((entry (member var (env-lexical-variables env) :key #'car)))
268     (when (eq (cadar entry) :lexical-var)
269       entry)))
270
271 (defun variable-symbol-macro-p (var env)
272   (let ((entry (member var (env-lexical-variables env) :key #'car)))
273     (when (eq (cadar entry) 'sb!sys:macro)
274       entry)))
275
276 (defvar *var-declarations* '(special))
277
278 (defun var-declaration (declaration var env)
279   (if (not (member declaration *var-declarations*))
280       (error "~S is not a recognized variable declaration." declaration)
281       (let ((id (or (var-lexical-p var env) var)))
282         (dolist (decl (env-declarations env))
283           (when (and (eq (car decl) declaration)
284                      (eq (cadr decl) id))
285             (return decl))))))
286
287 (defun var-special-p (var env)
288   (or (not (null (var-declaration 'special var env)))
289       (var-globally-special-p var)))
290
291 (defun var-globally-special-p (symbol)
292   (eq (info :variable :kind symbol) :special))
293 \f
294 ;;;; handling of special forms
295
296 ;;; Here are some comments from the original PCL on the difficulty of
297 ;;; doing this portably across different CLTL1 implementations. This
298 ;;; is no longer directly relevant because this code now only runs on
299 ;;; SBCL, but the comments are retained for culture: they might help
300 ;;; explain some of the design decisions which were made in the code.
301 ;;;
302 ;;; and I quote...
303 ;;;
304 ;;;     The set of special forms is purposely kept very small because
305 ;;;     any program analyzing program (read code walker) must have
306 ;;;     special knowledge about every type of special form. Such a
307 ;;;     program needs no special knowledge about macros...
308 ;;;
309 ;;; So all we have to do here is a define a way to store and retrieve
310 ;;; templates which describe how to walk the 24 special forms and we
311 ;;; are all set...
312 ;;;
313 ;;; Well, its a nice concept, and I have to admit to being naive
314 ;;; enough that I believed it for a while, but not everyone takes
315 ;;; having only 24 special forms as seriously as might be nice. There
316 ;;; are (at least) 3 ways to lose:
317 ;;
318 ;;;   1 - Implementation x implements a Common Lisp special form as 
319 ;;;       a macro which expands into a special form which:
320 ;;;      - Is a common lisp special form (not likely)
321 ;;;      - Is not a common lisp special form (on the 3600 IF --> COND).
322 ;;;
323 ;;;     * We can save ourselves from this case (second subcase really)
324 ;;;       by checking to see whether there is a template defined for 
325 ;;;       something before we check to see whether we can macroexpand it.
326 ;;;
327 ;;;   2 - Implementation x implements a Common Lisp macro as a special form.
328 ;;;
329 ;;;     * This is a screw, but not so bad, we save ourselves from it by
330 ;;;       defining extra templates for the macros which are *likely* to
331 ;;;       be implemented as special forms. [Note: As of sbcl-0.6.9, these
332 ;;;       extra templates have been deleted, since this is not a problem
333 ;;;       in SBCL and we no longer try to make this walker portable
334 ;;;       across other possibly-broken CL implementations.]
335 ;;;
336 ;;;   3 - Implementation x has a special form which is not on the list of
337 ;;;       Common Lisp special forms.
338 ;;;
339 ;;;     * This is a bad sort of a screw and happens more than I would 
340 ;;;       like to think, especially in the implementations which provide 
341 ;;;       more than just Common Lisp (3600, Xerox etc.).
342 ;;;       The fix is not terribly satisfactory, but will have to do for
343 ;;;       now. There is a hook in get walker-template which can get a
344 ;;;       template from the implementation's own walker. That template
345 ;;;       has to be converted, and so it may be that the right way to do
346 ;;;       this would actually be for that implementation to provide an
347 ;;;       interface to its walker which looks like the interface to this
348 ;;;       walker.
349
350 (defmacro get-walker-template-internal (x)
351   `(get ,x 'walker-template))
352
353 (defmacro define-walker-template (name
354                                   &optional (template '(nil repeat (eval))))
355   `(eval-when (:load-toplevel :execute)
356      (setf (get-walker-template-internal ',name) ',template)))
357
358 (defun get-walker-template (x)
359   (cond ((symbolp x)
360          (get-walker-template-internal x))
361         ((and (listp x) (eq (car x) 'lambda))
362          '(lambda repeat (eval)))
363         (t
364          (error "can't get template for ~S" x))))
365 \f
366 ;;;; the actual templates
367
368 ;;; ANSI special forms
369 (define-walker-template block                (nil nil repeat (eval)))
370 (define-walker-template catch                (nil eval repeat (eval)))
371 (define-walker-template declare              walk-unexpected-declare)
372 (define-walker-template eval-when            (nil quote repeat (eval)))
373 (define-walker-template flet                 walk-flet)
374 (define-walker-template function             (nil call))
375 (define-walker-template go                   (nil quote))
376 (define-walker-template if                   walk-if)
377 (define-walker-template labels               walk-labels)
378 (define-walker-template lambda               walk-lambda)
379 (define-walker-template let                  walk-let)
380 (define-walker-template let*                 walk-let*)
381 (define-walker-template locally              walk-locally)
382 (define-walker-template macrolet             walk-macrolet)
383 (define-walker-template multiple-value-call  (nil eval repeat (eval)))
384 (define-walker-template multiple-value-prog1 (nil return repeat (eval)))
385 (define-walker-template multiple-value-setq  walk-multiple-value-setq)
386 (define-walker-template multiple-value-bind  walk-multiple-value-bind)
387 (define-walker-template progn                (nil repeat (eval)))
388 (define-walker-template progv                (nil eval eval repeat (eval)))
389 (define-walker-template quote                (nil quote))
390 (define-walker-template return-from          (nil quote repeat (return)))
391 (define-walker-template setq                 walk-setq)
392 (define-walker-template symbol-macrolet      walk-symbol-macrolet)
393 (define-walker-template tagbody              walk-tagbody)
394 (define-walker-template the                  (nil quote eval))
395 (define-walker-template throw                (nil eval eval))
396 (define-walker-template unwind-protect       (nil return repeat (eval)))
397
398 ;;; SBCL-only special forms
399 (define-walker-template sb!ext:truly-the     (nil quote eval))
400 (define-walker-template named-lambda         walk-named-lambda)
401 \f
402 (defvar *walk-form-expand-macros-p* nil)
403
404 (defun walk-form (form
405                   &optional environment
406                             (walk-function
407                              (lambda (subform context env)
408                                (declare (ignore context env))
409                                subform)))
410   (walker-environment-bind (new-env environment :walk-function walk-function)
411     (walk-form-internal form :eval new-env)))
412
413 ;;; WALK-FORM-INTERNAL is the main driving function for the code
414 ;;; walker. It takes a form and the current context and walks the form
415 ;;; calling itself or the appropriate template recursively.
416 ;;;
417 ;;;   "It is recommended that a program-analyzing-program process a form
418 ;;;    that is a list whose car is a symbol as follows:
419 ;;;
420 ;;;     1. If the program has particular knowledge about the symbol,
421 ;;;        process the form using special-purpose code. All of the
422 ;;;        standard special forms should fall into this category.
423 ;;;     2. Otherwise, if MACRO-FUNCTION is true of the symbol apply
424 ;;;        either MACROEXPAND or MACROEXPAND-1 and start over.
425 ;;;     3. Otherwise, assume it is a function call. "
426 (defun walk-form-internal (form context env)
427   ;; First apply the walk-function to perform whatever translation
428   ;; the user wants to this form. If the second value returned
429   ;; by walk-function is T then we don't recurse...
430   (catch form
431     (multiple-value-bind (newform walk-no-more-p)
432         (funcall (env-walk-function env) form context env)
433       (catch newform
434         (cond
435          (walk-no-more-p newform)
436          ((not (eq form newform))
437           (walk-form-internal newform context env))
438          ((not (consp newform))
439           (let ((symmac (car (variable-symbol-macro-p newform env))))
440             (if symmac
441                 (let ((newnewform (walk-form-internal (cddr symmac)
442                                                       context
443                                                       env)))
444                   (if (eq newnewform (cddr symmac))
445                       (if *walk-form-expand-macros-p* newnewform newform)
446                       newnewform))
447                 newform)))
448          (t
449           (let* ((fn (car newform))
450                  (template (get-walker-template fn)))
451             (if template
452                 (if (symbolp template)
453                     (funcall template newform context env)
454                     (walk-template newform template context env))
455                 (multiple-value-bind (newnewform macrop)
456                     (walker-environment-bind
457                         (new-env env :walk-form newform)
458                       (sb-xc:macroexpand-1 newform new-env))
459                   (cond
460                    (macrop
461                     (let ((newnewnewform (walk-form-internal newnewform
462                                                              context
463                                                              env)))
464                       (if (eq newnewnewform newnewform)
465                           (if *walk-form-expand-macros-p* newnewform newform)
466                           newnewnewform)))
467                    ((and (symbolp fn)
468                          (not (fboundp fn))
469                          (special-operator-p fn))
470                     ;; This shouldn't happen, since this walker is now
471                     ;; maintained as part of SBCL, so it should know
472                     ;; about all the special forms that SBCL knows
473                     ;; about.
474                     (bug "unexpected special form ~S" fn))
475                    (t
476                     ;; Otherwise, walk the form as if it's just a
477                     ;; standard function call using a template for
478                     ;; standard function call.
479                     (walk-template
480                      newnewform '(call repeat (eval)) context env))))))))))))
481
482 (defun walk-template (form template context env)
483   (if (atom template)
484       (ecase template
485         ((eval function test effect return)
486          (walk-form-internal form :eval env))
487         ((quote nil) form)
488         (set
489           (walk-form-internal form :set env))
490         ((lambda call)
491          (cond ((legal-fun-name-p form)
492                 form)
493                (t (walk-form-internal form context env)))))
494       (case (car template)
495         (repeat
496           (walk-template-handle-repeat form
497                                        (cdr template)
498                                        ;; For the case where nothing
499                                        ;; happens after the repeat
500                                        ;; optimize away the call to
501                                        ;; LENGTH.
502                                        (if (null (cddr template))
503                                            ()
504                                            (nthcdr (- (length form)
505                                                       (length
506                                                         (cddr template)))
507                                                    form))
508                                        context
509                                        env))
510         (if
511           (walk-template form
512                          (if (if (listp (cadr template))
513                                  (eval (cadr template))
514                                  (funcall (cadr template) form))
515                              (caddr template)
516                              (cadddr template))
517                          context
518                          env))
519         (remote
520           (walk-template form (cadr template) context env))
521         (otherwise
522           (cond ((atom form) form)
523                 (t (recons form
524                            (walk-template
525                              (car form) (car template) context env)
526                            (walk-template
527                              (cdr form) (cdr template) context env))))))))
528
529 (defun walk-template-handle-repeat (form template stop-form context env)
530   (if (eq form stop-form)
531       (walk-template form (cdr template) context env)
532       (walk-template-handle-repeat-1 form
533                                      template
534                                      (car template)
535                                      stop-form
536                                      context
537                                      env)))
538
539 (defun walk-template-handle-repeat-1 (form template repeat-template
540                                            stop-form context env)
541   (cond ((null form) ())
542         ((eq form stop-form)
543          (if (null repeat-template)
544              (walk-template stop-form (cdr template) context env)
545              (error "while handling code walker REPEAT:
546                      ~%ran into STOP while still in REPEAT template")))
547         ((null repeat-template)
548          (walk-template-handle-repeat-1
549            form template (car template) stop-form context env))
550         (t
551          (recons form
552                  (walk-template (car form) (car repeat-template) context env)
553                  (walk-template-handle-repeat-1 (cdr form)
554                                                 template
555                                                 (cdr repeat-template)
556                                                 stop-form
557                                                 context
558                                                 env)))))
559
560 (defun walk-repeat-eval (form env)
561   (and form
562        (recons form
563                (walk-form-internal (car form) :eval env)
564                (walk-repeat-eval (cdr form) env))))
565
566 (defun recons (x car cdr)
567   (if (or (not (eq (car x) car))
568           (not (eq (cdr x) cdr)))
569       (cons car cdr)
570       x))
571
572 (defun relist (x &rest args)
573   (if (null args)
574       nil
575       (relist-internal x args nil)))
576
577 (defun relist* (x &rest args)
578   (relist-internal x args t))
579
580 (defun relist-internal (x args *p)
581   (if (null (cdr args))
582       (if *p
583           (car args)
584           (recons x (car args) nil))
585       (recons x
586               (car args)
587               (relist-internal (cdr x) (cdr args) *p))))
588 \f
589 ;;;; special walkers
590
591 (defun walk-declarations (body fn env
592                                &optional doc-string-p declarations old-body
593                                &aux (form (car body)) macrop new-form)
594   (cond ((and (stringp form)                    ;might be a doc string
595               (cdr body)                        ;isn't the returned value
596               (null doc-string-p)               ;no doc string yet
597               (null declarations))              ;no declarations yet
598          (recons body
599                  form
600                  (walk-declarations (cdr body) fn env t)))
601         ((and (listp form) (eq (car form) 'declare))
602          ;; We got ourselves a real live declaration. Record it, look
603          ;; for more.
604          (dolist (declaration (cdr form))
605            (let ((type (car declaration))
606                  (name (cadr declaration))
607                  (args (cddr declaration)))
608              (if (member type *var-declarations*)
609                  (note-declaration `(,type
610                                      ,(or (var-lexical-p name env) name)
611                                      ,.args)
612                                    env)
613                  (note-declaration declaration env))
614              (push declaration declarations)))
615          (recons body
616                  form
617                  (walk-declarations
618                    (cdr body) fn env doc-string-p declarations)))
619         ((and form
620               (listp form)
621               (null (get-walker-template (car form)))
622               (progn
623                 (multiple-value-setq (new-form macrop)
624                                      (sb-xc:macroexpand-1 form env))
625                 macrop))
626          ;; This form was a call to a macro. Maybe it expanded
627          ;; into a declare?  Recurse to find out.
628          (walk-declarations (recons body new-form (cdr body))
629                             fn env doc-string-p declarations
630                             (or old-body body)))
631         (t
632          ;; Now that we have walked and recorded the declarations,
633          ;; call the function our caller provided to expand the body.
634          ;; We call that function rather than passing the real-body
635          ;; back, because we are RECONSING up the new body.
636          (funcall fn (or old-body body) env))))
637
638 (defun walk-unexpected-declare (form context env)
639   (declare (ignore context env))
640   (warn "encountered ~S ~_in a place where a DECLARE was not expected"
641         form)
642   form)
643
644 (defun walk-arglist (arglist context env &optional (destructuringp nil)
645                                          &aux arg)
646   (cond ((null arglist) ())
647         ((symbolp (setq arg (car arglist)))
648          (or (member arg lambda-list-keywords)
649              (note-lexical-binding arg env))
650          (recons arglist
651                  arg
652                  (walk-arglist (cdr arglist)
653                                context
654                                env
655                                (and destructuringp
656                                     (not (member arg
657                                                  lambda-list-keywords))))))
658         ((consp arg)
659          (prog1 (recons arglist
660                         (if destructuringp
661                             (walk-arglist arg context env destructuringp)
662                             (relist* arg
663                                      (car arg)
664                                      (walk-form-internal (cadr arg) :eval env)
665                                      (cddr arg)))
666                         (walk-arglist (cdr arglist) context env nil))
667                 (if (symbolp (car arg))
668                     (note-lexical-binding (car arg) env)
669                     (note-lexical-binding (cadar arg) env))
670                 (or (null (cddr arg))
671                     (not (symbolp (caddr arg)))
672                     (note-lexical-binding (caddr arg) env))))
673           (t
674            (error "can't understand something in the arglist ~S" arglist))))
675
676 (defun walk-let (form context env)
677   (walk-let/let* form context env nil))
678
679 (defun walk-let* (form context env)
680   (walk-let/let* form context env t))
681
682 (defun walk-let/let* (form context old-env sequentialp)
683   (walker-environment-bind (new-env old-env)
684     (let* ((let/let* (car form))
685            (bindings (cadr form))
686            (body (cddr form))
687            (walked-bindings
688              (walk-bindings-1 bindings
689                               old-env
690                               new-env
691                               context
692                               sequentialp))
693            (walked-body
694              (walk-declarations body #'walk-repeat-eval new-env)))
695       (relist*
696         form let/let* walked-bindings walked-body))))
697
698 (defun walk-locally (form context env)
699   (declare (ignore context))
700   (let* ((locally (car form))
701          (body (cdr form))
702          (walked-body
703           (walk-declarations body #'walk-repeat-eval env)))
704     (relist*
705      form locally walked-body)))
706
707 (defun walk-let-if (form context env)
708   (let ((test (cadr form))
709         (bindings (caddr form))
710         (body (cdddr form)))
711     (walk-form-internal
712       `(let ()
713          (declare (special ,@(mapcar (lambda (x) (if (listp x) (car x) x))
714                                      bindings)))
715          (flet ((.let-if-dummy. () ,@body))
716            (if ,test
717                (let ,bindings (.let-if-dummy.))
718                (.let-if-dummy.))))
719       context
720       env)))
721
722 (defun walk-multiple-value-setq (form context env)
723   (let ((vars (cadr form)))
724     (if (some (lambda (var)
725                 (variable-symbol-macro-p var env))
726               vars)
727         (let* ((temps (mapcar (lambda (var)
728                                 (declare (ignore var))
729                                 (gensym))
730                               vars))
731                (sets (mapcar (lambda (var temp) `(setq ,var ,temp))
732                              vars
733                              temps))
734                (expanded `(multiple-value-bind ,temps ,(caddr form)
735                              ,@sets))
736                (walked (walk-form-internal expanded context env)))
737           (if (eq walked expanded)
738               form
739               walked))
740         (walk-template form '(nil (repeat (set)) eval) context env))))
741
742 (defun walk-multiple-value-bind (form context old-env)
743   (walker-environment-bind (new-env old-env)
744     (let* ((mvb (car form))
745            (bindings (cadr form))
746            (mv-form (walk-template (caddr form) 'eval context old-env))
747            (body (cdddr form))
748            walked-bindings
749            (walked-body
750              (walk-declarations
751                body
752                (lambda (real-body real-env)
753                  (setq walked-bindings
754                        (walk-bindings-1 bindings
755                                         old-env
756                                         new-env
757                                         context
758                                         nil))
759                  (walk-repeat-eval real-body real-env))
760                new-env)))
761       (relist* form mvb walked-bindings mv-form walked-body))))
762
763 (defun walk-bindings-1 (bindings old-env new-env context sequentialp)
764   (and bindings
765        (let ((binding (car bindings)))
766          (recons bindings
767                  (if (symbolp binding)
768                      (prog1 binding
769                             (note-lexical-binding binding new-env))
770                      (prog1 (relist* binding
771                                      (car binding)
772                                      (walk-form-internal (cadr binding)
773                                                          context
774                                                          (if sequentialp
775                                                              new-env
776                                                              old-env))
777                                      ;; Save cddr for DO/DO*; it is
778                                      ;; the next value form. Don't
779                                      ;; walk it now, though.
780                                      (cddr binding))    
781                             (note-lexical-binding (car binding) new-env)))
782                  (walk-bindings-1 (cdr bindings)
783                                   old-env
784                                   new-env
785                                   context
786                                   sequentialp)))))
787
788 (defun walk-bindings-2 (bindings walked-bindings context env)
789   (and bindings
790        (let ((binding (car bindings))
791              (walked-binding (car walked-bindings)))
792          (recons bindings
793                  (if (symbolp binding)
794                      binding
795                      (relist* binding
796                               (car walked-binding)
797                               (cadr walked-binding)
798                               (walk-template (cddr binding)
799                                              '(eval)
800                                              context
801                                              env)))
802                  (walk-bindings-2 (cdr bindings)
803                                   (cdr walked-bindings)
804                                   context
805                                   env)))))
806
807 (defun walk-lambda (form context old-env)
808   (walker-environment-bind (new-env old-env)
809     (let* ((arglist (cadr form))
810            (body (cddr form))
811            (walked-arglist (walk-arglist arglist context new-env))
812            (walked-body
813              (walk-declarations body #'walk-repeat-eval new-env)))
814       (relist* form
815                (car form)
816                walked-arglist
817                walked-body))))
818
819 (defun walk-named-lambda (form context old-env)
820   (walker-environment-bind (new-env old-env)
821     (let* ((name (second form))
822            (arglist (third form))
823            (body (cdddr form))
824            (walked-arglist (walk-arglist arglist context new-env))
825            (walked-body
826              (walk-declarations body #'walk-repeat-eval new-env)))
827       (relist* form
828                (car form)
829                name
830                walked-arglist
831                walked-body))))
832
833 (defun walk-setq (form context env)
834   (if (cdddr form)
835       (let* ((expanded (let ((rforms nil)
836                              (tail (cdr form)))
837                          (loop (when (null tail) (return (nreverse rforms)))
838                                (let ((var (pop tail)) (val (pop tail)))
839                                  (push `(setq ,var ,val) rforms)))))
840              (walked (walk-repeat-eval expanded env)))
841         (if (eq expanded walked)
842             form
843             `(progn ,@walked)))
844       (let* ((var (cadr form))
845              (val (caddr form))
846              (symmac (car (variable-symbol-macro-p var env))))
847         (if symmac
848             (let* ((expanded `(setf ,(cddr symmac) ,val))
849                    (walked (walk-form-internal expanded context env)))
850               (if (eq expanded walked)
851                   form
852                   walked))
853             (relist form 'setq
854                     (walk-form-internal var :set env)
855                     (walk-form-internal val :eval env))))))
856
857 (defun walk-symbol-macrolet (form context old-env)
858   (declare (ignore context))
859   (let* ((bindings (cadr form))
860          (body (cddr form)))
861     (walker-environment-bind
862         (new-env old-env
863                  :lexical-variables
864                  (append (mapcar (lambda (binding)
865                                    `(,(car binding)
866                                      sb!sys:macro . ,(cadr binding)))
867                                  bindings)
868                          (env-lexical-variables old-env)))
869       (relist* form 'symbol-macrolet bindings
870                (walk-declarations body #'walk-repeat-eval new-env)))))
871
872 (defun walk-tagbody (form context env)
873   (recons form (car form) (walk-tagbody-1 (cdr form) context env)))
874
875 (defun walk-tagbody-1 (form context env)
876   (and form
877        (recons form
878                (walk-form-internal (car form)
879                                    (if (symbolp (car form)) 'quote context)
880                                    env)
881                (walk-tagbody-1 (cdr form) context env))))
882
883 (defun walk-macrolet (form context old-env)
884   (walker-environment-bind (macro-env
885                             nil
886                             :walk-function (env-walk-function old-env))
887     (labels ((walk-definitions (definitions)
888                (and definitions
889                     (let ((definition (car definitions)))
890                       (recons definitions
891                               (relist* definition
892                                        (car definition)
893                                        (walk-arglist (cadr definition)
894                                                      context
895                                                      macro-env
896                                                      t)
897                                        (walk-declarations (cddr definition)
898                                                           #'walk-repeat-eval
899                                                           macro-env))
900                               (walk-definitions (cdr definitions)))))))
901       (with-new-definition-in-environment (new-env old-env form)
902         (relist* form
903                  (car form)
904                  (walk-definitions (cadr form))
905                  (walk-declarations (cddr form)
906                                     #'walk-repeat-eval
907                                     new-env))))))
908
909 (defun walk-flet (form context old-env)
910   (labels ((walk-definitions (definitions)
911              (if (null definitions)
912                  ()
913                  (recons definitions
914                          (walk-lambda (car definitions) context old-env)
915                          (walk-definitions (cdr definitions))))))
916     (recons form
917             (car form)
918             (recons (cdr form)
919                     (walk-definitions (cadr form))
920                     (with-new-definition-in-environment (new-env old-env form)
921                       (walk-declarations (cddr form)
922                                          #'walk-repeat-eval
923                                          new-env))))))
924
925 (defun walk-labels (form context old-env)
926   (with-new-definition-in-environment (new-env old-env form)
927     (labels ((walk-definitions (definitions)
928                (if (null definitions)
929                    ()
930                    (recons definitions
931                            (walk-lambda (car definitions) context new-env)
932                            (walk-definitions (cdr definitions))))))
933       (recons form
934               (car form)
935               (recons (cdr form)
936                       (walk-definitions (cadr form))
937                       (walk-declarations (cddr form)
938                                          #'walk-repeat-eval
939                                          new-env))))))
940
941 (defun walk-if (form context env)
942   (destructuring-bind (if predicate arm1 &optional arm2) form
943     (declare (ignore if)) ; should be 'IF
944     (relist form
945             'if
946             (walk-form-internal predicate context env)
947             (walk-form-internal arm1 context env)
948             (walk-form-internal arm2 context env))))
949 \f
950 ;;;; examples
951
952 #|
953 ;;; Here are some examples of the kinds of things you should be able
954 ;;; to do with your implementation of the macroexpansion environment
955 ;;; hacking mechanism.
956 ;;;
957 ;;; WITH-LEXICAL-MACROS is kind of like MACROLET, but it only takes
958 ;;; names of the macros and actual macroexpansion functions to use to
959 ;;; macroexpand them. The win about that is that for macros which want
960 ;;; to wrap several MACROLETs around their body, they can do this but
961 ;;; have the macroexpansion functions be compiled. See the WITH-RPUSH
962 ;;; example.
963 ;;;
964 ;;; If the implementation had a special way of communicating the
965 ;;; augmented environment back to the evaluator that would be totally
966 ;;; great. It would mean that we could just augment the environment
967 ;;; then pass control back to the implementations own compiler or
968 ;;; interpreter. We wouldn't have to call the actual walker. That
969 ;;; would make this much faster. Since the principal client of this is
970 ;;; defmethod it would make compiling defmethods faster and that would
971 ;;; certainly be a win.
972
973 (defmacro with-lexical-macros (macros &body body &environment old-env)
974   (with-augmented-environment (new-env old-env :macros macros)
975     (walk-form (cons 'progn body) :environment new-env)))
976
977 (defun expand-rpush (form env)
978   (declare (ignore env))
979   `(push ,(caddr form) ,(cadr form)))
980
981 (defmacro with-rpush (&body body)
982   `(with-lexical-macros ,(list (list 'rpush #'expand-rpush)) ,@body))
983 |#