summaryrefslogtreecommitdiff
path: root/modules/language/python/number.scm
blob: 3d95ded7b0bdb431d6601dffcb9e9924416c0367 (about) (plain)
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
(define-module (language python number)
  #:use-module (oop pf-objects)
  #:use-module (oop goops)
  #:use-module (rnrs bytevectors)
  #:use-module (language python hash)
  #:use-module (language python list)
  #:use-module (language python try)
  #:use-module (language python for)
  #:use-module (language python def)
  #:use-module (language python exceptions)
  #:use-module (language python bytes)
  #:use-module (language python persist)
  #:export (py-int py-float py-complex
                   py-/ py-logand py-logior py-logxor py-abs py-trunc
                   py-lshift py-rshift py-mod py-floordiv py-round py-iadd
		   py-lognot py-matmul
                   <py-int> <py-float> <py-complex> 
                   py-divmod pyfloat-listing pyint-listing pycomplex-listing
                   py-as-integer-ratio py-conjugate py-fromhex py-hex py-imag
                   py-is-integer py-real hex py-bin py-index
		   py-ifloordiv py-ilshift py-imod py-imul py-imatmul
		   py-bit-length py-to-bytes
		   py-ilogior py-ilogand py-ipow py-isub py-i/
		   py-irshift py-ilogxor))

(define-syntax-rule (aif it p x y) (let ((it p)) (if it x y)))

