/
classes.lisp
4404 lines (3671 loc) · 167 KB
/
classes.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
;; -*- Mode: LISP; Syntax: COMMON-LISP; Package: CLPYTHON; Readtable: PY-AST-USER-READTABLE -*-
;;
;; This software is Copyright (c) Franz Inc. and Willem Broekema.
;; Franz Inc. and Willem Broekema grant you the rights to
;; distribute and use this software as governed by the terms
;; of the Lisp Lesser GNU Public License
;; (http://opensource.franz.com/preamble.html),
;; known as the LLGPL.
;;; To have Emacs properly indent the DEF-PY-METHOD form, add to .emacs:
;;; (put 'def-py-method 'fi:common-lisp-indent-hook (get 'defmethod 'fi:common-lisp-indent-hook))
(in-package :clpython)
(in-syntax *ast-user-readtable*)
;; TODO: ensure all items listed in this table are implemented
;; http://www.python.org/doc/current/library/inspect.html
;; Python metatype. Class `type' and subclasses thereof are instances
;; of py-meta-type.
(defun finalize-inheritance (c)
(closer-mop:finalize-inheritance c))
(defmethod initialize-instance :after ((cls py-meta-type) &rest initargs)
(declare (ignore initargs))
(finalize-inheritance cls))
(defmethod initialize-instance :after ((cls py-type) &rest initargs)
(declare (ignore initargs))
(finalize-inheritance cls))
;; Lisp type/object
(defclass py-lisp-type (py-type)
()
(:documentation "Metaclass for proxy classes")
(:metaclass py-meta-type))
(defclass py-lisp-object (object)
((lisp-object :initarg :lisp-object :accessor proxy-lisp-val))
(:metaclass py-lisp-type)
(:documentation "Base class for proxy classes"))
(defun ensure-class (&rest args)
(apply #'closer-mop:ensure-class args))
(defun ensure-class-using-class (&rest args)
(apply #'closer-mop:ensure-class-using-class args))
(defun class-direct-superclasses (&rest args)
(apply #'closer-mop:class-direct-superclasses args))
;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;
;;;
;;; This is a bit ugly, but method classes must be evaluated prior to their
;;; use. Therefore here are method classes, and below their methods.
;;;
;;; Note that PY-METHOD is not a Lisp FUNCTION.
(defclass py-method (object)
((func :initarg :func :accessor py-method-func))
(:metaclass py-type))
(defclass py-class-method (py-method)
((class :initarg :class))
(:metaclass py-type))
(defclass py-attribute-method (py-method)
()
(:metaclass py-type))
(defclass py-class-attribute-method (py-attribute-method)
()
(:metaclass py-type))
(defclass py-writable-attribute-method (py-attribute-method)
((write-func :initarg :writer :accessor attribute-writer))
(:metaclass py-type))
(defun make-writable-attribute (reader writer)
(make-instance 'py-writable-attribute-method :func reader :writer writer))
(defmethod print-object ((x py-writable-attribute-method) stream)
(print-unreadable-object (x stream)
(with-slots (func write-func) x
(format stream ":func ~S :write-func ~S" func write-func))))
(defclass py-static-method (py-method)
()
(:metaclass py-type))
(defparameter *writable-attribute-methods* (make-hash-table :test #'eq))
(eval-when (:compile-toplevel :load-toplevel :execute)
(defun ensure-pkg-symbol (str pkg)
(check-type str string)
(or (find-symbol str pkg)
(intern str pkg)))
(defun ensure-user-symbol (str)
(ensure-pkg-symbol str #.(find-package :clpython.user)))
) ;; eval-when
(defmacro def-py-method (cls.meth &rest args)
;; As `cls.meth' is a symbol, but methods of Python classes are always in
;; lowercase, the `meth' part is converted to lowercase iff the symbol name
;; is all in upper case. This means you cannot create a full-upper-case method
;; name with DEF-PY-METHOD.
(labels ()
(let* ((cm (symbol-name cls.meth))
(dot-pos (or (position #\. cm)
(error "Need dot in name: (def-py-method classname.methodname ..); got: ~A"
cls.meth)))
;; The class names must be a symbol defined in the same pkg
;; as the `cls.meth' argument to this macro.
(cls (intern (subseq cm 0 dot-pos) (symbol-package cls.meth)))
(meth (let ((methname (subseq cm (1+ dot-pos))))
(when (not (some #'lower-case-p methname))
;; Can't use (every #'upper-case-p) because of dashes
(setf methname (nstring-downcase methname)))
(ensure-user-symbol methname)))
(modifiers (loop while (keywordp (car args)) collect (pop args)))
(func-name (if (eq (car modifiers) :attribute-write)
(ensure-user-symbol (format nil "~A-~A" cls.meth '#:writer))
cls.meth)))
(assert (<= (length modifiers) 1) ()
"Multiple modifiers for a py-method: ~A. Todo?" modifiers)
`(progn ,(destructuring-bind (func-args &body func-body) args
(loop with real-args
with body = `(locally ,@func-body) ;; allows DECLARE forms at head
for sym in func-args
for sym-name = (when (symbolp sym) (symbol-name sym))
if (not (symbolp sym))
do (push sym real-args)
else if (char= #\^ (aref sym-name (1- (length sym-name))))
do (let ((real-name (intern (subseq sym-name 0 (1- (length sym-name)))
#.*package*)))
(push real-name real-args)
(setf body `(let ((,real-name (deproxy ,real-name)))
(declare (ignorable ,real-name))
,body)))
else do (push sym real-args)
finally (return (progn (setf real-args (nreverse real-args))
`(defun ,func-name ,real-args
;; Make all args ignorable. Otherwise there will be warnings for
;; unused variables even if there is (declare (ignore ..)) in the
;; function body: function body is wrapped in a LOCALLY.
;; XXX Ugly, should parse declare-ignore declarations.
,(let ((sym-args (remove-if-not (lambda (s) (and (symbolp s)
(not (char= (aref (string s) 0) #\&))))
real-args)))
`(declare (ignorable ,@sym-args)))
(block ,cls.meth
,body))))))
(register-method ',cls ',meth
,(ecase (car modifiers)
((nil) `(let ((f (function ,cls.meth)))
f))
(:static `(make-instance 'py-static-method
:func (function ,cls.meth)))
(:attribute `(make-instance 'py-attribute-method
:func (function ,cls.meth)))
(:class-attribute `(make-instance 'py-class-attribute-method
:func (function ,cls.meth)))
(:attribute-read `(let ((x (make-instance 'py-writable-attribute-method
:func (function ,cls.meth))))
(setf (gethash ',cls.meth *writable-attribute-methods*) x)
x))
(:attribute-write `(let ((f (function ,func-name))
(read-f (or (gethash ',cls.meth
*writable-attribute-methods*)
(error "Attribute read function ~A not defined yet"
',cls.meth))))
(setf (slot-value read-f 'write-func) f)
read-f ;; read function is already stored in dict
))))))))
(defun register-method (cls-name attr val)
(check-type attr symbol)
(let* ((cls (or (find-class cls-name) (error "No such class: ~A" cls-name))))
(assert (typep cls 'dict-mixin))
(class.raw-attr-set cls attr val)))
;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;
;;;
;;; dynamic class creation
(defun make-py-class (&rest args)
(declare (dynamic-extent args))
(multiple-value-bind (cls kind)
(apply #'make-py-class-1 args)
(assert (member kind '(:metaclass :class :condition)))
cls))
(defun apply-namespace-to-cls (namespace cls)
(assert (eq-hash-table-p namespace)) ;; may not hold when using __prepare__ etc
(loop for key being each hash-key in namespace
using (hash-value val)
do (assert (symbolp key))
(class.raw-attr-set cls key val)))
(defun make-py-class-1 (&key name context-name namespace supers cls-metaclass mod-metaclass)
(declare (ignore context-name)) ;; XXX for now
(flet ((make-condition-exception ()
(assert (not *exceptions-are-python-objects*))
(values (let ((cond-class-name (apply #'define-exception-subclass
name (mapcar 'class-name supers))))
(find-class cond-class-name))
:condition)))
#+(or)(assert (symbolp name))
#+(or)(assert (listp supers))
#+(or)(assert (typep namespace 'dict))
;; XXX is this a true restriction? Custom metaclasses may allow
;; more kinds of `bases' in their __new__(...) ?
;; either:
;; 1) all supers are subtype of 'py-type (to create a new metaclass)
;; 2) all supers are subtype of 'object (to create new "regular user-level" class)
(flet ((of-type-class (s) (typep s 'class))
(subclass-of-py-dl-object-p (s) (subtypep s (ltv-find-class 'object)))
(subclass-of-py-type-p (s) (subtypep s (ltv-find-class 'py-type))))
(unless (every #'of-type-class supers)
(py-raise '{TypeError} "Not all superclasses are classes (got: ~A)." supers))
;; Handle the case where exceptions are not Python object instances.
(when (and (not *exceptions-are-python-objects*)
(loop for s in supers thereis (subtypep s 'condition)))
(unless (loop for s in supers always (subtypep s 'condition))
(py-raise '{TypeError}
"Unsupported heterogeneous superclasses: some CONDITION, some not: ~A." supers))
(return-from make-py-class-1 (make-condition-exception)))
(loop for s in supers
unless (or (subclass-of-py-type-p s)
(subclass-of-py-dl-object-p s))
do (error "BUG? Superclass ~A is neither sub of 'type nor sub of 'object~@[~A~]!"
s (unless *exceptions-are-python-objects* " not a subtype of 'condition")))
#+(or)
(let ((core-supers (remove-if-not (lambda (s) (typep s 'py-type)) supers)))
(when core-supers
(py-raise '{TypeError} "Cannot subclass from these classes: ~A" core-supers)))
(when (and (some #'subclass-of-py-type-p supers)
(some #'subclass-of-py-dl-object-p supers))
(py-raise 'TypeError "Superclasses are at different levels (some metaclass, ~
some regular class) (got: ~A)." supers))
(let ((metaclass (or cls-metaclass
(when supers (class-of (car supers)))
mod-metaclass
(ltv-find-class 'py-type))))
#+(or)(warn "metaclass: ~A" metaclass)
(unless (typep metaclass 'class)
(py-raise '{TypeError} "Metaclass must be a class (got: ~A)" metaclass))
(unless (or (eq metaclass (ltv-find-class 'py-meta-type))
(subtypep metaclass (ltv-find-class 'py-type)))
(py-raise '{TypeError}
"Metaclass must be subclass of `type' (got class: ~A)" metaclass))
;; When inheriting from py-lisp-type (like `int'), use
;; py-meta-type as metaclass.
(when (or (eq metaclass (ltv-find-class 'py-lisp-type))
#+(or)(eq metaclass (ltv-find-class 'py-type)))
(setf metaclass (ltv-find-class 'py-type)))
#+(or)(warn "metaclass 2: ~A" metaclass)
;; Subclass of `type' has metaclass 'py-meta-type
(when (eq metaclass (ltv-find-class 'py-meta-type))
(let ((cls (ensure-class
(make-symbol (symbol-name name))
:direct-superclasses supers
:metaclass (ltv-find-class 'py-meta-type)
#+(or):dict #+(or)namespace)))
(apply-namespace-to-cls namespace cls)
(return-from make-py-class-1 (values cls :metaclass))))
;; Not a subclass of `type', so at the `object' level
(let ((__new__ (class.attr-no-magic metaclass '{__new__})))
(assert __new__ ()
"recur: no __new__ found for class ~A, yet it is a subclass of PY-TYPE ?!" metaclass)
#+(or)(warn "binding __new__: ~A ~A" __new__ metaclass)
(let ((cls (if (and (eq (class-of __new__) (ltv-find-class 'py-static-method))
(eq (py-method-func __new__) (symbol-function 'py-type.__new__)))
;; Optimize common case: py-type.__new__
(progn
#+(or)(warn "Inlining make-py-class")
(py-type.__new__ metaclass
(string name)
supers ;; MAKE-TUPLE-FROM-LIST not needed
namespace))
(let ((bound-_new_ (bind-val __new__ metaclass (py-class-of metaclass))))
;; If __new__ is a static method, then bound-_new_ will
;; be the underlying function.
(or (py-call bound-_new_ metaclass
(string name)
(make-tuple-from-list supers) ;; ensure not NIL
namespace)
(break "Class' bound __new__ returned NIL: ~A" bound-_new_))))))
;; Call __init__ when the "thing" returned by
;; <metaclass>.__new__ is of type <metaclass>.
(if (typep cls metaclass)
(let ((__init__ (class.attr-no-magic metaclass '{__init__})))
#+(or)(warn " __init__ method ~A is: ~A" metaclass __init__)
(when __init__
(py-call __init__ cls)))
#+(or)(warn "Not calling __init__ method, as class ~A is not instance of metaclass ~A"
cls metaclass))
(values cls :class)))))))
;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;
(defconstant +the-true+ 1)
(defconstant +the-false+ 0)
(defun py-bool (lisp-val)
(if lisp-val +the-true+ +the-false+))
(define-compiler-macro py-bool (lisp-val)
`(if ,lisp-val +the-true+ +the-false+))
;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;
;;;
;;; Built-in Python object types:
;;;
;;; -- type ----------- repr ----- subclassable -- examples -------------------
;;; py-lisp-object: lisp value yes number, string, tuples, vectors, dict
;;; object: py cls inst no function, method
;;; dicted-object: py cls inst yes file, module, property
;;;
;; (defun f (&rest args)
;; (with-parsed-py-arglist ("f" (a b) args)
;; (+ a b)))
;;
;; (f 1 2) (f 1 :b 2) (f :a 1 :b 2)
(defmacro with-parsed-py-arglist ( (func-name formal-args actual-args) &body body)
(let ((alist '#:alist))
`(let* ((,alist (parse-poskey-arglist ,func-name ',formal-args ,actual-args))
,@(loop for f in formal-args
collect `(,f (cdr (assoc ',f ,alist :test #'eq)))))
,@body)))
(defun parse-poskey-arglist (func-name formal-pos-args actual-args)
(let ((pos-args (loop until (symbolp (car actual-args))
collect (pop actual-args)))
(kw-args (loop for aa = actual-args then (cddr aa)
for key = (pop actual-args)
for val = (pop actual-args)
while aa
unless (and (symbolp key) val)
do (error "Invalid arglist: ~S" actual-args)
collect (cons key val))))
(let ((res ())
(formal-pos-args (copy-list formal-pos-args)))
(loop while (and formal-pos-args pos-args)
do (push (cons (pop formal-pos-args) (pop pos-args)) res))
(when pos-args
(py-raise '{TypeError} "Too many arguments for function ~A (got: ~A)"
func-name))
(loop for (key . val) in kw-args
do (let ((fkw (find key formal-pos-args :test #'string=))) ;; (string= |:a| '|a|)
(if fkw
(progn (setf formal-pos-args (delete fkw formal-pos-args :test #'eq))
(push (cons fkw val) res))
(py-raise '{ValueError}
"Invalid argument list: unknown keyword arg (or duplicated arg): ~A"
key))))
(loop for f in formal-pos-args
do (push (cons f nil) res))
res)))
;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;
;;;
;;; Core objects (function, method, None...; not subclassable by the user)
;;;
(def-py-method py-type.__class__ :attribute (x)
(py-class-of x))
;; py-class-method
(def-py-method py-class-method.__new__ :static (cls func)
(make-instance cls))
(defun classp (x)
(checking-reader-conditionals
#+allegro (excl::classp x)
#+cmu (pcl::classp x)
#+lispworks (clos::classp x)
#+sbcl (sb-pcl::classp x)
#-(or allegro cmu lispworks sbcl) (typep x 'class)))
(def-py-method py-class-method.__get__ (x inst class)
(let ((arg (if (classp inst) inst (py-class-of inst))))
(make-instance 'py-bound-method
:func (slot-value x 'func)
:instance arg)))
(def-py-method py-class-method.__init__ (x^ func)
(setf (slot-value x 'func) func))
(def-py-method py-class-method.__call__ (x^ &rest args)
(break "todo")
#+(or)(apply #'py-call (py-method-func x) (slot-value x 'instance) args)
#+(or)
(let ((arg (if (classp obj) obj (py-class-of obj))))
(apply #'py-call (py-method-func x) arg args)))
;; py-attribute-method
(def-py-method py-attribute-method.__get__ (x inst class)
(if (and inst (not (none-p inst)))
(py-call (slot-value x 'func) inst)
nil))
(def-py-method py-attribute-method.__set__ (x obj val)
(py-raise '{TypeError}
"Attribute ~A of object ~A is read-only (value: ~A)"
x obj (py-call (slot-value x 'func) obj)))
(def-py-method py-attribute-method.__repr__ (x)
(with-output-to-string (s)
(print-unreadable-object (x s :type t :identity t))))
;; py-class-attribute-method
(def-py-method py-class-attribute-method.__get__ (x inst class)
(unless (classp inst)
(break "py-class-attribute-method.__get__ wants class instance as first arg! ~A ~A ~A"
x inst class))
(py-call (slot-value x 'func) inst))
;; py-writable-attribute-method
(def-py-method py-writable-attribute-method.__set__ (x obj val)
(if (slot-boundp x 'write-func)
(py-call (slot-value x 'write-func) obj val)
(error "No writer defined for writable attribute: ~A" x)))
(def-py-method py-writable-attribute-method.__get__ (x inst class)
(if (and inst (not (none-p inst)))
(py-call (slot-value x 'func) inst)
nil))
(defclass py-bound-method (py-method)
((instance :initarg :instance :accessor py-method-instance))
(:metaclass py-type))
(defmethod print-object ((x py-bound-method) stream)
(print-unreadable-object (x stream :identity t :type nil)
(with-slots (instance func) x
(format stream "bound-method ~A on the ~A ~A"
(py-function-name func)
(class-name (py-class-of instance))
instance))))
(def-py-method py-bound-method.__repr__ (x)
(with-output-to-string (s)
(print-object x s)))
(def-py-method py-bound-method.__call__ (x &rest args)
(when (and (null (cdr args))
(eq (car args) '{__dict__}))
#+(or)(break "pym.c args: ~A ~A" x args))
(with-slots (func instance) x
(if (functionp func)
(apply (the function func) instance args)
(apply #'py-call func instance args))))
(def-py-method py-bound-method.__get__ (x &rest args)
;; Somewhat surprisingly, when a bound method is __get__ again, the
;; underlying function is bound again:
;;
;; >>> class C:
;; ... def m(self): pass
;; ...
;; >>> x,y = C(), C()
;; >>> m = x.m
;; >>> m
;; <bound method C.m of <__main__.C instance at 0x4021e8ec>>
;; >>> m2 = m.__get__(y,C)
;; >>> m2
;; <bound method C.m of <__main__.C instance at 0x4021e92c>>
;; >>> x
;; <__main__.C instance at 0x4021e8ec>
;; >>> y
;; <__main__.C instance at 0x4021e92c>
(apply #'py-call (x.class-attr-no-magic.bind (py-method-func x) '{__get__}) args))
(def-py-method py-bound-method.__name__ :attribute (x)
(py-bound-method.__repr__ x))
(defclass py-unbound-method (py-method)
((class :initarg :class :accessor py-method-class))
(:metaclass py-type))
(def-py-method py-unbound-method.__repr__ (x)
(with-output-to-string (s)
(print-object x s)))
(defmethod print-object ((x py-unbound-method) stream)
(print-unreadable-object (x stream :identity t :type nil)
(with-slots (class func) x
(format stream "unbound-method ~A on class ~A"
(py-function-name func)
(class-name class)))))
(def-py-method py-unbound-method.__call__ (x &rest args)
(with-slots (func) x
(apply #'py-call func args)))
(def-py-method py-unbound-method.__get__ (x &rest args)
;; same as py-bound-method.__get__ ?!
(apply #'py-call (x.class-attr-no-magic.bind (py-method-func x) '{__get__}) args))
;; py-static-method
(def-py-method py-static-method.__new__ :static (cls func)
(assert (eq cls (ltv-find-class 'py-static-method)))
(make-instance 'py-static-method :func func))
(def-py-method py-static-method.__get__ (x inst class)
(slot-value x 'func))
(def-py-method py-static-method.__repr__ (x)
(with-output-to-string (s)
(print-unreadable-object (x s :identity t)
(format s "the static method ~A" (slot-value x 'func)))))
(def-py-method py-static-method.__call__ (x &rest args)
(apply #'py-call (slot-value x 'func) args))
(defmethod print-object ((x py-static-method) stream)
(print-unreadable-object (x stream :identity t :type t)
(format stream ":func ~A" (slot-value x 'func))))
;; Function (Core object)
(defclass py-lisp-function (object)
()
(:metaclass py-type))
(finalize-inheritance (find-class 'py-lisp-function))
(def-py-method py-lisp-function.__repr__ (func)
(with-output-to-string (s)
(print-object func s)))
(def-py-method py-lisp-function.__get__ (func inst cls)
(assert inst)
(let ((to-make (cond ((none-p inst)
(if (and (typep cls 'class)
(eq (class-name cls) 'py-none))
:bound-method
:unbound-method))
((none-p cls)
(py-raise '{ValueError}
"function.__get__(None, None) : invalid args"))
(t
:bound-method))))
(ecase to-make
(:bound-method (make-instance 'py-bound-method :instance inst :func func))
(:unbound-method (make-instance 'py-unbound-method :class cls :func func)))))
(def-py-method py-lisp-function.__name__ :attribute (func)
(function-name func))
(defclass funcallable-python-class (closer-mop:funcallable-standard-class py-type)
()
(:metaclass py-meta-type))
(defmethod closer-mop:validate-superclass ((class funcallable-python-class) superclass)
(declare (ignorable class superclass))
t)
;; Temporary (?) hack to get things running on SBCL 1.0.16,
;; where instantiating a py-function leads to strange errors.
;; See <http://common-lisp.net/pipermail/clpython-devel/2008-May/000048.html>
(defparameter *create-simple-lambdas-for-python-functions*
(checking-reader-conditionals
#+(or allegro lispworks) nil
#+sbcl t
#-(or allegro lispworks sbcl) t)
"Whether Python function are real CLOS funcallable instances, or just normal lambdas.
Note that in the latter case, functions miss their name and attribute dict, but should
otherwise work well.")
(defstruct (simple-function-data (:conc-name sfd-))
func name attributes)
(defparameter *simple-function-data* (make-hash-table :test 'eq)
"Mapping from function to SIMPLE-FUNCTION-DATA")
(defun register-simple-function (func name)
(setf (gethash func *simple-function-data*)
(make-simple-function-data :func func
:name name
:attributes (make-hash-table :test 'eq))))
(defgeneric py-function-lambda (x)
;; XXX this function is also used when *create-simple-lambdas-for-python-functions*
;; which is not quite kosher.
(:method ((x function)) x))
(defclass py-function (standard-generic-function dicted-object)
;; mop:funcallable-standard-class defines :name initarg, but how to to access it portably...
((fname :initarg :fname :initform nil :accessor py-function-name)
(context-name :initarg :context-name :initform nil :accessor py-function-context-name)
(lambda :initarg :lambda :initform nil :accessor py-function-lambda))
(:metaclass funcallable-python-class))
;; XXX On LispWorks this is not guaranteed to work:
;; http://article.gmane.org/gmane.lisp.lispworks.general/8999
;; Maybe switch to simple lambda's there too?
(defun set-funcallable-instance-function (inst func)
(closer-mop:set-funcallable-instance-function inst func))
(defgeneric function-name (f)
(:method ((f function))
(let ((data (gethash f *simple-function-data*)))
(when data
(string (sfd-name data)))))
(:method ((f py-function)) (string (py-function-name f))))
(defun make-py-function (&key name context-name lambda)
(if *create-simple-lambdas-for-python-functions*
(progn (register-simple-function lambda name)
lambda)
(let ((x (make-instance 'py-function
:fname (string name)
:lambda lambda
:context-name context-name)))
(set-funcallable-instance-function x lambda)
;; fill dict?
x)))
(def-py-method py-function.__get__ (func inst cls)
(py-lisp-function.__get__ func inst cls))
(def-py-method py-function.__hash__ (func)
(sxhash func))
(def-py-method py-function.__repr__ (func)
(with-output-to-string (s)
(if (typep func 'py-function)
(print-object func s)
(format s "~A" (or (function-name func) func)))))
(defmethod print-object ((x py-function) stream)
(print-unreadable-object (x stream :identity t)
(format stream "python-function ~A~@[ (~A)~]"
(py-function-name x)
(unless (compiled-function-p (py-function-lambda x)) "interpreted"))
(when (string/= (py-function-name x)
(py-function-context-name x))
(format stream " (~A)" (py-function-context-name x)))))
(def-py-method py-function.__name__ :attribute-read (func)
(or (and (typep func 'py-function)
(py-function-name func))
(whereas ((data (gethash func *simple-function-data*)))
(or (whereas ((ht (sfd-attributes data))
(name (gethash '{__name__} ht)))
(string name))
(string (sfd-name data))))
(py-raise '{AttributeError} "Function ~A has no attribute `__name__'." func)))
(def-py-method py-function.__name__ :attribute-write (func name)
(if (typep func 'py-function)
(setf (py-function-name func) name)
(or (whereas ((data (gethash func *simple-function-data*)))
(setf (sfd-name data) name))
(py-raise '{AttributeError} "Cannot set attribute `__name__' of ~A." func))))
(def-py-method py-function._fif :attribute (x)
"The funcallable instance function of X."
;; CLPython-specific.
(when (typep x 'py-function)
(setf x (py-function-lambda x)))
(assert (functionp x))
x)
(def-py-method py-function.__setattr__ (func attr val)
(when (stringp attr)
(setf attr (ensure-user-symbol attr)))
(check-type attr symbol)
(when (eq attr '{__dict__})
(when (typep val 'symbol-hash-table)
(setf val (sht-ht val)))
(check-type val hash-table) ;; XXX or custom ht
(let ((ht (make-eq-hash-table)))
(loop for key being the hash-key in val
using (hash-value value)
for key.sym = (typecase key
(symbol key)
(string (ensure-user-symbol key))
(t (py-raise '{TypeError} "Invalid key of type ~A in replacement dict (key: ~A)."
(type-of key) key)))
do (setf (gethash key.sym ht) value))
(etypecase func
(py-function (setf (dict func) ht))
(function (let ((data (gethash func *simple-function-data*)))
(setf (sfd-attributes data) ht)))))
(return-from py-function.__setattr__))
(etypecase func
(py-function (progn (let ((meth (funky-dict-get (dict (find-class 'py-function)) attr)))
(when (typep meth 'py-writable-attribute-method)
(return-from py-function.__setattr__
(py-writable-attribute-method.__set__ meth func val))))
(let ((d (or (dict func) (setf (dict func) (make-eq-hash-table)))))
(setf (gethash attr d) val))))
(function (let ((ht (whereas ((data (gethash func *simple-function-data*)))
(or (sfd-attributes data)
(setf (sfd-attributes data) (make-eq-hash-table))))))
(unless ht
(py-raise '{AttributeError} "Cannot set attribute on function ~A." func))
(setf (gethash attr ht) val)))))
(def-py-method py-function.__getattribute__ (func attr)
(when (stringp attr)
(setf attr (ensure-user-symbol attr)))
(check-type attr symbol)
(whereas ((val (funky-dict-get (dict (find-class 'py-function)) attr)))
(return-from py-function.__getattribute__
(bind-val val func (find-class 'py-function))))
(or (etypecase func
(py-function (whereas ((d (or (dict func)
(and (eq attr '{__dict__})
(setf (dict func) (make-eq-hash-table))))))
(if (eq attr '{__dict__})
(make-symbol-hash-table d)
(values (gethash attr d)))))
(function (whereas ((data (gethash func *simple-function-data*))
(ht (or (sfd-attributes data)
(and (eq attr '{__dict__})
(setf (sfd-attributes data) (make-eq-hash-table))))))
(if (eq attr '{__dict__})
(make-symbol-hash-table ht)
(values (gethash attr ht))))))
(py-raise '{AttributeError} "Function ~A has no attribute `~A'." func attr)))
(def-py-method py-function.__delattr__ (func attr)
(when (stringp attr)
(setf attr (ensure-user-symbol attr)))
(check-type attr symbol)
(assert (not (eq attr '{__dict__})) () "Error: todo: function delattr of __dict__")
(let ((ok (etypecase func
(py-function (whereas ((d (dict func)))
(setf (py-subs d attr) nil)))
(function (whereas ((data (gethash func *simple-function-data*))
(ht (sfd-attributes data)))
(remhash attr ht))))))
(unless ok
(py-raise '{AttributeError} "Function ~A has no attribute `~A' to delete." func attr))))
(def-py-method py-function.func_code :attribute (x)
"Read-only attribute: the underlying lambda. (In CPython the bytecode vector.)"
(py-function-lambda x))
(def-py-method py-function._dis :attribute (x)
;; CLPython-specific attribute, to ease debugging.
;;
;; Calling DISASSEMBLE directly on X will print (at least) two functions:
;; - the instructions that load and call the funcallable instance function
;; - the instructions of the funcallable instance function
;; The first is not very interesting imho.
;;
;; DISASSEMBLE accepts fbound symbols or lambda expressions, according to the spec.
;; It might thus be Allegro-specific that its DISASSEMBLE accepts a function object.
(when (typep x 'py-function)
(setf x (py-function-lambda x)))
(eval `(disassemble ,x)))
#+clpython-source-level-debugging
(def-py-method py-function._src :attribute (x)
(when (typep x 'py-function)
(setf x (py-function-lambda x)))
(when (excl::closurep x) ;; needed?
(setq x (excl::cl_shared x)))
(let ((*print-level* 2))
(excl::dump-lisp-source x)))
(defmethod py-function-name ((x function))
(declare (ignorable x))
#+allegro (format nil "~A" (excl::func_name x))
#-allegro (call-next-method))
(defmethod py-function-name ((x t))
;; fall-back
(format nil "~A" x))
(def-py-method py-function.__call__ (func &rest args)
(apply func args))
(defun function-arglist (f)
(check-type f function)
#+allegro (excl:arglist f)
#-allegro nil)
(def-py-method py-function.__doc__ :attribute-read (func^)
(let ((fname (py-function-name func))
(arglist (function-arglist func))
(documentation (documentation func 'function)))
(with-output-to-string (s)
(when fname (write-string fname s))
(format s "~A" (or arglist "(unknown args)"))
(when (and documentation (or fname arglist))
(terpri s))
(when documentation (write-string documentation s)))))
(def-py-method py-function.__doc__ :attribute-write (func^ doc)
(setf (documentation func 'function) doc))
;; Enumerate (core object)
(defclass py-enumerate (object)
((gener :initarg :gener))
(:metaclass py-type))
(finalize-inheritance (find-class 'py-enumerate))
(def-py-method py-enumerate.__new__ :static (cls iterable)
#+(or)(assert (subtypep cls 'py-enumerate))
(let ((gener (make-iterator-from-function
:name :enumerater
:func (let ((iter (get-py-iterate-fun iterable))
(i 0))
(lambda ()
(let ((val (funcall iter)))
(when val
(prog1
(make-tuple-from-list (list i val))
(incf i)))))))))
(make-instance cls :gener gener)))
(def-py-method py-enumerate.__repr__ (x)
(with-output-to-string (s)
(print-unreadable-object (x s :identity t :type t))))
(def-py-method py-enumerate.__iter__ (x)
(slot-value x 'gener))
(defclass py-slice (object)
((start :initarg :start :accessor slice-start)
(stop :initarg :stop :accessor slice-stop)
(step :initarg :step :accessor slice-step))
(:metaclass py-type))
(defmethod print-object ((x py-slice) stream)
(print-unreadable-object (x stream)
(with-slots (start stop step) x
(format stream ":start ~A :stop ~A :step ~A"
start stop step))))
(defun make-slice (start stop step)
(make-instance 'py-slice
:start (or start (load-time-value *the-none*))
:stop (or stop (load-time-value *the-none*))
:step (or step (load-time-value *the-none*))))
(def-py-method py-slice.indices (x^ length^)
"Return tuple of three integers: START, STOP, STEP.
In case of empty range, returns (0,0,1)."
(setf length (py-val->integer length :min 0))
(multiple-value-bind (start stop step)
(destructuring-bind (kind &rest args)
(slice-indices x length)
(ecase kind
((:empty-slice-bogus :empty-slice-before :empty-slice-after :empty-slice-between)
(values 0 0 1))
(:nonempty-slice
(destructuring-bind (start stop num) args
(declare (ignore num))
(values start (1+ stop) 1)))
(:nonempty-stepped-slice
(destructuring-bind (start stop step num) args
(declare (ignore num))
(values start stop step)))))
(make-tuple-from-list (list start stop step))))
;; XXX THis comment ignores fourth value for extended stepped slices
;;
;; Function SLICE-INDICES returns multiple values, best explained by example:
;; Assume x = [0,1,2] so LENGTH = 3
;;
;; -slice- -extr- -assignment- -values-
;; x[:0] [] x[:0] = [42] => [42,0,1,2] :empty-slice-before
;; x[3:] [] x[3:] = [42] => [0,1,2,42] :empty-slice-after
;; x[1:1] [] x[1:1] = [42]=> [0,42,1,2] :empty-slice-between 0 1 = BEFORE-I, AFTER-I
;; x[1:2] [1] x[1:2] = [42]=> [0,42,2] :nonempty-slice 1 1 = FIRST-I, LAST-I
;; x[1:] [1,2] x[1:] = [42] => [0,42] :nonempty-slice 1 2
;; x[:1] [0] x[:1] = [42] => [42,1 2] :nonempty-slice 0 0
;; x[:] [0,1,2](copy) x[:] = [42] => [42](modifies) :nonempty-slice 0 2
;; x[2:1] [] (error) :empty-slice-bogus
;; x[100:200] [] :empty-slice-bogus
;;
;; These have implicit step=1. Other steps result in a `stepped-slice'
;; Now with other step values, using x = range(10) = [0,1,2,3,4,5,6,7,8,9] so LENGTH = 10
;;
;; -slice- -extr- -assignment- -values-
;; x[::0] - - - - - step=0 is error - - - - - - - - - - - - - - - -
;; x[::2] [0,2,4,6,8] :extended-slice 0 9 2 = FIRST LAST STEP
;; x[::-2] [9,7,5,4,1] x[..] = [1,2,3,4,5] => :nonempty-stepped-slice 9 1 -2
;; [0, 5, 2, 4, 4, 3, 6, 2, 8, 1]
;; x[0:2:-1] [] (error) (error)
;; x[100:200:2] [] (error) :empty-slice-bogus
;; x[0:0:4] [] x[..] = [] => ok :empty-slice-bogus
;; x[0:1:4] [0] x[..] = [42] => [42, 2, ..] :nonempty-stepped-slice 0 0 4
;;
;; Assigning to a stepped-slice can only when the thing assigned
;; containes the same number of items as teh stepped slice. For an
;; empty-slice-bogus, this means only the empty list (or another
;; iterable containing 0 items) can be assigned to it.
(defun slice-indices (x length)
"Return three integers: START, STOP, STEP.
START and END are _inclusive_, absolute indices >= 0. STEP is != 0."
(check-type x py-slice)
(check-type length integer)
(let* ((start (or (slice-start x) (load-time-value *the-none*)))
(stop (or (slice-stop x) (load-time-value *the-none*)))
(step (or (slice-step x) (load-time-value *the-none*)))
reversed-p)
(setf step (if (none-p step) 1 (py-val->integer step))
reversed-p (minusp step)
start (if (none-p start)
(if reversed-p (1- length) 0)
(py-val->integer start))
stop (if (none-p stop)
(if reversed-p -1 length)
(py-val->integer stop)))
(assert (every #'integerp (list start stop step)))
(when (minusp start) (incf start length))
(when (minusp stop) (unless (and reversed-p (= stop -1)) ;; XXX right?
(incf stop length)))
(cond ((= step 0)
(py-raise '{ValueError} "Slice step cannot be zero (got: ~S)." x))
((or (and (plusp step) (or (> start length)
(minusp stop)
(> start stop)))
(and (minusp step) (or (minusp start)
(>= stop length)
(< start stop))))
(values :empty-slice-bogus))
((= step 1)
(setf start (max 0 start)
stop (min length stop))
(assert (<= 0 start stop length))
(cond ((= start stop)