object.stk 37.5 KB
Newer Older
eg's avatar
eg committed
1 2
;;;;
;;;; object.stk	-- -- A variation of the Gregor Kickzales Tiny CLOS for STklos
3 4 5 6
;;;;
;;;; Copyright © 1993-2010 Erick Gallesio - I3S-CNRS/ESSI <eg@unice.fr>
;;;;
;;;;
eg's avatar
eg committed
7 8 9 10
;;;; This program is free software; you can redistribute it and/or modify
;;;; it under the terms of the GNU General Public License as published by
;;;; the Free Software Foundation; either version 2 of the License, or
;;;; (at your option) any later version.
11
;;;;
eg's avatar
eg committed
12 13 14 15
;;;; This program is distributed in the hope that it will be useful,
;;;; but WITHOUT ANY WARRANTY; without even the implied warranty of
;;;; MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
;;;; GNU General Public License for more details.
16
;;;;
eg's avatar
eg committed
17 18
;;;; You should have received a copy of the GNU General Public License
;;;; along with this program; if not, write to the Free Software
19
;;;; Foundation, Inc., 59 Temple Place - Suite 330, Boston, MA 02111-1307,
eg's avatar
eg committed
20
;;;; USA.
21
;;;;
eg's avatar
eg committed
22 23
;;;;           Author: Erick Gallesio [eg@unice.fr]
;;;;    Creation date: 20-Feb-1994 21:09
24
;;;; Last file update:  1-Jan-2010 14:52 (eg)
eg's avatar
eg committed
25 26 27 28 29 30 31


#|
//FIXMOI

* decoupage du source
* methods rapides
32
* Vérification que tous les points du mop sont implémentés
eg's avatar
eg committed
33 34 35

|#

36
(define-module STKLOS-OBJECT
37
  (import SCHEME)
38 39 40 41 42
  (export				  ; Define the exported symbols of this file
    find-class is-a?
    ensure-metaclass ensure-metaclass-with-supers
    ensure-class
    ensure-generic-function
43
    ensure-method add-method!
44 45
    object-eqv? object-equal?
    write-object display-object
46
    slot-unbound slot-missing
47 48
    slot-definition-name  slot-definition-options slot-definition-allocation
    slot-definition-getter slot-definition-setter slot-definition-accessor
49
    slot-definition-init-form slot-definition-init-keyword
50 51 52 53
    slot-init-function class-slot-definition
    compute-get-n-set
    allocate-instance initialize make-instance make
    no-next-method  no-applicable-method no-method ;; next-method-exists?
54
    change-class change-object-class
55
    shallow-clone deep-clone
56
    apply-generic apply-method apply-methods compute-applicable-methods
57
    method-more-specific? sort-applicable-methods
58
    method-procedure method-specializers method-generic-function
59
    method-specializers-equal?
60 61 62 63
    class-subclasses class-methods class-name class-direct-supers
    class-direct-subclasses class-precedence-list class-direct-methods
    class-direct-slots class-slots
    generic-function-name generic-function-methods
64
    generic-function-documentation
65 66 67 68 69 70 71 72 73 74 75 76
    slot-value))

(define-module STKLOS-COMPILER
  (import STKLOS-OBJECT))

(select-module STKLOS-OBJECT)



(define extended-lambda->lambda		;; Compiler function used here
  (in-module STKLOS-COMPILER extended-lambda->lambda))

eg's avatar
eg committed
77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97

(define class-redefinition (void))	;; forward declaration

;=============================================================================
;
;			      U t i l i t i e s
;
;=============================================================================

(define (%error-bad-class who obj)   (error who "bad class ~S" obj))
(define (%error-bad-generic who obj) (error who "bad generic function ~S" obj))
(define (%error-bad-method who obj)  (error who "bad method ~S" obj))

(define make-closure eval)

