diff --git a/lib/python/format.x b/lib/python/format.x index 7e589a6..299e75d 100644 --- a/lib/python/format.x +++ b/lib/python/format.x @@ -421,7 +421,7 @@ ((if (= conv 111) #t (if (= conv 120) #t (= conv 88))) (do (def b (if (= conv 111) 8 16)) - (def m (%py-fmt-base v b (= conv 88))) + (def m (%py-fmt-base (%py-index-of v) b (= conv 88))) (def pfx (if alt (if (= conv 111) "0o" (if (= conv 88) "0X" "0x")) diff --git a/lib/python/runtime-call.x b/lib/python/runtime-call.x index c1647a4..70bfbaf 100644 --- a/lib/python/runtime-call.x +++ b/lib/python/runtime-call.x @@ -676,7 +676,8 @@ ; the bigint path are stated once. The SIGN GOES BEFORE THE PREFIX: ; bin(-15) is -0b1111, not 0b-1111. (def %py-based-str - (fn (_ v base pfx) + (fn (_ v0 base pfx) + (def v (%py-index-of v0)) (if (not (eq? (python-num-py-type (python-boolnorm v)) (lit int))) (Err raise (lit type) "an integer is required" ()) (let ((m (%py-fmt-base (python-boolnorm v) base #f))) @@ -693,9 +694,12 @@ (def %py-divmod (fn (_ a b) - (if (if (python-num? a) (python-num? b) #f) - (python-tuple-new (list (python-floordiv a b) (python-mod a b))) - (%py-op-refuse "divmod()" a b)))) + (match + ((if (python-num? a) (python-num? b) #f) + (python-tuple-new (list (python-floordiv a b) (python-mod a b)))) + ((if (python-obj-is a) #t (python-obj-is b)) + (%py-binop a b "__divmod__" "__rdivmod__" "divmod()")) + (#t (%py-op-refuse "divmod()" a b))))) ; A CLOSURE HAS NO PREDICATE, so its type handle is taken from one built ; here and compared -- the same trick the arithmetic seams use for float. diff --git a/lib/python/runtime-num.x b/lib/python/runtime-num.x index 74f9e12..6212c6f 100644 --- a/lib/python/runtime-num.x +++ b/lib/python/runtime-num.x @@ -85,15 +85,49 @@ (if (null? m) %py-NotImplemented (m y))) %py-NotImplemented))) +; The plain operation each dunder stands for, which a plain number on the +; left of an int subclass's instance answers with: 1.5 + C(2) is float's add. +; The plain operation each dunder stands for, which a plain number on the +; left of an int subclass's instance answers with: 1.5 + C(2) is float's add. +; Each is reached by name when called, since most are defined below. +(def %py-binop-plain + (list (pair "__add__" (fn (_ x y) (python-add x y))) + (pair "__sub__" (fn (_ x y) (python-sub x y))) + (pair "__mul__" (fn (_ x y) (python-mul x y))) + (pair "__truediv__" (fn (_ x y) (python-div x y))) + (pair "__floordiv__" (fn (_ x y) (python-floordiv x y))) + (pair "__mod__" (fn (_ x y) (python-mod x y))) + (pair "__pow__" (fn (_ x y) (%py-pow x y))) + (pair "__divmod__" (fn (_ x y) (%py-divmod x y))) + (pair "__lshift__" (fn (_ x y) (%py-lshift x y))) + (pair "__rshift__" (fn (_ x y) (%py-rshift x y))) + (pair "__and__" (fn (_ x y) (%py-bitand x y))) + (pair "__or__" (fn (_ x y) (%py-bitor x y))) + (pair "__xor__" (fn (_ x y) (%py-bitxor x y))))) +; Is A a plain number whose own method goes first against the object B? +; Python asks the right operand's reflected method first only when its class +; derives from the left's type; a number beside an object carrying a number +; otherwise answers for itself. +(def %py-num-first? + (fn (_ a b) + (match + ((python-obj-is a) #f) + ((not (python-obj-is b)) #f) + ((not (python-num? a)) #f) + ((not (python-num? (python-obj-native b))) #f) + (#t (not (python-subclass? (python-obj-class b) (python-type-of a))))))) (def %py-binop (fn (_ a b name rname opname) - (let ((r1 (%py-side a b name))) + (let ((plain (if (%py-num-first? a b) (python-alist-find name %py-binop-plain) ()))) + (let ((r1 (if (not (null? plain)) + ((rest plain) a (python-obj-native b)) + (%py-side a b name)))) (if (not (eq? r1 %py-NotImplemented)) r1 (let ((r2 (%py-side b a rname))) (if (not (eq? r2 %py-NotImplemented)) r2 - (%py-op-refuse opname a b))))))) + (%py-op-refuse opname a b)))))))) ; augmented + on a list is list.extend, which takes any iterable -- while ; plain + demands a list. Python draws that line and the corpus tests it. @@ -272,7 +306,7 @@ ; CPython's words. (def %py-repeat-count (fn (_ k) - (let ((n (python-boolnorm k))) + (let ((n (python-boolnorm (%py-index-of k)))) (if (eq? (python-num-py-type n) (lit int)) n (Err raise (lit type) @@ -397,12 +431,36 @@ (%py-binop a b "__matmul__" "__rmatmul__" "@") (%py-op-refuse "@" a b)))) +; * with an object on one side. Its __mul__ or __rmul__ answers first; when +; neither does and the other side is a sequence, the object is a repeat count +; -- 'ab' * n for an int subclass's n -- read through __index__. +(def %py-seq-operand? + (fn (_ v) + (match + ((python-obj-is v) #f) + ((python-str-is v) #t) + ((python-list? v) #t) + ((python-tuple-is v) #t) + ((python-bytes-is v) #t) + (#t (python-dq-is v))))) +(def %py-mul-obj + (fn (_ a b) + (if (if (%py-seq-operand? a) #t (%py-seq-operand? b)) + (let ((r1 (%py-side a b "__mul__"))) + (if (not (eq? r1 %py-NotImplemented)) + r1 + (let ((r2 (%py-side b a "__rmul__"))) + (match + ((not (eq? r2 %py-NotImplemented)) r2) + ((%py-seq-operand? a) (python-mul a (%py-repeat-count b))) + (#t (python-mul (%py-repeat-count a) b)))))) + (%py-binop a b "__mul__" "__rmul__" "*")))) + (def python-mul (fn (_ a b) (match ((%py-plain-nums? a b) (* a b)) - ((if (python-obj-is a) #t (python-obj-is b)) - (%py-binop a b "__mul__" "__rmul__" "*")) + ((if (python-obj-is a) #t (python-obj-is b)) (%py-mul-obj a b)) ((python-dq-is a) (python-dq-repeat a b)) ((python-dq-is b) (python-dq-repeat b a)) ((python-list? a) @@ -1029,7 +1087,22 @@ (Err raise (lit overflow) "cannot convert float infinity to integer" ())) (#t (Err raise (lit value) "cannot convert float NaN to integer" ()))))) +; round() on an object: its own __round__ answers, and otherwise an instance +; of a class over int or float rounds the number it carries. (def %py-round + (fn (_ . a) + (match + ((if (null? a) #f (python-obj-is (first a))) + (let ((m (python-dunder (first a) "__round__"))) + (match + ((not (null? m)) (apply m (rest a))) + ((python-num? (python-obj-native (first a))) + (apply %py-round-num (pair (python-obj-native (first a)) (rest a)))) + (#t (Err raise (lit type) + (Str8 append "type " (Str8 append (python-class-name (python-obj-class (first a))) + " doesn't define __round__ method")) ()))))) + (#t (apply %py-round-num a))))) +(def %py-round-num (fn (_ . a) (if (null? a) (Err raise (lit type) "round() missing required argument 'number' (pos 1)" ()) diff --git a/lib/python/runtime-py-type.x b/lib/python/runtime-py-type.x index 4e3f0f1..0d878da 100644 --- a/lib/python/runtime-py-type.x +++ b/lib/python/runtime-py-type.x @@ -724,15 +724,89 @@ (go 0 0))) "bit_count" (list "self") 1 #f)) +; int's arithmetic, as the methods a subclass of int inherits. A plain int +; never reaches these -- the operators take machine numbers directly -- but an +; instance of `class C(int)` is an object carrying its int, and the operators +; ask an object's class. Each row works on the value the instance carries, +; and answers NotImplemented for an operand that is no number, so the other +; side's reflected method is asked and the refusal names the subclass. The +; answer is a plain int, as CPython's is. +(def %py-int-intlike? + (fn (_ v) (if (python-num? v) (eq? (python-num-py-type (python-boolnorm v)) (lit int)) #f))) +(def %py-int-op + (fn (_ op ok? flip) + (fn (_ self o) + (let ((b (python-native-of o))) + (if (ok? b) + (if flip (op b (python-native-of self)) (op (python-native-of self) b)) + %py-NotImplemented))))) +(def %py-int-num-op (fn (_ op flip) (%py-int-op op python-num? flip))) +(def %py-int-bit-op (fn (_ op flip) (%py-int-op op %py-int-intlike? flip))) +(def %py-int-un-op (fn (_ op) (fn (_ self) (op (python-native-of self))))) +(def %py-int-arith-rows + (list + (pair "__add__" (%py-int-num-op python-add #f)) + (pair "__radd__" (%py-int-num-op python-add #t)) + (pair "__sub__" (%py-int-num-op python-sub #f)) + (pair "__rsub__" (%py-int-num-op python-sub #t)) + (pair "__mul__" (%py-int-num-op python-mul #f)) + (pair "__rmul__" (%py-int-num-op python-mul #t)) + (pair "__truediv__" (%py-int-num-op python-div #f)) + (pair "__rtruediv__" (%py-int-num-op python-div #t)) + (pair "__floordiv__" (%py-int-num-op python-floordiv #f)) + (pair "__rfloordiv__" (%py-int-num-op python-floordiv #t)) + (pair "__mod__" (%py-int-num-op python-mod #f)) + (pair "__rmod__" (%py-int-num-op python-mod #t)) + (pair "__divmod__" (%py-int-num-op %py-divmod #f)) + (pair "__rdivmod__" (%py-int-num-op %py-divmod #t)) + (pair "__pow__" (%py-int-num-op %py-pow #f)) + (pair "__rpow__" (%py-int-num-op %py-pow #t)) + (pair "__lshift__" (%py-int-bit-op %py-lshift #f)) + (pair "__rlshift__" (%py-int-bit-op %py-lshift #t)) + (pair "__rshift__" (%py-int-bit-op %py-rshift #f)) + (pair "__rrshift__" (%py-int-bit-op %py-rshift #t)) + (pair "__and__" (%py-int-bit-op %py-bitand #f)) + (pair "__rand__" (%py-int-bit-op %py-bitand #t)) + (pair "__or__" (%py-int-bit-op %py-bitor #f)) + (pair "__ror__" (%py-int-bit-op %py-bitor #t)) + (pair "__xor__" (%py-int-bit-op %py-bitxor #f)) + (pair "__rxor__" (%py-int-bit-op %py-bitxor #t)) + (pair "__neg__" (%py-int-un-op %py-neg)) + (pair "__pos__" (%py-int-un-op %py-pos)) + (pair "__invert__" (%py-int-un-op %py-invert)) + (pair "__abs__" (%py-int-un-op %py-abs-num)) + (pair "__eq__" (%py-int-num-op python-eq #f)) + (pair "__lt__" (%py-int-num-op python-lt #f)) + (pair "__gt__" (%py-int-num-op python-gt #f)) + (pair "__le__" (%py-int-num-op python-le #f)) + (pair "__ge__" (%py-int-num-op python-ge #f)) + ; what int(), float(), an index, bool() and hash() read off an instance + (pair "__int__" (%py-int-un-op python-boolnorm)) + (pair "__index__" (%py-int-un-op python-boolnorm)) + (pair "__float__" (%py-int-un-op %py-float-ctor)) + (pair "__bool__" (%py-int-un-op (fn (_ n) (not (= (python-boolnorm n) 0))))) + (pair "__hash__" (%py-int-un-op %py-hash)) + ; an int as the rational and the complex number it also is + (pair "real" (python-desc-new (lit property) (%py-int-un-op python-boolnorm))) + (pair "imag" (python-desc-new (lit property) (fn (_ self) 0))) + (pair "numerator" (python-desc-new (lit property) (%py-int-un-op python-boolnorm))) + (pair "denominator" (python-desc-new (lit property) (fn (_ self) 1))) + (pair "conjugate" (python-sig! (%py-int-un-op python-boolnorm) "conjugate" (list "self") 1 #f)) + (pair "as_integer_ratio" + (python-sig! (fn (_ self) (python-tuple-new (list (python-boolnorm (python-native-of self)) 1))) + "as_integer_ratio" (list "self") 1 #f)) + (pair "is_integer" (python-sig! (fn (_ self) #t) "is_integer" (list "self") 1 #f)))) + (def %py-cls-int (python-class-new "int" python-cls-object - (list (pair "%ctor" %py-int-ctor) - (pair "to_bytes" %py-int-to-bytes) - (pair "bit_length" %py-int-bit-length) - (pair "bit_count" %py-int-bit-count) - ; a classmethod, as in Python: int.from_bytes and (5).from_bytes - ; both bind the class - (pair "from_bytes" (python-desc-new (lit classmethod) %py-int-from-bytes))) + (pair (pair "%ctor" %py-int-ctor) + (pair (pair "to_bytes" %py-int-to-bytes) + (pair (pair "bit_length" %py-int-bit-length) + (pair (pair "bit_count" %py-int-bit-count) + ; a classmethod, as in Python: int.from_bytes and (5).from_bytes + ; both bind the class + (pair (pair "from_bytes" (python-desc-new (lit classmethod) %py-int-from-bytes)) + %py-int-arith-rows))))) "int")) ; An int's attribute is a method of the int class bound to the value -- a @@ -745,9 +819,10 @@ (Err raise (lit attribute) (Str8 append "'int' object has no attribute '" (Str8 append name "'")) ())) ((%py-desc-is m) - (if (eq? (%py-desc-py-type m) (lit classmethod)) - (%py-bound-new (%py-desc-fn m) %py-cls-int) - (%py-desc-fn m))) + (match + ((eq? (%py-desc-py-type m) (lit classmethod)) (%py-bound-new (%py-desc-fn m) %py-cls-int)) + ((eq? (%py-desc-py-type m) (lit property)) ((%py-desc-fn m) v)) + (#t (%py-desc-fn m)))) (#t (%py-bound-new m v)))))) (def %py-cls-bool (python-class-new "bool" %py-cls-int diff --git a/lib/python/runtime-seq.x b/lib/python/runtime-seq.x index c1b42ab..ed3bd35 100644 --- a/lib/python/runtime-seq.x +++ b/lib/python/runtime-seq.x @@ -346,9 +346,17 @@ ; A SEQUENCE'S INDEX IS AN INTEGER, and a bool is one: True indexes 1, as in ; Python. Anything else is refused in the sequence's own words -- CPython says ; "string indices" for a str and "byte indices" for bytes, and names the rest. +; What an object's __index__ answers, or the value itself: an int subclass's +; instance, or any class with __index__, stands wherever an int index does. +(def %py-index-of + (fn (_ v) + (if (python-obj-is v) + (let ((m (python-dunder v "__index__"))) + (if (null? m) v (python-boolnorm (m)))) + v))) (def %py-seq-index (fn (_ i what) - (let ((k (python-boolnorm i))) + (let ((k (python-boolnorm (%py-index-of i)))) (if (eq? (python-num-py-type k) (lit int)) k (Err raise (lit type) diff --git a/lib/python/runtime-str.x b/lib/python/runtime-str.x index 7d666a4..038f29d 100644 --- a/lib/python/runtime-str.x +++ b/lib/python/runtime-str.x @@ -300,14 +300,19 @@ ; what makes `cls` the child in `Sub.method()` -- and a ; property stays the descriptor, since `C.v` in Python is the ; property object, not a value it has no instance to compute. - (if (%py-desc-is m) - (let ((f (%py-desc-fn m)) (k (%py-desc-py-type m))) - (if (eq? k (lit static)) - f - (if (eq? k (lit classmethod)) - (%py-bound-new f cls) - m))) - m))))) + ; + ; A descriptor the PROGRAM wrote is asked, as Python asks it: + ; __get__(None, cls), so one that answers itself for a class + ; still can, and one that computes from the class does. + (match + ((%py-desc-is m) + (let ((f (%py-desc-fn m)) (k (%py-desc-py-type m))) + (match + ((eq? k (lit static)) f) + ((eq? k (lit classmethod)) (%py-bound-new f cls)) + (#t m)))) + ((%py-desc-get? m) ((python-dunder m "__get__") () cls)) + (#t m)))))) (python-sweep!) ; What a builtin type offers beyond the methods on its class object: the @@ -592,7 +597,7 @@ (def %py-chr (fn (_ n0) - (def n (python-boolnorm n0)) + (def n (python-boolnorm (%py-index-of n0))) (match ((not (eq? (python-num-py-type n) (lit int))) (Err raise (lit type) "an integer is required" ())) @@ -720,9 +725,13 @@ (def %py-format-spec (fn (_ v spec) - (if (Str8 =? spec "") - (python-str v) - (do + (match + ((Str8 =? spec "") (python-str v)) + ; an instance of a class over int or float formats the number it + ; carries, as int.__format__ and float.__format__ do + ((if (python-obj-is v) (python-num? (python-obj-native v)) #f) + (%py-format-spec (python-obj-native v) spec)) + (#t (do (def ps (%py-spec-parse spec)) (def fill (List ref 0 ps)) (def align (List ref 1 ps)) @@ -905,7 +914,7 @@ (Str8 append "Unknown format code '" (Str8 append type (Str8 append "' for object of type '" - (Str8 append (if (eq? py-type (lit int)) "int" "float") "'")))) ()))))))))) + (Str8 append (if (eq? py-type (lit int)) "int" "float") "'")))) ())))))))))) (python-sweep!) ; Digits grouped by k from the right with sep. diff --git a/tests/specs/C3-int-subclass.spec.md b/tests/specs/C3-int-subclass.spec.md new file mode 100644 index 0000000..e198512 --- /dev/null +++ b/tests/specs/C3-int-subclass.spec.md @@ -0,0 +1,85 @@ +# int subclasses and class-level __get__ + +An instance of a class over int carries its int, and int's own methods give +it int's arithmetic, comparisons and conversions. A descriptor the program +wrote is asked for its value when it is read from a class, as it is from an +instance. Each expected output is a python3.14 run of the same program. + +### an int subclass is made, converted and tested like an int + +```python +(python-run "class C(int): pass\nc = C(3)\nprint(type(c).__name__, c, repr(c), isinstance(c, int), isinstance(c, C))\nprint(C(), C('12'), C('ff', 16), C(4.9), C(True))\nd = int.__new__(C, 5)\nprint(type(d).__name__, d)\nclass Tagged(int):\n def __new__(cls, value, tag):\n self = int.__new__(cls, value)\n self.tag = tag\n return self\nt = Tagged(7, 'seven')\nprint(t, t.tag, type(t).__name__)\nprint(int(c), type(int(c)).__name__, float(c), type(float(c)).__name__)\nprint(bool(C(0)), bool(C(2)), hash(C(9)) == hash(9))\n") +``` +--- +```output +C 3 3 True True +0 12 255 4 1 +C 5 +7 seven Tagged +3 int 3.0 float +False True True +``` + +### arithmetic on an int subclass answers a plain int, and refuses by the subclass's name + +```python +(python-run "class C(int): pass\nc = C(6)\nprint(c + 1, 1 + c, c - C(1), 10 - c, c * 2, 2 * c, c / 4, 3 / c)\nprint(c // 4, 20 // c, c % 4, 20 % c, c ** 2, 2 ** c, divmod(c, 4), divmod(20, c))\nprint(c | 1, 1 | c, c & 3, c ^ 2, c << 1, 1 << c, c >> 1, -c, +c, ~c, abs(C(-2)))\nprint(c + 1.5, 1.5 * c, c + True, type(c + 0).__name__, type(-c).__name__, type(c * 1.0).__name__)\nfor f in (lambda: c + 'a', lambda: 'a' * C(2), lambda: c & 1.5, lambda: c << 1.0):\n try:\n print(f())\n except TypeError as e:\n print('TypeError', e)\nn = C(5)\nn += 1\nprint(n, type(n).__name__)\n") +``` +--- +```output +7 7 5 4 12 12 1.5 0.5 +1 3 2 2 36 64 (1, 2) (3, 2) +7 7 2 4 12 64 3 -6 6 -7 2 +7.5 9.0 7 int int float +TypeError unsupported operand type(s) for +: 'C' and 'str' +aa +TypeError unsupported operand type(s) for &: 'C' and 'float' +TypeError unsupported operand type(s) for <<: 'C' and 'float' +6 int +``` + +### an int subclass compares, hashes, formats and indexes as its int + +```python +(python-run "class C(int): pass\nc = C(6)\nprint(c == 6, 6 == c, c != 6, c < 7, c > C(2), c <= 6, c >= 7, c == 6.0, c == 'a')\nprint({c: 'x'}[6], {6: 'y'}[c], sorted([C(3), 1, C(2), 2.5]), max(C(1), C(4)), sum([C(1), C(2)]))\nprint('%d %s %r %x %05d' % (c, c, c, c, c), '{} {:03d} {:x}'.format(c, c, c), f'{c:>4}|', str(c), format(c, 'b'))\nprint(list(range(C(3))), [10, 20, 30][C(1)], 'abc'[C(2)], hex(c), bin(c), oct(c), round(c), c.bit_length())\nprint(c.real, c.numerator, c.denominator, c.to_bytes(2, 'big'), (5).__add__(1), int.__add__(4, 2))\nprint((7).real, (7).imag, (7).denominator, True.numerator, (7).conjugate(), (6).as_integer_ratio(), (6).is_integer())\n") +``` +--- +```output +True True False True True True False True False +x y [1, 2, 2.5, 3] 4 3 +6 6 6 6 00006 6 006 6 6| 6 110 +[0, 1, 2] 20 c 0x6 0b110 0o6 6 3 +6 6 1 b'\x00\x06' 6 6 +7 0 1 1 7 (6, 1) True +``` + +### a subclass's own methods come first, and its hash follows its __eq__ + +```python +(python-run "class C(int):\n def __add__(self, other):\n return 'C.add'\n def __str__(self):\n return 'S'\n def __repr__(self):\n return 'R'\n def __eq__(self, other):\n return 'C.eq'\n __hash__ = int.__hash__\nc = C(2)\nprint(c + 1, 1 + c, c * 3, str(c), repr(c), [c], '%s' % c, f'{c}', c == 1, hash(c) == hash(2))\nclass Flip(int):\n def __radd__(self, other):\n return ('radd', other)\nprint(1 + Flip(2), Flip(2) + 1, 1.5 + Flip(2))\nclass OnlyEq(int):\n def __eq__(self, other):\n return True\ntry:\n hash(OnlyEq(1))\nexcept TypeError as e:\n print('TypeError', e)\nclass Up(int):\n def __add__(self, other):\n return Up(int(self) + int(other))\nprint(type(Up(1) + 2).__name__, Up(1) + 2, type(Up(1) - 2).__name__)\n") +``` +--- +```output +C.add 3 6 S R [R] S S C.eq True +('radd', 1) 3 3.5 +TypeError unhashable type: 'OnlyEq' +Up 3 int +``` + +### a descriptor read from a class is asked with __get__(None, cls) + +```python +(python-run "class Desc:\n def __get__(self, obj, owner=None):\n return ('get', obj is None, owner.__name__)\nclass Plain:\n pass\nclass A:\n d = Desc()\n p = Plain()\n @property\n def prop(self):\n return 'prop'\nprint(A.d)\nprint(A().d)\nclass B(A):\n pass\nprint(B.d, getattr(B, 'd'))\nprint(type(A.__dict__['d']).__name__, type(vars(A)['d']).__name__, type(A.p).__name__)\nprint(type(A.prop).__name__, A().prop)\nclass Meta(type):\n m = Desc()\nclass E(metaclass=Meta):\n pass\nprint(E.m)\nclass SelfIfClass:\n def __get__(self, obj, owner=None):\n return self if obj is None else 'on ' + type(obj).__name__\nclass F:\n s = SelfIfClass()\nprint(type(F.s).__name__, F().s)\nclass Data:\n def __get__(self, obj, owner=None):\n return 'data' if obj is not None else 'class'\n def __set__(self, obj, value):\n print('set', value)\nclass G:\n x = Data()\ng = G()\ng.x = 4\nprint(g.x, G.x)\n") +``` +--- +```output +('get', True, 'A') +('get', False, 'A') +('get', True, 'B') ('get', True, 'B') +Desc Desc Plain +property prop +('get', False, 'Meta') +SelfIfClass on F +set 4 +data class +```