0.8.16.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      :vars (when (eql (caar macros) *key-to-walker-environment*)
157              (copy-tree (remove :lexical-var (fourth (cadar macros))
158                                 :key #'cadr)))
159      :funs (append (mapcar (lambda (f)
160                              (cons (car f)
161                                    (sb!c::make-functional :lexenv lexenv)))
162                            funs)
163                    (mapcar (lambda (m)
164                              (list* (car m)
165                                     'sb!c::macro
166                                     (if (eq (car m)
167                                             *key-to-walker-environment*)
168                                         (walker-info-to-bogo-fun (cadr m))
169                                         (coerce (cadr m) 'function))))
170                            macros)))))
171
172 (defun environment-function (env fn)
173   (when env
174     (let ((entry (assoc fn (sb!c::lexenv-funs env) :test #'equal)))
175       (and entry
176            (sb!c::functional-p (cdr entry))
177            (cdr entry)))))
178
179 (defun environment-macro (env macro)
180   (when env
181     (let ((entry (assoc macro (sb!c::lexenv-funs env) :test #'eq)))
182       (and entry
183            (eq (cadr entry) 'sb!c::macro)
184            (if (eq macro *key-to-walker-environment*)
185                (values (bogo-fun-to-walker-info (cddr entry)))
186                (values (function-lambda-expression (cddr entry))))))))
187 \f
188 ;;;; other environment hacking, not so SBCL-specific as the
189 ;;;; environment hacking in the previous section
190
191 (defmacro with-new-definition-in-environment
192           ((new-env old-env macrolet/flet/labels-form) &body body)
193   (let ((functions (make-symbol "Functions"))
194         (macros (make-symbol "Macros")))
195     `(let ((,functions ())
196            (,macros ()))
197        (ecase (car ,macrolet/flet/labels-form)
198          ((flet labels)
199           (dolist (fn (cadr ,macrolet/flet/labels-form))
200             (push fn ,functions)))
201          ((macrolet)
202           (dolist (mac (cadr ,macrolet/flet/labels-form))
203             (push (list (car mac)
204                         (convert-macro-to-lambda (cadr mac)
205                                                  (cddr mac)
206                                                  ,old-env
207                                                  (string (car mac))))
208                   ,macros))))
209        (with-augmented-environment
210               (,new-env ,old-env :functions ,functions :macros ,macros)
211          ,@body))))
212
213 (defun convert-macro-to-lambda (llist body env &optional (name "dummy macro"))
214   (let ((gensym (make-symbol name)))
215     (eval-in-lexenv `(defmacro ,gensym ,llist ,@body)
216                     (sb!c::make-restricted-lexenv env))
217     (macro-function gensym)))
218 \f
219 ;;;; the actual walker
220
221 ;;; As the walker walks over the code, it communicates information to
222 ;;; itself about the walk. This information includes the walk
223 ;;; function, variable bindings, declarations in effect etc. This
224 ;;; information is inherently lexical, so the walker passes it around
225 ;;; in the actual environment the walker passes to macroexpansion
226 ;;; functions. This is what makes the NESTED-WALK-FORM facility work
227 ;;; properly.
228 (defmacro walker-environment-bind ((var env &rest key-args)
229                                       &body body)
230   `(with-augmented-environment
231      (,var ,env :macros (walker-environment-bind-1 ,env ,.key-args))
232      .,body))
233
234 (defvar *key-to-walker-environment* (gensym))
235
236 (defun env-lock (env)
237   (environment-macro env *key-to-walker-environment*))
238
239 (defun walker-environment-bind-1 (env &key (walk-function nil wfnp)
240                                            (walk-form nil wfop)
241                                            (declarations nil decp)
242                                            (lexical-vars nil lexp))
243   (let ((lock (env-lock env)))
244     (list
245       (list *key-to-walker-environment*
246             (list (if wfnp walk-function (car lock))
247                   (if wfop walk-form     (cadr lock))
248                   (if decp declarations  (caddr lock))
249                   (if lexp lexical-vars  (cadddr lock)))))))
250
251 (defun env-walk-function (env)
252   (car (env-lock env)))
253
254 (defun env-walk-form (env)
255   (cadr (env-lock env)))
256
257 (defun env-declarations (env)
258   (caddr (env-lock env)))
259
260 (defun env-lexical-variables (env)
261   (cadddr (env-lock env)))
262
263 (defun note-declaration (declaration env)
264   (push declaration (caddr (env-lock env))))
265
266 (defun note-lexical-binding (thing env)
267   (push (list thing :lexical-var) (cadddr (env-lock env))))
268
269 (defun var-lexical-p (var env)
270   (let ((entry (member var (env-lexical-variables env) :key #'car)))
271     (when (eq (cadar entry) :lexical-var)
272       entry)))
273
274 (defun variable-symbol-macro-p (var env)
275   (let ((entry (member var (env-lexical-variables env) :key #'car)))
276     (when (eq (cadar entry) 'sb!sys:macro)
277       entry)))
278
279 (defvar *var-declarations* '(special))
280
281 (defun var-declaration (declaration var env)
282   (if (not (member declaration *var-declarations*))
283       (error "~S is not a recognized variable declaration." declaration)
284       (let ((id (or (var-lexical-p var env) var)))
285         (dolist (decl (env-declarations env))
286           (when (and (eq (car decl) declaration)
287                      (eq (cadr decl) id))
288             (return decl))))))
289
290 (defun var-special-p (var env)
291   (or (not (null (var-declaration 'special var env)))
292       (var-globally-special-p var)))
293
294 (defun var-globally-special-p (symbol)
295   (eq (info :variable :kind symbol) :special))
296 \f
297 ;;;; handling of special forms
298
299 ;;; Here are some comments from the original PCL on the difficulty of
300 ;;; doing this portably across different CLTL1 implementations. This
301 ;;; is no longer directly relevant because this code now only runs on
302 ;;; SBCL, but the comments are retained for culture: they might help
303 ;;; explain some of the design decisions which were made in the code.
304 ;;;
305 ;;; and I quote...
306 ;;;
307 ;;;     The set of special forms is purposely kept very small because
308 ;;;     any program analyzing program (read code walker) must have
309 ;;;     special knowledge about every type of special form. Such a
310 ;;;     program needs no special knowledge about macros...
311 ;;;
312 ;;; So all we have to do here is a define a way to store and retrieve
313 ;;; templates which describe how to walk the 24 special forms and we
314 ;;; are all set...
315 ;;;
316 ;;; Well, its a nice concept, and I have to admit to being naive
317 ;;; enough that I believed it for a while, but not everyone takes
318 ;;; having only 24 special forms as seriously as might be nice. There
319 ;;; are (at least) 3 ways to lose:
320 ;;
321 ;;;   1 - Implementation x implements a Common Lisp special form as 
322 ;;;       a macro which expands into a special form which:
323 ;;;      - Is a common lisp special form (not likely)
324 ;;;      - Is not a common lisp special form (on the 3600 IF --> COND).
325 ;;;
326 ;;;     * We can save ourselves from this case (second subcase really)
327 ;;;       by checking to see whether there is a template defined for 
328 ;;;       something before we check to see whether we can macroexpand it.
329 ;;;
330 ;;;   2 - Implementation x implements a Common Lisp macro as a special form.
331 ;;;
332 ;;;     * This is a screw, but not so bad, we save ourselves from it by
333 ;;;       defining extra templates for the macros which are *likely* to
334 ;;;       be implemented as special forms. [Note: As of sbcl-0.6.9, these
335 ;;;       extra templates have been deleted, since this is not a problem
336 ;;;       in SBCL and we no longer try to make this walker portable
337 ;;;       across other possibly-broken CL implementations.]
338 ;;;
339 ;;;   3 - Implementation x has a special form which is not on the list of
340 ;;;       Common Lisp special forms.
341 ;;;
342 ;;;     * This is a bad sort of a screw and happens more than I would 
343 ;;;       like to think, especially in the implementations which provide 
344 ;;;       more than just Common Lisp (3600, Xerox etc.).
345 ;;;       The fix is not terribly satisfactory, but will have to do for
346 ;;;       now. There is a hook in get walker-template which can get a
347 ;;;       template from the implementation's own walker. That template
348 ;;;       has to be converted, and so it may be that the right way to do
349 ;;;       this would actually be for that implementation to provide an
350 ;;;       interface to its walker which looks like the interface to this
351 ;;;       walker.
352
353 (defmacro get-walker-template-internal (x)
354   `(get ,x 'walker-template))
355
356 (defmacro define-walker-template (name
357                                   &optional (template '(nil repeat (eval))))
358   `(eval-when (:load-toplevel :execute)
359      (setf (get-walker-template-internal ',name) ',template)))
360
361 (defun get-walker-template (x context)
362   (cond ((symbolp x)
363          (get-walker-template-internal x))
364         ((and (listp x) (eq (car x) 'lambda))
365          '(lambda repeat (eval)))
366         (t
367          ;; FIXME: In an ideal world we would do something similar to
368          ;; COMPILER-ERROR here, replacing the form within the walker
369          ;; with an error-signalling form. This is slightly less
370          ;; pretty, but informative non the less. Best is the enemy of
371          ;; good, etc.
372          (error "Illegal function call in method body:~%  ~S"
373                 context))))
374 \f
375 ;;;; the actual templates
376
377 ;;; ANSI special forms
378 (define-walker-template block                (nil nil repeat (eval)))
379 (define-walker-template catch                (nil eval repeat (eval)))
380 (define-walker-template declare              walk-unexpected-declare)
381 (define-walker-template eval-when            (nil quote repeat (eval)))
382 (define-walker-template flet                 walk-flet)
383 (define-walker-template function             (nil call))
384 (define-walker-template go                   (nil quote))
385 (define-walker-template if                   walk-if)
386 (define-walker-template labels               walk-labels)
387 (define-walker-template lambda               walk-lambda)
388 (define-walker-template let                  walk-let)
389 (define-walker-template let*                 walk-let*)
390 (define-walker-template locally              walk-locally)
391 (define-walker-template macrolet             walk-macrolet)
392 (define-walker-template multiple-value-call  (nil eval repeat (eval)))
393 (define-walker-template multiple-value-prog1 (nil return repeat (eval)))
394 (define-walker-template multiple-value-setq  walk-multiple-value-setq)
395 (define-walker-template multiple-value-bind  walk-multiple-value-bind)
396 (define-walker-template progn                (nil repeat (eval)))
397 (define-walker-template progv                (nil eval eval repeat (eval)))
398 (define-walker-template quote                (nil quote))
399 (define-walker-template return-from          (nil quote repeat (return)))
400 (define-walker-template setq                 walk-setq)
401 (define-walker-template symbol-macrolet      walk-symbol-macrolet)
402 (define-walker-template tagbody              walk-tagbody)
403 (define-walker-template the                  (nil quote eval))
404 (define-walker-template throw                (nil eval eval))
405 (define-walker-template unwind-protect       (nil return repeat (eval)))
406
407 ;;; SBCL-only special forms
408 (define-walker-template sb!ext:truly-the     (nil quote eval))
409 ;;; FIXME: maybe we don't need this one any more, given that
410 ;;; NAMED-LAMBDA now expands into (FUNCTION (NAMED-LAMBDA ...))?
411 (define-walker-template named-lambda         walk-named-lambda)
412 \f
413 (defvar *walk-form-expand-macros-p* nil)
414
415 (defun walk-form (form
416                   &optional environment
417                             (walk-function
418                              (lambda (subform context env)
419                                (declare (ignore context env))
420                                subform)))
421   (walker-environment-bind (new-env environment :walk-function walk-function)
422     (walk-form-internal form :eval new-env)))
423
424 ;;; WALK-FORM-INTERNAL is the main driving function for the code
425 ;;; walker. It takes a form and the current context and walks the form
426 ;;; calling itself or the appropriate template recursively.
427 ;;;
428 ;;;   "It is recommended that a program-analyzing-program process a form
429 ;;;    that is a list whose car is a symbol as follows:
430 ;;;
431 ;;;     1. If the program has particular knowledge about the symbol,
432 ;;;        process the form using special-purpose code. All of the
433 ;;;        standard special forms should fall into this category.
434 ;;;     2. Otherwise, if MACRO-FUNCTION is true of the symbol apply
435 ;;;        either MACROEXPAND or MACROEXPAND-1 and start over.
436 ;;;     3. Otherwise, assume it is a function call. "
437 (defun walk-form-internal (form context env)
438   ;; First apply the walk-function to perform whatever translation
439   ;; the user wants to this form. If the second value returned
440   ;; by walk-function is T then we don't recurse...
441   (catch form
442     (multiple-value-bind (newform walk-no-more-p)
443         (funcall (env-walk-function env) form context env)
444       (catch newform
445         (cond
446          (walk-no-more-p newform)
447          ((not (eq form newform))
448           (walk-form-internal newform context env))
449          ((not (consp newform))
450           (let ((symmac (car (variable-symbol-macro-p newform env))))
451             (if symmac
452                 (let ((newnewform (walk-form-internal (cddr symmac)
453                                                       context
454                                                       env)))
455                   (if (eq newnewform (cddr symmac))
456                       (if *walk-form-expand-macros-p* newnewform newform)
457                       newnewform))
458                 newform)))
459          (t
460           (let* ((fn (car newform))
461                  (template (get-walker-template fn newform)))
462             (if template
463                 (if (symbolp template)
464                     (funcall template newform context env)
465                     (walk-template newform template context env))
466                 (multiple-value-bind (newnewform macrop)
467                     (walker-environment-bind
468                         (new-env env :walk-form newform)
469                       (sb-xc:macroexpand-1 newform new-env))
470                   (cond
471                    (macrop
472                     (let ((newnewnewform (walk-form-internal newnewform
473                                                              context
474                                                              env)))
475                       (if (eq newnewnewform newnewform)
476                           (if *walk-form-expand-macros-p* newnewform newform)
477                           newnewnewform)))
478                    ((and (symbolp fn)
479                          (not (fboundp fn))
480                          (special-operator-p fn))
481                     ;; This shouldn't happen, since this walker is now
482                     ;; maintained as part of SBCL, so it should know
483                     ;; about all the special forms that SBCL knows
484                     ;; about.
485                     (bug "unexpected special form ~S" fn))
486                    (t
487                     ;; Otherwise, walk the form as if it's just a
488                     ;; standard function call using a template for
489                     ;; standard function call.
490                     (walk-template
491                      newnewform '(call repeat (eval)) context env))))))))))))
492
493 (defun walk-template (form template context env)
494   (if (atom template)
495       (ecase template
496         ((eval function test effect return)
497          (walk-form-internal form :eval env))
498         ((quote nil) form)
499         (set
500           (walk-form-internal form :set env))
501         ((lambda call)
502          (cond ((legal-fun-name-p form)
503                 form)
504                (t (walk-form-internal form context env)))))
505       (case (car template)
506         (repeat
507           (walk-template-handle-repeat form
508                                        (cdr template)
509                                        ;; For the case where nothing
510                                        ;; happens after the repeat
511                                        ;; optimize away the call to
512                                        ;; LENGTH.
513                                        (if (null (cddr template))
514                                            ()
515                                            (nthcdr (- (length form)
516                                                       (length
517                                                         (cddr template)))
518                                                    form))
519                                        context
520                                        env))
521         (if
522           (walk-template form
523                          (if (if (listp (cadr template))
524                                  (eval (cadr template))
525                                  (funcall (cadr template) form))
526                              (caddr template)
527                              (cadddr template))
528                          context
529                          env))
530         (remote
531           (walk-template form (cadr template) context env))
532         (otherwise
533           (cond ((atom form) form)
534                 (t (recons form
535                            (walk-template
536                              (car form) (car template) context env)
537                            (walk-template
538                              (cdr form) (cdr template) context env))))))))
539
540 (defun walk-template-handle-repeat (form template stop-form context env)
541   (if (eq form stop-form)
542       (walk-template form (cdr template) context env)
543       (walk-template-handle-repeat-1
544        form template (car template) stop-form context env)))
545
546 (defun walk-template-handle-repeat-1 (form template repeat-template
547                                            stop-form context env)
548   (cond ((null form) ())
549         ((eq form stop-form)
550          (if (null repeat-template)
551              (walk-template stop-form (cdr template) context env)
552              (error "while handling code walker REPEAT:
553                      ~%ran into STOP while still in REPEAT template")))
554         ((null repeat-template)
555          (walk-template-handle-repeat-1
556            form template (car template) stop-form context env))
557         (t
558          (recons form
559                  (walk-template (car form) (car repeat-template) context env)
560                  (walk-template-handle-repeat-1 (cdr form)
561                                                 template
562                                                 (cdr repeat-template)
563                                                 stop-form
564                                                 context
565                                                 env)))))
566
567 (defun walk-repeat-eval (form env)
568   (and form
569        (recons form
570                (walk-form-internal (car form) :eval env)
571                (walk-repeat-eval (cdr form) env))))
572
573 (defun recons (x car cdr)
574   (if (or (not (eq (car x) car))
575           (not (eq (cdr x) cdr)))
576       (cons car cdr)
577       x))
578
579 (defun relist (x &rest args)
580   (if (null args)
581       nil
582       (relist-internal x args nil)))
583
584 (defun relist* (x &rest args)
585   (relist-internal x args t))
586
587 (defun relist-internal (x args *p)
588   (if (null (cdr args))
589       (if *p
590           (car args)
591           (recons x (car args) nil))
592       (recons x
593               (car args)
594               (relist-internal (cdr x) (cdr args) *p))))
595 \f
596 ;;;; special walkers
597
598 (defun walk-declarations (body fn env
599                                &optional doc-string-p declarations old-body
600                                &aux (form (car body)) macrop new-form)
601   (cond ((and (stringp form)                    ;might be a doc string
602               (cdr body)                        ;isn't the returned value
603               (null doc-string-p)               ;no doc string yet
604               (null declarations))              ;no declarations yet
605          (recons body
606                  form
607                  (walk-declarations (cdr body) fn env t)))
608         ((and (listp form) (eq (car form) 'declare))
609          ;; We got ourselves a real live declaration. Record it, look
610          ;; for more.
611          (dolist (declaration (cdr form))
612            (let ((type (car declaration))
613                  (name (cadr declaration))
614                  (args (cddr declaration)))
615              (if (member type *var-declarations*)
616                  (note-declaration `(,type
617                                      ,(or (var-lexical-p name env) name)
618                                      ,.args)
619                                    env)
620                  (note-declaration declaration env))
621              (push declaration declarations)))
622          (recons body
623                  form
624                  (walk-declarations
625                    (cdr body) fn env doc-string-p declarations)))
626         ((and form
627               (listp form)
628               (null (get-walker-template (car form) form))
629               (progn
630                 (multiple-value-setq (new-form macrop)
631                                      (sb-xc:macroexpand-1 form env))
632                 macrop))
633          ;; This form was a call to a macro. Maybe it expanded
634          ;; into a declare?  Recurse to find out.
635          (walk-declarations (recons body new-form (cdr body))
636                             fn env doc-string-p declarations
637                             (or old-body body)))
638         (t
639          ;; Now that we have walked and recorded the declarations,
640          ;; call the function our caller provided to expand the body.
641          ;; We call that function rather than passing the real-body
642          ;; back, because we are RECONSING up the new body.
643          (funcall fn (or old-body body) env))))
644
645 (defun walk-unexpected-declare (form context env)
646   (declare (ignore context env))
647   (warn "encountered ~S ~_in a place where a DECLARE was not expected"
648         form)
649   form)
650
651 (defun walk-arglist (arglist context env &optional (destructuringp nil)
652                                          &aux arg)
653   (cond ((null arglist) ())
654         ((symbolp (setq arg (car arglist)))
655          (or (member arg lambda-list-keywords)
656              (note-lexical-binding arg env))
657          (recons arglist
658                  arg
659                  (walk-arglist (cdr arglist)
660                                context
661                                env
662                                (and destructuringp
663                                     (not (member arg
664                                                  lambda-list-keywords))))))
665         ((consp arg)
666          (prog1 (recons arglist
667                         (if destructuringp
668                             (walk-arglist arg context env destructuringp)
669                             (relist* arg
670                                      (car arg)
671                                      (walk-form-internal (cadr arg) :eval env)
672                                      (cddr arg)))
673                         (walk-arglist (cdr arglist) context env nil))
674                 (if (symbolp (car arg))
675                     (note-lexical-binding (car arg) env)
676                     (note-lexical-binding (cadar arg) env))
677                 (or (null (cddr arg))
678                     (not (symbolp (caddr arg)))
679                     (note-lexical-binding (caddr arg) env))))
680           (t
681            (error "can't understand something in the arglist ~S" arglist))))
682
683 (defun walk-let (form context env)
684   (walk-let/let* form context env nil))
685
686 (defun walk-let* (form context env)
687   (walk-let/let* form context env t))
688
689 (defun walk-let/let* (form context old-env sequentialp)
690   (walker-environment-bind (new-env old-env)
691     (let* ((let/let* (car form))
692            (bindings (cadr form))
693            (body (cddr form))
694            (walked-bindings
695              (walk-bindings-1 bindings
696                               old-env
697                               new-env
698                               context
699                               sequentialp))
700            (walked-body
701              (walk-declarations body #'walk-repeat-eval new-env)))
702       (relist*
703         form let/let* walked-bindings walked-body))))
704
705 (defun walk-locally (form context env)
706   (declare (ignore context))
707   (let* ((locally (car form))
708          (body (cdr form))
709          (walked-body
710           (walk-declarations body #'walk-repeat-eval env)))
711     (relist*
712      form locally walked-body)))
713
714 (defun walk-multiple-value-setq (form context env)
715   (let ((vars (cadr form)))
716     (if (some (lambda (var)
717                 (variable-symbol-macro-p var env))
718               vars)
719         (let* ((temps (mapcar (lambda (var)
720                                 (declare (ignore var))
721                                 (gensym))
722                               vars))
723                (sets (mapcar (lambda (var temp) `(setq ,var ,temp))
724                              vars
725                              temps))
726                (expanded `(multiple-value-bind ,temps ,(caddr form)
727                              ,@sets))
728                (walked (walk-form-internal expanded context env)))
729           (if (eq walked expanded)
730               form
731               walked))
732         (walk-template form '(nil (repeat (set)) eval) context env))))
733
734 (defun walk-multiple-value-bind (form context old-env)
735   (walker-environment-bind (new-env old-env)
736     (let* ((mvb (car form))
737            (bindings (cadr form))
738            (mv-form (walk-template (caddr form) 'eval context old-env))
739            (body (cdddr form))
740            walked-bindings
741            (walked-body
742              (walk-declarations
743                body
744                (lambda (real-body real-env)
745                  (setq walked-bindings
746                        (walk-bindings-1 bindings
747                                         old-env
748                                         new-env
749                                         context
750                                         nil))
751                  (walk-repeat-eval real-body real-env))
752                new-env)))
753       (relist* form mvb walked-bindings mv-form walked-body))))
754
755 (defun walk-bindings-1 (bindings old-env new-env context sequentialp)
756   (and bindings
757        (let ((binding (car bindings)))
758          (recons bindings
759                  (if (symbolp binding)
760                      (prog1 binding
761                             (note-lexical-binding binding new-env))
762                      (prog1 (relist* binding
763                                      (car binding)
764                                      (walk-form-internal (cadr binding)
765                                                          context
766                                                          (if sequentialp
767                                                              new-env
768                                                              old-env))
769                                      ;; Save cddr for DO/DO*; it is
770                                      ;; the next value form. Don't
771                                      ;; walk it now, though.
772                                      (cddr binding))    
773                             (note-lexical-binding (car binding) new-env)))
774                  (walk-bindings-1 (cdr bindings)
775                                   old-env
776                                   new-env
777                                   context
778                                   sequentialp)))))
779
780 (defun walk-bindings-2 (bindings walked-bindings context env)
781   (and bindings
782        (let ((binding (car bindings))
783              (walked-binding (car walked-bindings)))
784          (recons bindings
785                  (if (symbolp binding)
786                      binding
787                      (relist* binding
788                               (car walked-binding)
789                               (cadr walked-binding)
790                               (walk-template (cddr binding)
791                                              '(eval)
792                                              context
793                                              env)))
794                  (walk-bindings-2 (cdr bindings)
795                                   (cdr walked-bindings)
796                                   context
797                                   env)))))
798
799 (defun walk-lambda (form context old-env)
800   (walker-environment-bind (new-env old-env)
801     (let* ((arglist (cadr form))
802            (body (cddr form))
803            (walked-arglist (walk-arglist arglist context new-env))
804            (walked-body
805              (walk-declarations body #'walk-repeat-eval new-env)))
806       (relist* form
807                (car form)
808                walked-arglist
809                walked-body))))
810
811 (defun walk-named-lambda (form context old-env)
812   (walker-environment-bind (new-env old-env)
813     (let* ((name (second form))
814            (arglist (third form))
815            (body (cdddr form))
816            (walked-arglist (walk-arglist arglist context new-env))
817            (walked-body
818              (walk-declarations body #'walk-repeat-eval new-env)))
819       (relist* form
820                (car form)
821                name
822                walked-arglist
823                walked-body))))
824
825 (defun walk-setq (form context env)
826   (if (cdddr form)
827       (let* ((expanded (let ((rforms nil)
828                              (tail (cdr form)))
829                          (loop (when (null tail) (return (nreverse rforms)))
830                                (let ((var (pop tail)) (val (pop tail)))
831                                  (push `(setq ,var ,val) rforms)))))
832              (walked (walk-repeat-eval expanded env)))
833         (if (eq expanded walked)
834             form
835             `(progn ,@walked)))
836       (let* ((var (cadr form))
837              (val (caddr form))
838              (symmac (car (variable-symbol-macro-p var env))))
839         (if symmac
840             (let* ((expanded `(setf ,(cddr symmac) ,val))
841                    (walked (walk-form-internal expanded context env)))
842               (if (eq expanded walked)
843                   form
844                   walked))
845             (relist form 'setq
846                     (walk-form-internal var :set env)
847                     (walk-form-internal val :eval env))))))
848
849 (defun walk-symbol-macrolet (form context old-env)
850   (declare (ignore context))
851   (let* ((bindings (cadr form))
852          (body (cddr form)))
853     (walker-environment-bind
854         (new-env old-env
855                  :lexical-vars
856                  (append (mapcar (lambda (binding)
857                                    `(,(car binding)
858                                      sb!sys:macro . ,(cadr binding)))
859                                  bindings)
860                          (env-lexical-variables old-env)))
861       (relist* form 'symbol-macrolet bindings
862                (walk-declarations body #'walk-repeat-eval new-env)))))
863
864 (defun walk-tagbody (form context env)
865   (recons form (car form) (walk-tagbody-1 (cdr form) context env)))
866
867 (defun walk-tagbody-1 (form context env)
868   (and form
869        (recons form
870                (walk-form-internal (car form)
871                                    (if (symbolp (car form)) 'quote context)
872                                    env)
873                (walk-tagbody-1 (cdr form) context env))))
874
875 (defun walk-macrolet (form context old-env)
876   (walker-environment-bind (macro-env
877                             nil
878                             :walk-function (env-walk-function old-env))
879     (labels ((walk-definitions (definitions)
880                (and definitions
881                     (let ((definition (car definitions)))
882                       (recons definitions
883                               (relist* definition
884                                        (car definition)
885                                        (walk-arglist (cadr definition)
886                                                      context
887                                                      macro-env
888                                                      t)
889                                        (walk-declarations (cddr definition)
890                                                           #'walk-repeat-eval
891                                                           macro-env))
892                               (walk-definitions (cdr definitions)))))))
893       (with-new-definition-in-environment (new-env old-env form)
894         (relist* form
895                  (car form)
896                  (walk-definitions (cadr form))
897                  (walk-declarations (cddr form)
898                                     #'walk-repeat-eval
899                                     new-env))))))
900
901 (defun walk-flet (form context old-env)
902   (labels ((walk-definitions (definitions)
903              (if (null definitions)
904                  ()
905                  (recons definitions
906                          (walk-lambda (car definitions) context old-env)
907                          (walk-definitions (cdr definitions))))))
908     (recons form
909             (car form)
910             (recons (cdr form)
911                     (walk-definitions (cadr form))
912                     (with-new-definition-in-environment (new-env old-env form)
913                       (walk-declarations (cddr form)
914                                          #'walk-repeat-eval
915                                          new-env))))))
916
917 (defun walk-labels (form context old-env)
918   (with-new-definition-in-environment (new-env old-env form)
919     (labels ((walk-definitions (definitions)
920                (if (null definitions)
921                    ()
922                    (recons definitions
923                            (walk-lambda (car definitions) context new-env)
924                            (walk-definitions (cdr definitions))))))
925       (recons form
926               (car form)
927               (recons (cdr form)
928                       (walk-definitions (cadr form))
929                       (walk-declarations (cddr form)
930                                          #'walk-repeat-eval
931                                          new-env))))))
932
933 (defun walk-if (form context env)
934   (destructuring-bind (if predicate arm1 &optional arm2) form
935     (declare (ignore if)) ; should be 'IF
936     (relist form
937             'if
938             (walk-form-internal predicate context env)
939             (walk-form-internal arm1 context env)
940             (walk-form-internal arm2 context env))))
941 \f
942 ;;;; examples
943
944 #|
945 ;;; Here are some examples of the kinds of things you should be able
946 ;;; to do with your implementation of the macroexpansion environment
947 ;;; hacking mechanism.
948 ;;;
949 ;;; WITH-LEXICAL-MACROS is kind of like MACROLET, but it only takes
950 ;;; names of the macros and actual macroexpansion functions to use to
951 ;;; macroexpand them. The win about that is that for macros which want
952 ;;; to wrap several MACROLETs around their body, they can do this but
953 ;;; have the macroexpansion functions be compiled. See the WITH-RPUSH
954 ;;; example.
955 ;;;
956 ;;; If the implementation had a special way of communicating the
957 ;;; augmented environment back to the evaluator that would be totally
958 ;;; great. It would mean that we could just augment the environment
959 ;;; then pass control back to the implementations own compiler or
960 ;;; interpreter. We wouldn't have to call the actual walker. That
961 ;;; would make this much faster. Since the principal client of this is
962 ;;; defmethod it would make compiling defmethods faster and that would
963 ;;; certainly be a win.
964
965 (defmacro with-lexical-macros (macros &body body &environment old-env)
966   (with-augmented-environment (new-env old-env :macros macros)
967     (walk-form (cons 'progn body) :environment new-env)))
968
969 (defun expand-rpush (form env)
970   (declare (ignore env))
971   `(push ,(caddr form) ,(cadr form)))
972
973 (defmacro with-rpush (&body body)
974   `(with-lexical-macros ,(list (list 'rpush #'expand-rpush)) ,@body))
975 |#