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