closer-mop.lisp 24.4 KB
Newer Older
Pascal Costanza's avatar
Pascal Costanza committed
1
2
(in-package :closer-mop)

3
4
5
6
7
8
9
;; This is a useful utility function.

(defun required-args (lambda-list &optional (collector #'identity))
  (loop for arg in lambda-list
        until (member arg lambda-list-keywords)
        collect (funcall collector arg)))

Pascal Costanza's avatar
Pascal Costanza committed
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
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
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
;; We need a new standard-generic-function for various things.

(cl:defclass standard-generic-function (cl:standard-generic-function)
  ()
  (:metaclass clos:funcallable-standard-class))

;; The following ensures that the new standard-generic-function is used.

(defun ensure-generic-function
       (name &rest args
             &key (generic-function-class 'standard-generic-function)
             &allow-other-keys)
  (declare (dynamic-extent args))
  (when (fboundp name)
    (let ((function (fdefinition name)))
      (unless (typep function 'generic-function)
        (cerror "Discard existing definition and create generic function."
                "~S is already fbound, but not as a generic function." name)
        (fmakunbound name))))
  (if (fboundp name)
      (let ((function (fdefinition name)))
        (apply #'ensure-generic-function-using-class
               function name args))
    (apply #'ensure-generic-function-using-class nil name
           :generic-function-class generic-function-class
           args)))

;; We need a new standard-class for various things.

(cl:defclass standard-class (cl:standard-class)
  ())

;; validate-superclass for metaclass classes is a little bit
;; more tricky than for class metaobject classes because
;; we don't want to make all standard-classes compatible to
;; each other.

;; Our validate-superclass may get passed a class-prototype
;; as its second argument, so don't expect its readers to
;; yield useful information. (In ANSI parlance, "the
;; consequences are undefined...")

(cl:defmethod validate-superclass
           ((class standard-class)
            (superclass cl:standard-class))
  (or (when (eq (class-of class) (find-class 'standard-class))
        (member (class-of superclass)
                (list (find-class 'cl:standard-class)
                      (find-class 'standard-class))))
      (call-next-method)
      (when (eq (class-of superclass) (find-class 'cl:standard-class))
        (validate-superclass class (class-prototype (find-class 'standard-class))))))

;; The following macro ensures that the new standard-class is used
;; by default. It would have been useful to fix other deficiencies
;; in a complete redefinition of defclass, but there is no portable
;; way to ensure the necessary compile-time effects as specified
;; by ANSI Common Lisp. Therefore, we just expand to the original
;; cl:defclass.
    
(defmacro defclass (name (&rest supers) &body options)
  (if (member :metaclass options :key #'car)
      `(cl:defclass ,name ,supers ,@options)
    `(cl:defclass ,name ,supers ,@options
       (:metaclass standard-class))))

;; We need a new funcallable-standard-class for various things.

(cl:defclass funcallable-standard-class (clos:funcallable-standard-class)
  ())

;; See the comment on validate-superclass for standard-class above.

(cl:defmethod validate-superclass
           ((class funcallable-standard-class)
            (superclass clos:funcallable-standard-class))
  (or (when (eq (class-of class) (find-class 'funcallable-standard-class))
        (member (class-of superclass)
                (list (find-class 'clos:funcallable-standard-class)
                      (find-class 'funcallable-standard-class))))
      (call-next-method)
      (when (eq (class-of superclass) (find-class 'clos:funcallable-standard-class))
        (validate-superclass class (class-prototype (find-class 'funcallable-standard-class))))))

;; We also need a new funcallable-standard-object because the default one
;; is not an instance of clos:funcallable-standard-class.

(cl:defclass funcallable-standard-object (clos:funcallable-standard-object)
  ()
  (:metaclass clos:funcallable-standard-class))

;; The following code ensures that possibly incorrect lists of direct
;; superclasses are corrected.

(defun modify-superclasses (direct-superclasses &optional (standardp t))
  (if (null direct-superclasses)
      (list (if standardp
                (find-class 'standard-object)
              (find-class 'funcallable-standard-object)))
    (let ((standard-object (if standardp
                               (find-class 'standard-object)
                             (find-class 'clos:funcallable-standard-object))))
      (if (eq (car (last direct-superclasses)) standard-object)
          (if standardp
              direct-superclasses
            (append (butlast direct-superclasses)
                    (list (find-class 'funcallable-standard-object))))
        (remove standard-object direct-superclasses)))))

;; During class re/initialization, we take care of the following things:
;; - Optimization of slot accessors is deactivated.
;; - Lists of direct superclasses are corrected.
;; - Removal of direct subclasses.

(cl:defmethod initialize-instance :around
125
126
  ((class standard-class) &rest initargs
   &key (direct-superclasses ()))
127
128
  (declare (dynamic-extent initargs))
  (apply #'call-next-method class
Pascal Costanza's avatar
Pascal Costanza committed
129
         :direct-superclasses (modify-superclasses direct-superclasses)
130
131
132
         :optimize-slot-access nil
         initargs))

Pascal Costanza's avatar
Pascal Costanza committed
133
(cl:defmethod reinitialize-instance :around
134
135
  ((class standard-class) &rest initargs
   &key  (direct-superclasses () direct-superclasses-p))
Pascal Costanza's avatar
Pascal Costanza committed
136
137
138
139
140
141
142
143
144
  (declare (dynamic-extent initargs))
  (when direct-superclasses-p
    (setq direct-superclasses (modify-superclasses direct-superclasses))
    (loop for superclass in (copy-list (class-direct-superclasses class))
          unless (member superclass direct-superclasses)
          do (remove-direct-subclass superclass class)))
  (if direct-superclasses-p
      (apply #'call-next-method class
             :direct-superclasses direct-superclasses
Pascal Costanza's avatar
Pascal Costanza committed
145
             :optimize-slot-access nil
Pascal Costanza's avatar
Pascal Costanza committed
146
             initargs)
Pascal Costanza's avatar
Pascal Costanza committed
147
148
149
    (apply #'call-next-method class
           :optimize-slot-access nil
           initargs)))
Pascal Costanza's avatar
Pascal Costanza committed
150
151

(cl:defmethod initialize-instance :around
152
153
  ((class funcallable-standard-class) &rest initargs
   &key (direct-superclasses ()))
154
155
  (declare (dynamic-extent initargs))
  (apply #'call-next-method class
Pascal Costanza's avatar
Pascal Costanza committed
156
         :direct-superclasses (modify-superclasses direct-superclasses nil)
157
158
159
         :optimize-slot-access nil
         initargs))

Pascal Costanza's avatar
Pascal Costanza committed
160
(cl:defmethod reinitialize-instance :around
161
162
  ((class funcallable-standard-class) &rest initargs
   &key (direct-superclasses () direct-superclasses-p))
Pascal Costanza's avatar
Pascal Costanza committed
163
164
165
166
167
168
169
170
171
  (declare (dynamic-extent initargs))
  (when direct-superclasses-p
    (setq direct-superclasses (modify-superclasses direct-superclasses nil))
    (loop for superclass in (copy-list (class-direct-superclasses class))
          unless (member superclass direct-superclasses)
          do (remove-direct-subclass superclass class)))
  (if direct-superclasses-p
      (apply #'call-next-method class
             :direct-superclasses direct-superclasses
Pascal Costanza's avatar
Pascal Costanza committed
172
             :optimize-slot-access nil
Pascal Costanza's avatar
Pascal Costanza committed
173
             initargs)
Pascal Costanza's avatar
Pascal Costanza committed
174
175
176
    (apply #'call-next-method class
           :optimize-slot-access nil
           initargs)))
Pascal Costanza's avatar
Pascal Costanza committed
177
178
179
180
181
182
183
184

;; The following is necessary for forward-referenced-classes.
;; Since we replace the original funcallable-standard-object with
;; a new one, we have to prevent LispWorks from trying to use
;; the original one when forward-ferenced-classes are resolved.

(cl:defmethod change-class :around
  ((class forward-referenced-class)
Pascal Costanza's avatar
Pascal Costanza committed
185
186
   (new-class funcallable-standard-class)
   &rest initargs
187
   &key (direct-superclasses ()))
Pascal Costanza's avatar
Pascal Costanza committed
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
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
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
  (declare (dynamic-extent initargs))
  (apply #'call-next-method class new-class
         :optimize-slot-access nil
         :direct-superclasses (modify-superclasses direct-superclasses nil)
         initargs))

;;; In LispWorks, the slot accessors (slot-value-using-class, etc.) are specialized
;;; on slot names instead of effective slot definitions. In order to fix this,
;;; we need to rewire the slot access protocol.

(cl:defmethod slot-value-using-class
           ((class standard-class) object (slot symbol))
  (declare (optimize (speed 3) (debug 0) (safety 0)
                     (compilation-speed 0)))
  (let ((slotd (find slot (class-slots class)
                     :test #'eq
                     :key #'slot-definition-name)))
    (if slotd
        (slot-value-using-class class object slotd)
      (slot-missing class object slot 'slot-value))))

(cl:defmethod slot-value-using-class
           ((class standard-class) object (slotd standard-effective-slot-definition))
  (declare (optimize (speed 3) (debug 0) (safety 0)
                     (compilation-speed 0)))
  (slot-value-using-class
   (load-time-value (class-prototype (find-class 'cl:standard-class)))
   object
   (slot-definition-name slotd)))

(cl:defmethod (setf slot-value-using-class)
           (new-value (class standard-class) object (slot symbol))
  (declare (optimize (speed 3) (debug 0) (safety 0)
                     (compilation-speed 0)))
  (let ((slotd (find slot (class-slots class)
                     :test #'eq
                     :key #'slot-definition-name)))
    (if slotd
        (setf (slot-value-using-class class object slotd)
              new-value)
      (slot-missing class object slot 'setf new-value))))

(cl:defmethod (setf slot-value-using-class)
           (new-value (class standard-class) object (slotd standard-effective-slot-definition))
  (declare (optimize (speed 3) (debug 0) (safety 0)
                     (compilation-speed 0)))
  (setf (slot-value-using-class
         (load-time-value (class-prototype (find-class 'cl:standard-class)))
         object
         (slot-definition-name slotd))
        new-value))

(cl:defmethod slot-boundp-using-class
           ((class standard-class) object (slot symbol))
  (declare (optimize (speed 3) (debug 0) (safety 0)
                     (compilation-speed 0)))
  (let ((slotd (find slot (class-slots class)
                     :test #'eq
                     :key #'slot-definition-name)))
    (if slotd
        (slot-boundp-using-class class object slotd)
      (slot-missing class object slot 'slot-boundp))))

(cl:defmethod slot-boundp-using-class
           ((class standard-class) object (slotd standard-effective-slot-definition))
  (declare (optimize (speed 3) (debug 0) (safety 0)
                     (compilation-speed 0)))
  (slot-boundp-using-class
   (load-time-value (class-prototype (find-class 'cl:standard-class)))
   object
   (slot-definition-name slotd)))

(cl:defmethod slot-makunbound-using-class
           ((class standard-class) object (slot symbol))
  (declare (optimize (speed 3) (debug 0) (safety 0)
                     (compilation-speed 0)))
  (let ((slotd (find slot (class-slots class)
                     :test #'eq
                     :key #'slot-definition-name)))
    (if slotd
        (slot-makunbound-using-class class object slotd)
      (slot-missing class object slot 'slot-makunbound))))

(cl:defmethod slot-makunbound-using-class
           ((class standard-class) object (slotd standard-effective-slot-definition))
  (declare (optimize (speed 3) (debug 0) (safety 0)
                     (compilation-speed 0)))
  (slot-makunbound-using-class
   (load-time-value (class-prototype (find-class 'cl:standard-class)))
   object
   (slot-definition-name slotd)))

;; In LispWorks, eql specializers are lists. We cannot change this
;; but we can soften some of the incompatibilities.

(deftype eql-specializer ()
  '(or eql-specializer*
       (satisfies clos:eql-specializer-p)))

(cl:defgeneric eql-specializer-object (eql-specializer)
  (:method ((cons cons))
   (if (clos:eql-specializer-p cons)
       (cadr cons)
     (error "~S is not an eql-specializer." cons))))

(defun intern-eql-specializer (object)
  `(eql ,object))

(cl:defclass eql-specializer* (metaobject)
297
298
299
  ((obj :reader eql-specializer-object
        :initarg eso
        :initform (error "Use intern-eql-specializer to create eql-specializers."))
Pascal Costanza's avatar
Pascal Costanza committed
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
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
   (direct-methods :reader specializer-direct-methods
                   :accessor es-direct-methods
                   :initform ())))

(defvar *eql-specializers* (make-hash-table))

(defun intern-eql-specializer* (object)
  (or (gethash object *eql-specializers*)
      (setf (gethash object *eql-specializers*)
            (make-instance 'eql-specializer* 'eso object))))

(cl:defmethod add-direct-method ((specializer eql-specializer*) (method method))
  (pushnew method (es-direct-methods specializer)))

(cl:defmethod remove-direct-method ((specializer eql-specializer*) (method method))
  (removef (es-direct-methods specializer) method))

(cl:defgeneric specializer-direct-generic-functions (specializer)
  (:method ((class class))
   (remove-duplicates
    (mapcar #'method-generic-function
            (specializer-direct-methods class))))
  (:method ((eql-specializer eql-specializer*))
   (remove-duplicates
    (mapcar #'method-generic-function
            (specializer-direct-methods eql-specializer))))
  (:method ((cons cons))
   (specializer-direct-generic-functions
    (intern-eql-specializer*
     (eql-specializer-object cons)))))

;; The following method ensures that remove-method is called.

(cl:defmethod add-method :before ((gf standard-generic-function) (method method))
  (when-let (old-method (find-method gf (method-qualifiers method)
                                     (method-specializers method) nil))
    (remove-method gf old-method)))

;; The following two methods ensure that add/remove-direct-method is called,
;; and that the dependent protocol for generic function works.

(cl:defmethod add-method :after ((gf standard-generic-function) (method method))
  (loop for specializer in (method-specializers method)
        do (add-direct-method
            (if (consp specializer)
                (intern-eql-specializer*
                 (eql-specializer-object specializer))
              specializer)
            method))
  #+lispworks4.3
  (map-dependents
   gf (lambda (dep) (update-dependent gf dep 'add-method method))))

(cl:defmethod remove-method :after ((gf standard-generic-function) (method method))
  (loop for specializer in (method-specializers method)
        do (remove-direct-method
            (if (consp specializer)
                (intern-eql-specializer*
                 (eql-specializer-object specializer))
              specializer)
            method))
  #+lispworks4.3
  (map-dependents
   gf (lambda (dep) (update-dependent gf dep 'remove-method method))))

(cl:defgeneric find-method-combination (gf combi combi-options)
  (:method ((gf generic-function) (combi symbol) combi-options)
   (when combi-options
     (error "This implementation of find-method-combination cannot handle method combination options."))
   (clos::find-a-method-combination-type combi)))

;; In LispWorks, make-method-lambda expects different arguments than those
;; specified in AMOP. We just bridge this. The method lambda returned
;; still doesn't conform to AMOP, but may be good enough.

(cl:defgeneric make-method-lambda (gf method lambda-expression env)
  (:method ((gf cl:standard-generic-function)
            (method standard-method)
            lambda-expression env)
   (declare (ignorable env))
   (destructuring-bind
       (lambda (&rest args) &body body)
       lambda-expression
     (declare (ignore lambda))
     (loop with documentation = :unbound
           for tail on body
           while (or (stringp (car tail))
                     (and (consp (car tail))
                          (eq (caar tail) 'declare)))
           if (stringp (car tail))
           do (setf documentation
                    (if (eq documentation :unbound)
                        (car tail)
                      (error "Too many documentation strings in lambda expression ~S."
                             lambda-expression)))
           else append (loop for declaration in (cdar tail) 
                             if (eq (car declaration) 'ignore)
                             collect `(ignorable ,@(cdr declaration))
                             and collect `(dynamic-extent ,@(cdr declaration))
                             else collect declaration) into declarations
           finally (multiple-value-bind
                       (method-lambda method-args)
                       (clos:make-method-lambda
                        gf method args declarations
                        `(progn ,@tail) env)
                     (if (eq documentation :unbound)
                         (return (values method-lambda method-args))
                       (return (values
                                `(lambda ,(cadr method-lambda)
                                   ,documentation
                                   ,@(cddr method-lambda))
                                method-args))))))))

(defun ensure-method (gf lambda-expression 
                         &key (method-class (generic-function-method-class gf))
                         (qualifiers ())
                         (lambda-list (cadr lambda-expression))
417
                         (specializers (required-args lambda-list (constantly (find-class 't)))))
Pascal Costanza's avatar
Pascal Costanza committed
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
  (multiple-value-bind
      (method-lambda method-args)
      (make-method-lambda
       gf (class-prototype method-class)
       lambda-expression ())
    (let ((method  (apply #'make-instance
                          method-class
                          :qualifiers qualifiers
                          :lambda-list lambda-list
                          :specializers specializers
                          :function (compile nil method-lambda)
                          method-args)))
      (add-method gf method)
      method)))

;; helper function for creating a generic function lambda list
;; from a method lambda list.
(defun create-gf-lambda-list (method-lambda-list)
  (loop with stop-keywords = '#.(remove '&optional lambda-list-keywords)
        for arg in method-lambda-list
        until (member arg stop-keywords)
        collect arg into gf-lambda-list
        finally (return (if (member arg '(&rest &key))
                            (append gf-lambda-list '(&key))
                          gf-lambda-list))))

;; The defmethod macro is needed in order to ensure that make-method-lambda
;; is called. (Unfortunately, this doesn't work in the other CL implementations.)

(defmacro defmethod (&whole form name &body body &environment env)
  (loop for tail on body
        until (listp (car tail))
        collect (car tail) into qualifiers
        finally
        (destructuring-bind
            ((&rest specialized-args) &body body) tail
          (loop with documentation = :unbound
                for tail on body
                while (or (stringp (car tail))
                          (and (consp (car tail))
                               (eq (caar tail) 'declare)))
                if (stringp (car tail))
                do (setq documentation
                         (if (eq documentation :unbound)
                             (car tail)
                           (error "Too many documentation strings for defmethod form ~S." form)))
                else append (cdar tail) into declarations
                finally
                (let* ((lambda-list (extract-lambda-list specialized-args))
                       (gf-lambda-list (create-gf-lambda-list lambda-list))
                       (gf (if (fboundp name)
                               (ensure-generic-function name)
                             (ensure-generic-function name :lambda-list gf-lambda-list)))
                       (method-class (generic-function-method-class gf))
                       (lambda-expression `(lambda ,lambda-list
                                             (declare ,@declarations)
                                             (block ,name
                                               ,@tail))))
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
                  (if (equal (compute-applicable-methods
                              #'make-method-lambda
                              (list gf (class-prototype method-class)
                                    lambda-expression env))
                             (list (find-method
                                    #'make-method-lambda '()
                                    (list (find-class 'cl:standard-generic-function)
                                          (find-class 'standard-method)
                                          (find-class 't)
                                          (find-class 't))
                                    nil)))
                      (return-from defmethod `(cl:defmethod ,@(rest form)))
                    (multiple-value-bind
                        (method-lambda method-args)
                        (make-method-lambda
                         gf (class-prototype method-class)
                         lambda-expression env)
                      (with-unique-names (gf method)
                        (return-from defmethod
                          `(let ((,gf (if (fboundp ',name)
                                          (ensure-generic-function ',name)
                                        (ensure-generic-function
                                         ',name :lambda-list ',gf-lambda-list)))
                                 (,method
                                  (make-instance
                                   ',method-class
                                   :qualifiers ',qualifiers
                                   :specializers
                                   (list
                                    ,@(mapcar
                                       (lambda (specializer-name)
                                         (typecase specializer-name
                                           (symbol `(find-class ',specializer-name))
                                           (cons (cond
                                                  ((> (length specializer-name) 2)
                                                   (error "Invalid specializer ~S in defmethod form ~S."
                                                          specializer-name form))
                                                  ((eq (car specializer-name) 'eql)
                                                   `(intern-eql-specializer ,(cadr specializer-name)))
                                                  (t (error "Invalid specializer ~S in defmethod form ~S."
                                                            specializer-name form))))
                                           (t (error "Invalid specializer ~S in defmethod form ~S."
                                                     specializer-name form))))
                                       (extract-specializer-names specialized-args)))
                                   :lambda-list ',lambda-list
                                   :function (function ,method-lambda)
                                   ,@(unless (eq documentation :unbound)
                                       (list :documentation documentation))
                                   ,@method-args)))
                             (add-method ,gf ,method)
                             ,method))))))))))
Pascal Costanza's avatar
Pascal Costanza committed
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569

;; The following macro ensures that the new standard-generic-function
;; is used by default. It also ensures that make-method-lambda is called
;; for the default methods, by expanding into defmethod forms.

(defvar *gf-initial-methods* (make-hash-table :test #'equal))

(defmacro defgeneric (&whole form name (&rest args) &body options)
  (unless (every #'consp options)
    (error "Illegal generic functions options in defgeneric form ~S." form))
  `(progn
     (loop for method in (gethash ',name *gf-initial-methods*)
           do (remove-method (method-generic-function method) method))
     (cl:defgeneric ,name ,args
       ,@(remove :method options :key #'car :test #'eq)
       ,@(unless (member :generic-function-class options :key #'car :test #'eq)
           '((:generic-function-class standard-generic-function))))
     (setf (gethash ',name *gf-initial-methods*)
           (list ,@(loop for method-spec in (remove :method options :key #'car :test-not #'eq)
                         collect `(defmethod ,name ,@(cdr method-spec)))))
     (fdefinition ',name)))

;; The following can be used in direct-slot-definition-class to get the correct initargs
;; for a slot. Use it like this:
;;
;; (defmethod direct-slot-definition-class
;;            ((class my-standard-class) &rest initargs)
;;   (declare (dynamic-extent initargs))
;;   (destructuring-bind
;;       (&key key-of-interest &allow-other-keys)
;;       (fix-slot-initargs initargs)
;;     ...))

(defvar *standard-slot-keys*
  '(:name :documentation
    :initargs :initform :initfunction
    :readers :writers))

(defun fix-slot-initargs (initargs)
  initargs)

(eval-when (:compile-toplevel :load-toplevel :execute)
  (pushnew :closer-mop *features*))