-
Notifications
You must be signed in to change notification settings - Fork 9
/
prototypes.lisp
1627 lines (1369 loc) · 53 KB
/
prototypes.lisp
1
2
3
4
5
6
7
8
9
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
125
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
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
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
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
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
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
417
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
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
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
570
571
572
573
574
575
576
577
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
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
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
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
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
790
791
792
793
794
795
796
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
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
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
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
;;; prototypes.lisp --- an alternative object system for Common Lisp
;; Copyright (C) 2007-2013 David O'Toole
;; Author: David O'Toole [email protected]
;; Keywords: oop
;;
;; This file 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 3, or (at your option)
;; any later version.
;;
;; This file 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.
;;
;; You should have received a copy of the GNU General Public License
;; along with this program; see the file COPYING. If not, write to
;; the Free Software Foundation, Inc., 51 Franklin Street, Fifth
;; Floor, Boston, MA 02110-1301, USA.
;;; Commentary:
;; This file implements a simple prototype-based object system for
;; Common Lisp. In this alternative view of object-orientation, there
;; are no classes; instead, objects are cloned from other objects
;; called "prototypes", from which the new objects may inherit data
;; and behavior. The details of inheritance, message passing, and
;; field lookup are inspired by Smalltalk, Objective-C, the Io
;; language, and the Garnet UI toolkit.
;; http://en.wikipedia.org/wiki/Prototype-based_programming
;; http://en.wikipedia.org/wiki/Message_passing
;; http://www.cliki.net/Garnet
;; http://iolanguage.com/about/
;;; Code:
(in-package :blocky)
(defvar *self* nil)
(defun split-string-on-lines (string)
(with-input-from-string (stream string)
(loop for line = (read-line stream nil)
while line collect line)))
(defvar *debug-on-error* t)
(defvar *author* nil)
(defvar *copyright-notice*
"Welcome to Blocky.
Copyright (C) 2006-2013 by David T O'Toole <[email protected]>
http://blocky.io/
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 3 of the License, or
(at your option) any later version.
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.
You should have received a copy of the GNU General Public License
along with this program, in the included file named \"COPYING\".
If not, see <http://www.gnu.org/licenses/>.
On some platforms, Blocky is distributed along with libSDL 1.2 (Simple
Direct Media Layer), which is provided under the terms of the GNU
Lesser General Public License. See also the file LIBSDL-LICENSE for
details.
Some functions in the file logic.lisp are based on code written by
Peter Norvig in his book 'Paradigms of Artificial Intelligence
Programming'. See logic.lisp for details.
Some of the OpenGL functions in console.lisp are derived from code in
Bart Botta's CL-OPENGL tutorials; see http://3bb.cc/tutorials/cl-opengl/
This program includes the free DejaVu fonts family in the subdirectory
./standard/. For more information, see the file named
DEJAVU-FONTS-LICENSE in that subdirectory.
Please see the included text files \"COPYING\" and \"CREDITS\" for
more information.
")
;;; Extended argument lists
(defun extended-arglist-p (lambda-list)
"An extended argument list is like an ordinary CL argument list,
but with each argument's entry replaced by a triple:
(ARGUMENT-NAME DATA-TYPE &rest OPTIONS)
These triples may be arranged in the extended argument list just as
in a `destructuring-bind', i.e. `&optional', `&key', and all the
other destructuring features:
((POSITIONAL-ARG1 TYPE OPTIONS) (POSITIONAL-ARG2 TYPE OPTIONS)
&KEY (KEYWORD-ARG1 TYPE OPTIONS) (KEYWORD-ARG2 TYPE OPTIONS))
ARG is the argument name (a symbol). DATA-TYPE is a Common Lisp
identifier such as `integer' or `(or integer symbol)' or the like.
See the documentation for the function `schema-option' for more
information on the OPTIONS field.
NOTE: &key and &optional are not yet implemented for extended
arglists.
"
(and (not (null lambda-list))
(listp (first lambda-list))
(not (null (first lambda-list)))))
(defun schemap (datum)
(and (consp datum)
(every #'consp datum)
(every #'symbolp
(mapcar #'first datum))))
(defun schema-name (schema)
(first schema))
(defun schema-type (schema)
(second schema))
(defun schema-options (schema)
(nthcdr 2 schema))
(defun schema-option (schema option)
"Find the value (if any) of the option named OPTION within the
extended argument list schema SCHEMA. The following keywords are
valid for OPTION:
:DEFAULT The default value for the argument. With no default,
the presentation history is consulted for a value.
:DOCUMENTATION The documentation string.
:LABEL User-visible name of the argument. If left unset, the
default is `foo bar baz' for the command
`foo-bar-baz'.
:WHEN Only read the value if this predicate-form returns
non-nil when invoked on the value.
Not yet supported:
:PROMPT A string (or a form evaluating to a string) used as the
prompt for this argument.
:PROMPT-MODE :raw means that prompt is just printed.
:normal (the default) specifies standard reformatting:
Command Name (type1) : <---- bright red input star
(type2 [default: foo) ...
(keywords) :Keyword Name (type3)
:DEFAULT-TYPE The presentation type of the argument value. Use
this with :default when the default value could
be interpreted more than one way.
:PROVIDE-DEFAULT When non-nil, the above options relating to
defaults are activated.
:DISPLAY-DEFAULT When non-nil, the default is printed in the
prompt. Default is t.
:CONFIRM ..."
(assert (keywordp option))
(getf (schema-options schema) option))
(defun make-lambda-list-entry (entry)
"Make an ordinary lambda list item corresponding to ENTRY, an
element of an extended argument list."
(assert (and (not (null entry))
(listp entry)))
(let ((name (schema-name entry))
(default (schema-option entry :default)))
(if (null default)
name
(list name default))))
(defun make-lambda-list (arglist)
"Return an ordinary function lambda list corresponding to the
extended argument list ARGLIST."
(cons '&optional (mapcar #'make-lambda-list-entry arglist)))
;;; Method dictionary
(defvar *methods* nil)
(defun initialize-methods ()
(setf *methods* (make-hash-table :test 'equal)))
(initialize-methods)
(defun make-method-id (prototype method)
(let ((name (object-name (find-prototype prototype))))
(assert (stringp name))
(concatenate 'string
(subseq name (1+ (position (character ":") name)))
"%"
(symbol-name method))))
(defun find-method-id (prototype method &optional create)
(assert prototype)
(assert method)
(let ((pointer (find-prototype prototype)))
(block searching
(loop while pointer do
(let ((id (make-method-id pointer method)))
(let ((result (gethash id *methods*)))
(if (or result create)
(return-from searching id)
(prog1 nil
(setf pointer (find-super pointer))))))))))
(defun find-method-data (name method &optional no-error)
(assert (hash-table-p *methods*))
(let ((id (find-method-id name method no-error)))
(let ((result (gethash id *methods*)))
(if result
(values-list result)
(unless no-error (error "Cannot find method: ~S"
(list name method)))))))
(defun add-method-to-dictionary (prototype method arglist &optional options)
(when (null *methods*)
(initialize-methods))
(let ((id (find-method-id prototype method :create)))
(assert (stringp id))
(setf (gethash id *methods*) (list arglist options prototype method))
(values id arglist)))
(defun method-defun-symbol (method-symbol-name prototype-name)
(intern (concatenate 'string
prototype-name "%" method-symbol-name )))
(defun method-options (name method &optional noerror)
(multiple-value-bind (schema options)
(find-method-data name method noerror)
(declare (ignore schema))
options))
(defun method-option (name method option)
(getf (method-options name method)
option))
(defun method-schema (prototype method)
(assert (hash-table-p *methods*))
(let ((id (find-method-id (object-name (find-prototype prototype))
(make-keyword method))))
(assert (stringp id))
(let ((result (gethash id *methods*)))
(when result
(first result)))))
(defun method-argument-entry (prototype method index)
(assert (integerp index))
(let ((schema (method-schema prototype method)))
(assert (< index (length schema)))
(nth index schema)))
(defun method-argument-count (prototype method)
(length (method-schema prototype method)))
(defun method-argument-type (prototype method index)
(schema-type (method-argument-entry prototype method index)))
(defun method-argument-name (prototype method index)
(schema-name (method-argument-entry prototype method index)))
(defun method-argument-options (prototype method index)
(schema-options (method-argument-entry prototype method index)))
;;; Prototype dictionary
(defvar *prototypes* nil)
(defun initialize-prototypes ()
(setf *prototypes* (make-hash-table :test 'equal)))
(initialize-prototypes)
(defun add-prototype (object)
(when (null *prototypes*)
(initialize-prototypes))
(setf (gethash (object-name object)
*prototypes*)
(find-object object)))
(defun find-prototype (name &optional noerror)
(assert (hash-table-p *prototypes*))
(if (object-p name)
name
(or (gethash name *prototypes*)
(unless noerror
(error "Cannot find prototype named ~S" name)))))
;;; UUID object dictionary
(defun make-uuid ()
(uuid:print-bytes
nil
(uuid:make-v4-uuid)))
;; why doesn't v3 work? produces always same id
;; (uuid:make-v3-uuid uuid:+namespace-oid+ "blocky.io")))
(defvar *database* nil)
(defun initialize-database ()
(setf *database*
(make-hash-table :test 'equal :size 8192)))
(initialize-database)
(defun add-object-to-database (object)
(when (null *database*)
(initialize-database))
(setf (gethash (object-uuid object)
*database*)
object))
(defun remove-object-from-database (object)
(assert (hash-table-p *database*))
(remhash (find-uuid object) *database*))
(defun find-object-by-uuid (uuid &optional noerror)
(or (gethash uuid *database*)
(unless noerror
(error "Cannot find object for uuid ~S" uuid))))
(defun purge-all-objects ()
(flet ((count-entries () (+ (hash-table-count *database*)
(hash-table-count *prototypes*))))
(let ((before-count (count-entries)))
(message "Searching in ~A objects for externals..." before-count)
(flet ((purge (id object)
(let ((name (object-name object)))
(unless (and (stringp name)
(search "BLOCKY:" name))
(remhash id *database*)))))
(maphash #'purge *database*)
(maphash #'purge *prototypes*)
(let ((delta (- before-count (count-entries))))
(message "Removed ~A external objects." delta))))))
;;; Finding any object by proto-name or UUID
(defun find-object (thing &optional no-error)
(when (not (null thing))
(let ((result
(etypecase thing
(symbol (find-prototype (make-prototype-id thing)))
(string (or (find-object-by-uuid thing :noerror)
(find-prototype thing :noerror)))
(object thing))))
(prog1 result
(unless no-error
(when (null result)
(error "Cannot find object: ~S" thing)))))))
(defun find-super (object)
(object-super (find-object object)))
(defun find-super-prototype-name (object)
(let ((super (object-super (find-object object))))
(when super (object-name (find-object super)))))
(defun object-eq (a b)
(when (and a b)
(eq (find-object a)
(find-object b))))
(defun find-schema (method &optional target)
(let ((source (or (when target
(find-super-prototype-name
(send :as-target target)))
"BLOCKY:BLOCK")))
(method-schema source method)))
;;; Emacs Lisp compatibilty macro
(defmacro while (test &body body)
`(loop while ,test do ,@body))
;;; Utility functions
(defun-memo make-keyword (S) (:test 'eq)
"Make the symbol or string S into a keyword symbol."
(etypecase S
(string (intern (string-upcase S) :keyword))
(symbol (intern (symbol-name S) :keyword))))
(defun make-non-keyword (S)
"Make the symbol or string S into a non-keyword symbol."
(etypecase S
(symbol (intern (symbol-name S)))
(string (intern (string-upcase S)))))
(defun merge-hashes (a b &optional predicate)
(prog1 a
(maphash #'(lambda (key value)
(when (or (null predicate)
(funcall predicate key))
(setf (gethash key a) value)))
b)))
(defun make-prototype-id (thing &optional (package (project-package)) create)
(let ((delimiter ":"))
(if (null thing)
(error "Cannot make a prototype ID for nil.")
(string-upcase
(cond
((string= "BLOCKY:BLOCK" thing) thing)
((blocky:object-p thing)
(object-name thing))
; ((blockyp thing) (object-name
((stringp thing)
(apply #'concatenate 'string
(if (search delimiter thing)
(list thing)
(list (package-name package)
delimiter thing))))
((symbolp thing)
(let ((thing-package (symbol-package thing)))
;; check if name is already in Blocky
(let ((prefix (if (eq thing-package (find-package :common-lisp))
;; (let ((prefix (if (find-prototype (concatenate 'string "BLOCKY"
;; (symbol-name thing)))
;; override if so
"BLOCKY"
(package-name thing-package))))
(concatenate 'string prefix delimiter (symbol-name thing))))))))))
;; (let ((proto (find-prototype name :noerror)))
;; (if proto
;; name
;; (if create name))
;; (concatenate 'string "BLOCKY" delimiter (symbol-name thing))))))))))))))
;;; Object data structure
;; Each object's "bookkeeping data" is stored in a structure. The
;; structure represents the object, and typically the programmer will
;; not need to access these structure fields.
(defstruct object
;; The most important features of an object are its "fields" or data
;; members. We use a hash table (or plist) to represent the field
;; collection. Methods are just function-valued fields. See
;; `field-value' and `set-field-value'.
fields
;; Objects can inherit field values from a prototype object which
;; then influences the new object's behavior. We must store a link
;; to this "super" object so that `field-value' can obtain the
;; inherited field values.
super
;; Objects may have names. A name is a string that identifies the
;; object. Named objects are "prototypes" from which other objects
;; may be created or "cloned".
name
;; Here's the uuid string.
uuid
;; The last few methods called are cached in this alist.
cache)
(defun find-uuid (object)
(when object
(object-uuid (find-object object))))
(defun verify (thing)
(assert (object-p (find-object thing))))
(defun blockyp (thing)
(or (blocky:object-p thing)
(and (stringp thing)
(find-object thing :no-error))))
;;; Fields
;; An object's field collection is either a hash table or plist. The
;; function `field-value' implements the chaining field lookups that
;; make behavior inheritance work in BLOCKY.
;; If a field value is not present in a given object's field
;; collection, the object's super is also checked for a value, and
;; then its super, and so on. This is how objects can inherit data
;; and behavior from prototypes. See `field-value'.
;; When you set the value of any field, the super's value is
;; hidden from that point on. There is no way to remove a local field
;; value. See `set-field-value'.
(defvar *lookup-failure* (gensym)
"A value returned in order to signify the failure of a field lookup.
When looking up fields, we need a default value to indicate that a
lookup failed (see `gethash'). But this value could be a perfectly
legitimate field value, and the system would then falsely report a
field lookup error because it could not tell the difference. By using
an uninterned symbol as that default value, we can be sure that it
won't be `eq' to anything. See `field-value'.
This is only used internally. In most situations, a field access or
method call that references a non-existent field will signal a
`no-such-field' error.")
(define-condition no-such-field (error)
((field-name :initarg :field-name :accessor field-name)
(object :initarg :object :accessor object))
(:report (lambda (condition stream)
;; TODO improve object printing
(format stream "No such field ~S in object ~S."
(field-name condition)
(object condition)))))
;; Next come the main user-level functions for setting/getting field
;; values.
(defun fref (fields key)
(etypecase fields
(list (getf fields key *lookup-failure*))
(hash-table (gethash key fields *lookup-failure*))))
(defun set-fref (fields key value)
(etypecase fields
(list (setf (getf fields key) value))
(hash-table (setf (gethash key fields) value)))
(values value fields))
(defsetf fref set-fref)
(defun field-value (field thing &optional noerror)
"Return the value of FIELD in the object THING.
If the FIELD has no value in THING, then the object's super is also
checked, and so on. If a value is found during these checks, it is
returned. If a value cannot be found, an error of type `no-such-field'
is signaled, unless NOERROR is non-nil; in that case,
`*lookup-failure*' is returned. See also `has-field'."
(declare (optimize (speed 3))
(inline fref set-fref object-fields object-super))
(let ((pointer (find-object thing))
result found)
;; search the chain of objects for a field value.
(loop while (and pointer (not found)) do
(setf result (fref (object-fields pointer) field))
(if (eq *lookup-failure* result)
;; it's not here. search the super, if any.
(setf pointer (find-object (object-super pointer)))
;; we found a value in this object.
(setf found t)))
(if found result
(if noerror
*lookup-failure*
(error 'no-such-field :field-name field :object thing)))))
(defun map-fields (function object)
"For each field in OBJECT's field collection, the supplied FUNCTION
is invoked with the field-name and corresponding value as its two
arguments."
(let ((fields (object-fields object)))
(etypecase fields
(hash-table (prog1 nil (maphash function fields)))
(list (loop while fields
do (funcall function
(pop fields)
(pop fields)))))))
(defun has-local-value (field thing)
(let ((object (find-object thing)))
(not (eq *lookup-failure* (fref (object-fields object) field)))))
(defun set-field-value (field thing value)
"Set OBJECT's FIELD to VALUE.
The new value overrides any inherited value."
(declare (inline set-fref object-fields find-object))
(prog1 value
(let ((object (find-object thing)))
(multiple-value-bind (value fields)
(set-fref (object-fields object) field value)
;; don't lose new list heads
(prog1 value
(when (list fields)
(setf (object-fields object) fields)))))))
(defsetf field-value set-field-value)
(defun has-field (field object)
"Return non-nil if FIELD has any value in OBJECT or its supers."
(not (eq *lookup-failure* (field-value field object :noerror))))
(defun has-method (method object)
(let ((val (field-value method object :no-error)))
(and val (symbolp val) (fboundp val))))
(defun with-fields-ex (fields expression binding-type body)
(assert (member binding-type '(let symbol-macrolet)))
(assert (listp fields))
(let ((object-sym (gensym)))
(labels ((make-clause (sym)
(list (make-non-keyword sym)
`(field-value ,(make-keyword sym) ,object-sym))))
`(let ((,object-sym ,expression))
(,binding-type ,(mapcar #'make-clause fields)
,@body)))))
(defmacro with-fields (fields expression &body body)
"Bind FIELDS from the object EXPRESSION to names in the local
environment in evaluating BODY. Local symbol macros are used, meaning
that each reference (get or set) is a slot access on the object."
(with-fields-ex fields expression 'symbol-macrolet body))
(defmacro with-field-values (fields expression &body body)
"Bind the names in FIELDS to the values of the corresponding fields
in EXPRESSION, in evaluating BODY. Each slot is accessed only once,
upon binding."
(with-fields-ex fields expression 'let body))
;;; Basic SLIME auto documentation support
(defvar *method-documentation* nil)
(defvar *method-arglists* nil)
(defun initialize-documentation-tables ()
(setf *method-documentation* (make-hash-table :test 'equal))
(setf *method-arglists* (make-hash-table :test 'equal)))
(defun method-documentation (method-symbol)
(if (null *method-documentation*)
(prog1 nil (initialize-documentation-tables))
(gethash (make-keyword method-symbol)
*method-documentation*)))
(defun set-method-documentation (method-symbol docstring)
(unless *method-documentation*
(initialize-documentation-tables))
(setf (gethash (make-keyword method-symbol)
*method-documentation*)
docstring))
(defsetf method-documentation set-method-documentation)
(defun method-arglist (method-symbol)
(if (null *method-arglists*)
(prog1 :not-available (initialize-documentation-tables))
(gethash (make-keyword method-symbol)
*method-arglists* :not-available)))
(defun method-arglist-for-swank (method-symbol)
(let ((result (method-arglist method-symbol)))
(if (listp result)
(cons 'self result)
result)))
(defun set-method-arglist (method-symbol arglist)
(unless *method-arglists*
(initialize-documentation-tables))
(setf (gethash (make-keyword method-symbol)
*method-arglists*)
arglist))
(defsetf method-arglist set-method-arglist)
;;; Methods and messages
;; Methods are function-valued fields whose first argument is the
;; object to operate on. The remaining arguments are the arguments to
;; the method. The `define-method' macro defined later will insert
;; this implicit `self' argument for you, and implement some syntactic
;; sugar.
;; First we implement method caching, which avoids hash table lookups
;; for repeatedly used methods. (This is similar to the GNU Objective C
;; implementation.)
(defconstant +cache-size+ 6)
(defun initialize-method-cache (object)
(setf (object-cache object)
(list (cons nil nil) (cons nil nil) (cons nil nil)
(cons nil nil) (cons nil nil) (cons nil nil))))
(defun cache-method (object method func)
(let ((cache (object-cache object))
(entry nil))
(assert (listp cache))
(rotatef (sixth cache)
(fifth cache)
(fourth cache)
(third cache)
(second cache)
(first cache))
(setf entry (first cache))
(setf (car entry) method)
(setf (cdr entry) func)))
(defun method-cache-lookup (object method)
(declare (optimize (speed 3))
(inline object-cache)
(type keyword method))
(cdr (assoc method (object-cache object))))
;; Next comes the basic function for sending a message synchronously
;; and obtaining a return value.
;; When a message cannot be delivered because no corresponding
;; function was found, BLOCKY attempts to re-send the message via the
;; object's `forward-message' method (if any).
;; An object's `forward-message' method should accept the method-key as the
;; first argument, and the arguments of the original message as the
;; remaining arguments.
;; We also want to be able to invoke the prototype (or "super's")
;; version of a method; for example during initialization, one might
;; wish to run the super's initializer as the first statement in the
;; child's.
(defvar *forward-message-handler* nil)
(defmacro with-forward-message-handler (form &body body)
`(let ((*forward-message-handler* ,form)) ,@body))
(defun send (method thing &rest args)
"Invoke the method identified by the keyword METHOD on the OBJECT with ARGS.
If the method is not found, attempt to forward the message."
;; See also `send-queue' and `send-super'
(let ((object (find-object thing)))
(when (not (object-p object))
(error "Cannot send message to non-object: ~A. Did you forget the `self' argument?" object))
;; check the cache
(let ((func (method-cache-lookup object method))
(*self* object))
(if func
;; cache hit. invoke the method and finish up.
(apply func object args)
;; cache miss. look for a value.
(progn (setf func (field-value method object :noerror))
(if (not (eq *lookup-failure* func))
;; store in local cache and then invoke the method
(progn
(cache-method object method func)
(apply func object args))
;; no such method. try another handler
(let ((handler (or *forward-message-handler* object)))
(if (has-field :forward-message handler)
(apply (field-value :forward-message handler)
method args)
(error (format nil "Could not invoke method ~S" method))))))))))
(define-condition null-next (error)
((method-key :initarg :message :accessor method-key)
(object :initarg :object :accessor object))
(:report (lambda (condition stream)
(format stream "Cannot find next method ~S for object ~S."
(method-key condition)
(object condition)))))
(defun definition (method object)
(block finding
(loop while object do
(when (has-local-value method object)
(return-from finding
(values (field-value method object) object)))
(setf object (find-super object)))))
(defun definer (method object)
(multiple-value-bind (definition definer)
(definition method object)
(declare (ignore definition))
definer))
(defun next-definer (method object)
(if (has-local-value method object)
(definer method (find-super object))
(next-definer method (find-super object))))
(defun next-definition (method object)
(field-value method (next-definer method object)))
(defvar *next-search-start* nil)
(defun send-super (method object &rest arguments)
"Invoke next version of METHOD on OBJECT, passing ARGUMENTS. We do
this by finding the current implementation (via slot lookup), then
finding the next implementation after that."
(apply (next-definition method (find-object object))
object arguments))
;;; Dynamically binding the recipient of a message
(defvar *target* nil)
(defmacro with-target (target &rest body)
`(let ((*target* ,target))
,@body))
;;; Message queueing
;; In some situations, an object will wish to queue up messages to be
;; sent elsewhere at a later time. `send-queue' will do this.
;; First we need a general queue mechanism.
(defstruct queue head tail count max)
(define-condition empty-queue (error) ())
(defun unqueue (Q)
(when (null (queue-head Q))
(error 'empty-queue))
(when (eq (queue-head Q)
(queue-tail Q))
;; only one item is in the queue; kill the tail pointer
(setf (queue-tail Q) nil))
;; now unqueue
(decf (queue-count Q))
(pop (queue-head Q)))
(defun queue (item Q)
(let ((element (cons item nil)))
(if (null (queue-tail Q))
;; handle empty queue
(progn
(setf (queue-tail Q) element
(queue-head Q) (queue-tail Q)
(queue-count Q) 1))
;; handle nonempty queue
(progn
(setf (cdr (queue-tail Q))
element)
(pop (queue-tail Q))
(incf (queue-count Q)))))
;; now prevent exceeding any max that's been set. this is useful to
;; prevent allocating all memory when you don't care about throwing
;; away old objects.
(when (and (numberp (queue-max Q))
(< (queue-max Q) (queue-count Q)))
(unqueue Q)))
(defvar *message-queue* nil "This variable is bound to the current
message queue, if any.")
(defun queue-message (method-key receiver args)
"Enter a message into the current `*message-queue*'."
(queue (list method-key receiver args) *message-queue*))
(defun queued-messages-p ()
"Return non-nil if there are queued messages."
(not (null (queue-head *message-queue*))))
(defun unqueue-message ()
"Remove the next message from the queue. The returned message is a
list of the form (METHOD-KEY RECEIVER ARGS)."
(unqueue *message-queue*))
(defun unqueue-and-send-message ()
(let ((msg (unqueue-message)))
(destructuring-bind (method-key receiver args) msg
(apply #'send method-key receiver args))))
(defmacro with-message-queue (expr &body body)
"Run the BODY forms, capturing any queued output messages to the
message queue resulting from the evaluation of EXPR."
`(let ((*message-queue* ,expr))
,@body))
(defun send-queue (method-key object &rest args)
"Queue a message. Returns nil."
(queue-message method-key object args))
;;; Field reference syntax
;; Within method bodies, you can access the fields of `self' with the
;; shorthand
;;
;; %foo
;;
;; instead of writing
;;
;; (field-value :foo self)
;;
;; For example:
;;
;; (princ %name)
;; (setf %width 10)
;;
(defvar *field-reference-prefix* "%")
(defun transform-tree (tester transformer tree)
(cond ((consp tree)
;; it's a cons. process the two subtrees.
(destructuring-bind (left . right) tree
(cons
;; process left subtree.
(if (funcall tester left)
(funcall transformer left)
;; nothing to transform here. move on down the left side.
(if (consp left)
(transform-tree tester transformer left)
left))
;; process right subtree.
(transform-tree tester transformer right))))
;; it's not a cons. test it.
((funcall tester tree)
(funcall transformer tree))
;; it failed the test. leave it alone.
(t tree)))
;;; field references of the form %foo
(defun field-reference-p (form)
"Return non-nil if FORM is a symbol like %foo."
(if (symbolp form)
(let ((name (symbol-name form)))
(and (> (length name) 1)
(string= "%" (subseq name 0 1))
;; don't catch double %%
(not (string= "%" (subseq name 1 2)))))))
(defmacro with-input-values (symbols form &body body)
(assert (every #'symbolp symbols))
(let ((thing (gensym)))
(flet ((make-clause (symbol)
`(,symbol (evaluate
(input-block ,thing
,(make-keyword symbol))))))
`(let* ((,thing ,form)
,@(mapcar #'make-clause symbols))
,@body))))
(defun input-reference-p (form)
"Return non-nil if FORM is a symbol like %%foo."
(if (symbolp form)
(let ((name (symbol-name form)))
(and (> (length name) 2)
(string= "%%" (subseq name 0 2))))))
(defun make-accessor-macrolet-clause (symbol)
(list symbol
`(field-value
,(make-keyword
;; strip percent sign
(subseq (symbol-name symbol) 1))
self)))
(defun make-input-accessor-defun-forms (symbol)
(let ((accessor (make-non-keyword
(concatenate 'string
"%%"
(symbol-name symbol)))))
`(unless (fboundp ',accessor)
(defun ,accessor (thing)
;; see also blocks.lisp, `define-block-macro'
(input-block thing ,symbol))
(export ',accessor))))
(defun make-input-accessor-macrolet-clause (symbol)
(list symbol
`(input-block
self
,(make-keyword
;; strip double percent sign
(subseq (symbol-name symbol) 2)))))
(defun make-accessor-flet-clause (symbol)
`(,symbol (thing)
(field-value ,symbol thing)))
(defun transform-method-body (body)
(let (fields inputs)
;; collect %foo symbols used in body
(transform-tree #'field-reference-p
#'(lambda (symbol)
;; don't modify input
(prog1 symbol
;; just collect
(pushnew symbol fields)))
body)
;; similarly, collect %%foo symbols
(transform-tree #'input-reference-p
#'(lambda (symbol)
(prog1 symbol
(pushnew symbol inputs)))
body)
;; arrange for the substitution
`(symbol-macrolet
,(append
(mapcar #'make-accessor-macrolet-clause fields)
(mapcar #'make-input-accessor-macrolet-clause inputs))
,@body)))
;; (defun transform-field-reference (ref)
;; "Change the symbol REF from %foo to (field-value :foo self)."
;; (let ((name (symbol-name ref)))