Skip to content
Permalink
Newer
Older
100644 927 lines (837 sloc) 27.1 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
if(typeof obj == "boolean"){
15
return obj ? 1 : 0
16
}
17
return obj.$brython_value !== undefined ? obj.$brython_value : obj
20
// dictionary for built-in class 'int'
21
var int = {
22
__class__: _b_.type,
23
__dir__: _b_.object.__dir__,
25
$infos: {
26
__module__: "builtins",
27
__name__: "int"
28
},
29
$is_class: true,
30
$native: true,
31
$descriptors: {
Mar 10, 2018
32
"numerator": true,
33
"denominator": true,
34
"imag": true,
35
"real": true
Sep 5, 2014
37
}
38
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
45
int.from_bytes = function() {
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)
Sep 5, 2014
87
}
88
89
int.to_bytes = function(){
90
var $ = $B.args("to_bytes", 3,
91
{self: null, len: null, byteorder: null, signed: null},
92
["self", "len", "byteorder", "*", "signed"],
93
arguments, {signed: false}, null, null),
94
self = $.self,
95
len = $.len,
96
byteorder = $.byteorder,
97
signed = $.signed
98
if(! _b_.isinstance(len, _b_.int)){
99
throw _b_.TypeError.$factory("integer argument expected, got " +
101
}
102
if(["little", "big"].indexOf(byteorder) == -1){
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)
109
}
110
111
if(self < 0){
112
if(! signed){
113
throw _b_.OverflowError.$factory(
114
"can't convert negative int to unsigned")
115
}
116
self = Math.pow(256, len) + self
117
}
118
119
var res = [],
120
value = self
121
122
while(value > 0){
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")
128
}
129
value = quotient
130
}
131
while(res.length < len){
132
res.push(0)
133
}
134
if(byteorder == "big"){
135
res.reverse()
136
}
137
return {
138
__class__: _b_.bytes,
139
source: res
140
}
Sep 5, 2014
141
}
142
143
int.__abs__ = function(self){return _b_.abs(self)}
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
}
Sep 5, 2014
167
168
int.__ceil__ = function(self){return Math.ceil(int_value(self))}
170
int.__divmod__ = function(self, other){
171
if(! _b_.isinstance(other, int)){
172
return _b_.NotImplemented
173
}
174
return $B.fast_tuple([int.__floordiv__(self, other),
175
int.__mod__(self, other)])
176
}
Mar 10, 2018
178
int.__eq__ = function(self, other){
Sep 5, 2014
179
// compare object "self" to class "int"
180
if(_b_.isinstance(other, int)){
181
return self.valueOf() == int_value(other).valueOf()
182
}
183
if(_b_.isinstance(other, _b_.float)){
184
return self.valueOf() == other.valueOf()
185
}
186
if(_b_.isinstance(other, _b_.complex)){
187
if(other.$imag != 0){return _b_.False}
Mar 10, 2018
188
return self.valueOf() == other.$real
Sep 5, 2014
189
}
190
return _b_.NotImplemented
Sep 5, 2014
191
}
192
193
int.__float__ = function(self){
194
return new Number(self)
195
}
196
197
function preformat(self, fmt){
str
Feb 10, 2018
198
if(fmt.empty){return _b_.str.$factory(self)}
Mar 10, 2018
199
if(fmt.type && 'bcdoxXn'.indexOf(fmt.type) == -1){
200
throw _b_.ValueError.$factory("Unknown format code '" + fmt.type +
201
"' for object of type 'int'")
202
}
204
switch(fmt.type){
205
case undefined:
Mar 10, 2018
206
case "d":
207
res = self.toString()
208
break
Mar 10, 2018
209
case "b":
210
res = (fmt.alternate ? "0b" : "") + self.toString(2)
211
break
Mar 10, 2018
212
case "c":
213
res = _b_.chr(self)
214
break
Mar 10, 2018
215
case "o":
216
res = (fmt.alternate ? "0o" : "") + self.toString(8)
217
break
Mar 10, 2018
218
case "x":
219
res = (fmt.alternate ? "0x" : "") + self.toString(16)
220
break
Mar 10, 2018
221
case "X":
222
res = (fmt.alternate ? "0X" : "") + self.toString(16).toUpperCase()
223
break
Mar 10, 2018
224
case "n":
225
return self // fix me
226
}
228
if(fmt.sign !== undefined){
229
if((fmt.sign == " " || fmt.sign == "+" ) && self >= 0){
230
res = fmt.sign + res
231
}
232
}
233
return res
234
}
235
236
Mar 10, 2018
237
int.__format__ = function(self, format_spec){
238
var fmt = new $B.parse_format_spec(format_spec)
Mar 10, 2018
239
if(fmt.type && 'eEfFgG%'.indexOf(fmt.type) != -1){
240
// Call __format__ on float(self)
241
return _b_.float.__format__(self, format_spec)
Mar 10, 2018
243
fmt.align = fmt.align || ">"
244
var res = preformat(self, fmt)
245
if(fmt.comma){
Mar 10, 2018
246
var sign = res[0] == "-" ? "-" : "",
247
rest = res.substr(sign.length),
248
len = rest.length,
249
nb = Math.ceil(rest.length/3),
250
chunks = []
Mar 10, 2018
251
for(var i = 0; i < nb; i++){
252
chunks.push(rest.substring(len - 3 * i - 3, len - 3 * i))
253
}
254
chunks.reverse()
Mar 10, 2018
255
res = sign + chunks.join(",")
256
}
257
return $B.format_width(res, fmt)
Sep 5, 2014
258
}
259
260
int.__floordiv__ = function(self, other){
261
if(other.__class__ === $B.long_int){
262
return $B.long_int.__floordiv__($B.long_int.$factory(self), other)
263
}
264
if(_b_.isinstance(other, int)){
266
if(other == 0){throw _b_.ZeroDivisionError.$factory("division by zero")}
Mar 10, 2018
267
return Math.floor(self / other)
Sep 5, 2014
268
}
Sep 5, 2014
270
}
271
272
int.__hash__ = function(self){
273
if(self.$brython_value){
274
// int subclass
275
var hash_method = $B.$getattr(self.__class__, '__hash__')
276
if(hash_method === int.__hash__){
277
if(typeof self.$brython_value == "number"){
278
return self.$brython_value
279
}else{ // long int
280
return $B.long_int.__hash__(self.$brython_value)
281
}
282
}else{
283
return hash_method(self)
284
}
285
}
286
return self.valueOf()
Sep 5, 2014
288
289
//int.__ior__ = function(self,other){return self | other} // bitwise OR
Sep 5, 2014
290
291
int.__index__ = function(self){
292
return int_value(self)
293
}
Sep 5, 2014
294
295
int.__init__ = function(self, value){
Mar 10, 2018
296
if(value === undefined){value = 0}
Sep 5, 2014
297
self.toString = function(){return value}
298
return _b_.None
Sep 5, 2014
299
}
300
301
int.__int__ = function(self){return self}
Sep 5, 2014
302
303
int.__invert__ = function(self){return ~self}
Sep 5, 2014
304
Mar 10, 2018
306
int.__lshift__ = function(self, other){
308
if(_b_.isinstance(other, int)){
310
try{
311
return int.$factory($B.long_int.__lshift__($B.long_int.$factory(self),
312
$B.long_int.$factory(other)))
313
}catch(err){
314
console.log('err in lshift', self, other)
315
throw err
316
}
Mar 10, 2018
321
int.__mod__ = function(self, other) {
Sep 5, 2014
322
// can't use Javascript % because it works differently for negative numbers
323
if(_b_.isinstance(other,_b_.tuple) && other.length == 1){other = other[0]}
324
if(other.__class__ === $B.long_int){
325
return $B.long_int.__mod__($B.long_int.$factory(self), other)
326
}
Mar 10, 2018
329
if(other === false){other = 0}
330
else if(other === true){other = 1}
331
if(other == 0){throw _b_.ZeroDivisionError.$factory(
332
"integer division or modulo by zero")}
Mar 10, 2018
333
return (self % other + other) % other
Sep 5, 2014
334
}
Sep 5, 2014
336
}
337
Mar 10, 2018
338
int.__mul__ = function(self, other){
340
if(_b_.isinstance(other, int)){
341
if(other.__class__ == $B.long_int){
342
return $B.long_int.__mul__($B.long_int.$factory(self),
343
$B.long_int.$factory(other))
344
}
Mar 10, 2018
346
var res = self * other
347
if(res > $B.min_int && res < $B.max_int){
348
return res
349
}else{
Mar 10, 2018
350
return int.$factory($B.long_int.__mul__($B.long_int.$factory(self),
351
$B.long_int.$factory(other)))
352
}
Sep 5, 2014
355
}
356
Feb 22, 2019
357
int.__ne__ = function(self, other){
358
var res = int.__eq__(self, other)
359
return (res === _b_.NotImplemented) ? res : !res
360
}
361
362
int.__neg__ = function(self){return -self}
Sep 5, 2014
363
364
int.__new__ = function(cls, value){
Mar 10, 2018
365
if(cls === undefined){
366
throw _b_.TypeError.$factory("int.__new__(): not enough arguments")
367
}else if(! _b_.isinstance(cls, _b_.type)){
368
throw _b_.TypeError.$factory("int.__new__(X): X is not a type object")
369
}
370
if(cls === int){
371
return int.$factory(value)
372
}
Mar 10, 2018
377
}
Sep 5, 2014
378
}
379
380
int.__pos__ = function(self){return self}
Sep 5, 2014
381
Feb 20, 2020
382
function extended_euclidean(a, b){
383
var d, u, v
384
if(b == 0){
385
return [a, 1, 0]
386
}else{
387
[d, u, v] = extended_euclidean(b, a % b)
388
return [d, v, u - Math.floor(a / b) * v]
389
}
390
}
391
Mar 10, 2018
392
int.__pow__ = function(self, other, z){
393
if(! _b_.isinstance(other, int)){
394
return _b_.NotImplemented
395
}
396
if(typeof other == "number" || _b_.isinstance(other, int)){
397
other = int_value(other)
398
switch(other.valueOf()) {
399
case 0:
400
return int.$factory(1)
401
case 1:
402
return int.$factory(self.valueOf())
403
}
404
if(z !== undefined && z !== _b_.None){
405
// If z is provided, the algorithm is faster than computing
406
// self ** other then applying the modulo z
407
if(z == 1){return 0}
408
var result = 1,
409
base = self % z,
410
exponent = other,
411
long_int = $B.long_int
412
if(exponent < 0){
413
var gcd, inv, _
414
[gcd, inv, _] = extended_euclidean(self, z)
415
if(gcd !== 1){
416
throw _b_.ValueError.$factory("not relative primes: " +
417
self + ' and ' + z)
418
}
419
return int.__pow__(inv, -exponent, z)
420
}
421
while(exponent > 0){
422
if(exponent % 2 == 1){
423
if(result * base > $B.max_int){
424
result = long_int.__mul__(
425
long_int.$factory(result),
426
long_int.$factory(base))
427
result = long_int.__mod__(result, z)
428
}else{
429
result = (result * base) % z
430
}
431
}
432
exponent = exponent >> 1
433
if(base * base > $B.max_int){
434
base = long_int.__mul__(long_int.$factory(base),
435
long_int.$factory(base))
436
base = long_int.__mod__(base, z)
437
}else{
438
base = (base * base) % z
439
}
440
}
441
return result
442
}
443
var res = Math.pow(self.valueOf(), other.valueOf())
444
if(res > $B.min_int && res < $B.max_int){
445
return other > 0 ? res : new Number(res)
446
}else if(res !== Infinity && !isFinite(res)){
447
return res
448
}else{
449
if($B.BigInt){
450
return {
451
__class__: $B.long_int,
452
value: ($B.BigInt(self) ** $B.BigInt(other)).toString(),
453
pos: true
454
}
455
}
456
return $B.long_int.__pow__($B.long_int.$from_int(self),
457
$B.long_int.$from_int(other))
458
}
Sep 5, 2014
459
}
460
if(_b_.isinstance(other, _b_.float)) {
461
other = _b_.float.numerator(other)
462
if(self >= 0){
463
return new Number(Math.pow(self, other))
464
}else{
466
return _b_.complex.__pow__($B.make_complex(self, 0), other)
468
}else if(_b_.isinstance(other, _b_.complex)){
Mar 10, 2018
469
var preal = Math.pow(self, other.$real),
470
ln = Math.log(self)
Mar 10, 2018
471
return $B.make_complex(preal * Math.cos(ln), preal * Math.sin(ln))
Sep 5, 2014
472
}
473
var rpow = $B.$getattr(other, "__rpow__", _b_.None)
474
if(rpow !== _b_.None){
475
return rpow(self)
476
}
Mar 10, 2018
477
$err("**", other)
Sep 5, 2014
478
}
479
480
function __newobj__(){
481
// __newobj__ is called with a generator as only argument
482
var $ = $B.args('__newobj__', 0, {}, [], arguments, {}, 'args', null),
483
args = $.args
484
var res = args.slice(1)
485
res.__class__ = args[0]
486
return res
487
}
488
489
int.__reduce_ex__ = function(self){
490
return $B.fast_tuple([
491
__newobj__,
492
$B.fast_tuple([self.__class__ || int, int_value(self)]),
493
_b_.None,
494
_b_.None,
495
_b_.None])
496
}
497
498
int.__repr__ = function(self){
499
$B.builtins_repr_check(int, arguments) // in brython_builtins.js
500
return int_value(self).toString()
Sep 5, 2014
501
}
502
503
// bitwise right shift
Mar 10, 2018
504
int.__rshift__ = function(self, other){
505
self = int_value(self)
506
if(typeof other == "number" || _b_.isinstance(other, int)){
Feb 11, 2018
508
return int.$factory($B.long_int.__rshift__($B.long_int.$factory(self),
509
$B.long_int.$factory(other)))
Sep 5, 2014
513
514
int.__setattr__ = function(self, attr, value){
515
if(typeof self == "number" || typeof self == "boolean"){
516
var cl_name = $B.class_name(self)
517
if(_b_.dir(self).indexOf(attr) > -1){
518
throw _b_.AttributeError.$factory("attribute '" + attr +
519
`' of '${cl_name}' objects is not writable`)
521
throw _b_.AttributeError.$factory(`'${cl_name}' object` +
522
` has no attribute '${attr}'`)
524
throw _b_.AttributeError.$factory(msg)
Sep 5, 2014
525
}
526
// subclasses of int can have attributes set
527
_b_.dict.$setitem(self.__dict__, attr, value)
528
return _b_.None
Sep 5, 2014
529
}
530
531
int.__sub__ = function(self, other){
532
self = int_value(self)
533
if(_b_.isinstance(other, int)){
534
if(other.__class__ == $B.long_int){
535
return $B.long_int.__sub__($B.long_int.$factory(self),
536
$B.long_int.$factory(other))
537
}
538
other = int_value(other)
539
var res = self - other
540
if(res > $B.min_int && res < $B.max_int){
541
return res
542
}else{
543
return $B.long_int.__sub__($B.long_int.$factory(self),
544
$B.long_int.$factory(other))
545
}
546
}
547
return _b_.NotImplemented
548
}
549
Mar 10, 2018
550
int.__truediv__ = function(self, other){
551
if(_b_.isinstance(other, int)){
553
if(other == 0){
554
throw _b_.ZeroDivisionError.$factory("division by zero")
555
}
Mar 10, 2018
556
if(other.__class__ === $B.long_int){
557
return new Number(self / parseInt(other.value))
558
}
559
return new Number(self / other)
Sep 5, 2014
560
}
Sep 5, 2014
562
}
563
564
int.bit_length = function(self){
565
s = _b_.bin(self)
566
s = $B.$getattr(s, "lstrip")("-0b") // remove leading zeros and minus sign
Sep 5, 2014
567
return s.length // len('100101') --> 6
568
}
569
570
// descriptors
571
int.numerator = function(self){
572
return int_value(self)
573
}
574
int.denominator = function(self){
575
return int.$factory(1)
576
}
577
int.imag = function(self){
578
return int.$factory(0)
579
}
580
int.real = function(self){
581
return self
582
}
583
584
for(var attr of ['numerator', 'denominator', 'imag', 'real']){
585
int[attr].setter = (function(x){
586
return function(self, value){
587
throw _b_.AttributeError.$factory(`attribute '${x}' of ` +
588
`'${$B.class_name(self)}' objects is not writable`)
589
}
590
})(attr)
591
}
592
Mar 10, 2018
593
$B.max_int32 = (1 << 30) * 2 - 1
594
$B.min_int32 = - $B.max_int32
596
// code for operands & | ^
Mar 10, 2018
597
var $op_func = function(self, other){
598
self = int_value(self)
599
if(typeof other == "number" || _b_.isinstance(other, int)){
Mar 10, 2018
600
if(other.__class__ === $B.long_int){
601
return $B.long_int.__sub__($B.long_int.$factory(self),
602
$B.long_int.$factory(other))
Mar 23, 2018
605
if(self > $B.max_int32 || self < $B.min_int32 ||
606
other > $B.max_int32 || other < $B.min_int32){
Mar 10, 2018
607
return $B.long_int.__sub__($B.long_int.$factory(self),
608
$B.long_int.$factory(other))
Mar 21, 2018
610
return self - other
Jun 7, 2015
611
}
Sep 5, 2014
613
}
614
Mar 10, 2018
615
$op_func += "" // source code
616
var $ops = {"&": "and", "|": "or", "^": "xor"}
Sep 5, 2014
617
for(var $op in $ops){
Mar 10, 2018
618
var opf = $op_func.replace(/-/gm, $op)
619
opf = opf.replace(new RegExp("sub", "gm"), $ops[$op])
620
eval("int.__" + $ops[$op] + "__ = " + opf)
Sep 5, 2014
621
}
622
623
624
// comparison methods
Mar 10, 2018
625
var $comp_func = function(self, other){
Mar 23, 2018
626
if(other.__class__ === $B.long_int){
Feb 11, 2018
627
return $B.long_int.__lt__(other, $B.long_int.$factory(self))
629
if(_b_.isinstance(other, int)){
630
other = int_value(other)
631
return self.valueOf() > other.valueOf()
632
}else if(_b_.isinstance(other, _b_.float)){
633
return self.valueOf() > _b_.float.numerator(other)
634
}else if(_b_.isinstance(other, _b_.bool)) {
Feb 11, 2018
635
return self.valueOf() > _b_.bool.__hash__(other)
Sep 5, 2014
636
}
637
if(_b_.hasattr(other, "__int__") || _b_.hasattr(other, "__index__")){
638
return int.__gt__(self, $B.$GetInt(other))
Sep 5, 2014
642
}
Mar 10, 2018
643
$comp_func += "" // source code
Sep 5, 2014
645
for(var $op in $B.$comps){
Mar 10, 2018
646
eval("int.__"+$B.$comps[$op] + "__ = " +
647
$comp_func.replace(/>/gm, $op).
648
replace(/__gt__/gm,"__" + $B.$comps[$op] + "__").
649
replace(/__lt__/, "__" + $B.$inv_comps[$op] + "__"))
Sep 5, 2014
650
}
651
652
// add "reflected" methods
653
var r_opnames = ["add", "sub", "mul", "truediv", "floordiv", "mod", "pow",
654
"lshift", "rshift", "and", "xor", "or", "divmod"]
655
656
for(var r_opname of r_opnames){
657
if(int["__r" + r_opname + "__"] === undefined &&
658
int['__' + r_opname + '__']){
659
int["__r" + r_opname + "__"] = (function(name){
660
return function(self, other){
661
if(_b_.isinstance(other, int)){
662
other = int_value(other)
663
return int["__" + name + "__"](other, self)
664
}
665
return _b_.NotImplemented
666
}
667
})(r_opname)
668
}
669
}
Sep 5, 2014
670
Mar 10, 2018
671
var $valid_digits = function(base) {
672
var digits = ""
673
if(base === 0){return "0"}
674
if(base < 10){
Mar 21, 2018
675
for(var i = 0; i < base; i++){digits += String.fromCharCode(i + 48)}
Sep 5, 2014
676
return digits
677
}
678
Mar 10, 2018
679
var digits = "0123456789"
Sep 5, 2014
680
// A = 65 (10 + 55)
Mar 21, 2018
681
for (var i = 10; i < base; i++) {digits += String.fromCharCode(i + 55)}
Sep 5, 2014
682
return digits
683
}
684
685
int.$factory = function(value, base){
686
// int() with no argument returns 0
Mar 10, 2018
687
if(value === undefined){return 0}
689
// int() of an integer returns the integer if base is undefined
Mar 10, 2018
690
if(typeof value == "number" &&
691
(base === undefined || base == 10)){return parseInt(value)}
693
if(_b_.isinstance(value, _b_.complex)){
694
throw _b_.TypeError.$factory("can't convert complex to int")
Dec 28, 2014
695
}
Mar 10, 2018
697
var $ns = $B.args("int", 2, {x:null, base:null}, ["x", "base"], arguments,
698
{"base": 10}, null, null),
699
value = $ns["x"],
700
base = $ns["base"]
702
if(_b_.isinstance(value, _b_.float) && base == 10){
703
value = _b_.float.numerator(value) // for float subclasses
Mar 10, 2018
704
if(value < $B.min_int || value > $B.max_int){
Feb 11, 2018
705
return $B.long_int.$from_float(value)
707
else{
708
return value > 0 ? Math.floor(value) : Math.ceil(value)
709
}
Sep 5, 2014
711
Mar 10, 2018
712
if(! (base >=2 && base <= 36)){
Dec 26, 2014
713
// throw error (base must be 0, or 2-36)
714
if(base != 0){
715
throw _b_.ValueError.$factory("invalid base")
716
}
Dec 26, 2014
717
}
718
Mar 10, 2018
719
if(typeof value == "number"){
Mar 10, 2018
721
if(base == 10){
722
if(value < $B.min_int || value > $B.max_int){
723
return $B.long_int.$factory(value)
724
}
Mar 10, 2018
726
}else if(value.toString().search("e") > -1){
Dec 26, 2014
727
// can't convert to another base if value is too big
Mar 10, 2018
728
throw _b_.OverflowError.$factory("can't convert to base " + base)
Dec 26, 2014
729
}else{
Mar 10, 2018
730
var res = parseInt(value, base)
731
if(value < $B.min_int || value > $B.max_int){
732
return $B.long_int.$factory(value, base)
733
}
Dec 26, 2014
735
}
736
}
Sep 5, 2014
737
Mar 10, 2018
738
if(value === true){return Number(1)}
739
if(value === false){return Number(0)}
740
if(value.__class__ === $B.long_int){
741
var z = parseInt(value.value)
Mar 10, 2018
742
if(z > $B.min_int && z < $B.max_int){return z}
743
else{return value}
744
}
Sep 5, 2014
745
Mar 10, 2018
746
base = $B.$GetInt(base)
747
function invalid(value, base){
748
throw _b_.ValueError.$factory("invalid literal for int() with base " +
749
base + ": '" + _b_.str.$factory(value) + "'")
750
}
Sep 5, 2014
751
752
if(_b_.isinstance(value, _b_.str)){
753
value = value.valueOf()
754
}
Mar 10, 2018
755
if(typeof value == "string") {
756
var _value = value.trim() // remove leading/trailing whitespace
757
if(_value.length == 2 && base == 0 &&
758
(_value == "0b" || _value == "0o" || _value == "0x")){
759
throw _b_.ValueError.$factory("invalid value")
760
}
761
if(_value.length > 2) {
Mar 10, 2018
762
var _pre = _value.substr(0, 2).toUpperCase()
763
if(base == 0){
764
if(_pre == "0B"){base = 2}
765
if(_pre == "0O"){base = 8}
766
if(_pre == "0X"){base = 16}
767
}else if(_pre == "0X" && base != 16){invalid(_value, base)}
768
else if(_pre == "0O" && base != 8){invalid(_value, base)}
769
if((_pre == "0B" && base == 2) || _pre == "0O" || _pre == "0X"){
Mar 10, 2018
770
_value = _value.substr(2)
771
while(_value.startsWith("_")){
772
_value = _value.substr(1)
773
}
Mar 10, 2018
774
}
775
}else if(base == 0){
776
// eg int("1\n", 0)
777
base = 10
Mar 10, 2018
778
}
779
var _digits = $valid_digits(base),
780
_re = new RegExp("^[+-]?[" + _digits + "]" +
781
"[" + _digits + "_]*$", "i"),
782
match = _re.exec(_value)
783
if(match === null){
784
invalid(value, base)
785
}else{
786
value = _value.replace(/_/g, "")
Mar 10, 2018
787
}
788
if(base <= 10 && ! isFinite(value)){
789
invalid(_value, base)
790
}
791
var res = parseInt(value, base)
Mar 10, 2018
792
if(res < $B.min_int || res > $B.max_int){
793
return $B.long_int.$factory(value, base)
Mar 10, 2018
794
}
795
return res
Sep 5, 2014
796
}
798
if(_b_.isinstance(value, [_b_.bytes, _b_.bytearray])){
799
return int.$factory($B.$getattr(value, "decode")("latin-1"), base)
800
}
802
for(var special_method of ["__int__", "__index__", "__trunc__"]){
803
var num_value = $B.$getattr(value.__class__ || $B.get_class(value),
805
if(num_value !== _b_.None){
806
return $B.$call(num_value)(value)
809
throw _b_.TypeError.$factory(
810
"int() argument must be a string, a bytes-like " +
811
"object or a number, not '" + $B.class_name(value) + "'")
Sep 5, 2014
812
}
813
814
$B.set_func_names(int, "builtins")
Sep 5, 2014
816
_b_.int = int
817
Feb 11, 2018
819
$B.$bool = function(obj){ // return true or false
Mar 10, 2018
820
if(obj === null || obj === undefined ){ return false}
821
switch(typeof obj){
822
case "boolean":
823
return obj
824
case "number":
825
case "string":
826
if(obj){return true}
827
return false
828
default:
829
if(obj.$is_class){return true}
830
var klass = obj.__class__ || $B.get_class(obj),
831
missing = {},
832
bool_method = $B.$getattr(klass, "__bool__", missing)
833
if(bool_method === missing){
834
try{return _b_.len(obj) > 0}
Mar 10, 2018
835
catch(err){return true}
837
var res = $B.$call(bool_method)(obj)
838
if(res !== true && res !== false){
839
throw _b_.TypeError.$factory("__bool__ should return " +
840
"bool, returned " + $B.class_name(res))
841
}
842
return res
Mar 10, 2018
843
}
844
}
Feb 11, 2018
845
}
846
847
var bool = {
848
__bases__: [int],
Feb 11, 2018
849
__class__: _b_.type,
850
__mro__: [int, _b_.object],
851
$infos:{
852
__name__: "bool",
853
__module__: "builtins"
854
},
Feb 11, 2018
855
$is_class: true,
856
$native: true,
857
$descriptors: {
858
"numerator": true,
859
"denominator": true,
860
"imag": true,
861
"real": true
862
}
Feb 11, 2018
865
bool.__and__ = function(self, other){
866
if(_b_.isinstance(other, bool)){
867
return self && other
868
}else if(_b_.isinstance(other, int)){
869
return int.__and__(bool.__index__(self), int.__index__(other))
870
}
871
return _b_.NotImplemented
874
bool.__float__ = function(self){
875
return self ? new Number(1) : new Number(0)
876
}
877
Mar 10, 2018
878
bool.__hash__ = bool.__index__ = bool.__int__ = function(self){
879
if(self.valueOf()) return 1
880
return 0
881
}
882
Feb 11, 2018
883
bool.__neg__ = function(self){return -$B.int_or_bool(self)}
Feb 11, 2018
885
bool.__or__ = function(self, other){
886
if(_b_.isinstance(other, bool)){
887
return self || other
888
}else if(_b_.isinstance(other, int)){
889
return int.__or__(bool.__index__(self), int.__index__(other))
890
}
891
return _b_.NotImplemented
Feb 11, 2018
894
bool.__pos__ = $B.int_or_bool
896
bool.__repr__ = function(self){
897
$B.builtins_repr_check(bool, arguments) // in brython_builtins.js
898
return self ? "True" : "False"
Feb 11, 2018
901
bool.__xor__ = function(self, other) {
902
if(_b_.isinstance(other, bool)){
903
return self ^ other ? true : false
904
}else if(_b_.isinstance(other, int)){
905
return int.__xor__(bool.__index__(self), int.__index__(other))
906
}
907
return _b_.NotImplemented
Feb 11, 2018
910
bool.$factory = function(){
911
// Calls $B.$bool, which is used inside the generated JS code and skips
912
// arguments control.
Mar 10, 2018
913
var $ = $B.args("bool", 1, {x: null}, ["x"],
914
arguments,{x: false}, null, null)
Feb 11, 2018
915
return $B.$bool($.x)
916
}
917
918
bool.numerator = int.numerator
919
bool.denominator = int.denominator
920
bool.real = int.real
921
bool.imag = int.imag
922
Feb 11, 2018
923
_b_.bool = bool
Feb 11, 2018
925
$B.set_func_names(bool, "builtins")
Sep 5, 2014
927
})(__BRYTHON__)