Skip to content
Permalink
Newer
Older
100644 950 lines (857 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){
438
return other > 0 ? res : new Number(res)
439
}else if(res !== Infinity && !isFinite(res)){
440
return res
441
}else{
442
if($B.BigInt){
443
return {
444
__class__: $B.long_int,
445
value: ($B.BigInt(self) ** $B.BigInt(other)).toString(),
446
pos: true
447
}
448
}
449
return $B.long_int.__pow__($B.long_int.$from_int(self),
450
$B.long_int.$from_int(other))
May 19, 2017
451
}
Sep 5, 2014
452
}
453
if(_b_.isinstance(other, _b_.float)) {
454
other = _b_.float.numerator(other)
455
if(self >= 0){
456
return new Number(Math.pow(self, other))
457
}else{
459
return _b_.complex.__pow__($B.make_complex(self, 0), other)
461
}else if(_b_.isinstance(other, _b_.complex)){
Mar 10, 2018
462
var preal = Math.pow(self, other.$real),
463
ln = Math.log(self)
Mar 10, 2018
464
return $B.make_complex(preal * Math.cos(ln), preal * Math.sin(ln))
Sep 5, 2014
465
}
466
var rpow = $B.$getattr(other, "__rpow__", _b_.None)
467
if(rpow !== _b_.None){
468
return rpow(self)
469
}
Mar 10, 2018
470
$err("**", other)
Sep 5, 2014
471
}
472
473
function __newobj__(){
474
// __newobj__ is called with a generator as only argument
475
var $ = $B.args('__newobj__', 0, {}, [], arguments, {}, 'args', null),
476
args = $.args
477
var res = args.slice(1)
478
res.__class__ = args[0]
479
return res
480
}
481
482
int.__reduce_ex__ = function(self){
483
return $B.fast_tuple([
484
__newobj__,
485
$B.fast_tuple([self.__class__ || int, int_value(self)]),
486
_b_.None,
487
_b_.None,
488
_b_.None])
489
}
490
491
int.__repr__ = function(self){
492
return int_value(self).toString()
Sep 5, 2014
493
}
494
495
// bitwise right shift
Mar 10, 2018
496
int.__rshift__ = function(self, other){
497
if(_b_.isinstance(other, int)){
Feb 11, 2018
499
return int.$factory($B.long_int.__rshift__($B.long_int.$factory(self),
500
$B.long_int.$factory(other)))
502
var rrshift = $B.$getattr(other, "__rrshift__", _b_.None)
503
if(rrshift !== _b_.None){return rrshift(self)}
504
$err('>>', other)
505
}
Sep 5, 2014
506
507
int.__setattr__ = function(self, attr, value){
Mar 10, 2018
508
if(typeof self == "number"){
509
if(int.$factory[attr] === undefined){
510
throw _b_.AttributeError.$factory(
511
"'int' object has no attribute '" + attr + "'")
Mar 10, 2018
513
throw _b_.AttributeError.$factory(
514
"'int' object attribute '" + attr + "' is read-only")
Sep 5, 2014
516
}
517
// subclasses of int can have attributes set
518
_b_.dict.$setitem(self.__dict__, attr, value)
519
return _b_.None
Sep 5, 2014
520
}
521
522
int.__str__ = int.__repr__
Sep 5, 2014
523
Mar 10, 2018
524
int.__truediv__ = function(self, other){
525
if(_b_.isinstance(other, int)){
527
if(other == 0){
528
throw _b_.ZeroDivisionError.$factory("division by zero")
529
}
Mar 10, 2018
530
if(other.__class__ === $B.long_int){
531
return new Number(self / parseInt(other.value))
532
}
533
return new Number(self / other)
Sep 5, 2014
534
}
535
if(_b_.isinstance(other, _b_.float)){
536
other = _b_.float.numerator(other)
Mar 10, 2018
537
if(!other.valueOf()){
538
throw _b_.ZeroDivisionError.$factory("division by zero")
Mar 10, 2018
539
}
540
return new Number(self / other)
Sep 5, 2014
541
}
542
if(_b_.isinstance(other, _b_.complex)){
Mar 10, 2018
543
var cmod = other.$real * other.$real + other.$imag * other.$imag
544
if(cmod == 0){throw _b_.ZeroDivisionError.$factory("division by zero")}
Mar 10, 2018
545
return $B.make_complex(self * other.$real / cmod,
546
-self * other.$imag / cmod)
Sep 5, 2014
547
}
548
if(_b_.hasattr(other, "__rtruediv__")){
549
return $B.$getattr(other, "__rtruediv__")(self)
Mar 10, 2018
550
}
551
$err("/", other)
Sep 5, 2014
552
}
553
554
int.bit_length = function(self){
555
s = _b_.bin(self)
556
s = $B.$getattr(s, "lstrip")("-0b") // remove leading zeros and minus sign
Sep 5, 2014
557
return s.length // len('100101') --> 6
558
}
559
560
// descriptors
561
int.numerator = function(self){return self}
562
int.denominator = function(self){return int.$factory(1)}
563
int.imag = function(self){return int.$factory(0)}
564
int.real = function(self){return self}
565
Mar 10, 2018
566
$B.max_int32 = (1 << 30) * 2 - 1
567
$B.min_int32 = - $B.max_int32
569
// code for operands & | ^
Mar 10, 2018
570
var $op_func = function(self, other){
571
if(_b_.isinstance(other, int)) {
Mar 10, 2018
572
if(other.__class__ === $B.long_int){
573
return $B.long_int.__sub__($B.long_int.$factory(self),
574
$B.long_int.$factory(other))
Mar 23, 2018
577
if(self > $B.max_int32 || self < $B.min_int32 ||
578
other > $B.max_int32 || other < $B.min_int32){
Mar 10, 2018
579
return $B.long_int.__sub__($B.long_int.$factory(self),
580
$B.long_int.$factory(other))
Mar 21, 2018
582
return self - other
Jun 7, 2015
583
}
584
if(_b_.isinstance(other, _b_.bool)){
585
return self - other
586
}
587
var rsub = $B.$getattr(other, "__rsub__", _b_.None)
588
if(rsub !== _b_.None){
589
return rsub(self)
590
}
Mar 10, 2018
591
$err("-", other)
Sep 5, 2014
592
}
593
Mar 10, 2018
594
$op_func += "" // source code
595
var $ops = {"&": "and", "|": "or", "^": "xor"}
Sep 5, 2014
596
for(var $op in $ops){
Mar 10, 2018
597
var opf = $op_func.replace(/-/gm, $op)
598
opf = opf.replace(new RegExp("sub", "gm"), $ops[$op])
599
eval("int.__" + $ops[$op] + "__ = " + opf)
Sep 5, 2014
600
}
601
602
// code for + and -
Mar 10, 2018
603
var $op_func = function(self, other){
604
if(_b_.isinstance(other, int)){
Mar 10, 2018
606
if(typeof other == "number"){
607
var res = self.valueOf() - other.valueOf()
608
if(res > $B.min_int && res < $B.max_int){return res}
Feb 11, 2018
609
else{return $B.long_int.__sub__($B.long_int.$factory(self),
610
$B.long_int.$factory(other))}
Mar 10, 2018
611
}else if(typeof other == "boolean"){
Mar 21, 2018
612
return other ? self - 1 : self
613
}else{
Feb 11, 2018
614
return $B.long_int.__sub__($B.long_int.$factory(self),
615
$B.long_int.$factory(other))
Sep 5, 2014
617
}
618
if(_b_.isinstance(other, _b_.float)){
619
return new Number(self - _b_.float.numerator(other))
Sep 5, 2014
620
}
621
if(_b_.isinstance(other, _b_.complex)){
622
if(other.$imag == 0){
623
// 1 - 0.0j is complex(1, 0.0) : the imaginary part is 0.0,
624
// *not* -0.0 (cf. https://bugs.python.org/issue22548)
625
return $B.make_complex(self - other.$real, 0)
626
}
Mar 10, 2018
627
return $B.make_complex(self - other.$real, -other.$imag)
Sep 5, 2014
628
}
629
if(_b_.isinstance(other, _b_.bool)){
Mar 10, 2018
630
var bool_value = 0;
631
if(other.valueOf()){bool_value = 1}
632
return self - bool_value
Sep 5, 2014
633
}
634
if(_b_.isinstance(other, _b_.complex)){
635
return $B.make_complex(self.valueOf() - other.$real, other.$imag)
Sep 5, 2014
636
}
637
var rsub = $B.$getattr(other, "__rsub__", _b_.None)
638
if(rsub !== _b_.None){return rsub(self)}
639
//console.log("err", self, other)
640
//console.log($B.frames_stack.slice())
Mar 10, 2018
641
throw $err("-", other)
Sep 5, 2014
642
}
Mar 10, 2018
643
$op_func += "" // source code
644
var $ops = {"+": "add", "-": "sub"}
Sep 5, 2014
645
for(var $op in $ops){
Mar 10, 2018
646
var opf = $op_func.replace(/-/gm, $op)
647
opf = opf.replace(new RegExp("sub", "gm"), $ops[$op])
648
eval("int.__" + $ops[$op] + "__ = " + opf)
Sep 5, 2014
649
}
650
651
// comparison methods
Mar 10, 2018
652
var $comp_func = function(self, other){
Mar 23, 2018
653
if(other.__class__ === $B.long_int){
Feb 11, 2018
654
return $B.long_int.__lt__(other, $B.long_int.$factory(self))
656
if(_b_.isinstance(other, int)){
657
other = int_value(other)
658
return self.valueOf() > other.valueOf()
659
}else if(_b_.isinstance(other, _b_.float)){
660
return self.valueOf() > _b_.float.numerator(other)
661
}else if(_b_.isinstance(other, _b_.bool)) {
Feb 11, 2018
662
return self.valueOf() > _b_.bool.__hash__(other)
Sep 5, 2014
663
}
664
if(_b_.hasattr(other, "__int__") || _b_.hasattr(other, "__index__")){
665
return int.__gt__(self, $B.$GetInt(other))
Sep 5, 2014
669
}
Mar 10, 2018
670
$comp_func += "" // source code
Sep 5, 2014
672
for(var $op in $B.$comps){
Mar 10, 2018
673
eval("int.__"+$B.$comps[$op] + "__ = " +
674
$comp_func.replace(/>/gm, $op).
675
replace(/__gt__/gm,"__" + $B.$comps[$op] + "__").
676
replace(/__lt__/, "__" + $B.$inv_comps[$op] + "__"))
Sep 5, 2014
677
}
678
679
// add "reflected" methods
680
$B.make_rmethods(int)
Sep 5, 2014
681
Mar 10, 2018
682
var $valid_digits = function(base) {
683
var digits = ""
684
if(base === 0){return "0"}
685
if(base < 10){
Mar 21, 2018
686
for(var i = 0; i < base; i++){digits += String.fromCharCode(i + 48)}
Sep 5, 2014
687
return digits
688
}
689
Mar 10, 2018
690
var digits = "0123456789"
Sep 5, 2014
691
// A = 65 (10 + 55)
Mar 21, 2018
692
for (var i = 10; i < base; i++) {digits += String.fromCharCode(i + 55)}
Sep 5, 2014
693
return digits
694
}
695
696
int.$factory = function(value, base){
697
// int() with no argument returns 0
Mar 10, 2018
698
if(value === undefined){return 0}
700
// int() of an integer returns the integer if base is undefined
Mar 10, 2018
701
if(typeof value == "number" &&
702
(base === undefined || base == 10)){return parseInt(value)}
704
if(_b_.isinstance(value, _b_.complex)){
705
throw _b_.TypeError.$factory("can't convert complex to int")
Dec 28, 2014
706
}
Mar 10, 2018
708
var $ns = $B.args("int", 2, {x:null, base:null}, ["x", "base"], arguments,
709
{"base": 10}, null, null),
710
value = $ns["x"],
711
base = $ns["base"]
713
if(_b_.isinstance(value, _b_.float) && base == 10){
714
value = _b_.float.numerator(value) // for float subclasses
Mar 10, 2018
715
if(value < $B.min_int || value > $B.max_int){
Feb 11, 2018
716
return $B.long_int.$from_float(value)
718
else{
719
return value > 0 ? Math.floor(value) : Math.ceil(value)
720
}
Sep 5, 2014
722
Mar 10, 2018
723
if(! (base >=2 && base <= 36)){
Dec 26, 2014
724
// throw error (base must be 0, or 2-36)
725
if(base != 0){
726
throw _b_.ValueError.$factory("invalid base")
727
}
Dec 26, 2014
728
}
729
Mar 10, 2018
730
if(typeof value == "number"){
Mar 10, 2018
732
if(base == 10){
733
if(value < $B.min_int || value > $B.max_int){
734
return $B.long_int.$factory(value)
735
}
Mar 10, 2018
737
}else if(value.toString().search("e") > -1){
Dec 26, 2014
738
// can't convert to another base if value is too big
Mar 10, 2018
739
throw _b_.OverflowError.$factory("can't convert to base " + base)
Dec 26, 2014
740
}else{
Mar 10, 2018
741
var res = parseInt(value, base)
742
if(value < $B.min_int || value > $B.max_int){
743
return $B.long_int.$factory(value, base)
744
}
Dec 26, 2014
746
}
747
}
Sep 5, 2014
748
Mar 10, 2018
749
if(value === true){return Number(1)}
750
if(value === false){return Number(0)}
751
if(value.__class__ === $B.long_int){
752
var z = parseInt(value.value)
Mar 10, 2018
753
if(z > $B.min_int && z < $B.max_int){return z}
754
else{return value}
755
}
Sep 5, 2014
756
Mar 10, 2018
757
base = $B.$GetInt(base)
758
function invalid(value, base){
759
throw _b_.ValueError.$factory("invalid literal for int() with base " +
760
base + ": '" + _b_.str.$factory(value) + "'")
761
}
Sep 5, 2014
762
763
if(_b_.isinstance(value, _b_.str)){
764
value = value.valueOf()
765
}
Mar 10, 2018
766
if(typeof value == "string") {
767
var _value = value.trim() // remove leading/trailing whitespace
768
if(_value.length == 2 && base == 0 &&
769
(_value == "0b" || _value == "0o" || _value == "0x")){
770
throw _b_.ValueError.$factory("invalid value")
771
}
772
if(_value.length > 2) {
Mar 10, 2018
773
var _pre = _value.substr(0, 2).toUpperCase()
774
if(base == 0){
775
if(_pre == "0B"){base = 2}
776
if(_pre == "0O"){base = 8}
777
if(_pre == "0X"){base = 16}
778
}else if(_pre == "0X" && base != 16){invalid(_value, base)}
779
else if(_pre == "0O" && base != 8){invalid(_value, base)}
780
if((_pre == "0B" && base == 2) || _pre == "0O" || _pre == "0X"){
Mar 10, 2018
781
_value = _value.substr(2)
782
while(_value.startsWith("_")){
783
_value = _value.substr(1)
784
}
Mar 10, 2018
785
}
786
}else if(base == 0){
787
// eg int("1\n", 0)
788
base = 10
Mar 10, 2018
789
}
790
var _digits = $valid_digits(base),
791
_re = new RegExp("^[+-]?[" + _digits + "]" +
792
"[" + _digits + "_]*$", "i"),
793
match = _re.exec(_value)
794
if(match === null){
795
invalid(value, base)
796
}else{
797
value = _value.replace(/_/g, "")
Mar 10, 2018
798
}
799
if(base <= 10 && ! isFinite(value)){
800
invalid(_value, base)
801
}
802
var res = parseInt(value, base)
Mar 10, 2018
803
if(res < $B.min_int || res > $B.max_int){
804
return $B.long_int.$factory(value, base)
Mar 10, 2018
805
}
806
return res
Sep 5, 2014
807
}
809
if(_b_.isinstance(value, [_b_.bytes, _b_.bytearray])){
810
return int.$factory($B.$getattr(value, "decode")("latin-1"), base)
811
}
813
for(var special_method of ["__int__", "__index__", "__trunc__"]){
814
var num_value = $B.$getattr(value.__class__ || $B.get_class(value),
816
if(num_value !== _b_.None){
817
return $B.$call(num_value)(value)
820
throw _b_.TypeError.$factory(
821
"int() argument must be a string, a bytes-like " +
822
"object or a number, not '" + $B.class_name(value) + "'")
Sep 5, 2014
823
}
824
825
$B.set_func_names(int, "builtins")
Sep 5, 2014
827
_b_.int = int
828
Feb 11, 2018
830
$B.$bool = function(obj){ // return true or false
Mar 10, 2018
831
if(obj === null || obj === undefined ){ return false}
832
switch(typeof obj){
833
case "boolean":
834
return obj
835
case "number":
836
case "string":
837
if(obj){return true}
838
return false
839
default:
840
if(obj.$is_class){return true}
841
var klass = obj.__class__ || $B.get_class(obj),
842
missing = {},
843
bool_method = $B.$getattr(klass, "__bool__", missing)
844
if(bool_method === missing){
845
try{return _b_.len(obj) > 0}
Mar 10, 2018
846
catch(err){return true}
848
var res = $B.$call(bool_method)(obj)
849
if(res !== true && res !== false){
850
throw _b_.TypeError.$factory("__bool__ should return " +
851
"bool, returned " + $B.class_name(res))
852
}
853
return res
Mar 10, 2018
854
}
855
}
Feb 11, 2018
856
}
857
858
var bool = {
859
__bases__: [int],
Feb 11, 2018
860
__class__: _b_.type,
861
__mro__: [int, _b_.object],
862
$infos:{
863
__name__: "bool",
864
__module__: "builtins"
865
},
Feb 11, 2018
866
$is_class: true,
867
$native: true
868
}
Feb 22, 2019
870
var methods = $B.op2method.subset("operations", "binary", "comparisons",
871
"boolean")
Feb 22, 2019
873
for(var op in methods){
874
var method = "__" + methods[op] + "__"
875
bool[method] = (function(op){
876
return function(self, other){
877
var value = self ? 1 : 0
878
if(int[op] !== undefined){
879
return int[op](value, other)
880
}
881
}
882
})(method)
Feb 11, 2018
885
bool.__and__ = function(self, other){
886
if(_b_.isinstance(other, bool)){
887
return self && other
888
}else if(_b_.isinstance(other, int)){
889
return int.__and__(bool.__index__(self), int.__index__(other))
890
}
891
return _b_.NotImplemented
894
bool.__float__ = function(self){
895
return self ? new Number(1) : new Number(0)
896
}
897
Mar 10, 2018
898
bool.__hash__ = bool.__index__ = bool.__int__ = function(self){
899
if(self.valueOf()) return 1
900
return 0
901
}
902
Feb 11, 2018
903
bool.__neg__ = function(self){return -$B.int_or_bool(self)}
Feb 11, 2018
905
bool.__or__ = function(self, other){
906
if(_b_.isinstance(other, bool)){
907
return self || other
908
}else if(_b_.isinstance(other, int)){
909
return int.__or__(bool.__index__(self), int.__index__(other))
910
}
911
return _b_.NotImplemented
Feb 11, 2018
914
bool.__pos__ = $B.int_or_bool
Feb 11, 2018
916
bool.__repr__ = bool.__str__ = function(self){
917
return self ? "True" : "False"
Feb 11, 2018
920
bool.__setattr__ = function(self, attr){
921
if(_b_.dir(self).indexOf(attr) > -1){
922
var msg = "attribute '" + attr + "' of 'int' objects is not writable"
923
}else{
924
var msg = "'bool' object has no attribute '" + attr + "'"
925
}
926
throw _b_.AttributeError.$factory(msg)
Feb 11, 2018
929
bool.__xor__ = function(self, other) {
930
if(_b_.isinstance(other, bool)){
931
return self ^ other ? true : false
932
}else if(_b_.isinstance(other, int)){
933
return int.__xor__(bool.__index__(self), int.__index__(other))
934
}
935
return _b_.NotImplemented
Feb 11, 2018
938
bool.$factory = function(){
939
// Calls $B.$bool, which is used inside the generated JS code and skips
940
// arguments control.
Mar 10, 2018
941
var $ = $B.args("bool", 1, {x: null}, ["x"],
942
arguments,{x: false}, null, null)
Feb 11, 2018
943
return $B.$bool($.x)
944
}
945
946
_b_.bool = bool
Feb 11, 2018
948
$B.set_func_names(bool, "builtins")
Sep 5, 2014
950
})(__BRYTHON__)