macros.lisp 13.7 KB
Newer Older
Nikodemus Siivola's avatar
Nikodemus Siivola committed
1
2
(in-package :alexandria)

Nikodemus Siivola's avatar
Nikodemus Siivola committed
3
(defmacro with-gensyms (names &body forms)
lovrolu's avatar
lovrolu committed
4
  "Binds a set of variables to gensyms and evaluates the implicit progn FORMS.
5

lovrolu's avatar
lovrolu committed
6
7
Each element within NAMES is either a symbol SYMBOL or a pair (SYMBOL
STRING-DESIGNATOR). Bare symbols are equivalent to the pair (SYMBOL SYMBOL).
8

lovrolu's avatar
lovrolu committed
9
10
11
Each pair (SYMBOL STRING-DESIGNATOR) specifies that the variable named by SYMBOL
should be bound to a symbol constructed using GENSYM with the string designated
by STRING-DESIGNATOR being its first argument."
Nikodemus Siivola's avatar
Nikodemus Siivola committed
12
  `(let ,(mapcar (lambda (name)
Nikodemus Siivola's avatar
Nikodemus Siivola committed
13
14
15
16
17
18
19
                   (multiple-value-bind (symbol string)
                       (etypecase name
                         (symbol
                          (values name (symbol-name name)))
                         ((cons symbol (cons string-designator null))
                          (values (first name) (string (second name)))))
                     `(,symbol (gensym ,string))))
Nikodemus Siivola's avatar
Nikodemus Siivola committed
20
21
22
                 names)
     ,@forms))

