Skip to content
Permalink
Newer
Older
100644 923 lines (833 sloc) 27 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){
272
if(self.$brython_value){
273
// int subclass
274
var hash_method = $B.$getattr(self.__class__, '__hash__')
275
if(hash_method === int.__hash__){
276
if(typeof self.$brython_value == "number"){
277
return self.$brython_value
278
}else{ // long int
279
return $B.long_int.__hash__(self.$brython_value)
280
}
281
}else{
282
return hash_method(self)
283
}
284
}
285
return self.valueOf()
Sep 5, 2014
287
288
//int.__ior__ = function(self,other){return self | other} // bitwise OR
Sep 5, 2014
289
290
int.__index__ = function(self){
291
return int_value(self)
292
}
Sep 5, 2014
293
294
int.__init__ = function(self, value){
Mar 10, 2018
295
if(value === undefined){value = 0}
Sep 5, 2014
296
self.toString = function(){return value}
297
return _b_.None
Sep 5, 2014
298
}
299
300
int.__int__ = function(self){return self}
Sep 5, 2014
301
302
int.__invert__ = function(self){return ~self}
Sep 5, 2014
303
Mar 10, 2018
305
int.__lshift__ = function(self, other){
307
if(_b_.isinstance(other, int)){
309
try{
310
return int.$factory($B.long_int.__lshift__($B.long_int.$factory(self),
311
$B.long_int.$factory(other)))
312
}catch(err){
313
console.log('err in lshift', self, other)
314
throw err
315
}
Mar 10, 2018
320
int.__mod__ = function(self, other) {
Sep 5, 2014
321
// can't use Javascript % because it works differently for negative numbers
322
if(_b_.isinstance(other,_b_.tuple) && other.length == 1){other = other[0]}
323
if(other.__class__ === $B.long_int){
324
return $B.long_int.__mod__($B.long_int.$factory(self), other)
325
}
Mar 10, 2018
328
if(other === false){other = 0}
329
else if(other === true){other = 1}
330
if(other == 0){throw _b_.ZeroDivisionError.$factory(
331
"integer division or modulo by zero")}
Mar 10, 2018
332
return (self % other + other) % other
Sep 5, 2014
333
}
Sep 5, 2014
335
}
336
Mar 10, 2018
337
int.__mul__ = function(self, other){
339
if(_b_.isinstance(other, int)){
340
if(other.__class__ == $B.long_int){
341
return $B.long_int.__mul__($B.long_int.$factory(self),
342
$B.long_int.$factory(other))
343
}
Mar 10, 2018
345
var res = self * other
346
if(res > $B.min_int && res < $B.max_int){
347
return res
348
}else{
Mar 10, 2018
349
return int.$factory($B.long_int.__mul__($B.long_int.$factory(self),
350
$B.long_int.$factory(other)))
351
}
Sep 5, 2014
354
}
355
Feb 22, 2019
356
int.__ne__ = function(self, other){
357
var res = int.__eq__(self, other)
358
return (res === _b_.NotImplemented) ? res : !res
359
}
360
361
int.__neg__ = function(self){return -self}
Sep 5, 2014
362
363
int.__new__ = function(cls, value){
Mar 10, 2018
364
if(cls === undefined){
365
throw _b_.TypeError.$factory("int.__new__(): not enough arguments")
366
}else if(! _b_.isinstance(cls, _b_.type)){
367
throw _b_.TypeError.$factory("int.__new__(X): X is not a type object")
368
}
369
if(cls === int){return int.$factory(value)}
370
return {
371
__class__: cls,
Mar 10, 2018
374
}
Sep 5, 2014
375
}
376
377
int.__pos__ = function(self){return self}
Sep 5, 2014
378
Feb 20, 2020
379
function extended_euclidean(a, b){
380
var d, u, v
381
if(b == 0){
382
return [a, 1, 0]
383
}else{
384
[d, u, v] = extended_euclidean(b, a % b)
385
return [d, v, u - Math.floor(a / b) * v]
386
}
387
}
388
Mar 10, 2018
389
int.__pow__ = function(self, other, z){
390
if(! _b_.isinstance(other, int)){
391
return _b_.NotImplemented
392
}
393
if(typeof other == "number" || _b_.isinstance(other, int)){
394
other = int_value(other)
395
switch(other.valueOf()) {
396
case 0:
397
return int.$factory(1)
398
case 1:
399
return int.$factory(self.valueOf())
Feb 9, 2015
400
}
401
if(z !== undefined && z !== _b_.None){
May 19, 2017
402
// If z is provided, the algorithm is faster than computing
403
// self ** other then applying the modulo z
404
if(z == 1){return 0}
405
var result = 1,
406
base = self % z,
407
exponent = other,
408
long_int = $B.long_int
Feb 20, 2020
409
if(exponent < 0){
410
var gcd, inv, _
411
[gcd, inv, _] = extended_euclidean(self, z)
412
if(gcd !== 1){
413
throw _b_.ValueError.$factory("not relative primes: " +
414
self + ' and ' + z)
415
}
416
return int.__pow__(inv, -exponent, z)
417
}
418
while(exponent > 0){
419
if(exponent % 2 == 1){
420
if(result * base > $B.max_int){
421
result = long_int.__mul__(
422
long_int.$factory(result),
423
long_int.$factory(base))
424
result = long_int.__mod__(result, z)
425
}else{
426
result = (result * base) % z
427
}
428
}
429
exponent = exponent >> 1
430
if(base * base > $B.max_int){
431
base = long_int.__mul__(long_int.$factory(base),
432
long_int.$factory(base))
433
base = long_int.__mod__(base, z)
434
}else{
435
base = (base * base) % z
436
}
May 19, 2017
437
}
May 19, 2017
439
}
Mar 10, 2018
440
var res = Math.pow(self.valueOf(), other.valueOf())
441
if(res > $B.min_int && res < $B.max_int){
442
return other > 0 ? res : new Number(res)
443
}else if(res !== Infinity && !isFinite(res)){
444
return res
445
}else{
446
if($B.BigInt){
447
return {
448
__class__: $B.long_int,
449
value: ($B.BigInt(self) ** $B.BigInt(other)).toString(),
450
pos: true
451
}
452
}
453
return $B.long_int.__pow__($B.long_int.$from_int(self),
454
$B.long_int.$from_int(other))
May 19, 2017
455
}
Sep 5, 2014
456
}
457
if(_b_.isinstance(other, _b_.float)) {
458
other = _b_.float.numerator(other)
459
if(self >= 0){
460
return new Number(Math.pow(self, other))
461
}else{
463
return _b_.complex.__pow__($B.make_complex(self, 0), other)
465
}else if(_b_.isinstance(other, _b_.complex)){
Mar 10, 2018
466
var preal = Math.pow(self, other.$real),
467
ln = Math.log(self)
Mar 10, 2018
468
return $B.make_complex(preal * Math.cos(ln), preal * Math.sin(ln))
Sep 5, 2014
469
}
470
var rpow = $B.$getattr(other, "__rpow__", _b_.None)
471
if(rpow !== _b_.None){
472
return rpow(self)
473
}
Mar 10, 2018
474
$err("**", other)
Sep 5, 2014
475
}
476
477
function __newobj__(){
478
// __newobj__ is called with a generator as only argument
479
var $ = $B.args('__newobj__', 0, {}, [], arguments, {}, 'args', null),
480
args = $.args
481
var res = args.slice(1)
482
res.__class__ = args[0]
483
return res
484
}
485
486
int.__reduce_ex__ = function(self){
487
return $B.fast_tuple([
488
__newobj__,
489
$B.fast_tuple([self.__class__ || int, int_value(self)]),
490
_b_.None,
491
_b_.None,
492
_b_.None])
493
}
494
495
int.__repr__ = function(self){
496
$B.builtins_repr_check(int, arguments) // in brython_builtins.js
497
return int_value(self).toString()
Sep 5, 2014
498
}
499
500
// bitwise right shift
Mar 10, 2018
501
int.__rshift__ = function(self, other){
502
self = int_value(self)
503
if(typeof other == "number" || _b_.isinstance(other, int)){
Feb 11, 2018
505
return int.$factory($B.long_int.__rshift__($B.long_int.$factory(self),
506
$B.long_int.$factory(other)))
Sep 5, 2014
510
511
int.__setattr__ = function(self, attr, value){
512
if(typeof self == "number" || typeof self == "boolean"){
513
var cl_name = $B.class_name(self)
514
if(_b_.dir(self).indexOf(attr) > -1){
515
var msg = "attribute '" + attr + `' of '${cl_name}'` +
516
"objects is not writable"
518
var msg = `'${cl_name}' object has no attribute '${attr}'`
520
throw _b_.AttributeError.$factory(msg)
Sep 5, 2014
521
}
522
// subclasses of int can have attributes set
523
_b_.dict.$setitem(self.__dict__, attr, value)
524
return _b_.None
Sep 5, 2014
525
}
526
527
int.__sub__ = function(self, other){
528
self = int_value(self)
529
if(_b_.isinstance(other, int)){
530
if(other.__class__ == $B.long_int){
531
return $B.long_int.__sub__($B.long_int.$factory(self),
532
$B.long_int.$factory(other))
533
}
534
other = int_value(other)
535
var res = self - other
536
if(res > $B.min_int && res < $B.max_int){
537
return res
538
}else{
539
return $B.long_int.__sub__($B.long_int.$factory(self),
540
$B.long_int.$factory(other))
541
}
542
}
543
return _b_.NotImplemented
544
}
545
Mar 10, 2018
546
int.__truediv__ = function(self, other){
547
if(_b_.isinstance(other, int)){
549
if(other == 0){
550
throw _b_.ZeroDivisionError.$factory("division by zero")
551
}
Mar 10, 2018
552
if(other.__class__ === $B.long_int){
553
return new Number(self / parseInt(other.value))
554
}
555
return new Number(self / other)
Sep 5, 2014
556
}
Sep 5, 2014
558
}
559
560
int.bit_length = function(self){
561
s = _b_.bin(self)
562
s = $B.$getattr(s, "lstrip")("-0b") // remove leading zeros and minus sign
Sep 5, 2014
563
return s.length // len('100101') --> 6
564
}
565
566
// descriptors
567
int.numerator = function(self){
568
return int_value(self)
569
}
570
int.denominator = function(self){
571
return int.$factory(1)
572
}
573
int.imag = function(self){
574
return int.$factory(0)
575
}
576
int.real = function(self){
577
return self
578
}
579
580
for(var attr of ['numerator', 'denominator', 'imag', 'real']){
581
int[attr].setter = (function(x){
582
return function(self, value){
583
throw _b_.AttributeError.$factory(`attribute '${x}' of ` +
584
`'${$B.class_name(self)}' objects is not writable`)
585
}
586
})(attr)
587
}
588
Mar 10, 2018
589
$B.max_int32 = (1 << 30) * 2 - 1
590
$B.min_int32 = - $B.max_int32
592
// code for operands & | ^
Mar 10, 2018
593
var $op_func = function(self, other){
594
self = int_value(self)
595
if(typeof other == "number" || _b_.isinstance(other, int)){
Mar 10, 2018
596
if(other.__class__ === $B.long_int){
597
return $B.long_int.__sub__($B.long_int.$factory(self),
598
$B.long_int.$factory(other))
Mar 23, 2018
601
if(self > $B.max_int32 || self < $B.min_int32 ||
602
other > $B.max_int32 || other < $B.min_int32){
Mar 10, 2018
603
return $B.long_int.__sub__($B.long_int.$factory(self),
604
$B.long_int.$factory(other))
Mar 21, 2018
606
return self - other
Jun 7, 2015
607
}
Sep 5, 2014
609
}
610
Mar 10, 2018
611
$op_func += "" // source code
612
var $ops = {"&": "and", "|": "or", "^": "xor"}
Sep 5, 2014
613
for(var $op in $ops){
Mar 10, 2018
614
var opf = $op_func.replace(/-/gm, $op)
615
opf = opf.replace(new RegExp("sub", "gm"), $ops[$op])
616
eval("int.__" + $ops[$op] + "__ = " + opf)
Sep 5, 2014
617
}
618
619
620
// comparison methods
Mar 10, 2018
621
var $comp_func = function(self, other){
Mar 23, 2018
622
if(other.__class__ === $B.long_int){
Feb 11, 2018
623
return $B.long_int.__lt__(other, $B.long_int.$factory(self))
625
if(_b_.isinstance(other, int)){
626
other = int_value(other)
627
return self.valueOf() > other.valueOf()
628
}else if(_b_.isinstance(other, _b_.float)){
629
return self.valueOf() > _b_.float.numerator(other)
630
}else if(_b_.isinstance(other, _b_.bool)) {
Feb 11, 2018
631
return self.valueOf() > _b_.bool.__hash__(other)
Sep 5, 2014
632
}
633
if(_b_.hasattr(other, "__int__") || _b_.hasattr(other, "__index__")){
634
return int.__gt__(self, $B.$GetInt(other))
Sep 5, 2014
638
}
Mar 10, 2018
639
$comp_func += "" // source code
Sep 5, 2014
641
for(var $op in $B.$comps){
Mar 10, 2018
642
eval("int.__"+$B.$comps[$op] + "__ = " +
643
$comp_func.replace(/>/gm, $op).
644
replace(/__gt__/gm,"__" + $B.$comps[$op] + "__").
645
replace(/__lt__/, "__" + $B.$inv_comps[$op] + "__"))
Sep 5, 2014
646
}
647
648
// add "reflected" methods
649
var r_opnames = ["add", "sub", "mul", "truediv", "floordiv", "mod", "pow",
650
"lshift", "rshift", "and", "xor", "or", "divmod"]
651
652
for(var r_opname of r_opnames){
653
if(int["__r" + r_opname + "__"] === undefined &&
654
int['__' + r_opname + '__']){
655
int["__r" + r_opname + "__"] = (function(name){
656
return function(self, other){
657
if(_b_.isinstance(other, int)){
658
other = int_value(other)
659
return int["__" + name + "__"](other, self)
660
}
661
return _b_.NotImplemented
662
}
663
})(r_opname)
664
}
665
}
Sep 5, 2014
666
Mar 10, 2018
667
var $valid_digits = function(base) {
668
var digits = ""
669
if(base === 0){return "0"}
670
if(base < 10){
Mar 21, 2018
671
for(var i = 0; i < base; i++){digits += String.fromCharCode(i + 48)}
Sep 5, 2014
672
return digits
673
}
674
Mar 10, 2018
675
var digits = "0123456789"
Sep 5, 2014
676
// A = 65 (10 + 55)
Mar 21, 2018
677
for (var i = 10; i < base; i++) {digits += String.fromCharCode(i + 55)}
Sep 5, 2014
678
return digits
679
}
680
681
int.$factory = function(value, base){
682
// int() with no argument returns 0
Mar 10, 2018
683
if(value === undefined){return 0}
685
// int() of an integer returns the integer if base is undefined
Mar 10, 2018
686
if(typeof value == "number" &&
687
(base === undefined || base == 10)){return parseInt(value)}
689
if(_b_.isinstance(value, _b_.complex)){
690
throw _b_.TypeError.$factory("can't convert complex to int")
Dec 28, 2014
691
}
Mar 10, 2018
693
var $ns = $B.args("int", 2, {x:null, base:null}, ["x", "base"], arguments,
694
{"base": 10}, null, null),
695
value = $ns["x"],
696
base = $ns["base"]
698
if(_b_.isinstance(value, _b_.float) && base == 10){
699
value = _b_.float.numerator(value) // for float subclasses
Mar 10, 2018
700
if(value < $B.min_int || value > $B.max_int){
Feb 11, 2018
701
return $B.long_int.$from_float(value)
703
else{
704
return value > 0 ? Math.floor(value) : Math.ceil(value)
705
}
Sep 5, 2014
707
Mar 10, 2018
708
if(! (base >=2 && base <= 36)){
Dec 26, 2014
709
// throw error (base must be 0, or 2-36)
710
if(base != 0){
711
throw _b_.ValueError.$factory("invalid base")
712
}
Dec 26, 2014
713
}
714
Mar 10, 2018
715
if(typeof value == "number"){
Mar 10, 2018
717
if(base == 10){
718
if(value < $B.min_int || value > $B.max_int){
719
return $B.long_int.$factory(value)
720
}
Mar 10, 2018
722
}else if(value.toString().search("e") > -1){
Dec 26, 2014
723
// can't convert to another base if value is too big
Mar 10, 2018
724
throw _b_.OverflowError.$factory("can't convert to base " + base)
Dec 26, 2014
725
}else{
Mar 10, 2018
726
var res = parseInt(value, base)
727
if(value < $B.min_int || value > $B.max_int){
728
return $B.long_int.$factory(value, base)
729
}
Dec 26, 2014
731
}
732
}
Sep 5, 2014
733
Mar 10, 2018
734
if(value === true){return Number(1)}
735
if(value === false){return Number(0)}
736
if(value.__class__ === $B.long_int){
737
var z = parseInt(value.value)
Mar 10, 2018
738
if(z > $B.min_int && z < $B.max_int){return z}
739
else{return value}
740
}
Sep 5, 2014
741
Mar 10, 2018
742
base = $B.$GetInt(base)
743
function invalid(value, base){
744
throw _b_.ValueError.$factory("invalid literal for int() with base " +
745
base + ": '" + _b_.str.$factory(value) + "'")
746
}
Sep 5, 2014
747
748
if(_b_.isinstance(value, _b_.str)){
749
value = value.valueOf()
750
}
Mar 10, 2018
751
if(typeof value == "string") {
752
var _value = value.trim() // remove leading/trailing whitespace
753
if(_value.length == 2 && base == 0 &&
754
(_value == "0b" || _value == "0o" || _value == "0x")){
755
throw _b_.ValueError.$factory("invalid value")
756
}
757
if(_value.length > 2) {
Mar 10, 2018
758
var _pre = _value.substr(0, 2).toUpperCase()
759
if(base == 0){
760
if(_pre == "0B"){base = 2}
761
if(_pre == "0O"){base = 8}
762
if(_pre == "0X"){base = 16}
763
}else if(_pre == "0X" && base != 16){invalid(_value, base)}
764
else if(_pre == "0O" && base != 8){invalid(_value, base)}
765
if((_pre == "0B" && base == 2) || _pre == "0O" || _pre == "0X"){
Mar 10, 2018
766
_value = _value.substr(2)
767
while(_value.startsWith("_")){
768
_value = _value.substr(1)
769
}
Mar 10, 2018
770
}
771
}else if(base == 0){
772
// eg int("1\n", 0)
773
base = 10
Mar 10, 2018
774
}
775
var _digits = $valid_digits(base),
776
_re = new RegExp("^[+-]?[" + _digits + "]" +
777
"[" + _digits + "_]*$", "i"),
778
match = _re.exec(_value)
779
if(match === null){
780
invalid(value, base)
781
}else{
782
value = _value.replace(/_/g, "")
Mar 10, 2018
783
}
784
if(base <= 10 && ! isFinite(value)){
785
invalid(_value, base)
786
}
787
var res = parseInt(value, base)
Mar 10, 2018
788
if(res < $B.min_int || res > $B.max_int){
789
return $B.long_int.$factory(value, base)
Mar 10, 2018
790
}
791
return res
Sep 5, 2014
792
}
794
if(_b_.isinstance(value, [_b_.bytes, _b_.bytearray])){
795
return int.$factory($B.$getattr(value, "decode")("latin-1"), base)
796
}
798
for(var special_method of ["__int__", "__index__", "__trunc__"]){
799
var num_value = $B.$getattr(value.__class__ || $B.get_class(value),
801
if(num_value !== _b_.None){
802
return $B.$call(num_value)(value)
805
throw _b_.TypeError.$factory(
806
"int() argument must be a string, a bytes-like " +
807
"object or a number, not '" + $B.class_name(value) + "'")
Sep 5, 2014
808
}
809
810
$B.set_func_names(int, "builtins")
Sep 5, 2014
812
_b_.int = int
813
Feb 11, 2018
815
$B.$bool = function(obj){ // return true or false
Mar 10, 2018
816
if(obj === null || obj === undefined ){ return false}
817
switch(typeof obj){
818
case "boolean":
819
return obj
820
case "number":
821
case "string":
822
if(obj){return true}
823
return false
824
default:
825
if(obj.$is_class){return true}
826
var klass = obj.__class__ || $B.get_class(obj),
827
missing = {},
828
bool_method = $B.$getattr(klass, "__bool__", missing)
829
if(bool_method === missing){
830
try{return _b_.len(obj) > 0}
Mar 10, 2018
831
catch(err){return true}
833
var res = $B.$call(bool_method)(obj)
834
if(res !== true && res !== false){
835
throw _b_.TypeError.$factory("__bool__ should return " +
836
"bool, returned " + $B.class_name(res))
837
}
838
return res
Mar 10, 2018
839
}
840
}
Feb 11, 2018
841
}
842
843
var bool = {
844
__bases__: [int],
Feb 11, 2018
845
__class__: _b_.type,
846
__mro__: [int, _b_.object],
847
$infos:{
848
__name__: "bool",
849
__module__: "builtins"
850
},
Feb 11, 2018
851
$is_class: true,
852
$native: true,
853
$descriptors: {
854
"numerator": true,
855
"denominator": true,
856
"imag": true,
857
"real": true
858
}
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
892
bool.__repr__ = function(self){
893
$B.builtins_repr_check(bool, arguments) // in brython_builtins.js
894
return self ? "True" : "False"
Feb 11, 2018
897
bool.__xor__ = function(self, other) {
898
if(_b_.isinstance(other, bool)){
899
return self ^ other ? true : false
900
}else if(_b_.isinstance(other, int)){
901
return int.__xor__(bool.__index__(self), int.__index__(other))
902
}
903
return _b_.NotImplemented
Feb 11, 2018
906
bool.$factory = function(){
907
// Calls $B.$bool, which is used inside the generated JS code and skips
908
// arguments control.
Mar 10, 2018
909
var $ = $B.args("bool", 1, {x: null}, ["x"],
910
arguments,{x: false}, null, null)
Feb 11, 2018
911
return $B.$bool($.x)
912
}
913
914
bool.numerator = int.numerator
915
bool.denominator = int.denominator
916
bool.real = int.real
917
bool.imag = int.imag
918
Feb 11, 2018
919
_b_.bool = bool
Feb 11, 2018
921
$B.set_func_names(bool, "builtins")
Sep 5, 2014
923
})(__BRYTHON__)