(define (specializers l)
  (cond
   ((null? l) '())
   ((pair? l) (cons (if (pair? (car l)) (cadar l) '<top>)
 		    (specializers (cdr l))))
   (else      '<top>)))
98

eg's avatar
eg committed
99 100 101 102
(define (formals l)
  (if (pair? l)
      (cons (if (pair? (car l)) (caar l) (car l)) (formals (cdr l)))
      l))
103

eg's avatar
eg committed
104 105 106 107 108 109 110 111

(define (declare-slots slots)
  ;; This is a *HUGE* *HACK*. Since STklos compiler displays the
  ;; unknown symbols, slots accessors are not known at compilation
  ;; time and yield a message. So, we pre-declare them here.
  ;; In the abolute this code is false, since the keywords :accessor
  ;; :getter and :setter can have a different meaning than the usual
  ;; one for a peculiar meta-class. Anyway, the only risk is to
112
  ;; trust that a symbol is defined whereas it is not.
eg's avatar
eg committed
113 114 115 116
  (for-each (lambda (s)
	      (let ((getter   (slot-definition-getter   s))
		    (setter   (slot-definition-setter   s))
		    (accessor (slot-definition-accessor s)))
Erick Gallesio's avatar
Erick Gallesio committed
117 118 119
		(when getter   (register-new-global! getter))
		(when setter   (register-new-global! setter))
		(when accessor (register-new-global! accessor))))
eg's avatar
eg committed
120 121 122 123 124
	    slots)
  slots)


;--------------------------------------------------
125
(define (make class . l)	;; A temporary version used for bootstrapping
eg's avatar
eg committed
126 127 128 129 130 131 132 133 134 135 136 137 138 139 140 141 142 143 144 145 146 147 148 149 150 151
  (cond
    ((eq? class <generic>) (%make class
				  'generic
				  (key-get l :name '???)))
    ((eq? class <method>) (%make class
				  'method
				  (list (key-get l :generic-function #f)
					(key-get l :specializers     '())
					(key-get l :procedure        '()))))
    (else       	    (error 'basic-make "cannot make ~S with ~S" class l))))

;=============================================================================
;
; 			      Access to Meta objects
;
;=============================================================================

;// ;;;
;// ;;; Methods
;// ;;;
;// (define-method method-body ((m <method>))
;//   (let* ((spec (map class-name (slot-ref m 'specializers)))
;// 	 (proc (procedure-body (slot-ref m 'procedure)))
;// 	 (args (cdadr proc))
;// 	 (body (cddr proc)))
;//     (list* 'method (map list args spec) body)))
152
;//
eg's avatar
eg committed
153 154 155 156 157 158 159 160

;;;
;;; Classes
;;;
(define (class-name C)
  (if (class? C) (slot-ref C 'name) (%error-bad-class 'class-name C)))

(define (class-direct-supers C)
161 162
  (if (class? C)
      (slot-ref C 'direct-supers)
eg's avatar
eg committed
163 164 165
      (%error-bad-class 'class-direct-supers C)))

(define (class-direct-slots C)
166 167
  (if (class? C)
      (slot-ref C 'direct-slots)
eg's avatar
eg committed
168 169 170
      (%error-bad-class 'class-direct-slots C)))

(define (class-direct-subclasses C)
171 172
  (if (class? C)
      (slot-ref C 'direct-subclasses)
eg's avatar
eg committed
173 174 175
      (%error-bad-class 'class-direct-subclasses C)))

(define (class-direct-methods C)
176 177
  (if (class? C)
      (slot-ref C 'direct-methods)
eg's avatar
eg committed
178 179 180 181 182 183 184 185 186 187 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
      (%error-bad-class 'class-direct-methods C)))

(define (class-precedence-list C)
  (if (class? C)
      (slot-ref C 'cpl)
      (%error-bad-class 'class-precedence-list C)))

(define (class-slots C)
  (if (class? C)
      (slot-ref C 'slots)
      (%error-bad-class 'class-slots C)))

;;;
;;; Slots
;;;
(define (slot-definition-name s)
  (if (pair? s) (car s) s))

(define (slot-definition-options s)
  (and (pair? s) (cdr s)))

(define (slot-definition-allocation s)
  (if (symbol? s)
      :instance
      (key-get (cdr s) :allocation :instance)))

(define (slot-definition-getter s)
  (and (pair? s) (key-get (cdr s) :getter #f)))

(define (slot-definition-setter s)
  (and (pair? s) (key-get (cdr s) :setter #f)))

(define (slot-definition-accessor s)
  (and (pair? s) (key-get (cdr s) :accessor #f)))

(define (slot-definition-init-form s)
  (if (pair? s)
      (key-get (cdr s) :init-form (void))
      (void)))

(define (slot-definition-init-keyword s)
  (and (pair? s) (key-get (cdr s) :init-keyword #f)))

(define (slot-init-function c s)
  (let ((s (slot-definition-name s)))
    (cadr (assq s (slot-ref c 'getters-n-setters)))))

(define (class-slot-definition class slot-name)
  (assq slot-name (class-slots class)))

;;;
;;; Generic functions
;;;
(define (generic-function-name gf)
  (if (generic? gf)
233
      (slot-ref gf 'name)
eg's avatar
eg committed
234 235 236 237 238 239 240
      (%error-bad-generic 'generic-function-name gf)))

(define (generic-function-methods gf)
  (if (generic? gf)
      (slot-ref gf 'methods)
      (%error-bad-generic 'generic-function-methods gf)))

241 242 243 244 245
(define (generic-function-documentation gf)
  (if (generic? gf)
      (slot-ref gf 'documentation)
      (%error-bad-generic 'generic-function-documentation gf)))

eg's avatar
eg committed
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
;;;
;;; Methods
;;;
(define (method-generic-function m)
  (if (method? m)
      (slot-ref m 'generic-function)
      (%error-bad-method 'method-generic-function m)))

(define (method-specializers m)
  (if (method? m)
      (slot-ref m 'specializers)
      (%error-bad-method 'method-specializers m)))

(define (method-procedure m)
  (if (method? m)
      (slot-ref m 'procedure)
      (%error-bad-method 'method-procedure m)))

;=============================================================================

;;
;; is-a?
;;
(define (is-a? obj class)
  (and (memq class (class-precedence-list (class-of obj))) #t))

;;
;; Find-class
;;
(define (find-class name :optional (default #f default?))
  (let ((cls (if (symbol? name)
		 (symbol-value* name (current-module) #f)
		 name)))
    (if (is-a? cls <class>)
	cls
	(if default?
	    default
	    (error 'find-class "bad class ~S" name)))))

;;
;; %compute-slots
;;
(define (%compute-slots C)
  (define (remove-duplicate-slots l res)
290
    (if (null? l)
eg's avatar
eg committed
291 292 293 294
	res
	(let ((s (slot-definition-name (car l))))
	  (unless (symbol? s)
	    (error 'compute-slots "bad slot name ~S" s))
295
	  (remove-duplicate-slots (cdr l)
eg's avatar
eg committed
296 297 298
				  (if (assq s res) res (cons (car l) res))))))

  (define (build-slots-list cpl res)
299
    (if (null? cpl)
eg's avatar
eg committed
300
	(remove-duplicate-slots (reverse res) '())
301
	(build-slots-list (cdr cpl)
eg's avatar
eg committed
302 303 304 305 306 307 308 309 310 311 312 313 314 315 316 317
			  (append (class-direct-slots (car cpl)) res))))
  (define (sort-slots l)
    ;; Slots are sorted such that instance slots are always before other slots.
    ;; So, virtual slots are placed fist and, for instance, virtual slots can have
    ;; an initial value which depends of real slots.
    ;; Note that the following "sort" just displace non-instance slots at the
    ;; end keeping initial order (i.e. we don't use the STklos sort procedure
    ;; since it is not stable.
    (let Loop ((l l) (instance '()) (other '()))
      (cond
	((null? l)
	   (append (reverse! instance) (reverse! other)))
	((eq? (slot-definition-allocation (car l)) :instance)
	   (Loop (cdr l) (cons (car l) instance) other))
	(else
	   (Loop (cdr l) instance (cons (car l) other))))))
318

eg's avatar
eg committed
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
  (sort-slots (build-slots-list (class-precedence-list C) '())))


;=============================================================================
;
; 			M e t a c l a s s e s   s t u f f
;
;=============================================================================
(define ensure-metaclass-with-supers
  (let ((table-of-metas '()))
    (lambda (meta-supers)
      (let ((entry (assoc meta-supers table-of-metas)))
	(if entry
	    ;; Found a previously created metaclass
	    (cdr entry)
	    ;; Create a new meta-class which inherit from "meta-supers"
	    (let ((new (make <class> :dsupers meta-supers
			             :slots   '()
				     :name   (gensym "metaclass"))))
	      (set! table-of-metas (cons (cons meta-supers new) table-of-metas))
	      new))))))

(define (ensure-metaclass supers)
  (if (null? supers)
      (find-class <class>)
      (let* ((all-metas (map (lambda (x)
			       (if (is-a? x <class>)
				   x
				   (class-of (find-class x))))
			     supers))
	     (all-cpls  (apply append
350
			       (map (lambda (m) (cdr (class-precedence-list m)))
eg's avatar
eg committed
351 352 353 354 355 356 357 358 359 360 361 362 363 364 365 366 367 368 369 370 371
				    all-metas)))
	     (needed-metas '()))
	;; Find the most specific metaclasses.  The new metaclass will be
	;; a subclass of these.
	(for-each
	 (lambda (meta)
	   (when (and (not (member meta all-cpls)) (not (member meta needed-metas)))
	     (set! needed-metas (append needed-metas (list meta)))))
	 all-metas)
	;; Now return a subclass of the metaclasses we found.
	(if (null? (cdr needed-metas))
	    (car needed-metas)  ; If there's only one, just use it.
	    (ensure-metaclass-with-supers needed-metas)))))

;=============================================================================
;
; 			D e f i n e - c l a s s
;
;=============================================================================
;==== Define-class
(define-macro (define-class name supers slots . options)
372
  `(define ,name
eg's avatar
eg committed
373 374 375
      (ensure-class
        ',name					; name
	',supers				; supers
376
	',(declare-slots slots)			; slots
eg's avatar
eg committed
377 378 379 380 381 382 383 384 385 386 387 388
	,(or (key-get options :metaclass #f)	; metaclass
	     `(ensure-metaclass ',supers))
	,@options)))

;==== Ensure-class
(define (ensure-class name supers slots metaclass . options)

  (define (find-duplicate l)	; find a duplicate in a list; #f otherwise
    (cond
       ((null? l)		#f)
       ((memq (car l) (cdr l))	(car l))
       (else 			(find-duplicate (cdr l)))))
389 390

  (let ((supers (if (null? supers)
eg's avatar
eg committed
391 392 393 394 395 396 397 398 399 400 401 402 403
		    (list <object>)
		    (map find-class supers))))
    ;; Verify that all direct slots are different and that we don't inherit
    ;; several time from the same class
    (let ((tmp (find-duplicate supers)))
      (when tmp
	(error 'define-class "super class ~S is duplicated in class ~S" tmp name)))
    (let ((tmp (find-duplicate (map slot-definition-name slots))))
      (when tmp
	(error 'define-class "slot ~S is duplicated in class ~S" tmp name)))

    ;; Everything seems correct, build the class
    (let ((old (find-class name #f))
404
	  (cls (apply make metaclass :dsupers supers :slots slots
eg's avatar
eg committed
405 406 407 408 409 410 411 412 413 414 415
		      		     :name name options)))
      (when old (class-redefinition old cls))
      cls)))

;=============================================================================
;
; 			D e f i n e - g e n e r i c
;
;=============================================================================

; ==== Define-generic
416 417 418 419
(define-macro (define-generic gf :optional (meta '<generic>)
				 :key      (documentation #f))
  `(define ,gf (ensure-generic-function ',gf ,meta ,documentation)))

eg's avatar
eg committed
420 421

;==== Ensure-generic-function
422 423
(define (ensure-generic-function name :optional (metaclass <generic>)
				 		(documentation #f))
eg's avatar
eg committed
424 425 426
  (let ((old (symbol-value* name (current-module) #f)))
    (if (generic? old)
	old
427 428
	(%symbol-define name
			(make metaclass :name name
429 430
			      		:default (and (procedure? old) old)
					:documentation documentation)
eg's avatar
eg committed
431 432 433 434 435 436 437 438 439
			(current-module)))))

;=============================================================================
;
; 			D e f i n e - m e t h o d
;
;=============================================================================

;==== Add-method!
440 441 442 443 444 445 446 447
(define (%method-specializers-equal? gf m1 m2)
  (equal? (method-specializers m1)
	  (method-specializers m2)))

(define method-specializers-equal? ; will be redefined later as a method.
    %method-specializers-equal?)


eg's avatar
eg committed
448 449 450 451 452 453 454 455 456 457 458 459 460 461 462 463
(define (add-method-in-classes! m)
  ;; Add method in all the classes which appears in its specializers list
  (for-each* (lambda (x)
	       (let ((dm (class-direct-methods x)))
		 (unless (memq m dm)
		   (slot-set! x 'direct-methods (cons m dm)))))
	     (method-specializers m)))

(define (remove-method-in-classes! m)
  ;; Remove method in all the classes which appears in its specializers list
  (for-each* (lambda (x)
	       (slot-set! x 'direct-methods (delete! m (class-direct-methods x)
						     eq?)))
	      (method-specializers m)))

(define (compute-new-list-of-methods gf new)
464
  (let ((methods  (generic-function-methods gf)))
eg's avatar
eg committed
465 466 467
    (let Loop ((l methods))
      (if (null? l)
	  (cons new methods)
468
	  (if (method-specializers-equal? gf (car l) new)
469
	      (begin
eg's avatar
eg committed
470 471
		;; This spec. list already exists. Remove old method from dependents
		(remove-method-in-classes! (car l))
472
		(set-car! l new)
eg's avatar
eg committed
473 474 475 476 477 478 479 480 481 482 483 484 485 486 487 488 489 490 491 492 493 494 495
		methods)
	      (Loop (cdr l)))))))

;;
;; Add-method!
;;
(define (add-method! gf m)
  (slot-set! gf 'methods (compute-new-list-of-methods gf m))
  (add-method-in-classes! m)
  m)


(define (ensure-method gf args body :optional kind-of-method)
  (let* ((new  (extended-lambda->lambda `(method ,args ,@body)))
	 (args (cadr new))
	 (body (cddr new)))
    `(make ,(or kind-of-method '<method>)
          :generic-function ,gf
	  :specializers     (map* find-class ',(specializers args))
	  :procedure        (let ((next-method (void)))
			      (lambda ,(formals args)
				,@body)))))

496

eg's avatar
eg committed
497 498
;====  Method
(define-macro (method args . body)
499
  (ensure-method #f args body))
eg's avatar
eg committed
500 501 502 503 504 505


; ==== Define-method
(define-macro (define-method name args . body)
  (let ((gf (gensym "gf")))
    `(let ((,gf (ensure-generic-function ',name)))
506
       (add-method! ,gf ,(ensure-method gf args body))
eg's avatar
eg committed
507 508 509 510 511
       (values (void) ',name))))


;=============================================================================
;
512
; 			    Standard methods
eg's avatar
eg committed
513 514 515 516 517 518 519 520
; 			used by the C runtime
;
;=============================================================================

;==== Methods to compare objects
(define-method object-eqv?   (x y) #f)
(define-method object-equal? (x y) (eqv? x y))

521

eg's avatar
eg committed
522
;==== Methods to display/write an object
523

eg's avatar
eg committed
524
;     Code for writing objects must test that the slots they use are
525
;     bound. Otherwise a slot-unbound method will be called and will
eg's avatar
eg committed
526
;     conduct to an infinite loop.
527

eg's avatar
eg committed
528 529 530
;; Write
(define-method write-object (o file)
  (format file "#[instance ~A]" (number->string (address-of o) 16)))
531

eg's avatar
eg committed
532 533
(define-method write-object ((o <object>) file)
  (let ((class (class-of o)))
534 535
    (if (slot-bound? class 'name)
	(format file "#[~A ~A]" (class-name class)
eg's avatar
eg committed
536 537 538 539 540
		(number->string (address-of o) 16))
	(next-method))))

(define-method write-object((class <class>) file)
  (let ((meta (class-of class)))
541
    (if (and (slot-bound? class 'name) (slot-bound? meta 'name))
eg's avatar
eg committed
542 543 544 545 546 547 548 549
	(format file "#[~A ~A ~A]" (class-name meta) (class-name class)
		(number->string (address-of class) 16))
	(next-method))))

(define-method write-object((gf <generic>) file)
  (let ((meta (class-of gf)))
    (if (and (slot-bound? gf 'name) (slot-bound? meta 'name)
	     (slot-bound? gf 'methods))
550
	(format file "#[~A ~A (~A)]"
eg's avatar
eg committed
551 552 553 554 555 556
		(class-name meta)
		(generic-function-name gf)
		(length (generic-function-methods gf)))
	(next-method))))

;; Display (do the same thing as write by default)
557
(define-method display-object (o file)
eg's avatar
eg committed
558 559 560 561 562 563 564 565 566 567 568 569 570 571 572 573 574 575 576
  (write-object o file))

;==== Slot access

;; Avoid printing object itself in the error message, because it might
;; cause an infinite loop (via write-object method). Problem signaled
;; by Shiro Kawai <shiro@acm.org>.

(define-method slot-unbound ((c <class>) (o <object>) s)
  (error "slot ~S is unbound in #p~A (an object of class ~S)"
	 s (number->string (address-of o) 16) c))

(define-method slot-missing ((c <class>) (o <object>) name :optional value)
  (error "no slot with name `~S' in #p~A (an object of class ~S)"
	 name (number->string (address-of o) 16) c))

; ==== Methods for the possible error we can encounter when calling a gf

(define-method no-next-method ((gf <generic>) method args)
577
  (error "no next method for ~S in call ~S"
eg's avatar
eg committed
578 579 580 581 582 583 584 585 586 587 588 589 590 591 592 593 594 595 596 597 598 599 600 601 602 603 604 605 606 607 608 609 610 611 612 613 614 615 616 617 618 619 620 621 622 623 624 625 626 627 628 629
	 method (cons (generic-function-name gf) args)))

(define-method no-applicable-method ((gf <generic>) args)
  (error "no applicable method for ~S\nin call ~S"
	 gf (cons (generic-function-name gf) args)))

(define-method no-method ((gf <generic>) args)
  (error "no method defined for ~S"  gf))


;// (define-macro (next-method-exists?)
;//  `((with-module STklos %next-method-exists?) next-method))



;=============================================================================
;
;	      Cloning functions (from Rob Deline <rdeline@CS.CMU.EDU>)
;
;=============================================================================
(define-method shallow-clone ((self <object>))
  (let ((clone (%allocate-instance (class-of self)))
	(slots (map slot-definition-name
		    (class-slots (class-of self)))))
    (for-each (lambda (slot)
		(if (slot-bound? self slot)
		    (slot-set! clone slot (slot-ref self slot))))
	      slots)
    clone))

(define-method deep-clone ((self <object>))
  (let ((clone (%allocate-instance (class-of self)))
	(slots (map slot-definition-name
		    (class-slots (class-of self)))))
    (for-each (lambda (slot)
		(if (slot-bound? self slot)
		    (slot-set! clone slot
			       (let ((value (slot-ref self slot)))
				 (if (instance? value)
				     (deep-clone value)
				     value)))))
	      slots)
    clone))

;=============================================================================
;
; 		     	Class redefinition utilities
;;
;=============================================================================

;==== Remove-class-accessors
(define-method remove-class-accessors ((c <class>))
630
  (for-each
eg's avatar
eg committed
631 632 633 634 635 636 637
     (lambda (m) (if (is-a? m <accessor-method>) (remove-method-in-classes! m)))
     (class-direct-methods c)))


;==== Update-direct-method
(define-method update-direct-method ((m  <method>) (old <class>) (new <class>))
  (let Loop ((l (method-specializers m)))
638
    (when (pair? l)       	; Note: the <top> in dotted list is never used.
eg's avatar
eg committed
639 640 641 642 643 644 645 646
      (if (eq? (car l) old)     ; So we can work if we had only proper lists.
	(set-car! l new))
      (Loop (cdr l)))))

;==== Update-direct-subclass
(define-method update-direct-subclass ((c <class>) (old <class>) (new <class>))
  (let ((new-supers (map (lambda (cls) (if (eq? cls old) new cls))
			 (class-direct-supers c))))
647
    ;; Create a new class with same name as c. This will automagically call
eg's avatar
eg committed
648 649 650 651 652 653 654 655 656
    ;; class-redefinition on this subclass and redefine all its descent
    (ensure-class (class-name c)
		  new-supers
		  (class-direct-slots c)
		  (class-of c))))

;==== Class-redefinition
(define-method class-redefinition ((old <class>) (new <class>))
  ;; Work on direct methods:
657
  ;;		1. Remove accessor methods from the old class
eg's avatar
eg committed
658 659 660 661 662 663 664 665 666
  ;;		2. Patch the occurences of old in the specializers by new
  ;;		3. Displace the methods from old to new
  (remove-class-accessors old)					;; -1-
  (let ((methods (class-direct-methods old)))
    (for-each (lambda (m) (update-direct-method m old new))	;; -2-
	      methods)
    (slot-set! new 'direct-methods methods))			;; -3-

  ;; Remove the old class from the direct-subclasses list of its super classes
667
  (for-each (lambda (c) (slot-set! c 'direct-subclasses
eg's avatar
eg committed
668 669 670 671
				   (delete! old (class-direct-subclasses c) eq?)))
	    (class-direct-supers old))

  ;; Redefine all the subclasses of old to take into account modification
672
  (for-each
eg's avatar
eg committed
673 674 675 676 677 678 679 680 681 682 683 684 685 686
       (lambda (c) (update-direct-subclass c old new))
       (class-direct-subclasses old))

  ;; Invalidate class so that subsequent instances slot accesses invoke
  ;; change-object-class
  (slot-set! old 'redefined new))


;=============================================================================
;
; 			Utilities for INITIALIZE methods
;
;=============================================================================

687 688 689 690 691 692 693 694 695 696 697 698 699 700 701 702 703 704 705 706 707 708 709 710 711 712 713 714 715 716 717 718 719 720 721 722 723 724 725 726 727 728 729 730 731
(define (%find-inherited-get-n-set slot-name class)
  (let Loop ((l (cdr (class-precedence-list class))))
    (let ((r (assq slot-name (slot-ref (car l) 'getters-n-setters))))
      (if r
	  (cddr r)
	  (Loop (cdr l))))))

(define (%direct-slot? slot-name class)
  (memq slot-name (map slot-definition-name
		       (class-direct-slots class))))

(define (%make-active-getter-n-setter index keys)
  (let ((before-ref  (make-closure (key-get keys :before-slot-ref #f)))
	(after-ref   (make-closure (key-get keys :after-slot-ref #f)))
	(before-set! (make-closure (key-get keys :before-slot-set! #f)))
	(after-set!  (make-closure (key-get keys :after-slot-set! #f))))
    ;; Compute the getter and setter of an active slot at given index
    ;; The result is of the form '(getter setter (:before-ref ... :after-ref ...))
    (list (lambda (o)
	    (if before-ref
		(if (before-ref o)
		    (let ((res (%fast-slot-ref o index)))
		      (and after-ref
			   (not (eqv? res (void)))
			   (after-ref o))
		      res)
		    (void))
		(let ((res (%fast-slot-ref o index)))
		  (and after-ref
		       (not (eqv? res (void)))
		       (after-ref o))
		  res)))
	  (lambda (o v)
	    (if before-set!
		(when (before-set! o v)
		  (%fast-slot-set! o index v)
		  (and after-set! (after-set! o v)))
		(begin
		  (%fast-slot-set! o index v)
		  (and after-set! (after-set! o v)))))
	  (list
	     :before-slot-ref  before-ref
	     :after-slot-ref   after-ref
	     :before-slot-set! before-set!
	     :after-slot-set!  after-set!))))
eg's avatar
eg committed
732 733 734 735 736

;;;
;;; Compute-get-n-set
;;;
(define-method compute-get-n-set ((class <class>) s)
737 738 739 740 741 742 743 744 745
  (let ((name (slot-definition-name s)))
    (case (slot-definition-allocation s)
      ((:instance) ;; Instance slot
                   ;; get-n-set is just its offset
       		   (let ((already-allocated (slot-ref class 'nfields)))
		     (slot-set! class 'nfields (+ already-allocated 1))
		     already-allocated))

      ((:class)  ;; Class slot
746
       		 ;; Class-slots accessors are implemented as 2 closures around
747 748
       		 ;; a Scheme variable.
       		 (if (%direct-slot? name class)
eg's avatar
eg committed
749 750 751 752 753
		     ;; This slot is direct; create a new shared cell
		     (let ((shared-cell (void)))
		       (list (lambda (o)   shared-cell)
			     (lambda (o v) (set! shared-cell v))))
		     ;; Slot is inherited. Find its definition in superclass
754
		     (%find-inherited-get-n-set name class)))
755

756 757 758 759 760 761 762 763 764 765 766 767 768 769 770 771 772 773 774 775 776 777 778 779 780 781 782 783 784 785 786 787 788 789
      ((:each-subclass) ;; slot shared by instances of direct subclass only.
       			;; (Thomas Buerger, April 1998)
       			(let ((shared-cell (void)))
			  (list (lambda (o)   shared-cell)
				(lambda (o v) (set! shared-cell v)))))

      ((:virtual) ;; No allocation
     		  ;; slot-ref and slot-set! function must be given by the user
       		  (if (%direct-slot? name class)
		      (let* ((s   (slot-definition-options s))
			     (get (key-get s :slot-ref  #f))
			     (set (key-get s :slot-set! #f)))
			(unless (and get set)
			  (error
			      "a :slot-ref and a :slot-set! must be supplied in ~S"
			      s))
			(list (make-closure get)
			      (make-closure set)))
		      (%find-inherited-get-n-set name class)))
      ((:active) ;; Active slot
       		 ;; active slots admit a daemon before or after slot access
              (let ((index 	(slot-ref class 'nfields)))
		(slot-set! class 'nfields (+ index 1))
		(if (%direct-slot? name class)
		    (%make-active-getter-n-setter index (slot-definition-options s))
		    (let ((old (%find-inherited-get-n-set name class)))
		      ;; Old is of the form
		      ;;   (getter setter XXXX)
		      ;; where XXX is (:before-slot-ref closure ...)
		      ;; We must re-create the getter and setter since the offset
		      ;; of the slot can be different. but we MUST NOT re-evaluate
		      ;; the 4 daemons (they can be not exported closures).
		      (%make-active-getter-n-setter index (list-ref old 2))))))
      (else    (next-method)))))
eg's avatar
eg committed
790 791 792 793 794 795

(define-method compute-get-n-set ((o <object>) s)
  (error "allocation type \"~S\" is unknown" (slot-definition-allocation s)))


(define (compute-slot-accessors class slots)
796
  ;; accessors are made here in-line using a light version of ensure-method
eg's avatar
eg committed
797 798 799 800 801 802 803 804 805 806 807 808 809 810 811 812 813 814 815 816 817 818 819 820 821 822 823 824 825 826 827 828 829 830 831 832 833
  ;; in particular, the class of accessors is <accessor-method> and there
  ;; is no next method defined for them, since they are terminal.

  (define (make-reader name getter)
    (let ((gf (ensure-generic-function getter)))
      (add-method! gf
		   (make <accessor-method>
		         :generic-function gf
			 :specializers (list class)
			 :procedure    (lambda (o) (slot-ref o name))))))
  (define (make-writer name setter)
    (let ((gf (ensure-generic-function setter)))
      (add-method! gf
		   (make <accessor-method>
		         :generic-function gf
			 :specializers (list class <top>)
			 :procedure    (lambda (o v) (slot-set! o name v))))))
  ;;
  ;;
  (for-each
      (lambda (s)
	(let ((name     (slot-definition-name     s))
	      (getter   (slot-definition-getter   s))
	      (setter   (slot-definition-setter   s))
	      (accessor (slot-definition-accessor s)))
	  (when getter
	    (make-reader name getter))
	  (when setter
	    (make-writer name setter))
	  (when accessor
	    (make-reader name accessor)
	    (make-writer name accessor))))
      slots))


;;;
;;; compute-getters-n-setters
834
;;;
eg's avatar
eg committed
835 836 837 838 839 840 841 842 843

(define (compute-getters-n-setters class slots)

  (define (compute-slot-init-function s)
    (let ((init (slot-definition-init-form s)))
      (cond
	((eq? init (void))
	   #f)
	((eq? (slot-definition-allocation s) :class)
844 845 846 847 848 849
	   (let ((sn  (slot-definition-name s))
		 (o   (gensym))
		 (val (gensym)))
	     (make-closure `(lambda (,o)
			      (let ((,val (%slot-ref ,o ',sn)))
				(if (eq? ,val (void))
eg's avatar
eg committed
850
				    ,init
851
				    ,val))))))
eg's avatar
eg committed
852
	(else
853
	   (make-closure `(lambda (,(gensym)) ,init))))))
eg's avatar
eg committed
854 855 856 857


  (define (verify-accessors slot l)
    (if (pair? l)
858
	(let ((get (car l))
eg's avatar
eg committed
859 860 861 862 863 864 865 866 867 868
	      (set (cadr l)))
	  (unless (and (closure? get) (= (%procedure-arity get) 1))
	    (error "bad getter closure for slot `~S' in ~S: ~S" slot class get))
	  (unless (and (closure? set) (= (%procedure-arity set) 2))
	    (error "bad setter closure for slot `~S' in ~S: ~S" slot class set)))))

  (map (lambda (s)
	 (let* ((s     (if (pair? s) s (list s)))
		(g-n-s (compute-get-n-set class s))
		(name  (slot-definition-name s)))
869 870 871
	   ;; For each slot we have
	   ;;    '(name init-function getter setter <optional infos>)
	   ;; If slot is an instance slot, we have the simplest
eg's avatar
eg committed
872 873 874 875 876 877 878 879
	   ;; form '(name init-function . index)
	   (verify-accessors name g-n-s)
	   (list* name (compute-slot-init-function s) g-n-s)))
       slots))

;;;
;;; compute-cpl
;;;
880 881 882 883 884 885 886
;;; The current implementation was provided by Anthony Beurivé
;;; <beurive@labri.u-bordeaux.fr>. This implementation is monotonic and
;;; works "by level". For more information on monotonic superclass
;;; linearization  algorithm look at the paper
;;; 	A Monotonic Superclass Linearization for Dylan,
;;;     K. Barrett, B. Cassels, P. Haahr, D. A. Moon, K. Playford,
;;;     P. Tucker Withington,
eg's avatar
eg committed
887
;;;     OOPSLA 96.
888
;;; also available at
eg's avatar
eg committed
889 890 891 892 893 894 895 896 897 898 899 900 901 902 903 904 905 906 907 908 909 910 911 912 913 914 915 916 917 918 919 920 921 922 923 924 925 926 927 928 929 930 931 932 933 934 935 936 937 938 939 940 941 942 943 944 945 946 947 948 949 950 951 952 953 954 955 956 957 958 959 960 961 962 963 964 965 966 967 968 969 970 971 972 973
;;;	http://www.webcom.com/~haahr/dylan/linearization-oopsla96.html
;;;
(define (compute-cpl class)

  (define (reduce sequences cpl)
    (define (aux sequence)
      (if (and (pair? sequence) (memq (car sequence) cpl))
	  (aux (cdr sequence))
	  sequence))
    (map aux sequences))

  (define (delete-null-lists sequences)
    (if (pair? sequences)
	(let ((first (car sequences)))
	  (if (pair? first)
	      (cons first (delete-null-lists (cdr sequences)))
	      (delete-null-lists (cdr sequences))))
	'()))

  (define (select-candidate candidate sequences)
    (if (pair? sequences)
	(and (not (memq candidate (cdr (car sequences))))
	     (select-candidate candidate (cdr sequences)))
	candidate))

  (define (filter-candidates candidates sequences)
    (if (pair? candidates)
	(or (select-candidate (car candidates) sequences)
	    (filter-candidates (cdr candidates) sequences))
	#f)) ; No valid candidate (inconsistency).

  (define (next-class sequences)
    (let ((candidates (map car sequences)))
      (or (filter-candidates candidates sequences)
	  (car candidates)))) ; Arbitrarily brake the inconsistency.

  (define (step cpl sequences)
    (if (pair? sequences)
	(let ((new-cpl (cons (next-class sequences) cpl)))
	  (step new-cpl (delete-null-lists (reduce sequences new-cpl))))
	(reverse cpl)))

  (step '() (let ((supers (slot-ref class 'direct-supers)))
	      (cons (cons class supers)
		    (map (lambda (super)
			   (slot-ref super 'cpl))
			 supers)))))


;=============================================================================
;
; 			    I n i t i a l i z e
;
;=============================================================================

(define-method initialize ((object <object>) initargs)
  (%initialize-object object initargs))

(define-method initialize ((class <class>) initargs)
  (next-method)
  (let ((dslots (key-get initargs :slots   '()))
	(supers (key-get initargs :dsupers '())))

    (slot-set! class 'name	  	(key-get initargs :name '???))
    (slot-set! class 'direct-supers 	supers)
    (slot-set! class 'direct-slots  	dslots)
    (slot-set! class 'direct-subclasses '())
    (slot-set! class 'direct-methods    '())
    (slot-set! class 'cpl		(compute-cpl class))
    (slot-set! class 'redefined		#f)
    (let ((slots (%compute-slots class)))
      (slot-set! class 'slots	  	  slots)
      (slot-set! class 'nfields	  	  0)
      (slot-set! class 'getters-n-setters (compute-getters-n-setters class slots)))
    ;; Update the "direct-subclasses" of each inherited classes
    (for-each (lambda (x)
		(slot-set! x 'direct-subclasses
			   (cons class (slot-ref x 'direct-subclasses))))
	      supers)

    ;; Build getters - setters - accessors
    (compute-slot-accessors class dslots)))


(define-method initialize ((generic <generic>) initargs)
974 975
  (let ((previous-definition (key-get initargs :default #f))
	(doc		     (key-get initargs :documentation #f)))
eg's avatar
eg committed
976 977 978 979 980 981 982 983 984 985
    (next-method)
    (slot-set! generic 'name    (key-get initargs :name '???))
    (slot-set! generic 'methods
	       (if (procedure? previous-definition)
		   (list (make <method>	; /// FAST-METHOD
			   :specializers <top>
			   :generic-function generic
			   :procedure (let ((next-methhod #f))
					(lambda l
					  (apply previous-definition l)))))
986 987
		   '()))
    (slot-set! generic 'documentation doc)))
eg's avatar
eg committed
988 989 990 991 992 993 994 995 996 997

(define-method initialize ((method <method>) initargs)
  (next-method)
  (slot-set! method 'generic-function (key-get initargs :generic-function #f))
  (slot-set! method 'specializers     (key-get initargs :specializers '()))
  (slot-set! method 'procedure        (key-get initargs :procedure (lambda l '()))))


;=============================================================================
;
998
; 				     M a k e
eg's avatar
eg committed
999 1000 1001 1002 1003 1004 1005 1006
;
;     A new definition which overwrite the previous one which was built-in
;
;=============================================================================

(define-method allocate-instance ((class <class>) initargs)
  (%allocate-instance class))

Erick Gallesio's avatar
Erick Gallesio committed
1007
(define-method make-instance ((class <class>) . initargs)
eg's avatar
eg committed
1008 1009 1010 1011 1012 1013 1014 1015 1016 1017 1018 1019 1020 1021 1022 1023 1024
  (let ((instance (allocate-instance class initargs)))
    (initialize instance initargs)
    instance))

(define make make-instance)

;=============================================================================
;
; 			C h a n g e - c l a s s
;
;=============================================================================

(define (change-object-class old-instance old-class new-class)
  (let ((new-instance (allocate-instance new-class ())))
    ;; Initalize the slot of the new instance
    (for-each (lambda (slot)
		(if (slot-exists-using-class? old-class old-instance slot)
1025
		    ;; Slot was present in old instance; set it
1026 1027
		    (when (slot-bound-using-class? old-class old-instance slot)
		      (slot-set-using-class!
1028 1029 1030
			     new-class
			     new-instance
			     slot
eg's avatar
eg committed
1031 1032 1033
			     (slot-ref-using-class old-class old-instance slot)))
		    ;; slot was absent; initialize it with its default value
		    (let ((init (slot-init-function new-class slot)))
1034
		      (when init
eg's avatar
eg committed
1035
			  (slot-set-using-class!
1036 1037
			       new-class
			       new-instance
eg's avatar
eg committed
1038
			       slot
1039
			       (init new-instance))))))
eg's avatar
eg committed
1040 1041 1042 1043 1044 1045 1046 1047 1048 1049 1050 1051 1052 1053 1054
	      (map slot-definition-name (class-slots new-class)))
    ;; Exchange old an new instance in place to keep pointers valids
    (%modify-instance old-instance new-instance)
    old-instance))


(define-method change-class ((old-instance <object>) (new-class <class>))
  (change-object-class old-instance (class-of old-instance) new-class))

;=============================================================================
;
;				a p p l y - g e n e r i c
;
; Protocol for calling standard generic functions.
; This protocol is  not used for real <generic> functions (in this case we use
1055
; a completely C hard-coded protocol).
eg's avatar
eg committed
1056 1057 1058
; Apply-generic is used by STklos for calls to subclasses of <generic>.
;
; The code below is similar to the first MOP described in AMOP. In particular,
1059 1060
; it doesn't used the currified approach to gf call. There are 3 reasons for
; that:
eg's avatar
eg committed
1061 1062
;   - the protocol below is exposed to mimic completely the one written in C
;   - the currified protocol would be imho inefficient in C.
1063
;   - nobody (except persons really interested with playing with a MOP) will
eg's avatar
eg committed
1064 1065
;     probably use the following code
;=============================================================================
1066

eg's avatar
eg committed
1067 1068 1069 1070 1071 1072 1073 1074 1075
(define-method compute-applicable-methods ((gf <generic>) args)
  (apply find-method gf args))

(define-method method-more-specific? ((m1 <method>) (m2 <method>) targs)
  (%method-more-specific? m1 m2 targs))

(define-method sort-applicable-methods ((gf <generic>) methods args)
  (let ((targs (map class-of args)))
    (sort methods (lambda (m1 m2) (method-more-specific? m1 m2 targs)))))
1076

eg's avatar
eg committed
1077 1078 1079 1080 1081 1082 1083 1084 1085 1086 1087 1088 1089 1090 1091 1092 1093 1094 1095 1096 1097 1098 1099 1100 1101 1102
(define-method apply-method ((gf <generic>) methods build-next args)
  (let ((proc (method-procedure (car methods))))
    (%set-next-method! proc (build-next methods args))
    (apply proc args)))

(define-method apply-methods ((gf <generic>) (l <list>) args)
  (letrec ((next (lambda (procs args)
		   (lambda new-args
		     (let ((a (if (null? new-args) args new-args)))
		       (if (null? (cdr procs))
			   (no-next-method gf (car procs) a)
			   (apply-method gf (cdr procs) next a)))))))
    (apply-method gf l next args)))


;; ==== apply-generic

(define-method apply-generic ((gf <generic>) args)
  (if (null? (generic-function-methods gf))
      (no-method gf args))
  (let ((methods (compute-applicable-methods gf args)))
    (if methods
	(apply-methods gf (sort-applicable-methods gf methods args) args)
 	(no-applicable-method gf args))))


1103 1104 1105 1106 1107
; ======================================================================
; 	Functions redefined as methods ...
; ======================================================================
(define-method method-specializers-equal? ((gf <generic>) m1 m2)
  (%method-specializers-equal? gf m1 m2))
eg's avatar
eg committed
1108 1109 1110 1111 1112 1113 1114 1115 1116 1117 1118 1119 1120 1121 1122 1123 1124 1125 1126 1127 1128 1129 1130


;=============================================================================
;
; 				T o o l s
;
;=============================================================================
(define class-subclasses #f)
(define class-methods    #f)

(let ()
  (define (list2set l)
    (let Loop ((l l) (res '()))
      (cond
       ((null? l) 	   res)
       ((memq (car l) res) (Loop (cdr l) res))
       (else		   (Loop (cdr l) (cons (car l) res))))))

  (define (mapappend func . args)
    (if (memq '()  args)
	'()
	(append (apply func (map car args))
		(apply mapappend func (map cdr args)))))
1131 1132 1133

  ;; ==== class-subclasses
  (set! class-subclasses
eg's avatar
eg committed
1134 1135
	(lambda (c)
	  (letrec ((allsubs (lambda (c)
1136
			      (cons c (mapappend allsubs
eg's avatar
eg committed
1137 1138 1139
						 (class-direct-subclasses c))))))
	    (list2set (cdr (allsubs c))))))
  ;; ==== class-methods
1140
  (set! class-methods
eg's avatar
eg committed
1141
	(lambda (c)
1142
	  (list2set (mapappend class-direct-methods
eg's avatar
eg committed
1143 1144
			       (cons c (class-subclasses c)))))))

1145
;==== CLOS like slot-value (but as a gf instead of proc as slot-ref or slot-set!)
eg's avatar
eg committed
1146 1147
(define-method slot-value ((o <object>) s) 		;; The getter
  (slot-ref o s))
1148

eg's avatar
eg committed
1149 1150 1151 1152
(define-method slot-value ((o <object>) s v)		;; The setter
  (slot-set! o s v))


1153 1154
;; Just tell C that the object system is now fully initialized
(%object-system-initialized)
eg's avatar
eg committed
1155

1156 1157
;; ======================================================================
(select-module STklos)
1158 1159
(%redefine-module-exports (find-module 'STKLOS-OBJECT))

eg's avatar
eg committed
1160

1161 1162
;; LocalWords:  supers metaclass OOPSLA linearization beurive labri fr Cassels
;; LocalWords:  Beuriv Playford Withington Haahr Gregor Kickzales init