Nikodemus Siivola's avatar
Nikodemus Siivola committed
23
(defmacro with-unique-names (names &body forms)
24
25
  "Alias for WITH-GENSYMS."
  `(with-gensyms ,names ,@forms))
Nikodemus Siivola's avatar
Nikodemus Siivola committed
26

Nikodemus Siivola's avatar
Nikodemus Siivola committed
27
(defmacro once-only (specs &body forms)
lovrolu's avatar
lovrolu committed
28
29
30
  "Constructs code whose primary goal is to help automate the handling of
multiple evaluation within macros. Multiple evaluation is handled by introducing
intermediate variables, in order to reuse the result of an expression.
Nikodemus Siivola's avatar
Nikodemus Siivola committed
31

lovrolu's avatar
lovrolu committed
32
The returned value is a list of the form
Nikodemus Siivola's avatar
Nikodemus Siivola committed
33

lovrolu's avatar
lovrolu committed
34
35
36
37
  (let ((<gensym-1> <expr-1>)
        ...
        (<gensym-n> <expr-n>))
    <res>)
Nikodemus Siivola's avatar
Nikodemus Siivola committed
38

lovrolu's avatar
lovrolu committed
39
40
41
42
where GENSYM-1, ..., GENSYM-N are the intermediate variables introduced in order
to evaluate EXPR-1, ..., EXPR-N once, only. RES is code that is the result of
evaluating the implicit progn FORMS within a special context determined by
SPECS. RES should make use of (reference) the intermediate variables.
Nikodemus Siivola's avatar
Nikodemus Siivola committed
43

lovrolu's avatar
lovrolu committed
44
45
46
47
48
49
50
51
52
53
54
55
56
Each element within SPECS is either a symbol SYMBOL or a pair (SYMBOL INITFORM).
Bare symbols are equivalent to the pair (SYMBOL SYMBOL).

Each pair (SYMBOL INITFORM) specifies a single intermediate variable:

- INITFORM is an expression evaluated to produce EXPR-i

- SYMBOL is the name of the variable that will be bound around FORMS to the
  corresponding gensym GENSYM-i, in order for FORMS to generate RES that
  references the intermediate variable

The evaluation of INITFORMs and binding of SYMBOLs resembles LET. INITFORMs of
all the pairs are evaluated before binding SYMBOLs and evaluating FORMS.
Nikodemus Siivola's avatar
Nikodemus Siivola committed
57
58

Example:
Nikodemus Siivola's avatar
Nikodemus Siivola committed
59

lovrolu's avatar
lovrolu committed
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
  The following expression

  (let ((x '(incf y)))
    (once-only (x)
      `(cons ,x ,x)))

  ;;; =>
  ;;; (let ((#1=#:X123 (incf y)))
  ;;;   (cons #1# #1#))

  could be used within a macro to avoid multiple evaluation like so

  (defmacro cons1 (x)
    (once-only (x)
      `(cons ,x ,x)))

  (let ((y 0))
    (cons1 (incf y)))

  ;;; => (1 . 1)

Example:

  The following expression demonstrates the usage of the INITFORM field

  (let ((expr '(incf y)))
    (once-only ((var `(1+ ,expr)))
      `(list ',expr ,var ,var)))

  ;;; =>
  ;;; (let ((#1=#:VAR123 (1+ (incf y))))
  ;;;   (list '(incf y) #1# #1))

  which could be used like so

  (defmacro print-succ-twice (expr)
    (once-only ((var `(1+ ,expr)))
      `(format t \"Expr: ~s, Once: ~s, Twice: ~s~%\" ',expr ,var ,var)))

  (let ((y 10))
    (print-succ-twice (incf y)))

  ;;; >>
  ;;; Expr: (INCF Y), Once: 12, Twice: 12"
Nikodemus Siivola's avatar
Nikodemus Siivola committed
104
105
106
107
108
109
110
111
112
  (let ((gensyms (make-gensym-list (length specs) "ONCE-ONLY"))
        (names-and-forms (mapcar (lambda (spec)
                                   (etypecase spec
                                     (list
                                      (destructuring-bind (name form) spec
                                        (cons name form)))
                                     (symbol
                                      (cons spec spec))))
                                 specs)))
Nikodemus Siivola's avatar
Nikodemus Siivola committed
113
    ;; bind in user-macro
Nikodemus Siivola's avatar
Nikodemus Siivola committed
114
115
    `(let ,(mapcar (lambda (g n) (list g `(gensym ,(string (car n)))))
                   gensyms names-and-forms)
Nikodemus Siivola's avatar
Nikodemus Siivola committed
116
       ;; bind in final expansion
Nikodemus Siivola's avatar
Nikodemus Siivola committed
117
118
119
       `(let (,,@(mapcar (lambda (g n)
                           ``(,,g ,,(cdr n)))
                         gensyms names-and-forms))
120
          ;; bind in user-macro
Nikodemus Siivola's avatar
Nikodemus Siivola committed
121
122
          ,(let ,(mapcar (lambda (n g) (list (car n) g))
                         names-and-forms gensyms)
Nikodemus Siivola's avatar
Nikodemus Siivola committed
123
124
             ,@forms)))))

125
126
127
128
129
(defun parse-body (body &key documentation whole)
  "Parses BODY into (values remaining-forms declarations doc-string).
Documentation strings are recognized only if DOCUMENTATION is true.
Syntax errors in body are signalled and WHOLE is used in the signal
arguments when given."
Nikodemus Siivola's avatar
Nikodemus Siivola committed
130
131
132
133
134
135
  (let ((doc nil)
        (decls nil)
        (current nil))
    (tagbody
     :declarations
       (setf current (car body))
136
137
138
139
       (when (and documentation (stringp current) (cdr body))
         (if doc
             (error "Too many documentation strings in ~S." (or whole body))
             (setf doc (pop body)))
Nikodemus Siivola's avatar
Nikodemus Siivola committed
140
         (go :declarations))
141
       (when (and (listp current) (eql (first current) 'declare))
Nikodemus Siivola's avatar
Nikodemus Siivola committed
142
143
144
         (push (pop body) decls)
         (go :declarations)))
    (values body (nreverse decls) doc)))
145

146
(defun parse-ordinary-lambda-list (lambda-list &key (normalize t)
147
                                   allow-specializers
148
149
150
                                   (normalize-optional normalize)
                                   (normalize-keyword normalize)
                                   (normalize-auxilary normalize))
Nikodemus Siivola's avatar
Nikodemus Siivola committed
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
  "Parses an ordinary lambda-list, returning as multiple values:

1. Required parameters.

2. Optional parameter specifications, normalized into form:

   (name init suppliedp)

3. Name of the rest parameter, or NIL.

4. Keyword parameter specifications, normalized into form:

   ((keyword-name name) init suppliedp)

5. Boolean indicating &ALLOW-OTHER-KEYS presence.

6. &AUX parameter specifications, normalized into form

   (name init).
170

171
172
7. Existence of &KEY in the lambda-list.

173
174
175
176
177
178
179
180
Signals a PROGRAM-ERROR is the lambda-list is malformed."
  (let ((state :required)
        (allow-other-keys nil)
        (auxp nil)
        (required nil)
        (optional nil)
        (rest nil)
        (keys nil)
181
        (keyp nil)
182
183
184
185
        (aux nil))
    (labels ((fail (elt)
               (simple-program-error "Misplaced ~S in ordinary lambda-list:~%  ~S"
                                     elt lambda-list))
186
187
188
189
190
             (check-variable (elt what &optional (allow-specializers allow-specializers))
               (unless (and (or (symbolp elt)
                                (and allow-specializers
                                     (consp elt) (= 2 (length elt)) (symbolp (first elt))))
                            (not (constantp elt)))
191
192
193
194
195
                 (simple-program-error "Invalid ~A ~S in ordinary lambda-list:~%  ~S"
                                       what elt lambda-list)))
             (check-spec (spec what)
               (destructuring-bind (init suppliedp) spec
                 (declare (ignore init))
196
                 (check-variable suppliedp what nil))))
197
198
199
200
201
202
203
204
205
      (dolist (elt lambda-list)
        (case elt
          (&optional
           (if (eq state :required)
               (setf state elt)
               (fail elt)))
          (&rest
           (if (member state '(:required &optional))
               (setf state elt)
206
               (fail elt)))
207
208
209
          (&key
           (if (member state '(:required &optional :after-rest))
               (setf state elt)
210
211
               (fail elt))
           (setf keyp t))
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
          (&allow-other-keys
           (if (eq state '&key)
               (setf allow-other-keys t
                     state elt)
               (fail elt)))
          (&aux
           (cond ((eq state '&rest)
                  (fail elt))
                 (auxp
                  (simple-program-error "Multiple ~S in ordinary lambda-list:~%  ~S"
                                        elt lambda-list))
                 (t
                  (setf auxp t
                        state elt))
                 ))
          (otherwise
           (when (member elt '#.(set-difference lambda-list-keywords
                                                '(&optional &rest &key &allow-other-keys &aux)))
             (simple-program-error
              "Bad lambda-list keyword ~S in ordinary lambda-list:~%  ~S"
              elt lambda-list))
           (case state
             (:required
              (check-variable elt "required parameter")
              (push elt required))
             (&optional
              (cond ((consp elt)
                     (destructuring-bind (name &rest tail) elt
                       (check-variable name "optional parameter")
241
242
                       (cond ((cdr tail)
                              (check-spec tail "optional-supplied-p parameter"))
243
244
                             ((and normalize-optional tail)
                              (setf elt (append elt '(nil))))
245
                             (normalize-optional
246
                              (setf elt (append elt '(nil nil)))))))
247
248
                    (t
                     (check-variable elt "optional parameter")
249
250
251
                     (when normalize-optional
                       (setf elt (cons elt '(nil nil))))))
              (push (ensure-list elt) optional))
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
             (&rest
              (check-variable elt "rest parameter")
              (setf rest elt
                    state :after-rest))
             (&key
              (cond ((consp elt)
                     (destructuring-bind (var-or-kv &rest tail) elt
                       (cond ((consp var-or-kv)
                              (destructuring-bind (keyword var) var-or-kv
                                (unless (symbolp keyword)
                                  (simple-program-error "Invalid keyword name ~S in ordinary ~
                                                         lambda-list:~%  ~S"
                                                        keyword lambda-list))
                                (check-variable var "keyword parameter")))
                             (t
                              (check-variable var-or-kv "keyword parameter")
268
269
                              (when normalize-keyword
                                (setf var-or-kv (list (make-keyword var-or-kv) var-or-kv)))))
270
271
272
273
274
275
                       (cond ((cdr tail)
                              (check-spec tail "keyword-supplied-p parameter"))
                             ((and normalize-keyword tail)
                              (setf tail (append tail '(nil))))
                             (normalize-keyword
                              (setf tail '(nil nil))))
276
277
278
                       (setf elt (cons var-or-kv tail))))
                    (t
                     (check-variable elt "keyword parameter")
279
280
                     (setf elt (if normalize-keyword
                                   (list (list (make-keyword elt) elt) nil nil)
281
                                   elt))))
282
283
284
285
286
287
              (push elt keys))
             (&aux
              (if (consp elt)
                  (destructuring-bind (var &optional init) elt
                    (declare (ignore init))
                    (check-variable var "&aux parameter"))
288
289
                  (progn
                    (check-variable elt "&aux parameter")
290
291
                    (setf elt (list* elt (when normalize-auxilary
                                           '(nil))))))
292
293
294
295
              (push elt aux))
             (t
              (simple-program-error "Invalid ordinary lambda-list:~%  ~S" lambda-list)))))))
    (values (nreverse required) (nreverse optional) rest (nreverse keys)
296
            allow-other-keys (nreverse aux) keyp)))
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330

;;;; DESTRUCTURING-*CASE

(defun expand-destructuring-case (key clauses case)
  (once-only (key)
    `(if (typep ,key 'cons)
         (,case (car ,key)
           ,@(mapcar (lambda (clause)
                       (destructuring-bind ((keys . lambda-list) &body body) clause
                         `(,keys
                           (destructuring-bind ,lambda-list (cdr ,key)
                             ,@body))))
                     clauses))
         (error "Invalid key to DESTRUCTURING-~S: ~S" ',case ,key))))

(defmacro destructuring-case (keyform &body clauses)
  "DESTRUCTURING-CASE, -CCASE, and -ECASE are a combination of CASE and DESTRUCTURING-BIND.
KEYFORM must evaluate to a CONS.

Clauses are of the form:

  ((CASE-KEYS . DESTRUCTURING-LAMBDA-LIST) FORM*)

The clause whose CASE-KEYS matches CAR of KEY, as if by CASE, CCASE, or ECASE,
is selected, and FORMs are then executed with CDR of KEY is destructured and
bound by the DESTRUCTURING-LAMBDA-LIST.

Example:

 (defun dcase (x)
   (destructuring-case x
     ((:foo a b)
      (format nil \"foo: ~S, ~S\" a b))
     ((:bar &key a b)
331
      (format nil \"bar: ~S, ~S\" a b))
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
     (((:alt1 :alt2) a)
      (format nil \"alt: ~S\" a))
     ((t &rest rest)
      (format nil \"unknown: ~S\" rest))))

  (dcase (list :foo 1 2))        ; => \"foo: 1, 2\"
  (dcase (list :bar :a 1 :b 2))  ; => \"bar: 1, 2\"
  (dcase (list :alt1 1))         ; => \"alt: 1\"
  (dcase (list :alt2 2))         ; => \"alt: 2\"
  (dcase (list :quux 1 2 3))     ; => \"unknown: 1, 2, 3\"

 (defun decase (x)
   (destructuring-case x
     ((:foo a b)
      (format nil \"foo: ~S, ~S\" a b))
     ((:bar &key a b)
348
      (format nil \"bar: ~S, ~S\" a b))
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
     (((:alt1 :alt2) a)
      (format nil \"alt: ~S\" a))))

  (decase (list :foo 1 2))        ; => \"foo: 1, 2\"
  (decase (list :bar :a 1 :b 2))  ; => \"bar: 1, 2\"
  (decase (list :alt1 1))         ; => \"alt: 1\"
  (decase (list :alt2 2))         ; => \"alt: 2\"
  (decase (list :quux 1 2 3))     ; =| error
"
  (expand-destructuring-case keyform clauses 'case))

(defmacro destructuring-ccase (keyform &body clauses)
  (expand-destructuring-case keyform clauses 'ccase))

(defmacro destructuring-ecase (keyform &body clauses)
  (expand-destructuring-case keyform clauses 'ecase))

(dolist (name '(destructuring-ccase destructuring-ecase))
  (setf (documentation name 'function) (documentation 'destructuring-case 'function)))