Skip to content
Permalink
Newer
Older
100644 947 lines (854 sloc) 28.4 KB
Sep 5, 2014
1
;(function($B){
2
3
var _b_ = $B.builtins
Sep 5, 2014
4
Mar 10, 2018
5
function $err(op, other){
6
var msg = "unsupported operand type(s) for " + op +
7
" : 'int' and '" + $B.class_name(other) + "'"
8
throw _b_.TypeError.$factory(msg)
Sep 5, 2014
9
}
10
11
function int_value(obj){
12
// Instances of int subclasses that call int.__new__(cls, value)
13
// have an attribute $brython_value set
14
return obj.$brython_value !== undefined ? obj.$brython_value : obj
17
// dictionary for built-in class 'int'
18
var int = {
19
__class__: _b_.type,
20
__dir__: _b_.object.__dir__,
21
$infos: {
22
__module__: "builtins",
23
__name__: "int"
24
},
25
$is_class: true,
26
$native: true,
27
$descriptors: {
Mar 10, 2018
28
"numerator": true,
29
"denominator": true,
30
"imag": true,
31
"real": true
Sep 5, 2014
33
}
34
35
int.as_integer_ratio = function(){
36
var $ = $B.args("as_integer_ratio", 1, {self:null}, ["self"],
37
arguments, {}, null, null)
38
return $B.$list([$.self, 1])
39
}
40
41
int.from_bytes = function() {
42
var $ = $B.args("from_bytes", 3,
43
{bytes:null, byteorder:null, signed:null},
44
["bytes", "byteorder", "signed"],
45
arguments, {signed: false}, null, null)
46
47
var x = $.bytes,
48
byteorder = $.byteorder,
49
signed = $.signed,
50
_bytes, _len
51
if(_b_.isinstance(x, [_b_.bytes, _b_.bytearray])){
52
_bytes = x.source
53
_len = x.source.length
54
}else{
55
_bytes = _b_.list.$factory(x)
56
_len = _bytes.length
57
for(var i = 0; i < _len; i++){
58
_b_.bytes.$factory([_bytes[i]])
59
}
60
}
61
if(byteorder == "big"){
62
_bytes.reverse()
63
}else if(byteorder != "little"){
64
throw _b_.ValueError.$factory(
65
"byteorder must be either 'little' or 'big'")
66
}
67
var num = _bytes[0]
68
if(signed && num >= 128){
69
num = num - 256
70
}
71
var _mult = 256
72
for(var i = 1; i < _len; i++){
73
num = $B.add($B.mul(_mult, _bytes[i]), num)
74
_mult = $B.mul(_mult, 256)
75
}
76
if(! signed){
77
return num
78
}
79
if(_bytes[_len - 1] < 128){
80
return num
81
}
82
return $B.sub(num, _mult)
Sep 5, 2014
83
}
84
85
int.to_bytes = function(){
86
var $ = $B.args("to_bytes", 3,
87
{self: null, len: null, byteorder: null, signed: null},
88
["self", "len", "byteorder", "*", "signed"],
89
arguments, {signed: false}, null, null),
90
self = $.self,
91
len = $.len,
92
byteorder = $.byteorder,
93
signed = $.signed
94
if(! _b_.isinstance(len, _b_.int)){
95
throw _b_.TypeError.$factory("integer argument expected, got " +
97
}
98
if(["little", "big"].indexOf(byteorder) == -1){
99
throw _b_.ValueError.$factory(
100
"byteorder must be either 'little' or 'big'")
101
}
102
103
if(_b_.isinstance(self, $B.long_int)){
104
return $B.long_int.to_bytes(self, len, byteorder, signed)
105
}
106
107
if(self < 0){
108
if(! signed){
109
throw _b_.OverflowError.$factory(
110
"can't convert negative int to unsigned")
111
}
112
self = Math.pow(256, len) + self
113
}
114
115
var res = [],
116
value = self
117
118
while(value > 0){
119
var quotient = Math.floor(value / 256),
120
rest = value - 256 * quotient
121
res.push(rest)
122
if(res.length > len){
123
throw _b_.OverflowError.$factory("int too big to convert")
124
}
125
value = quotient
126
}
127
while(res.length < len){
128
res.push(0)
129
}
130
if(byteorder == "big"){
131
res.reverse()
132
}
133
return {
134
__class__: _b_.bytes,
135
source: res
136
}
Sep 5, 2014
137
}
138
139
int.__abs__ = function(self){return _b_.abs(self)}
141
int.__bool__ = function(self){
142
return int_value(self).valueOf() == 0 ? false : true
143
}
Sep 5, 2014
144
145
int.__ceil__ = function(self){return Math.ceil(int_value(self))}
147
int.__divmod__ = function(self, other){
148
return $B.fast_tuple([int.__floordiv__(self, other),
149
int.__mod__(self, other)])
150
}
Mar 10, 2018
152
int.__eq__ = function(self, other){
Sep 5, 2014
153
// compare object "self" to class "int"
Mar 10, 2018
154
if(other === undefined){return self === int}
155
if(_b_.isinstance(other, int)){
156
return self.valueOf() == int_value(other).valueOf()
157
}
158
if(_b_.isinstance(other, _b_.float)){return self.valueOf() == other.valueOf()}
159
if(_b_.isinstance(other, _b_.complex)){
Mar 10, 2018
160
if(other.$imag != 0){return False}
161
return self.valueOf() == other.$real
Sep 5, 2014
162
}
163
return _b_.NotImplemented
Sep 5, 2014
164
}
165
166
int.__float__ = function(self){
167
return new Number(self)
168
}
169
170
function preformat(self, fmt){
str
Feb 10, 2018
171
if(fmt.empty){return _b_.str.$factory(self)}
Mar 10, 2018
172
if(fmt.type && 'bcdoxXn'.indexOf(fmt.type) == -1){
173
throw _b_.ValueError.$factory("Unknown format code '" + fmt.type +
174
"' for object of type 'int'")
175
}
177
switch(fmt.type){
178
case undefined:
Mar 10, 2018
179
case "d":
180
res = self.toString()
181
break
Mar 10, 2018
182
case "b":
183
res = (fmt.alternate ? "0b" : "") + self.toString(2)
184
break
Mar 10, 2018
185
case "c":
186
res = _b_.chr(self)
187
break
Mar 10, 2018
188
case "o":
189
res = (fmt.alternate ? "0o" : "") + self.toString(8)
190
break
Mar 10, 2018
191
case "x":
192
res = (fmt.alternate ? "0x" : "") + self.toString(16)
193
break
Mar 10, 2018
194
case "X":
195
res = (fmt.alternate ? "0X" : "") + self.toString(16).toUpperCase()
196
break
Mar 10, 2018
197
case "n":
198
return self // fix me
199
}
201
if(fmt.sign !== undefined){
202
if((fmt.sign == " " || fmt.sign == "+" ) && self >= 0){
203
res = fmt.sign + res
204
}
205
}
206
return res
207
}
208
209
Mar 10, 2018
210
int.__format__ = function(self, format_spec){
211
var fmt = new $B.parse_format_spec(format_spec)
Mar 10, 2018
212
if(fmt.type && 'eEfFgG%'.indexOf(fmt.type) != -1){
213
// Call __format__ on float(self)
214
return _b_.float.__format__(self, format_spec)
Mar 10, 2018
216
fmt.align = fmt.align || ">"
217
var res = preformat(self, fmt)
218
if(fmt.comma){
Mar 10, 2018
219
var sign = res[0] == "-" ? "-" : "",
220
rest = res.substr(sign.length),
221
len = rest.length,
222
nb = Math.ceil(rest.length/3),
223
chunks = []
Mar 10, 2018
224
for(var i = 0; i < nb; i++){
225
chunks.push(rest.substring(len - 3 * i - 3, len - 3 * i))
226
}
227
chunks.reverse()
Mar 10, 2018
228
res = sign + chunks.join(",")
229
}
230
return $B.format_width(res, fmt)
Sep 5, 2014
231
}
232
233
int.__floordiv__ = function(self, other){
234
if(other.__class__ === $B.long_int){
235
return $B.long_int.__floordiv__($B.long_int.$factory(self), other)
236
}
237
if(_b_.isinstance(other, int)){
239
if(other == 0){throw _b_.ZeroDivisionError.$factory("division by zero")}
Mar 10, 2018
240
return Math.floor(self / other)
Sep 5, 2014
241
}
242
if(_b_.isinstance(other, _b_.float)){
243
other = _b_.float.numerator(other) // for float subclasses
Mar 10, 2018
244
if(!other.valueOf()){
245
throw _b_.ZeroDivisionError.$factory("division by zero")
Mar 10, 2018
246
}
247
return new Number(Math.floor(self / other))
Sep 5, 2014
248
}
249
if(_b_.hasattr(other, "__rfloordiv__")){
250
return $B.$getattr(other, "__rfloordiv__")(self)
Sep 5, 2014
251
}
Mar 10, 2018
252
$err("//", other)
Sep 5, 2014
253
}
254
255
int.__hash__ = function(self){
Mar 23, 2018
256
if(self === undefined){
257
return int.__hashvalue__ || $B.$py_next_hash-- // for hash of int type (not instance of int)
258
}
259
return self.valueOf()
260
}
Sep 5, 2014
261
262
//int.__ior__ = function(self,other){return self | other} // bitwise OR
Sep 5, 2014
263
264
int.__index__ = function(self){
265
return int_value(self)
266
}
Sep 5, 2014
267
268
int.__init__ = function(self, value){
Mar 10, 2018
269
if(value === undefined){value = 0}
Sep 5, 2014
270
self.toString = function(){return value}
271
return _b_.None
Sep 5, 2014
272
}
273
274
int.__int__ = function(self){return self}
Sep 5, 2014
275
276
int.__invert__ = function(self){return ~self}
Sep 5, 2014
277
Mar 10, 2018
279
int.__lshift__ = function(self, other){
280
if(_b_.isinstance(other, int)){
Mar 10, 2018
282
return int.$factory($B.long_int.__lshift__($B.long_int.$factory(self),
283
$B.long_int.$factory(other)))
285
var rlshift = $B.$getattr(other, "__rlshift__", _b_.None)
286
if(rlshift !== _b_.None){return rlshift(self)}
Mar 10, 2018
287
$err("<<", other)
Mar 10, 2018
290
int.__mod__ = function(self, other) {
Sep 5, 2014
291
// can't use Javascript % because it works differently for negative numbers
292
if(_b_.isinstance(other,_b_.tuple) && other.length == 1){other = other[0]}
293
if(other.__class__ === $B.long_int){
294
return $B.long_int.__mod__($B.long_int.$factory(self), other)
295
}
296
if(_b_.isinstance(other, [int, _b_.float, bool])){
Mar 10, 2018
298
if(other === false){other = 0}
299
else if(other === true){other = 1}
300
if(other == 0){throw _b_.ZeroDivisionError.$factory(
301
"integer division or modulo by zero")}
Mar 10, 2018
302
return (self % other + other) % other
Sep 5, 2014
303
}
304
if(_b_.hasattr(other, "__rmod__")){
305
return $B.$getattr(other, "__rmod__")(self)
306
}
Mar 10, 2018
307
$err("%", other)
Sep 5, 2014
308
}
309
310
int.__mro__ = [_b_.object]
Sep 5, 2014
311
Mar 10, 2018
312
int.__mul__ = function(self, other){
313
Sep 5, 2014
314
var val = self.valueOf()
Jan 22, 2015
315
316
// this will be quick check, so lets do it early.
Mar 10, 2018
317
if(typeof other === "string") {
Jan 22, 2015
318
return other.repeat(val)
319
}
320
321
if(_b_.isinstance(other, int)){
Mar 10, 2018
323
var res = self * other
324
if(res > $B.min_int && res < $B.max_int){return res}
325
else{
326
return int.$factory($B.long_int.__mul__($B.long_int.$factory(self),
327
$B.long_int.$factory(other)))
328
}
330
if(_b_.isinstance(other, _b_.float)){
331
return new Number(self * _b_.float.numerator(other))
333
if(_b_.isinstance(other, _b_.bool)){
Mar 10, 2018
334
if(other.valueOf()){return self}
335
return int.$factory(0)
Sep 5, 2014
336
}
337
if(_b_.isinstance(other, _b_.complex)){
338
return $B.make_complex(int.__mul__(self, other.$real),
339
int.__mul__(self, other.$imag))
Sep 5, 2014
340
}
341
if(_b_.isinstance(other, [_b_.list, _b_.tuple])){
Sep 5, 2014
342
var res = []
343
// make temporary copy of list
Mar 10, 2018
344
var $temp = other.slice(0, other.length)
345
for(var i = 0; i < val; i++){res = res.concat($temp)}
346
if(_b_.isinstance(other, _b_.tuple)){res = _b_.tuple.$factory(res)}
Sep 5, 2014
347
return res
348
}
349
if(_b_.hasattr(other, "__rmul__")){
350
return $B.$getattr(other, "__rmul__")(self)
351
}
Mar 10, 2018
352
$err("*", other)
Sep 5, 2014
353
}
354
Feb 22, 2019
355
int.__ne__ = function(self, other){
356
var res = int.__eq__(self, other)
357
return (res === _b_.NotImplemented) ? res : !res
358
}
359
360
int.__neg__ = function(self){return -self}
Sep 5, 2014
361
362
int.__new__ = function(cls, value){
Mar 10, 2018
363
if(cls === undefined){
364
throw _b_.TypeError.$factory("int.__new__(): not enough arguments")
365
}else if(! _b_.isinstance(cls, _b_.type)){
366
throw _b_.TypeError.$factory("int.__new__(X): X is not a type object")
367
}
368
if(cls === int){return int.$factory(value)}
369
return {
370
__class__: cls,
Mar 10, 2018
373
}
Sep 5, 2014
374
}
375
376
int.__pos__ = function(self){return self}
Sep 5, 2014
377
Feb 20, 2020
378
function extended_euclidean(a, b){
379
var d, u, v
380
if(b == 0){
381
return [a, 1, 0]
382
}else{
383
[d, u, v] = extended_euclidean(b, a % b)
384
return [d, v, u - Math.floor(a / b) * v]
385
}
386
}
387
Mar 10, 2018
388
int.__pow__ = function(self, other, z){
389
if(typeof other == "number" || _b_.isinstance(other, int)){
390
other = int_value(other)
391
switch(other.valueOf()) {
392
case 0:
393
return int.$factory(1)
394
case 1:
395
return int.$factory(self.valueOf())
Feb 9, 2015
396
}
397
if(z !== undefined && z !== _b_.None){
May 19, 2017
398
// If z is provided, the algorithm is faster than computing
399
// self ** other then applying the modulo z
400
if(z == 1){return 0}
401
var result = 1,
402
base = self % z,
403
exponent = other,
404
long_int = $B.long_int
Feb 20, 2020
405
if(exponent < 0){
406
var gcd, inv, _
407
[gcd, inv, _] = extended_euclidean(self, z)
408
if(gcd !== 1){
409
throw _b_.ValueError.$factory("not relative primes: " +
410
self + ' and ' + z)
411
}
412
return int.__pow__(inv, -exponent, z)
413
}
414
while(exponent > 0){
415
if(exponent % 2 == 1){
416
if(result * base > $B.max_int){
417
result = long_int.__mul__(
418
long_int.$factory(result),
419
long_int.$factory(base))
420
result = long_int.__mod__(result, z)
421
}else{
422
result = (result * base) % z
423
}
424
}
425
exponent = exponent >> 1
426
if(base * base > $B.max_int){
427
base = long_int.__mul__(long_int.$factory(base),
428
long_int.$factory(base))
429
base = long_int.__mod__(base, z)
430
}else{
431
base = (base * base) % z
432
}
May 19, 2017
433
}
May 19, 2017
435
}
Mar 10, 2018
436
var res = Math.pow(self.valueOf(), other.valueOf())
437
if(res > $B.min_int && res < $B.max_int){return res}
May 19, 2017
438
else if(res !== Infinity && !isFinite(res)){return res}
440
if($B.BigInt){
441
return {
442
__class__: $B.long_int,
443
value: ($B.BigInt(self) ** $B.BigInt(other)).toString(),
444
pos: true
445
}
446
}
447
return $B.long_int.__pow__($B.long_int.$from_int(self),
448
$B.long_int.$from_int(other))
May 19, 2017
449
}
Sep 5, 2014
450
}
451
if(_b_.isinstance(other, _b_.float)) {
452
other = _b_.float.numerator(other)
453
if(self >= 0){return new Number(Math.pow(self, other))}
454
else{
455
// use complex power
456
return _b_.complex.__pow__($B.make_complex(self, 0), other)
458
}else if(_b_.isinstance(other, _b_.complex)){
Mar 10, 2018
459
var preal = Math.pow(self, other.$real),
460
ln = Math.log(self)
Mar 10, 2018
461
return $B.make_complex(preal * Math.cos(ln), preal * Math.sin(ln))
Sep 5, 2014
462
}
463
var rpow = $B.$getattr(other, "__rpow__", _b_.None)
464
if(rpow !== _b_.None){
465
return rpow(self)
466
}
Mar 10, 2018
467
$err("**", other)
Sep 5, 2014
468
}
469
470
function __newobj__(){
471
// __newobj__ is called with a generator as only argument
472
var $ = $B.args('__newobj__', 0, {}, [], arguments, {}, 'args', null),
473
args = $.args
474
var res = args.slice(1)
475
res.__class__ = args[0]
476
return res
477
}
478
479
int.__reduce_ex__ = function(self){
480
return $B.fast_tuple([
481
__newobj__,
482
$B.fast_tuple([self.__class__ || int, int_value(self)]),
483
_b_.None,
484
_b_.None,
485
_b_.None])
486
}
487
488
int.__repr__ = function(self){
489
return int_value(self).toString()
Sep 5, 2014
490
}
491
492
// bitwise right shift
Mar 10, 2018
493
int.__rshift__ = function(self, other){
494
if(_b_.isinstance(other, int)){
Feb 11, 2018
496
return int.$factory($B.long_int.__rshift__($B.long_int.$factory(self),
497
$B.long_int.$factory(other)))
499
var rrshift = $B.$getattr(other, "__rrshift__", _b_.None)
500
if(rrshift !== _b_.None){return rrshift(self)}
501
$err('>>', other)
502
}
Sep 5, 2014
503
504
int.__setattr__ = function(self, attr, value){
Mar 10, 2018
505
if(typeof self == "number"){
506
if(int.$factory[attr] === undefined){
507
throw _b_.AttributeError.$factory(
508
"'int' object has no attribute '" + attr + "'")
Mar 10, 2018
510
throw _b_.AttributeError.$factory(
511
"'int' object attribute '" + attr + "' is read-only")
Sep 5, 2014
513
}
514
// subclasses of int can have attributes set
515
_b_.dict.$setitem(self.__dict__, attr, value)
516
return _b_.None
Sep 5, 2014
517
}
518
519
int.__str__ = int.__repr__
Sep 5, 2014
520
Mar 10, 2018
521
int.__truediv__ = function(self, other){
522
if(_b_.isinstance(other, int)){
524
if(other == 0){
525
throw _b_.ZeroDivisionError.$factory("division by zero")
526
}
Mar 10, 2018
527
if(other.__class__ === $B.long_int){
528
return new Number(self / parseInt(other.value))
529
}
530
return new Number(self / other)
Sep 5, 2014
531
}
532
if(_b_.isinstance(other, _b_.float)){
533
other = _b_.float.numerator(other)
Mar 10, 2018
534
if(!other.valueOf()){
535
throw _b_.ZeroDivisionError.$factory("division by zero")
Mar 10, 2018
536
}
537
return new Number(self / other)
Sep 5, 2014
538
}
539
if(_b_.isinstance(other, _b_.complex)){
Mar 10, 2018
540
var cmod = other.$real * other.$real + other.$imag * other.$imag
541
if(cmod == 0){throw _b_.ZeroDivisionError.$factory("division by zero")}
Mar 10, 2018
542
return $B.make_complex(self * other.$real / cmod,
543
-self * other.$imag / cmod)
Sep 5, 2014
544
}
545
if(_b_.hasattr(other, "__rtruediv__")){
546
return $B.$getattr(other, "__rtruediv__")(self)
Mar 10, 2018
547
}
548
$err("/", other)
Sep 5, 2014
549
}
550
551
int.bit_length = function(self){
552
s = _b_.bin(self)
553
s = $B.$getattr(s, "lstrip")("-0b") // remove leading zeros and minus sign
Sep 5, 2014
554
return s.length // len('100101') --> 6
555
}
556
557
// descriptors
558
int.numerator = function(self){return self}
559
int.denominator = function(self){return int.$factory(1)}
560
int.imag = function(self){return int.$factory(0)}
561
int.real = function(self){return self}
562
Mar 10, 2018
563
$B.max_int32 = (1 << 30) * 2 - 1
564
$B.min_int32 = - $B.max_int32
566
// code for operands & | ^
Mar 10, 2018
567
var $op_func = function(self, other){
568
if(_b_.isinstance(other, int)) {
Mar 10, 2018
569
if(other.__class__ === $B.long_int){
570
return $B.long_int.__sub__($B.long_int.$factory(self),
571
$B.long_int.$factory(other))
Mar 23, 2018
574
if(self > $B.max_int32 || self < $B.min_int32 ||
575
other > $B.max_int32 || other < $B.min_int32){
Mar 10, 2018
576
return $B.long_int.__sub__($B.long_int.$factory(self),
577
$B.long_int.$factory(other))
Mar 21, 2018
579
return self - other
Jun 7, 2015
580
}
581
if(_b_.isinstance(other, _b_.bool)){
582
return self - other
583
}
584
var rsub = $B.$getattr(other, "__rsub__", _b_.None)
585
if(rsub !== _b_.None){
586
return rsub(self)
587
}
Mar 10, 2018
588
$err("-", other)
Sep 5, 2014
589
}
590
Mar 10, 2018
591
$op_func += "" // source code
592
var $ops = {"&": "and", "|": "or", "^": "xor"}
Sep 5, 2014
593
for(var $op in $ops){
Mar 10, 2018
594
var opf = $op_func.replace(/-/gm, $op)
595
opf = opf.replace(new RegExp("sub", "gm"), $ops[$op])
596
eval("int.__" + $ops[$op] + "__ = " + opf)
Sep 5, 2014
597
}
598
599
// code for + and -
Mar 10, 2018
600
var $op_func = function(self, other){
601
if(_b_.isinstance(other, int)){
Mar 10, 2018
603
if(typeof other == "number"){
604
var res = self.valueOf() - other.valueOf()
605
if(res > $B.min_int && res < $B.max_int){return res}
Feb 11, 2018
606
else{return $B.long_int.__sub__($B.long_int.$factory(self),
607
$B.long_int.$factory(other))}
Mar 10, 2018
608
}else if(typeof other == "boolean"){
Mar 21, 2018
609
return other ? self - 1 : self
610
}else{
Feb 11, 2018
611
return $B.long_int.__sub__($B.long_int.$factory(self),
612
$B.long_int.$factory(other))
Sep 5, 2014
614
}
615
if(_b_.isinstance(other, _b_.float)){
616
return new Number(self - _b_.float.numerator(other))
Sep 5, 2014
617
}
618
if(_b_.isinstance(other, _b_.complex)){
619
if(other.$imag == 0){
620
// 1 - 0.0j is complex(1, 0.0) : the imaginary part is 0.0,
621
// *not* -0.0 (cf. https://bugs.python.org/issue22548)
622
return $B.make_complex(self - other.$real, 0)
623
}
Mar 10, 2018
624
return $B.make_complex(self - other.$real, -other.$imag)
Sep 5, 2014
625
}
626
if(_b_.isinstance(other, _b_.bool)){
Mar 10, 2018
627
var bool_value = 0;
628
if(other.valueOf()){bool_value = 1}
629
return self - bool_value
Sep 5, 2014
630
}
631
if(_b_.isinstance(other, _b_.complex)){
632
return $B.make_complex(self.valueOf() - other.$real, other.$imag)
Sep 5, 2014
633
}
634
var rsub = $B.$getattr(other, "__rsub__", _b_.None)
635
if(rsub !== _b_.None){return rsub(self)}
636
//console.log("err", self, other)
637
//console.log($B.frames_stack.slice())
Mar 10, 2018
638
throw $err("-", other)
Sep 5, 2014
639
}
Mar 10, 2018
640
$op_func += "" // source code
641
var $ops = {"+": "add", "-": "sub"}
Sep 5, 2014
642
for(var $op in $ops){
Mar 10, 2018
643
var opf = $op_func.replace(/-/gm, $op)
644
opf = opf.replace(new RegExp("sub", "gm"), $ops[$op])
645
eval("int.__" + $ops[$op] + "__ = " + opf)
Sep 5, 2014
646
}
647
648
// comparison methods
Mar 10, 2018
649
var $comp_func = function(self, other){
Mar 23, 2018
650
if(other.__class__ === $B.long_int){
Feb 11, 2018
651
return $B.long_int.__lt__(other, $B.long_int.$factory(self))
653
if(_b_.isinstance(other, int)){
654
other = int_value(other)
655
return self.valueOf() > other.valueOf()
656
}else if(_b_.isinstance(other, _b_.float)){
657
return self.valueOf() > _b_.float.numerator(other)
658
}else if(_b_.isinstance(other, _b_.bool)) {
Feb 11, 2018
659
return self.valueOf() > _b_.bool.__hash__(other)
Sep 5, 2014
660
}
661
if(_b_.hasattr(other, "__int__") || _b_.hasattr(other, "__index__")){
662
return int.__gt__(self, $B.$GetInt(other))
Sep 5, 2014
666
}
Mar 10, 2018
667
$comp_func += "" // source code
Sep 5, 2014
669
for(var $op in $B.$comps){
Mar 10, 2018
670
eval("int.__"+$B.$comps[$op] + "__ = " +
671
$comp_func.replace(/>/gm, $op).
672
replace(/__gt__/gm,"__" + $B.$comps[$op] + "__").
673
replace(/__lt__/, "__" + $B.$inv_comps[$op] + "__"))
Sep 5, 2014
674
}
675
676
// add "reflected" methods
677
$B.make_rmethods(int)
Sep 5, 2014
678
Mar 10, 2018
679
var $valid_digits = function(base) {
680
var digits = ""
681
if(base === 0){return "0"}
682
if(base < 10){
Mar 21, 2018
683
for(var i = 0; i < base; i++){digits += String.fromCharCode(i + 48)}
Sep 5, 2014
684
return digits
685
}
686
Mar 10, 2018
687
var digits = "0123456789"
Sep 5, 2014
688
// A = 65 (10 + 55)
Mar 21, 2018
689
for (var i = 10; i < base; i++) {digits += String.fromCharCode(i + 55)}
Sep 5, 2014
690
return digits
691
}
692
693
int.$factory = function(value, base){
694
// int() with no argument returns 0
Mar 10, 2018
695
if(value === undefined){return 0}
697
// int() of an integer returns the integer if base is undefined
Mar 10, 2018
698
if(typeof value == "number" &&
699
(base === undefined || base == 10)){return parseInt(value)}
701
if(_b_.isinstance(value, _b_.complex)){
702
throw _b_.TypeError.$factory("can't convert complex to int")
Dec 28, 2014
703
}
Mar 10, 2018
705
var $ns = $B.args("int", 2, {x:null, base:null}, ["x", "base"], arguments,
706
{"base": 10}, null, null),
707
value = $ns["x"],
708
base = $ns["base"]
710
if(_b_.isinstance(value, _b_.float) && base == 10){
711
value = _b_.float.numerator(value) // for float subclasses
Mar 10, 2018
712
if(value < $B.min_int || value > $B.max_int){
Feb 11, 2018
713
return $B.long_int.$from_float(value)
715
else{
716
return value > 0 ? Math.floor(value) : Math.ceil(value)
717
}
Sep 5, 2014
719
Mar 10, 2018
720
if(! (base >=2 && base <= 36)){
Dec 26, 2014
721
// throw error (base must be 0, or 2-36)
722
if(base != 0){
723
throw _b_.ValueError.$factory("invalid base")
724
}
Dec 26, 2014
725
}
726
Mar 10, 2018
727
if(typeof value == "number"){
Mar 10, 2018
729
if(base == 10){
730
if(value < $B.min_int || value > $B.max_int){
731
return $B.long_int.$factory(value)
732
}
Mar 10, 2018
734
}else if(value.toString().search("e") > -1){
Dec 26, 2014
735
// can't convert to another base if value is too big
Mar 10, 2018
736
throw _b_.OverflowError.$factory("can't convert to base " + base)
Dec 26, 2014
737
}else{
Mar 10, 2018
738
var res = parseInt(value, base)
739
if(value < $B.min_int || value > $B.max_int){
740
return $B.long_int.$factory(value, base)
741
}
Dec 26, 2014
743
}
744
}
Sep 5, 2014
745
Mar 10, 2018
746
if(value === true){return Number(1)}
747
if(value === false){return Number(0)}
748
if(value.__class__ === $B.long_int){
749
var z = parseInt(value.value)
Mar 10, 2018
750
if(z > $B.min_int && z < $B.max_int){return z}
751
else{return value}
752
}
Sep 5, 2014
753
Mar 10, 2018
754
base = $B.$GetInt(base)
755
function invalid(value, base){
756
throw _b_.ValueError.$factory("invalid literal for int() with base " +
757
base + ": '" + _b_.str.$factory(value) + "'")
758
}
Sep 5, 2014
759
760
if(_b_.isinstance(value, _b_.str)){
761
value = value.valueOf()
762
}
Mar 10, 2018
763
if(typeof value == "string") {
764
var _value = value.trim() // remove leading/trailing whitespace
765
if(_value.length == 2 && base == 0 &&
766
(_value == "0b" || _value == "0o" || _value == "0x")){
767
throw _b_.ValueError.$factory("invalid value")
768
}
769
if(_value.length > 2) {
Mar 10, 2018
770
var _pre = _value.substr(0, 2).toUpperCase()
771
if(base == 0){
772
if(_pre == "0B"){base = 2}
773
if(_pre == "0O"){base = 8}
774
if(_pre == "0X"){base = 16}
775
}else if(_pre == "0X" && base != 16){invalid(_value, base)}
776
else if(_pre == "0O" && base != 8){invalid(_value, base)}
777
if((_pre == "0B" && base == 2) || _pre == "0O" || _pre == "0X"){
Mar 10, 2018
778
_value = _value.substr(2)
779
while(_value.startsWith("_")){
780
_value = _value.substr(1)
781
}
Mar 10, 2018
782
}
783
}else if(base == 0){
784
// eg int("1\n", 0)
785
base = 10
Mar 10, 2018
786
}
787
var _digits = $valid_digits(base),
788
_re = new RegExp("^[+-]?[" + _digits + "]" +
789
"[" + _digits + "_]*$", "i"),
790
match = _re.exec(_value)
791
if(match === null){
792
invalid(value, base)
793
}else{
794
value = _value.replace(/_/g, "")
Mar 10, 2018
795
}
796
if(base <= 10 && ! isFinite(value)){
797
invalid(_value, base)
798
}
799
var res = parseInt(value, base)
Mar 10, 2018
800
if(res < $B.min_int || res > $B.max_int){
801
return $B.long_int.$factory(value, base)
Mar 10, 2018
802
}
803
return res
Sep 5, 2014
804
}
806
if(_b_.isinstance(value, [_b_.bytes, _b_.bytearray])){
807
return int.$factory($B.$getattr(value, "decode")("latin-1"), base)
808
}
810
for(var special_method of ["__int__", "__index__", "__trunc__"]){
811
var num_value = $B.$getattr(value.__class__ || $B.get_class(value),
813
if(num_value !== _b_.None){
814
return $B.$call(num_value)(value)
817
throw _b_.TypeError.$factory(
818
"int() argument must be a string, a bytes-like " +
819
"object or a number, not '" + $B.class_name(value) + "'")
Sep 5, 2014
820
}
821
822
$B.set_func_names(int, "builtins")
Sep 5, 2014
824
_b_.int = int
825
Feb 11, 2018
827
$B.$bool = function(obj){ // return true or false
Mar 10, 2018
828
if(obj === null || obj === undefined ){ return false}
829
switch(typeof obj){
830
case "boolean":
831
return obj
832
case "number":
833
case "string":
834
if(obj){return true}
835
return false
836
default:
837
if(obj.$is_class){return true}
838
var klass = obj.__class__ || $B.get_class(obj),
839
missing = {},
840
bool_method = $B.$getattr(klass, "__bool__", missing)
841
if(bool_method === missing){
842
try{return _b_.len(obj) > 0}
Mar 10, 2018
843
catch(err){return true}
845
var res = $B.$call(bool_method)(obj)
846
if(res !== true && res !== false){
847
throw _b_.TypeError.$factory("__bool__ should return " +
848
"bool, returned " + $B.class_name(res))
849
}
850
return res
Mar 10, 2018
851
}
852
}
Feb 11, 2018
853
}
854
855
var bool = {
856
__bases__: [int],
Feb 11, 2018
857
__class__: _b_.type,
858
__mro__: [int, _b_.object],
859
$infos:{
860
__name__: "bool",
861
__module__: "builtins"
862
},
Feb 11, 2018
863
$is_class: true,
864
$native: true
865
}
Feb 22, 2019
867
var methods = $B.op2method.subset("operations", "binary", "comparisons",
868
"boolean")
Feb 22, 2019
870
for(var op in methods){
871
var method = "__" + methods[op] + "__"
872
bool[method] = (function(op){
873
return function(self, other){
874
var value = self ? 1 : 0
875
if(int[op] !== undefined){
876
return int[op](value, other)
877
}
878
}
879
})(method)
Feb 11, 2018
882
bool.__and__ = function(self, other){
883
if(_b_.isinstance(other, bool)){
884
return self && other
885
}else if(_b_.isinstance(other, int)){
886
return int.__and__(bool.__index__(self), int.__index__(other))
887
}
888
return _b_.NotImplemented
891
bool.__float__ = function(self){
892
return self ? new Number(1) : new Number(0)
893
}
894
Mar 10, 2018
895
bool.__hash__ = bool.__index__ = bool.__int__ = function(self){
896
if(self.valueOf()) return 1
897
return 0
898
}
899
Feb 11, 2018
900
bool.__neg__ = function(self){return -$B.int_or_bool(self)}
Feb 11, 2018
902
bool.__or__ = function(self, other){
903
if(_b_.isinstance(other, bool)){
904
return self || other
905
}else if(_b_.isinstance(other, int)){
906
return int.__or__(bool.__index__(self), int.__index__(other))
907
}
908
return _b_.NotImplemented
Feb 11, 2018
911
bool.__pos__ = $B.int_or_bool
Feb 11, 2018
913
bool.__repr__ = bool.__str__ = function(self){
914
return self ? "True" : "False"
Feb 11, 2018
917
bool.__setattr__ = function(self, attr){
918
if(_b_.dir(self).indexOf(attr) > -1){
919
var msg = "attribute '" + attr + "' of 'int' objects is not writable"
920
}else{
921
var msg = "'bool' object has no attribute '" + attr + "'"
922
}
923
throw _b_.AttributeError.$factory(msg)
Feb 11, 2018
926
bool.__xor__ = function(self, other) {
927
if(_b_.isinstance(other, bool)){
928
return self ^ other ? true : false
929
}else if(_b_.isinstance(other, int)){
930
return int.__xor__(bool.__index__(self), int.__index__(other))
931
}
932
return _b_.NotImplemented
Feb 11, 2018
935
bool.$factory = function(){
936
// Calls $B.$bool, which is used inside the generated JS code and skips
937
// arguments control.
Mar 10, 2018
938
var $ = $B.args("bool", 1, {x: null}, ["x"],
939
arguments,{x: false}, null, null)
Feb 11, 2018
940
return $B.$bool($.x)
941
}
942
943
_b_.bool = bool
Feb 11, 2018
945
$B.set_func_names(bool, "builtins")
Sep 5, 2014
947
})(__BRYTHON__)