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