(define-syntax-rule (mki py-iadd __iadd__)
  (define (py-iadd x y)
    ((ref x '__iadd__) y)))

(mki py-iadd __iadd__)

(mki py-matmul    __matmul__)
(mki py-ifloordiv __ifloordiv__)
(mki py-ilshift   __ilshift__)
(mki py-imod      __imod__)
(mki py-imul      __imul__)
(mki py-imatmul   __imatmul__)
(mki py-ilogior   __ior__)
(mki py-ilogand   __iand__)
(mki py-ipow      __ipow__)
(mki py-isub      __isub__)
(mki py-irshift   __irshift__)
(mki py-ilogxor   __ixor__)
(mki py-i/        __itruediv__)


(define-class <py-int>     () x)
(define-class <py-float>   () x)
(define-class <py-complex> () x)

(name-object <py-int>)
(name-object <py-float>)
(name-object <py-complex>)

(define-syntax-rule (mk <py-int>)
  (cpit <py-int> (o (lambda (o x) (slot-set! o 'x x)) (list (slot-ref o 'x)))))

(mk <py-int>)
(mk <py-float>)
(mk <py-complex>)

(define-syntax-rule (b0 op)
  (begin
    (define-method (op (o1 <py-int>) o2)
      (op (slot-ref o1 'x) o2))    
    (define-method (op (o1 <py-float>) o2)
      (op (slot-ref o1 'x) o2))
    (define-method (op (o1 <py-complex>) o2)
      (op (slot-ref o1 'x) o2))
    (define-method (op o2 (o1 <py-int>))
      (op o2 (slot-ref o1 'x)))    
    (define-method (op o2 (o1 <py-complex>))
      (op o2 (slot-ref o1 'x)))
    (define-method (op o2 (o1 <py-float>))
      (op o2 (slot-ref o1 'x)))))

(define-syntax-rule (mk-biop1 mk-biop0 op r1)
  (begin
    (mk-biop0 op)
    (define-method (op (o <p>) v)
      (aif it (ref o 'r1)
           (it v)
           (next-method)))))

(define-syntax-rule (mk-biop2 mk-biop0 rop op r1 r2)
  (begin
    (define-syntax-rule (rop x y) (op y x))
    (mk-biop1 mk-biop0 op r1)
    (define-method (op v (o <p>))
      (aif it (ref o 'r2)
           (it v)
           (next-method)))))

(define-syntax-rule (i0 op)
  (begin
    (define-method (op (o1 <py-int>) o2)
      (op (slot-ref o1 'x) o2))    
    (define-method (op o2 (o1 <py-int>))
      (op o2 (slot-ref o1 'x)))))

      
(mk-biop2 b0 r+ + __add__ __radd__)
(mk-biop2 b0 r- - __sub__ __rsub__)
(mk-biop2 b0 r* * __mul__ __rmul__)

(mk-biop1 b0 <  __le__)
(mk-biop1 b0 >  __ge__)
(mk-biop1 b0 <= __lt__)
(mk-biop1 b0 >= __gt__)
(mk-biop2 b0 rexpt expt __pow__ __rpow__)
(b0 py-equal?)


(define-method (py-lshift (o1 <integer>) (o2 <integer>))
  (ash o1 o2))
(define-method (py-rshift (o1 <integer>) (o2 <integer>))
  (ash o1 (- o2)))

(mk-biop2 i0 py-rlshift py-lshift __lshift__ __rlshift__)
(mk-biop2 i0 py-rrshift py-rshift __rshift__ __rrshift__)

(define-method (py-logand (o1 <integer>) (o2 <integer>))
  (logand o1 o2))
(define-method (py-logior (o1 <integer>) (o2 <integer>))
  (logior o1 o2))
(define-method (py-logxor (o1 <integer>) (o2 <integer>))
  (logxor o1 o2))
(define-method (py-lognot (o1 <integer>))
  (lognot o1))

(define-method (py-logand o1 (o2 <py-int>))
  (py-logand o1 (slot-ref o2 'x)))

(define-method (py-logand (o1 <py-int>) o2)
  (py-logand (slot-ref o1 'x) o2))

(define-method (py-logior o1 (o2 <py-int>))
  (py-logior o1 (slot-ref o2 'x)))

(define-method (py-logior (o1 <py-int>) o2)
  (py-logior (slot-ref o1 'x) o2))

(define-method (py-logxor o1 (o2 <py-int>))
  (py-logxor o1 (slot-ref o2 'x)))

(define-method (py-logxor (o1 <py-int>) o2)
  (py-logxor (slot-ref o1 'x) o2))

(define-method (py-lognot (o1 <py-int>))
  (lognot (slot-ref o1 'x)))

(define-method (py-logand (o1 <p>) o2)
  (aif it (ref o1 '__and__)
       (it o2)
       (next-method)))

(define-method (py-logand o1 (o2 <p>))
  (aif it (ref o1 '__rand__)
       (it o2)
       (next-method)))

(define-method (py-logior (o1 <p>) o2)
  (aif it (ref o1 '__or__)
       (it o2)
       (next-method)))

(define-method (py-logior o1 (o2 <p>))
  (aif it (ref o1 '__ror__)
       (it o2)
       (next-method)))

(define-method (py-logxor (o1 <p>) o2)
  (aif it (ref o1 '__xor__)
       (it o2)
       (next-method)))

(define-method (py-logxor o1 (o2 <p>))
  (aif it (ref o1 '__rxor__)
       (it o2)
       (next-method)))

(define-method (py-lognot (o1 <p>))
  (aif it (ref o1 '__not__)
       (it)
       (next-method)))


(define-method (py-/ (o1 <number>) (o2 <integer>))
  (/ o1 (exact->inexact o2)))
(define-method (py-/ (o1 <number>) (o2 <number>))
  (/ o1 o2))

(define-method (py-divmod (o1 <integer>) (o2 <integer>))
  (values
   (floor-quotient o1 o2)
   (modulo o1 o2)))

(define-method (py-divmod (o1 <number>) (o2 <number>))
  (values
   (floor-quotient o1 o2)
   (floor-remainder o1 o2)))

(define-method (py-floordiv (o1 <number>) (o2 <number>))
  (floor-quotient o1 o2))

(mk-biop2 b0 py-rfloordiv py-floordiv __floordiv__ __rfloordiv__)
(mk-biop2 b0 py-rdivmod py-divmod __divmod__  __rdivmod__)
(mk-biop2 b0 py-r/      py-/      __truediv__ __rtruediv__)

(mk-biop2 i0 py-rlogand py-logand __and__ __rand__)
(mk-biop2 i0 py-rlogior py-logior __or__  __ror__)
(mk-biop2 i0 py-rlogxor py-logxor __xor__ __rxor__)

(define-method (py-mod (o1 <integer>) (o2 <integer>))
  (modulo o1 o2))
(define-method (py-mod (o1 <real>)    (o2 <real>))
  (floor-remainder o1 o2))

(mk-biop2 i0 py-rmod py-mod __mod__ __rmod__)


(define-method (py-floor (o1 <integer>)) o1)
(define-method (py-floor (o1 <number> )) (inexact->exact (floor o1)))
(define-method (py-trunc (o1 <integer>)) (exact->inexact o1))
(define-method (py-trunc (o1 <number> ))
  (floor o1))

(define-syntax-rule (u0 f)
  (begin
    (define-method (f (o <py-int>  ))   (f (slot-ref o 'x)))
    (define-method (f (o <py-float>))   (f (slot-ref o 'x)))
    (define-method (f (o <py-complex>)) (f (slot-ref o 'x)))))

(define-syntax-rule (i0 f)
  (begin
    (define-method (f (o <py-int>  )) (f (slot-ref o 'x)))))

(define-syntax-rule (mk-unop u0 f r)
  (begin
    (u0 f)
    (define-method (f (o <p>))
      ((ref o 'r)))))

(u0 py-hash )
(mk-unop u0 -         __neg__   )
(mk-unop u0 py-trunc  __trunc__ )
(mk-unop i0 py-lognot __invert__)

(define-method (py-bit-length (i <integer>))
  (integer-length (abs i)))

(define-method (py-conjugate (i <complex>))
  (make-rectangular (real-part i) (- (imag-part i))))
(define-method (py-conjugate (i <number>)) i)

(define-method (py-imag (i <complex>)) (imag-part i))
(define-method (py-imag (i <number>)) i)

(define-method (py-real (i <complex>)) (real-part i))
(define-method (py-real (i <number>)) i)

(define-method (py-denominator (o <integer>)) 0)
(define-method (py-denominator (o <real>))
  (denominator (inexact->exact o)))

(define-method (py-numerator (o <integer>)) o)
(define-method (py-numerator (o <real>   ))
  (numerator (inexact->exact o)))

(define-method (py-as-integer-ratio (o <integer>))
  (list o 0))
(define-method (py-as-integer-ratio (o <real>))
  (let ((r (inexact->exact o)))
    (list (numerator r) (denominator r))))

(define-method (py-fromhex     (o <real>))
  (error "1.2.fromhex('0x1.ap4') is not implemented"))

(define (py-hex x)
  (+ "0x" (number->string (py-index x) 16)))
                               
(define-method (py-is-integer  (o <real>))
  (= 1 (denominator (inexact->exact o))))
(define-method (py-is-integer  (o <integer>)) #t)

(define-method (hex (o <integer>))
  (+ "0x" (number->string o 16)))

(define-method (py-abs (o <complex>))
  (magnitude o))
(define-method (py-abs (o <number>))
  (abs o))
(define-method (py-index  (o <integer>)) o)
(mk-unop u0 py-abs       __abs__)
(mk-unop u0 py-conjugate conjugate)
(mk-unop u0 py-imag imag)
(mk-unop u0 py-real real)
(mk-unop u0 py-denominator denominator)
(mk-unop u0 py-numerator   numerator)
(mk-unop u0 py-as-integer-ratio as_integer_ratio)
(mk-unop u0 py-fromhex fromhex)
(mk-unop i0 hex __hex__)
(mk-unop u0 py-is-integer is_integer)
(mk-unop u0 py-index __index__)

(define-method (write (o <py-float>) . l)
  (apply write (slot-ref o 'x) l))
(define-method (write (o <py-int>) . l)
  (apply write (slot-ref o 'x) l))

(define-method (py-from-bytes (o <p>) . l)
  (aif it (ref o 'from_bytes)
       (apply it l)
       (next-method)))

(define-method (py-from-bytes (o <integer>) . l)
  (apply py-from-bytes int l))

(define-method (py-to-bytes (o <p>) . l)
  (aif it (ref o 'to_bytes)
       (apply it l)
       (aif it (ref o '__int__)
            (apply py-to-bytes (int) l)
            (next-method))))

(define-method (py-to-bytes (o <integer>) . l)
  (apply
   (lam (length (= byteorder "big") (= signed #f))
        (let ((big? (cond
                     ((equal? byteorder "little")
                      #f)
                     ((equal? byteorder "big")
                      #t)
                     (else
                      (raise (ValueError "to_bytes with wrong byteorder"))))))
          
          (if (and (< o 0) (not signed))
              (raise (OverflowError
                      "to_byted, integer negative but not signed")))
          
          (if signed
              (let ((mask (ash 1 (- (* 8 length) 1))))
                (set! o (+ mask o))))
          
          (let lp ((o o) (l '()))
            (if (= o 0)
                (let ((n (len l)))
                  (if (> n length)
                      (raise (OverflowError
                              "to bytes number larger than size")))
                  (let lp ((i (len l)) (l l))
                    (if (< i length)
                        (lp (+ i 1) (cons 0 l))
                        (begin
                          (if signed
                              (let ((x (car l)))
                                (if (> (logand x #x80) 0)
                                    (raise
                                     "OverflowError to large number compared to size in to_bytes"))
                                (set-car! l (logior #x80 x))))
                          
                          (bytes
                            (if big?
                                l
                                (reverse l)))))))
                (lp (ash o -8) (cons (logand o #xff) l))))))
   l))

                        
        
  

(define-python-class int (<py> <py-int>)
  (define from_bytes
    (class-method
     (lam (self bytes byteorder (= signed #f))
	  (for ((x : bytes)) ((l '()))
	       (cons
		(let ((i (if (and (number? x) (integer? x))
			     x
			     (list-ref (bv-scm x) 0))))
		  (if (not (and (number? i) (integer? i)
				(>= i 0) (<= i 356)))
		      (raise (ValueError "wrong bytevector in from_bytes"))
		      i))
		l)
	       #:final
	       (begin
		 (if (equal? byteorder "little")
		     (set! l (reverse l)))
		 (let lp ((s 0) (i 0) (l l))
		   (if (pair? l)
		       (let ((x (car l)))
			 (if (null? (cdr l))
			     (if (and signed (not (= 0 (logand x #x80))))
				 (set! x (logand x #x7f))
				 (set! signed #f)))
			 (lp (logior s (ash x i)) (+ i 8) (cdr l)))
		       (if signed
			   (let ((mask (ash 1 (- i 1))))
			     (- s mask))
			   s))))))))
  (define __new__
    (letrec ((__new__
              (case-lambda
                ((self)
                 0)
                
                ((self n)
                 (let lp ((n n))
                   (cond
                    ((and (number? n) (integer? n))
                     (inexact->exact n))
		    ((boolean? n)
		     (if n 1 0))
                    ((number? n)
                     (lp (py-floor n)))
                    
                    ((string? n)
                     (lp (aif it (string->number n)
                              it
                              (raise
                               (ValueError
                                "invalid literal for int() with base 10")))))
                    (else
		     (catch #t
		       (lambda ()
			 (aif it (ref n '__int__)
			      (it)
			      (raise (ValueError
                                      (py-mod "could not make int from %r"
                                              (list n))))))
		       (lambda z
                         (raise
                          (ValueError (py-mod "could not make int from %r"
                                              (list n))))))))))
      
                ((self n k)
                 (__new__ self (string->number n k))))))
      __new__)))

(name-object int)

(define (proj? x)
  (if (number? x)
      x
      (and
       (or (is-a? x <py-complex>)
           (is-a? x <py-int>)
           (is-a? x <py-float>))
       (slot-ref x 'x))))

(define (projc? x)
  (if (number? x)
      (if (not (complex? x))
          x
          #f)
      (and
       (or (is-a? x <py-complex>)
           (is-a? x <py-int>)
           (is-a? x <py-float>))
       (let ((ret (slot-ref x 'x)))
         (if (not (complex? ret))
             ret
             #f)))))

(define-python-class float (<py> <py-float>)
  (define __init__
    (case-lambda
      ((self n)
       (let lp ((n n))
         (cond
          ((projc? n) =>
           (lambda (n)
             (slot-set! self 'x n)))
          ((string? n)
           (lp (string->number n)))
          (else
           (aif it (slot-ref n '__float__)
                (slot-set! self 'x it)
                (raise ValueError "could not make float from " n)))))))))

(name-object float)

(define-python-class py-complex (<py> <py-complex>)
  (define __init__
    (case-lambda
      ((self n)
       (cond
        ((proj? n) =>
         (lambda (n)
           (slot-set! self 'x n)))
        (else
         (raise ValueError "could not make complex from " n))))
      ((self n m)
       (cond
        ((projc? n) =>
         (lambda (n)        
           (cond
            ((projc? m)
             (lambda (m)
               (slot-set! self 'x (make-rectangular n m))))
            (else
             (raise ValueError "could not make complex from " n m)))))
        (else
         (raise ValueError "could not make complex from " n m)))))))

(name-object py-complex)

(define-method (py-class (o <integer>    )) int)
(define-method (py-class (o <real>       )) float)
(u0 py-class)
           
(define py-int   int)
(define py-float float)

(define-method (mk-int   (o <number>)) (slot-ref (py-int o)   'x))
(define-method (mk-float (o <number>)) (slot-ref (py-float o) 'x))

(mk-unop u0 mk-int   __int__)
(mk-unop u0 mk-float __float__)

(define (pyint-listing)
  (let ((l
         (to-pylist
          (map symbol->string
               '(__abs__ __add__ __and__ __class__ __cmp__ __coerce__
                         __delattr__ __div__ __divmod__ __doc__ __float__
                         __floordiv__ __format__ __getattribute__
                         __getnewargs__ __hash__ __hex__ __index__ __init__
                         __int__ __invert__ __long__ __lshift__ __mod__
                         __mul__ __neg__ __new__ __nonzero__ __oct__ __or__
                         __pos__ __pow__ __radd__ __rand__ __rdiv__
                         __rdivmod__ __reduce__ __reduce_ex__ __repr__
                         __rfloordiv__ __rlshift__ __rmod__ __rmul__ __ror__
                         __rpow__ __rrshift__ __rshift__ __rsub__ __rtruediv__
                         __rxor__ __setattr__ __sizeof__ __str__ __sub__
                         __subclasshook__ __truediv__ __trunc__ __xor__
                         bit_length conjugate denominator imag numerator from_bytes to_bytes
                         real)))))
    (pylist-sort! l)
    l))

(define (pyfloat-listing)
  (let ((l
         (to-pylist
          (map symbol->string
               '(__abs__ __add__ __class__ __coerce__ __delattr__ __div__
                         __divmod__ __doc__ __eq__ __float__ __floordiv__
                         __format__ __ge__ __getattribute__ __getformat__
                         __getnewargs__ __gt__ __hash__ __init__ __int__
                         __le__ __long__ __lt__ __mod__ __mul__ __ne__
                         __neg__ __new__ __nonzero__ __pos__ __pow__
                         __radd__ __rdiv__ __rdivmod__ __reduce__
                         __reduce_ex__ __repr__ __rfloordiv__ __rmod__
                         __rmul__ __rpow__ __rsub__ __rtruediv__
                         __setattr__ __setformat__ __sizeof__ __str__
                         __sub__ __subclasshook__ __truediv__ __trunc__
                         as_integer_ratio conjugate fromhex hex imag
                         is_integer real)))))
    (pylist-sort! l)
    l))

(define (pycomplex-listing)
  (let ((l
         (to-pylist
          (map symbol->string
               '(__abs__ __add__ __class__ __coerce__ __delattr__ __div__
                         __divmod__ __doc__ __eq__ __float__ __floordiv__
                         __format__ __ge__ __getattribute__ __getnewargs__
                         __gt__ __hash__ __init__ __int__ __le__ __long__
                         __lt__ __mod__ __mul__ __ne__ __neg__ __new__
                         __nonzero__ __pos__ __pow__ __radd__ __rdiv__
                         __rdivmod__ __reduce__ __reduce_ex__ __repr__
                         __rfloordiv__ __rmod__ __rmul__ __rpow__ __rsub__
                         __rtruediv__ __setattr__ __sizeof__ __str__
                         __sub__ __subclasshook__ __truediv__
                         conjugate imag real)))))
    (pylist-sort! l)
    l))

(define* (py-round x #:optional (digits 0))
  (let* ((f (expt 10.0 digits)))
    (inexact->exact
     (if (equal? digits 0)
         (round x)
         (/ (round (* x f)) f)))))
         
(define-method (py-bin (o <integer>))
  (number->string o 2))
(define-method (py-bin (o <py-int>))
  (number->string (slot-ref o 'x) 2))
(define (py-bin o)
  (+ "0b" (number->string (py-index o) 2)))