Skip to content
Permalink
Newer
Older
100644 906 lines (819 sloc) 27.5 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() {
Mar 10, 2018
42
var $ = $B.args("from_bytes", 3,
43
{bytes:null, byteorder:null, signed:null},
Mar 10, 2018
44
["bytes", "byteorder", "signed"],
45
arguments, {signed: false}, null, null)
Sep 5, 2014
46
47
var x = $.bytes,
48
byteorder = $.byteorder,
Mar 10, 2018
49
signed = $.signed,
50
_bytes, _len
51
if(_b_.isinstance(x, [_b_.bytes, _b_.bytearray])){
Mar 10, 2018
52
_bytes = x.source
53
_len = x.source.length
54
}else{
55
_bytes = _b_.list.$factory(x)
56
_len = _bytes.length
Mar 10, 2018
57
for(var i = 0; i < _len; i++){
58
_b_.bytes.$factory([_bytes[i]])
59
}
Sep 5, 2014
60
}
Mar 10, 2018
62
case "big":
63
var num = _bytes[_len - 1]
64
var _mult = 256
65
for(var i = _len - 2; i >= 0; i--){
66
// For operations, use the functions that can take or return
67
// big integers
68
num = $B.add($B.mul(_mult, _bytes[i]), num)
69
_mult = $B.mul(_mult,256)
70
}
71
if(! signed){return num}
72
if(_bytes[0] < 128){return num}
73
return $B.sub(num, _mult)
74
case "little":
75
var num = _bytes[0]
76
if(num >= 128){num = num - 256}
77
var _mult = 256
78
for(var i = 1; i < _len; i++){
79
num = $B.add($B.mul(_mult, _bytes[i]), num)
80
_mult = $B.mul(_mult, 256)
81
}
82
if(! signed){return num}
83
if(_bytes[_len - 1] < 128){return num}
84
return $B.sub(num, _mult)
Sep 5, 2014
85
}
86
Mar 10, 2018
87
throw _b_.ValueError.$factory("byteorder must be either 'little' or 'big'")
Sep 5, 2014
88
}
89
90
int.to_bytes = function(){
91
var $ = $B.args("to_bytes", 3,
92
{self: null, len: null, byteorder: null},
93
["self", "len", "byteorder"],
94
arguments, {}, "args", "kw"),
95
self = $.self,
96
len = $.len,
97
byteorder = $.byteorder,
98
kwargs = $.kw
99
if(! _b_.isinstance(len, _b_.int)){
100
throw _b_.TypeError.$factory("integer argument expected, got " +
102
}
103
if(["little", "big"].indexOf(byteorder) == -1){
104
throw _b_.ValueError.$factory("byteorder must be either 'little' or 'big'")
105
}
106
var signed = kwargs.$string_dict["signed"] || false,
107
res = []
108
109
if(self < 0){
110
if(! signed){
111
throw _b_.OverflowError.$factory("can't convert negative int to unsigned")
112
}
113
self = Math.pow(256, len) + self
114
}
115
var value = self
116
while(true){
117
var quotient = Math.floor(value / 256),
118
rest = value - 256 * quotient
119
res.push(rest)
120
if(quotient == 0){
121
break
122
}
123
value = quotient
124
}
125
if(res.length > len){
126
throw _b_.OverflowError.$factory("int too big to convert")
127
}else{
128
while(res.length < len){
129
res = res.concat([0])
130
}
131
}
132
if(byteorder == "big"){res = res.reverse()}
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)){
Mar 10, 2018
243
if(!other.valueOf()){
244
throw _b_.ZeroDivisionError.$factory("division by zero")
Mar 10, 2018
245
}
246
return Math.floor(self / other)
Sep 5, 2014
247
}
248
if(_b_.hasattr(other, "__rfloordiv__")){
249
return $B.$getattr(other, "__rfloordiv__")(self)
Sep 5, 2014
250
}
Mar 10, 2018
251
$err("//", other)
Sep 5, 2014
252
}
253
254
int.__hash__ = function(self){
Mar 23, 2018
255
if(self === undefined){
256
return int.__hashvalue__ || $B.$py_next_hash-- // for hash of int type (not instance of int)
257
}
258
return self.valueOf()
259
}
Sep 5, 2014
260
261
//int.__ior__ = function(self,other){return self | other} // bitwise OR
Sep 5, 2014
262
263
int.__index__ = function(self){
264
return int_value(self)
265
}
Sep 5, 2014
266
267
int.__init__ = function(self, value){
Mar 10, 2018
268
if(value === undefined){value = 0}
Sep 5, 2014
269
self.toString = function(){return value}
270
return _b_.None
Sep 5, 2014
271
}
272
273
int.__int__ = function(self){return self}
Sep 5, 2014
274
275
int.__invert__ = function(self){return ~self}
Sep 5, 2014
276
Mar 10, 2018
278
int.__lshift__ = function(self, other){
279
if(_b_.isinstance(other, int)){
Mar 10, 2018
281
return int.$factory($B.long_int.__lshift__($B.long_int.$factory(self),
282
$B.long_int.$factory(other)))
284
var rlshift = $B.$getattr(other, "__rlshift__", _b_.None)
285
if(rlshift !== _b_.None){return rlshift(self)}
Mar 10, 2018
286
$err("<<", other)
Mar 10, 2018
289
int.__mod__ = function(self, other) {
Sep 5, 2014
290
// can't use Javascript % because it works differently for negative numbers
291
if(_b_.isinstance(other,_b_.tuple) && other.length == 1){other = other[0]}
292
if(other.__class__ === $B.long_int){
293
return $B.long_int.__mod__($B.long_int.$factory(self), other)
294
}
295
if(_b_.isinstance(other, [int, _b_.float, bool])){
Mar 10, 2018
297
if(other === false){other = 0}
298
else if(other === true){other = 1}
299
if(other == 0){throw _b_.ZeroDivisionError.$factory(
300
"integer division or modulo by zero")}
Mar 10, 2018
301
return (self % other + other) % other
Sep 5, 2014
302
}
303
if(_b_.hasattr(other, "__rmod__")){
304
return $B.$getattr(other, "__rmod__")(self)
305
}
Mar 10, 2018
306
$err("%", other)
Sep 5, 2014
307
}
308
309
int.__mro__ = [_b_.object]
Sep 5, 2014
310
Mar 10, 2018
311
int.__mul__ = function(self, other){
312
Sep 5, 2014
313
var val = self.valueOf()
Jan 22, 2015
314
315
// this will be quick check, so lets do it early.
Mar 10, 2018
316
if(typeof other === "string") {
Jan 22, 2015
317
return other.repeat(val)
318
}
319
320
if(_b_.isinstance(other, int)){
Mar 10, 2018
322
var res = self * other
323
if(res > $B.min_int && res < $B.max_int){return res}
324
else{
325
return int.$factory($B.long_int.__mul__($B.long_int.$factory(self),
326
$B.long_int.$factory(other)))
327
}
329
if(_b_.isinstance(other, _b_.float)){
Mar 10, 2018
330
return new Number(self * other)
332
if(_b_.isinstance(other, _b_.bool)){
Mar 10, 2018
333
if(other.valueOf()){return self}
334
return int.$factory(0)
Sep 5, 2014
335
}
336
if(_b_.isinstance(other, _b_.complex)){
337
return $B.make_complex(int.__mul__(self, other.$real),
338
int.__mul__(self, other.$imag))
Sep 5, 2014
339
}
340
if(_b_.isinstance(other, [_b_.list, _b_.tuple])){
Sep 5, 2014
341
var res = []
342
// make temporary copy of list
Mar 10, 2018
343
var $temp = other.slice(0, other.length)
344
for(var i = 0; i < val; i++){res = res.concat($temp)}
345
if(_b_.isinstance(other, _b_.tuple)){res = _b_.tuple.$factory(res)}
Sep 5, 2014
346
return res
347
}
348
if(_b_.hasattr(other, "__rmul__")){
349
return $B.$getattr(other, "__rmul__")(self)
350
}
Mar 10, 2018
351
$err("*", other)
Sep 5, 2014
352
}
353
Feb 22, 2019
354
int.__ne__ = function(self, other){
355
var res = int.__eq__(self, other)
356
return (res === _b_.NotImplemented) ? res : !res
357
}
358
359
int.__neg__ = function(self){return -self}
Sep 5, 2014
360
361
int.__new__ = function(cls, value){
Mar 10, 2018
362
if(cls === undefined){
363
throw _b_.TypeError.$factory("int.__new__(): not enough arguments")
364
}else if(! _b_.isinstance(cls, _b_.type)){
365
throw _b_.TypeError.$factory("int.__new__(X): X is not a type object")
366
}
367
if(cls === int){return int.$factory(value)}
368
return {
369
__class__: cls,
Mar 10, 2018
372
}
Sep 5, 2014
373
}
374
375
int.__pos__ = function(self){return self}
Sep 5, 2014
376
Feb 20, 2020
377
function extended_euclidean(a, b){
378
var d, u, v
379
if(b == 0){
380
return [a, 1, 0]
381
}else{
382
[d, u, v] = extended_euclidean(b, a % b)
383
return [d, v, u - Math.floor(a / b) * v]
384
}
385
}
386
387
$B.use_bigint = 0
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
$B.use_bigint++
442
return {
443
__class__: $B.long_int,
444
value: ($B.BigInt(self) ** $B.BigInt(other)).toString(),
445
pos: true
446
}
447
}
448
return $B.long_int.__pow__($B.long_int.$from_int(self),
449
$B.long_int.$from_int(other))
May 19, 2017
450
}
Sep 5, 2014
451
}
452
if(_b_.isinstance(other, _b_.float)) {
Mar 10, 2018
453
if(self >= 0){return new Number(Math.pow(self, other.valueOf()))}
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)){
Mar 10, 2018
516
if(!other.valueOf()){
517
throw _b_.ZeroDivisionError.$factory("division by zero")
Mar 10, 2018
518
}
519
return new Number(self / other)
Sep 5, 2014
520
}
521
if(_b_.isinstance(other, _b_.complex)){
Mar 10, 2018
522
var cmod = other.$real * other.$real + other.$imag * other.$imag
523
if(cmod == 0){throw _b_.ZeroDivisionError.$factory("division by zero")}
Mar 10, 2018
524
return $B.make_complex(self * other.$real / cmod,
525
-self * other.$imag / cmod)
Sep 5, 2014
526
}
527
if(_b_.hasattr(other, "__rtruediv__")){
528
return $B.$getattr(other, "__rtruediv__")(self)
Mar 10, 2018
529
}
530
$err("/", other)
Sep 5, 2014
531
}
532
533
int.bit_length = function(self){
534
s = _b_.bin(self)
535
s = $B.$getattr(s, "lstrip")("-0b") // remove leading zeros and minus sign
Sep 5, 2014
536
return s.length // len('100101') --> 6
537
}
538
539
// descriptors
540
int.numerator = function(self){return self}
541
int.denominator = function(self){return int.$factory(1)}
542
int.imag = function(self){return int.$factory(0)}
543
int.real = function(self){return self}
544
Mar 10, 2018
545
$B.max_int32 = (1 << 30) * 2 - 1
546
$B.min_int32 = - $B.max_int32
548
// code for operands & | ^
Mar 10, 2018
549
var $op_func = function(self, other){
550
if(_b_.isinstance(other, int)) {
Mar 10, 2018
551
if(other.__class__ === $B.long_int){
552
return $B.long_int.__sub__($B.long_int.$factory(self),
553
$B.long_int.$factory(other))
Mar 23, 2018
556
if(self > $B.max_int32 || self < $B.min_int32 ||
557
other > $B.max_int32 || other < $B.min_int32){
Mar 10, 2018
558
return $B.long_int.__sub__($B.long_int.$factory(self),
559
$B.long_int.$factory(other))
Mar 21, 2018
561
return self - other
Jun 7, 2015
562
}
563
if(_b_.isinstance(other, _b_.bool)){return self - other}
564
var rsub = $B.$getattr(other, "__rsub__", _b_.None)
565
if(rsub !== _b_.None){return rsub(self)}
Mar 10, 2018
566
$err("-", other)
Sep 5, 2014
567
}
568
Mar 10, 2018
569
$op_func += "" // source code
570
var $ops = {"&": "and", "|": "or", "^": "xor"}
Sep 5, 2014
571
for(var $op in $ops){
Mar 10, 2018
572
var opf = $op_func.replace(/-/gm, $op)
573
opf = opf.replace(new RegExp("sub", "gm"), $ops[$op])
574
eval("int.__" + $ops[$op] + "__ = " + opf)
Sep 5, 2014
575
}
576
577
// code for + and -
Mar 10, 2018
578
var $op_func = function(self, other){
579
if(_b_.isinstance(other, int)){
Mar 10, 2018
581
if(typeof other == "number"){
582
var res = self.valueOf() - other.valueOf()
583
if(res > $B.min_int && res < $B.max_int){return res}
Feb 11, 2018
584
else{return $B.long_int.__sub__($B.long_int.$factory(self),
585
$B.long_int.$factory(other))}
Mar 10, 2018
586
}else if(typeof other == "boolean"){
Mar 21, 2018
587
return other ? self - 1 : self
588
}else{
Feb 11, 2018
589
return $B.long_int.__sub__($B.long_int.$factory(self),
590
$B.long_int.$factory(other))
Sep 5, 2014
592
}
593
if(_b_.isinstance(other, _b_.float)){
Mar 10, 2018
594
return new Number(self - other)
Sep 5, 2014
595
}
596
if(_b_.isinstance(other, _b_.complex)){
Mar 10, 2018
597
return $B.make_complex(self - other.$real, -other.$imag)
Sep 5, 2014
598
}
599
if(_b_.isinstance(other, _b_.bool)){
Mar 10, 2018
600
var bool_value = 0;
601
if(other.valueOf()){bool_value = 1}
602
return self - bool_value
Sep 5, 2014
603
}
604
if(_b_.isinstance(other, _b_.complex)){
605
return $B.make_complex(self.valueOf() - other.$real, other.$imag)
Sep 5, 2014
606
}
607
var rsub = $B.$getattr(other, "__rsub__", _b_.None)
608
if(rsub !== _b_.None){return rsub(self)}
609
console.log("err", self, other)
610
console.log($B.frames_stack.slice())
Mar 10, 2018
611
throw $err("-", other)
Sep 5, 2014
612
}
Mar 10, 2018
613
$op_func += "" // source code
614
var $ops = {"+": "add", "-": "sub"}
Sep 5, 2014
615
for(var $op in $ops){
Mar 10, 2018
616
var opf = $op_func.replace(/-/gm, $op)
617
opf = opf.replace(new RegExp("sub", "gm"), $ops[$op])
618
eval("int.__" + $ops[$op] + "__ = " + opf)
Sep 5, 2014
619
}
620
621
// comparison methods
Mar 10, 2018
622
var $comp_func = function(self, other){
Mar 23, 2018
623
if(other.__class__ === $B.long_int){
Feb 11, 2018
624
return $B.long_int.__lt__(other, $B.long_int.$factory(self))
626
if(_b_.isinstance(other, int)){
627
other = int_value(other)
628
return self.valueOf() > other.valueOf()
629
}else if(_b_.isinstance(other, _b_.float)){
630
return self.valueOf() > other.valueOf()
631
}else if(_b_.isinstance(other, _b_.bool)) {
Feb 11, 2018
632
return self.valueOf() > _b_.bool.__hash__(other)
Sep 5, 2014
633
}
634
if(_b_.hasattr(other, "__int__") || _b_.hasattr(other, "__index__")){
635
return int.__gt__(self, $B.$GetInt(other))
Sep 5, 2014
639
}
Mar 10, 2018
640
$comp_func += "" // source code
Sep 5, 2014
642
for(var $op in $B.$comps){
Mar 10, 2018
643
eval("int.__"+$B.$comps[$op] + "__ = " +
644
$comp_func.replace(/>/gm, $op).
645
replace(/__gt__/gm,"__" + $B.$comps[$op] + "__").
646
replace(/__lt__/, "__" + $B.$inv_comps[$op] + "__"))
Sep 5, 2014
647
}
648
649
// add "reflected" methods
650
$B.make_rmethods(int)
Sep 5, 2014
651
Mar 10, 2018
652
var $valid_digits = function(base) {
653
var digits = ""
654
if(base === 0){return "0"}
655
if(base < 10){
Mar 21, 2018
656
for(var i = 0; i < base; i++){digits += String.fromCharCode(i + 48)}
Sep 5, 2014
657
return digits
658
}
659
Mar 10, 2018
660
var digits = "0123456789"
Sep 5, 2014
661
// A = 65 (10 + 55)
Mar 21, 2018
662
for (var i = 10; i < base; i++) {digits += String.fromCharCode(i + 55)}
Sep 5, 2014
663
return digits
664
}
665
666
int.$factory = function(value, base){
667
// int() with no argument returns 0
Mar 10, 2018
668
if(value === undefined){return 0}
670
// int() of an integer returns the integer if base is undefined
Mar 10, 2018
671
if(typeof value == "number" &&
672
(base === undefined || base == 10)){return parseInt(value)}
674
if(_b_.isinstance(value, _b_.complex)){
675
throw _b_.TypeError.$factory("can't convert complex to int")
Dec 28, 2014
676
}
Mar 10, 2018
678
var $ns = $B.args("int", 2, {x:null, base:null}, ["x", "base"], arguments,
679
{"base": 10}, null, null),
680
value = $ns["x"],
681
base = $ns["base"]
683
if(_b_.isinstance(value, _b_.float) && base == 10){
684
value = _b_.float.numerator(value) // for float subclasses
Mar 10, 2018
685
if(value < $B.min_int || value > $B.max_int){
Feb 11, 2018
686
return $B.long_int.$from_float(value)
Mar 10, 2018
688
else{return value > 0 ? Math.floor(value) : Math.ceil(value)}
Sep 5, 2014
690
Mar 10, 2018
691
if(! (base >=2 && base <= 36)){
Dec 26, 2014
692
// throw error (base must be 0, or 2-36)
Mar 10, 2018
693
if(base != 0){throw _b_.ValueError.$factory("invalid base")}
Dec 26, 2014
694
}
695
Mar 10, 2018
696
if(typeof value == "number"){
Mar 10, 2018
698
if(base == 10){
699
if(value < $B.min_int || value > $B.max_int){
700
return $B.long_int.$factory(value)
701
}
Mar 10, 2018
703
}else if(value.toString().search("e") > -1){
Dec 26, 2014
704
// can't convert to another base if value is too big
Mar 10, 2018
705
throw _b_.OverflowError.$factory("can't convert to base " + base)
Dec 26, 2014
706
}else{
Mar 10, 2018
707
var res = parseInt(value, base)
708
if(value < $B.min_int || value > $B.max_int){
709
return $B.long_int.$factory(value, base)
710
}
Dec 26, 2014
712
}
713
}
Sep 5, 2014
714
Mar 10, 2018
715
if(value === true){return Number(1)}
716
if(value === false){return Number(0)}
717
if(value.__class__ === $B.long_int){
718
var z = parseInt(value.value)
Mar 10, 2018
719
if(z > $B.min_int && z < $B.max_int){return z}
720
else{return value}
721
}
Sep 5, 2014
722
Mar 10, 2018
723
base = $B.$GetInt(base)
724
function invalid(value, base){
725
throw _b_.ValueError.$factory("invalid literal for int() with base " +
726
base + ": '" + _b_.str.$factory(value) + "'")
727
}
Sep 5, 2014
728
729
if(_b_.isinstance(value, _b_.str)){value = value.valueOf()}
Mar 10, 2018
730
if(typeof value == "string") {
731
var _value = value.trim() // remove leading/trailing whitespace
732
if(_value.length == 2 && base == 0 &&
733
(_value == "0b" || _value == "0o" || _value == "0x")){
734
throw _b_.ValueError.$factory("invalid value")
735
}
736
if(_value.length > 2) {
Mar 10, 2018
737
var _pre = _value.substr(0, 2).toUpperCase()
738
if(base == 0){
739
if(_pre == "0B"){base = 2}
740
if(_pre == "0O"){base = 8}
741
if(_pre == "0X"){base = 16}
742
}else if(_pre == "0X" && base != 16){invalid(_value, base)}
743
else if(_pre == "0O" && base != 8){invalid(_value, base)}
744
if((_pre == "0B" && base == 2) || _pre == "0O" || _pre == "0X"){
Mar 10, 2018
745
_value = _value.substr(2)
746
while(_value.startsWith("_")){
747
_value = _value.substr(1)
748
}
Mar 10, 2018
749
}
750
}else if(base == 0){
751
// eg int("1\n", 0)
752
base = 10
Mar 10, 2018
753
}
754
var _digits = $valid_digits(base),
755
_re = new RegExp("^[+-]?[" + _digits + "]" +
756
"[" + _digits + "_]*$", "i"),
757
match = _re.exec(_value)
758
if(match === null){
759
invalid(value, base)
760
}else{
761
value = _value.replace(/_/g, "")
Mar 10, 2018
762
}
763
if(base <= 10 && ! isFinite(value)){
764
invalid(_value, base)
765
}
766
var res = parseInt(value, base)
Mar 10, 2018
767
if(res < $B.min_int || res > $B.max_int){
768
return $B.long_int.$factory(value, base)
Mar 10, 2018
769
}
770
return res
Sep 5, 2014
771
}
773
if(_b_.isinstance(value, [_b_.bytes, _b_.bytearray])){
774
return int.$factory($B.$getattr(value, "decode")("latin-1"), base)
775
}
777
var num_value = $B.to_num(value, ["__int__", "__index__", "__trunc__"])
778
if(num_value === null){
779
throw _b_.TypeError.$factory(
780
"int() argument must be a string, a bytes-like " +
781
"object or a number, not '" + $B.class_name(value) + "'")
782
}
783
return num_value
Sep 5, 2014
784
}
785
786
$B.set_func_names(int, "builtins")
Sep 5, 2014
788
_b_.int = int
789
Feb 11, 2018
791
$B.$bool = function(obj){ // return true or false
Mar 10, 2018
792
if(obj === null || obj === undefined ){ return false}
793
switch(typeof obj){
794
case "boolean":
795
return obj
796
case "number":
797
case "string":
798
if(obj){return true}
799
return false
800
default:
801
if(obj.$is_class){return true}
802
var klass = obj.__class__ || $B.get_class(obj),
803
missing = {},
804
bool_method = $B.$getattr(klass, "__bool__", missing)
805
if(bool_method === missing){
806
try{return _b_.len(obj) > 0}
Mar 10, 2018
807
catch(err){return true}
809
var res = $B.$call(bool_method)(obj)
810
if(res !== true && res !== false){
811
throw _b_.TypeError.$factory("__bool__ should return " +
812
"bool, returned " + $B.class_name(res))
813
}
814
return res
Mar 10, 2018
815
}
816
}
Feb 11, 2018
817
}
818
819
var bool = {
820
__bases__: [int],
Feb 11, 2018
821
__class__: _b_.type,
822
__mro__: [int, _b_.object],
823
$infos:{
824
__name__: "bool",
825
__module__: "builtins"
826
},
Feb 11, 2018
827
$is_class: true,
828
$native: true
829
}
Feb 22, 2019
831
var methods = $B.op2method.subset("operations", "binary", "comparisons",
832
"boolean")
833
for(var op in methods){
834
var method = "__" + methods[op] + "__"
835
bool[method] = (function(op){
836
return function(self, other){
837
var value = self ? 1 : 0
838
if(int[op] !== undefined){
839
return int[op](value, other)
840
}
841
}
842
})(method)
Feb 11, 2018
845
bool.__and__ = function(self, other){
846
if(_b_.isinstance(other, bool)){
847
return self && other
848
}else if(_b_.isinstance(other, int)){
849
return int.__and__(bool.__index__(self), int.__index__(other))
850
}
851
return _b_.NotImplemented
Mar 10, 2018
854
bool.__hash__ = bool.__index__ = bool.__int__ = function(self){
855
if(self.valueOf()) return 1
856
return 0
857
}
858
Feb 11, 2018
859
bool.__neg__ = function(self){return -$B.int_or_bool(self)}
Feb 11, 2018
861
bool.__or__ = function(self, other){
862
if(_b_.isinstance(other, bool)){
863
return self || other
864
}else if(_b_.isinstance(other, int)){
865
return int.__or__(bool.__index__(self), int.__index__(other))
866
}
867
return _b_.NotImplemented
Feb 11, 2018
870
bool.__pos__ = $B.int_or_bool
Feb 11, 2018
872
bool.__repr__ = bool.__str__ = function(self){
873
return self ? "True" : "False"
Feb 11, 2018
876
bool.__setattr__ = function(self, attr){
877
if(_b_.dir(self).indexOf(attr) > -1){
878
var msg = "attribute '" + attr + "' of 'int' objects is not writable"
879
}else{
880
var msg = "'bool' object has no attribute '" + attr + "'"
881
}
882
throw _b_.AttributeError.$factory(msg)
Feb 11, 2018
885
bool.__xor__ = function(self, other) {
886
if(_b_.isinstance(other, bool)){
887
return self ^ other ? true : false
888
}else if(_b_.isinstance(other, int)){
889
return int.__xor__(bool.__index__(self), int.__index__(other))
890
}
891
return _b_.NotImplemented
Feb 11, 2018
894
bool.$factory = function(){
895
// Calls $B.$bool, which is used inside the generated JS code and skips
896
// arguments control.
Mar 10, 2018
897
var $ = $B.args("bool", 1, {x: null}, ["x"],
898
arguments,{x: false}, null, null)
Feb 11, 2018
899
return $B.$bool($.x)
900
}
901
902
_b_.bool = bool
Feb 11, 2018
904
$B.set_func_names(bool, "builtins")
Sep 5, 2014
906
})(__BRYTHON__)