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