Permalink
Jul 28, 2018
Dec 18, 2019
Dec 17, 2020
Dec 17, 2020
Apr 23, 2018
Dec 17, 2020
Apr 23, 2018
Dec 17, 2020
Dec 17, 2020
Jul 28, 2018
Feb 22, 2019
Mar 10, 2018
Mar 10, 2018
Aug 2, 2018
Mar 10, 2018
Mar 10, 2018
Feb 22, 2019
Mar 10, 2018
Jul 28, 2018
Feb 20, 2020
Jul 28, 2018
May 19, 2017
Jul 28, 2018
Feb 20, 2020
Jul 28, 2018
Jun 30, 2020
Feb 15, 2020
Feb 11, 2018
Mar 10, 2018
Feb 22, 2019
Mar 10, 2018
Mar 23, 2018
Mar 10, 2018
Mar 10, 2018
Mar 10, 2018
Mar 10, 2018
Mar 10, 2018
Mar 10, 2018
Mar 10, 2018
Mar 10, 2018
Mar 10, 2018
Nov 28, 2018
Mar 10, 2018
Mar 10, 2018
Nov 28, 2018
Jun 14, 2018
Jan 11, 2021
Mar 10, 2018
Oct 27, 2019
Oct 27, 2019
Oct 22, 2019
Jan 7, 2021
Oct 22, 2019
Oct 22, 2019
Feb 11, 2018
Newer
100644
923 lines (833 sloc)
27 KB
11
function int_value(obj){
12
// Instances of int subclasses that call int.__new__(cls, value)
39
int.as_integer_ratio = function(){
40
var $ = $B.args("as_integer_ratio", 1, {self:null}, ["self"],
41
arguments, {}, null, null)
42
return $B.$list([$.self, 1])
43
}
44
46
var $ = $B.args("from_bytes", 3,
47
{bytes:null, byteorder:null, signed:null},
48
["bytes", "byteorder", "signed"],
49
arguments, {signed: false}, null, null)
50
51
var x = $.bytes,
52
byteorder = $.byteorder,
53
signed = $.signed,
54
_bytes, _len
55
if(_b_.isinstance(x, [_b_.bytes, _b_.bytearray])){
56
_bytes = x.source
57
_len = x.source.length
58
}else{
59
_bytes = _b_.list.$factory(x)
60
_len = _bytes.length
61
for(var i = 0; i < _len; i++){
62
_b_.bytes.$factory([_bytes[i]])
63
}
64
}
65
if(byteorder == "big"){
66
_bytes.reverse()
67
}else if(byteorder != "little"){
68
throw _b_.ValueError.$factory(
69
"byteorder must be either 'little' or 'big'")
70
}
71
var num = _bytes[0]
72
if(signed && num >= 128){
73
num = num - 256
74
}
75
var _mult = 256
76
for(var i = 1; i < _len; i++){
77
num = $B.add($B.mul(_mult, _bytes[i]), num)
78
_mult = $B.mul(_mult, 256)
79
}
80
if(! signed){
81
return num
82
}
83
if(_bytes[_len - 1] < 128){
84
return num
85
}
86
return $B.sub(num, _mult)
91
{self: null, len: null, byteorder: null, signed: null},
92
["self", "len", "byteorder", "*", "signed"],
93
arguments, {signed: false}, null, null),
98
if(! _b_.isinstance(len, _b_.int)){
99
throw _b_.TypeError.$factory("integer argument expected, got " +
103
throw _b_.ValueError.$factory(
104
"byteorder must be either 'little' or 'big'")
105
}
106
107
if(_b_.isinstance(self, $B.long_int)){
108
return $B.long_int.to_bytes(self, len, byteorder, signed)
123
var quotient = Math.floor(value / 256),
124
rest = value - 256 * quotient
125
res.push(rest)
126
if(res.length > len){
127
throw _b_.OverflowError.$factory("int too big to convert")
131
while(res.length < len){
132
res.push(0)
133
}
134
if(byteorder == "big"){
135
res.reverse()
145
int.__add__ = function(self, other){
146
self = int_value(self)
147
if(_b_.isinstance(other, int)){
148
if(other.__class__ == $B.long_int){
149
return $B.long_int.__add__($B.long_int.$factory(self),
150
$B.long_int.$factory(other))
151
}
152
other = int_value(other)
153
var res = self + other
154
if(res > $B.min_int && res < $B.max_int){
155
return res
156
}else{
157
return $B.long_int.__add__($B.long_int.$factory(self),
158
$B.long_int.$factory(other))
159
}
160
}
161
return _b_.NotImplemented
162
}
163
164
int.__bool__ = function(self){
165
return int_value(self).valueOf() == 0 ? false : true
166
}
184
if(_b_.isinstance(other, _b_.float)){return self.valueOf() == other.valueOf()}
185
if(_b_.isinstance(other, _b_.complex)){
198
if(fmt.type && 'bcdoxXn'.indexOf(fmt.type) == -1){
199
throw _b_.ValueError.$factory("Unknown format code '" + fmt.type +
227
if(fmt.sign !== undefined){
228
if((fmt.sign == " " || fmt.sign == "+" ) && self >= 0){
229
res = fmt.sign + res
230
}
231
}
250
for(var i = 0; i < nb; i++){
251
chunks.push(rest.substring(len - 3 * i - 3, len - 3 * i))
272
if(self.$brython_value){
273
// int subclass
274
var hash_method = $B.$getattr(self.__class__, '__hash__')
275
if(hash_method === int.__hash__){
276
if(typeof self.$brython_value == "number"){
277
return self.$brython_value
278
}else{ // long int
279
return $B.long_int.__hash__(self.$brython_value)
280
}
281
}else{
282
return hash_method(self)
283
}
284
}
285
return self.valueOf()
309
try{
310
return int.$factory($B.long_int.__lshift__($B.long_int.$factory(self),
311
$B.long_int.$factory(other)))
312
}catch(err){
313
console.log('err in lshift', self, other)
314
throw err
315
}
323
if(other.__class__ === $B.long_int){
324
return $B.long_int.__mod__($B.long_int.$factory(self), other)
325
}
328
if(other === false){other = 0}
329
else if(other === true){other = 1}
330
if(other == 0){throw _b_.ZeroDivisionError.$factory(
340
if(other.__class__ == $B.long_int){
341
return $B.long_int.__mul__($B.long_int.$factory(self),
342
$B.long_int.$factory(other))
343
}
349
return int.$factory($B.long_int.__mul__($B.long_int.$factory(self),
350
$B.long_int.$factory(other)))
351
}
356
int.__ne__ = function(self, other){
357
var res = int.__eq__(self, other)
358
return (res === _b_.NotImplemented) ? res : !res
359
}
360
364
if(cls === undefined){
365
throw _b_.TypeError.$factory("int.__new__(): not enough arguments")
367
throw _b_.TypeError.$factory("int.__new__(X): X is not a type object")
368
}
369
if(cls === int){return int.$factory(value)}
370
return {
371
__class__: cls,
379
function extended_euclidean(a, b){
380
var d, u, v
381
if(b == 0){
382
return [a, 1, 0]
383
}else{
384
[d, u, v] = extended_euclidean(b, a % b)
385
return [d, v, u - Math.floor(a / b) * v]
386
}
387
}
388
394
other = int_value(other)
395
switch(other.valueOf()) {
396
case 0:
397
return int.$factory(1)
398
case 1:
399
return int.$factory(self.valueOf())
402
// If z is provided, the algorithm is faster than computing
403
// self ** other then applying the modulo z
404
if(z == 1){return 0}
405
var result = 1,
406
base = self % z,
407
exponent = other,
408
long_int = $B.long_int
409
if(exponent < 0){
410
var gcd, inv, _
411
[gcd, inv, _] = extended_euclidean(self, z)
412
if(gcd !== 1){
413
throw _b_.ValueError.$factory("not relative primes: " +
414
self + ' and ' + z)
415
}
416
return int.__pow__(inv, -exponent, z)
417
}
418
while(exponent > 0){
419
if(exponent % 2 == 1){
420
if(result * base > $B.max_int){
421
result = long_int.__mul__(
422
long_int.$factory(result),
423
long_int.$factory(base))
424
result = long_int.__mod__(result, z)
425
}else{
426
result = (result * base) % z
427
}
428
}
429
exponent = exponent >> 1
430
if(base * base > $B.max_int){
431
base = long_int.__mul__(long_int.$factory(base),
432
long_int.$factory(base))
433
base = long_int.__mod__(base, z)
434
}else{
435
base = (base * base) % z
436
}
441
if(res > $B.min_int && res < $B.max_int){
442
return other > 0 ? res : new Number(res)
443
}else if(res !== Infinity && !isFinite(res)){
444
return res
445
}else{
446
if($B.BigInt){
447
return {
448
__class__: $B.long_int,
449
value: ($B.BigInt(self) ** $B.BigInt(other)).toString(),
450
pos: true
451
}
452
}
453
return $B.long_int.__pow__($B.long_int.$from_int(self),
454
$B.long_int.$from_int(other))
470
var rpow = $B.$getattr(other, "__rpow__", _b_.None)
471
if(rpow !== _b_.None){
472
return rpow(self)
473
}
477
function __newobj__(){
478
// __newobj__ is called with a generator as only argument
479
var $ = $B.args('__newobj__', 0, {}, [], arguments, {}, 'args', null),
480
args = $.args
481
var res = args.slice(1)
482
res.__class__ = args[0]
483
return res
484
}
485
486
int.__reduce_ex__ = function(self){
487
return $B.fast_tuple([
488
__newobj__,
489
$B.fast_tuple([self.__class__ || int, int_value(self)]),
490
_b_.None,
491
_b_.None,
492
_b_.None])
493
}
494
502
self = int_value(self)
503
if(typeof other == "number" || _b_.isinstance(other, int)){
505
return int.$factory($B.long_int.__rshift__($B.long_int.$factory(self),
506
$B.long_int.$factory(other)))
512
if(typeof self == "number" || typeof self == "boolean"){
513
var cl_name = $B.class_name(self)
514
if(_b_.dir(self).indexOf(attr) > -1){
515
var msg = "attribute '" + attr + `' of '${cl_name}'` +
516
"objects is not writable"
527
int.__sub__ = function(self, other){
528
self = int_value(self)
529
if(_b_.isinstance(other, int)){
530
if(other.__class__ == $B.long_int){
531
return $B.long_int.__sub__($B.long_int.$factory(self),
532
$B.long_int.$factory(other))
533
}
534
other = int_value(other)
535
var res = self - other
536
if(res > $B.min_int && res < $B.max_int){
537
return res
538
}else{
539
return $B.long_int.__sub__($B.long_int.$factory(self),
540
$B.long_int.$factory(other))
541
}
542
}
543
return _b_.NotImplemented
544
}
545
552
if(other.__class__ === $B.long_int){
553
return new Number(self / parseInt(other.value))
554
}
555
return new Number(self / other)
561
s = _b_.bin(self)
562
s = $B.$getattr(s, "lstrip")("-0b") // remove leading zeros and minus sign
567
int.numerator = function(self){
568
return int_value(self)
569
}
570
int.denominator = function(self){
571
return int.$factory(1)
572
}
573
int.imag = function(self){
574
return int.$factory(0)
575
}
576
int.real = function(self){
577
return self
578
}
579
580
for(var attr of ['numerator', 'denominator', 'imag', 'real']){
581
int[attr].setter = (function(x){
582
return function(self, value){
583
throw _b_.AttributeError.$factory(`attribute '${x}' of ` +
584
`'${$B.class_name(self)}' objects is not writable`)
585
}
586
})(attr)
587
}
594
self = int_value(self)
595
if(typeof other == "number" || _b_.isinstance(other, int)){
596
if(other.__class__ === $B.long_int){
597
return $B.long_int.__sub__($B.long_int.$factory(self),
598
$B.long_int.$factory(other))
601
if(self > $B.max_int32 || self < $B.min_int32 ||
602
other > $B.max_int32 || other < $B.min_int32){
603
return $B.long_int.__sub__($B.long_int.$factory(self),
604
$B.long_int.$factory(other))
614
var opf = $op_func.replace(/-/gm, $op)
615
opf = opf.replace(new RegExp("sub", "gm"), $ops[$op])
616
eval("int.__" + $ops[$op] + "__ = " + opf)
642
eval("int.__"+$B.$comps[$op] + "__ = " +
643
$comp_func.replace(/>/gm, $op).
644
replace(/__gt__/gm,"__" + $B.$comps[$op] + "__").
645
replace(/__lt__/, "__" + $B.$inv_comps[$op] + "__"))
649
var r_opnames = ["add", "sub", "mul", "truediv", "floordiv", "mod", "pow",
650
"lshift", "rshift", "and", "xor", "or", "divmod"]
651
652
for(var r_opname of r_opnames){
653
if(int["__r" + r_opname + "__"] === undefined &&
654
int['__' + r_opname + '__']){
655
int["__r" + r_opname + "__"] = (function(name){
656
return function(self, other){
657
if(_b_.isinstance(other, int)){
658
other = int_value(other)
659
return int["__" + name + "__"](other, self)
660
}
661
return _b_.NotImplemented
662
}
663
})(r_opname)
664
}
665
}
667
var $valid_digits = function(base) {
668
var digits = ""
669
if(base === 0){return "0"}
670
if(base < 10){
686
if(typeof value == "number" &&
687
(base === undefined || base == 10)){return parseInt(value)}
693
var $ns = $B.args("int", 2, {x:null, base:null}, ["x", "base"], arguments,
694
{"base": 10}, null, null),
695
value = $ns["x"],
696
base = $ns["base"]
717
if(base == 10){
718
if(value < $B.min_int || value > $B.max_int){
719
return $B.long_int.$factory(value)
720
}
726
var res = parseInt(value, base)
727
if(value < $B.min_int || value > $B.max_int){
728
return $B.long_int.$factory(value, base)
729
}
734
if(value === true){return Number(1)}
735
if(value === false){return Number(0)}
736
if(value.__class__ === $B.long_int){
743
function invalid(value, base){
744
throw _b_.ValueError.$factory("invalid literal for int() with base " +
745
base + ": '" + _b_.str.$factory(value) + "'")
746
}
751
if(typeof value == "string") {
752
var _value = value.trim() // remove leading/trailing whitespace
753
if(_value.length == 2 && base == 0 &&
754
(_value == "0b" || _value == "0o" || _value == "0x")){
755
throw _b_.ValueError.$factory("invalid value")
756
}
758
var _pre = _value.substr(0, 2).toUpperCase()
759
if(base == 0){
760
if(_pre == "0B"){base = 2}
761
if(_pre == "0O"){base = 8}
762
if(_pre == "0X"){base = 16}
763
}else if(_pre == "0X" && base != 16){invalid(_value, base)}
764
else if(_pre == "0O" && base != 8){invalid(_value, base)}
775
var _digits = $valid_digits(base),
776
_re = new RegExp("^[+-]?[" + _digits + "]" +
777
"[" + _digits + "_]*$", "i"),
778
match = _re.exec(_value)
805
throw _b_.TypeError.$factory(
806
"int() argument must be a string, a bytes-like " +
807
"object or a number, not '" + $B.class_name(value) + "'")
816
if(obj === null || obj === undefined ){ return false}
817
switch(typeof obj){
818
case "boolean":
819
return obj
820
case "number":
821
case "string":
822
if(obj){return true}
823
return false
824
default:
826
var klass = obj.__class__ || $B.get_class(obj),
827
missing = {},
828
bool_method = $B.$getattr(klass, "__bool__", missing)
829
if(bool_method === missing){
830
try{return _b_.len(obj) > 0}
833
var res = $B.$call(bool_method)(obj)
834
if(res !== true && res !== false){
835
throw _b_.TypeError.$factory("__bool__ should return " +
836
"bool, returned " + $B.class_name(res))
837
}
838
return res
852
$native: true,
853
$descriptors: {
854
"numerator": true,
855
"denominator": true,
856
"imag": true,
857
"real": true
858
}
862
if(_b_.isinstance(other, bool)){
863
return self && other
864
}else if(_b_.isinstance(other, int)){
865
return int.__and__(bool.__index__(self), int.__index__(other))
866
}
867
return _b_.NotImplemented
870
bool.__float__ = function(self){
871
return self ? new Number(1) : new Number(0)
872
}
873
882
if(_b_.isinstance(other, bool)){
883
return self || other
884
}else if(_b_.isinstance(other, int)){
885
return int.__or__(bool.__index__(self), int.__index__(other))
886
}
887
return _b_.NotImplemented
892
bool.__repr__ = function(self){
893
$B.builtins_repr_check(bool, arguments) // in brython_builtins.js
898
if(_b_.isinstance(other, bool)){
899
return self ^ other ? true : false
900
}else if(_b_.isinstance(other, int)){
901
return int.__xor__(bool.__index__(self), int.__index__(other))
902
}
903
return _b_.NotImplemented
906
bool.$factory = function(){
907
// Calls $B.$bool, which is used inside the generated JS code and skips
908
// arguments control.
914
bool.numerator = int.numerator
915
bool.denominator = int.denominator
916
bool.real = int.real
917
bool.imag = int.imag
918