Skip to content
Permalink
Newer
Older
100644 892 lines (805 sloc) 27.1 KB
Sep 5, 2014
1
;(function($B){
2
3
var _b_ = $B.builtins
Sep 5, 2014
4
Mar 10, 2018
5
function $err(op, other){
6
var msg = "unsupported operand type(s) for " + op +
7
": 'int' and '" + $B.class_name(other) + "'"
8
throw _b_.TypeError.$factory(msg)
Sep 5, 2014
9
}
10
11
function int_value(obj){
12
// Instances of int subclasses that call int.__new__(cls, value)
13
// have an attribute $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){
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,
370
__dict__: _b_.dict.$factory(),
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
Mar 10, 2018
387
int.__pow__ = function(self, other, z){
388
if(_b_.isinstance(other, int)){
389
other = int_value(other)
390
switch(other.valueOf()) {
391
case 0:
392
return int.$factory(1)
393
case 1:
394
return int.$factory(self.valueOf())
Feb 9, 2015
395
}
396
if(z !== undefined && z !== _b_.None){
May 19, 2017
397
// If z is provided, the algorithm is faster than computing
398
// self ** other then applying the modulo z
399
if(z == 1){return 0}
400
var result = 1,
401
base = self % z,
402
exponent = other,
403
long_int = $B.long_int
Feb 20, 2020
404
if(exponent < 0){
405
var gcd, inv, _
406
[gcd, inv, _] = extended_euclidean(self, z)
407
if(gcd !== 1){
408
throw _b_.ValueError.$factory("not relative primes: " +
409
self + ' and ' + z)
410
}
411
return int.__pow__(inv, -exponent, z)
412
}
413
while(exponent > 0){
414
if(exponent % 2 == 1){
415
if(result * base > $B.max_int){
416
result = long_int.__mul__(
417
long_int.$factory(result),
418
long_int.$factory(base))
419
result = long_int.__mod__(result, z)
420
}else{
421
result = (result * base) % z
422
}
423
}
424
exponent = exponent >> 1
425
if(base * base > $B.max_int){
426
base = long_int.__mul__(long_int.$factory(base),
427
long_int.$factory(base))
428
base = long_int.__mod__(base, z)
429
}else{
430
base = (base * base) % z
431
}
May 19, 2017
432
}
May 19, 2017
434
}
Mar 10, 2018
435
var res = Math.pow(self.valueOf(), other.valueOf())
436
if(res > $B.min_int && res < $B.max_int){return res}
May 19, 2017
437
else if(res !== Infinity && !isFinite(res)){return res}
Feb 11, 2018
439
return int.$factory($B.long_int.__pow__($B.long_int.$factory(self),
440
$B.long_int.$factory(other)))
May 19, 2017
441
}
Sep 5, 2014
442
}
443
if(_b_.isinstance(other, _b_.float)) {
Mar 10, 2018
444
if(self >= 0){return new Number(Math.pow(self, other.valueOf()))}
445
else{
446
// use complex power
447
return _b_.complex.__pow__($B.make_complex(self, 0), other)
449
}else if(_b_.isinstance(other, _b_.complex)){
Mar 10, 2018
450
var preal = Math.pow(self, other.$real),
451
ln = Math.log(self)
Mar 10, 2018
452
return $B.make_complex(preal * Math.cos(ln), preal * Math.sin(ln))
Sep 5, 2014
453
}
454
var rpow = $B.$getattr(other, "__rpow__", _b_.None)
455
if(rpow !== _b_.None){
456
return rpow(self)
457
}
Mar 10, 2018
458
$err("**", other)
Sep 5, 2014
459
}
460
461
int.__repr__ = function(self){
Mar 10, 2018
462
if(self === int){return "<class 'int'>"}
Sep 5, 2014
463
return self.toString()
464
}
465
466
// bitwise right shift
Mar 10, 2018
467
int.__rshift__ = function(self, other){
468
if(_b_.isinstance(other, int)){
Feb 11, 2018
470
return int.$factory($B.long_int.__rshift__($B.long_int.$factory(self),
471
$B.long_int.$factory(other)))
473
var rrshift = $B.$getattr(other, "__rrshift__", _b_.None)
474
if(rrshift !== _b_.None){return rrshift(self)}
475
$err('>>', other)
476
}
Sep 5, 2014
477
478
int.__setattr__ = function(self, attr, value){
Mar 10, 2018
479
if(typeof self == "number"){
480
if(int.$factory[attr] === undefined){
481
throw _b_.AttributeError.$factory(
482
"'int' object has no attribute '" + attr + "'")
Mar 10, 2018
484
throw _b_.AttributeError.$factory(
485
"'int' object attribute '" + attr + "' is read-only")
Sep 5, 2014
487
}
488
// subclasses of int can have attributes set
489
_b_.dict.$setitem(self.__dict__, attr, value)
490
return _b_.None
Sep 5, 2014
491
}
492
493
int.__str__ = int.__repr__
Sep 5, 2014
494
Mar 10, 2018
495
int.__truediv__ = function(self, other){
496
if(_b_.isinstance(other, int)){
498
if(other == 0){
499
throw _b_.ZeroDivisionError.$factory("division by zero")
500
}
Mar 10, 2018
501
if(other.__class__ === $B.long_int){
502
return new Number(self / parseInt(other.value))
503
}
504
return new Number(self / other)
Sep 5, 2014
505
}
506
if(_b_.isinstance(other, _b_.float)){
Mar 10, 2018
507
if(!other.valueOf()){
508
throw _b_.ZeroDivisionError.$factory("division by zero")
Mar 10, 2018
509
}
510
return new Number(self / other)
Sep 5, 2014
511
}
512
if(_b_.isinstance(other, _b_.complex)){
Mar 10, 2018
513
var cmod = other.$real * other.$real + other.$imag * other.$imag
514
if(cmod == 0){throw _b_.ZeroDivisionError.$factory("division by zero")}
Mar 10, 2018
515
return $B.make_complex(self * other.$real / cmod,
516
-self * other.$imag / cmod)
Sep 5, 2014
517
}
518
if(_b_.hasattr(other, "__rtruediv__")){
519
return $B.$getattr(other, "__rtruediv__")(self)
Mar 10, 2018
520
}
521
$err("/", other)
Sep 5, 2014
522
}
523
524
int.bit_length = function(self){
525
s = _b_.bin(self)
526
s = $B.$getattr(s, "lstrip")("-0b") // remove leading zeros and minus sign
Sep 5, 2014
527
return s.length // len('100101') --> 6
528
}
529
530
// descriptors
531
int.numerator = function(self){return self}
532
int.denominator = function(self){return int.$factory(1)}
533
int.imag = function(self){return int.$factory(0)}
534
int.real = function(self){return self}
535
Mar 10, 2018
536
$B.max_int32 = (1 << 30) * 2 - 1
537
$B.min_int32 = - $B.max_int32
539
// code for operands & | ^
Mar 10, 2018
540
var $op_func = function(self, other){
541
if(_b_.isinstance(other, int)) {
Mar 10, 2018
542
if(other.__class__ === $B.long_int){
543
return $B.long_int.__sub__($B.long_int.$factory(self),
544
$B.long_int.$factory(other))
Mar 23, 2018
547
if(self > $B.max_int32 || self < $B.min_int32 ||
548
other > $B.max_int32 || other < $B.min_int32){
Mar 10, 2018
549
return $B.long_int.__sub__($B.long_int.$factory(self),
550
$B.long_int.$factory(other))
Mar 21, 2018
552
return self - other
Jun 7, 2015
553
}
554
if(_b_.isinstance(other, _b_.bool)){return self - other}
555
var rsub = $B.$getattr(other, "__rsub__", _b_.None)
556
if(rsub !== _b_.None){return rsub(self)}
Mar 10, 2018
557
$err("-", other)
Sep 5, 2014
558
}
559
Mar 10, 2018
560
$op_func += "" // source code
561
var $ops = {"&": "and", "|": "or", "^": "xor"}
Sep 5, 2014
562
for(var $op in $ops){
Mar 10, 2018
563
var opf = $op_func.replace(/-/gm, $op)
564
opf = opf.replace(new RegExp("sub", "gm"), $ops[$op])
565
eval("int.__" + $ops[$op] + "__ = " + opf)
Sep 5, 2014
566
}
567
568
// code for + and -
Mar 10, 2018
569
var $op_func = function(self, other){
570
if(_b_.isinstance(other, int)){
Mar 10, 2018
572
if(typeof other == "number"){
573
var res = self.valueOf() - other.valueOf()
574
if(res > $B.min_int && res < $B.max_int){return res}
Feb 11, 2018
575
else{return $B.long_int.__sub__($B.long_int.$factory(self),
576
$B.long_int.$factory(other))}
Mar 10, 2018
577
}else if(typeof other == "boolean"){
Mar 21, 2018
578
return other ? self - 1 : self
579
}else{
Feb 11, 2018
580
return $B.long_int.__sub__($B.long_int.$factory(self),
581
$B.long_int.$factory(other))
Sep 5, 2014
583
}
584
if(_b_.isinstance(other, _b_.float)){
Mar 10, 2018
585
return new Number(self - other)
Sep 5, 2014
586
}
587
if(_b_.isinstance(other, _b_.complex)){
Mar 10, 2018
588
return $B.make_complex(self - other.$real, -other.$imag)
Sep 5, 2014
589
}
590
if(_b_.isinstance(other, _b_.bool)){
Mar 10, 2018
591
var bool_value = 0;
592
if(other.valueOf()){bool_value = 1}
593
return self - bool_value
Sep 5, 2014
594
}
595
if(_b_.isinstance(other, _b_.complex)){
596
return $B.make_complex(self.valueOf() - other.$real, other.$imag)
Sep 5, 2014
597
}
598
var rsub = $B.$getattr(other, "__rsub__", _b_.None)
599
if(rsub !== _b_.None){return rsub(self)}
Mar 10, 2018
600
throw $err("-", other)
Sep 5, 2014
601
}
Mar 10, 2018
602
$op_func += "" // source code
603
var $ops = {"+": "add", "-": "sub"}
Sep 5, 2014
604
for(var $op in $ops){
Mar 10, 2018
605
var opf = $op_func.replace(/-/gm, $op)
606
opf = opf.replace(new RegExp("sub", "gm"), $ops[$op])
607
eval("int.__" + $ops[$op] + "__ = " + opf)
Sep 5, 2014
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() > other.valueOf()
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
$B.make_rmethods(int)
Sep 5, 2014
640
Mar 10, 2018
641
var $valid_digits = function(base) {
642
var digits = ""
643
if(base === 0){return "0"}
644
if(base < 10){
Mar 21, 2018
645
for(var i = 0; i < base; i++){digits += String.fromCharCode(i + 48)}
Sep 5, 2014
646
return digits
647
}
648
Mar 10, 2018
649
var digits = "0123456789"
Sep 5, 2014
650
// A = 65 (10 + 55)
Mar 21, 2018
651
for (var i = 10; i < base; i++) {digits += String.fromCharCode(i + 55)}
Sep 5, 2014
652
return digits
653
}
654
655
int.$factory = function(value, base){
656
// int() with no argument returns 0
Mar 10, 2018
657
if(value === undefined){return 0}
659
// int() of an integer returns the integer if base is undefined
Mar 10, 2018
660
if(typeof value == "number" &&
661
(base === undefined || base == 10)){return parseInt(value)}
663
if(_b_.isinstance(value, _b_.complex)){
664
throw _b_.TypeError.$factory("can't convert complex to int")
Dec 28, 2014
665
}
Mar 10, 2018
667
var $ns = $B.args("int", 2, {x:null, base:null}, ["x", "base"], arguments,
668
{"base": 10}, null, null),
669
value = $ns["x"],
670
base = $ns["base"]
672
if(_b_.isinstance(value, _b_.float) && base == 10){
Mar 10, 2018
673
if(value < $B.min_int || value > $B.max_int){
Feb 11, 2018
674
return $B.long_int.$from_float(value)
Mar 10, 2018
676
else{return value > 0 ? Math.floor(value) : Math.ceil(value)}
Sep 5, 2014
678
Mar 10, 2018
679
if(! (base >=2 && base <= 36)){
Dec 26, 2014
680
// throw error (base must be 0, or 2-36)
Mar 10, 2018
681
if(base != 0){throw _b_.ValueError.$factory("invalid base")}
Dec 26, 2014
682
}
683
Mar 10, 2018
684
if(typeof value == "number"){
Mar 10, 2018
686
if(base == 10){
687
if(value < $B.min_int || value > $B.max_int){
688
return $B.long_int.$factory(value)
689
}
Mar 10, 2018
691
}else if(value.toString().search("e") > -1){
Dec 26, 2014
692
// can't convert to another base if value is too big
Mar 10, 2018
693
throw _b_.OverflowError.$factory("can't convert to base " + base)
Dec 26, 2014
694
}else{
Mar 10, 2018
695
var res = parseInt(value, base)
696
if(value < $B.min_int || value > $B.max_int){
697
return $B.long_int.$factory(value, base)
698
}
Dec 26, 2014
700
}
701
}
Sep 5, 2014
702
Mar 10, 2018
703
if(value === true){return Number(1)}
704
if(value === false){return Number(0)}
705
if(value.__class__ === $B.long_int){
706
var z = parseInt(value.value)
Mar 10, 2018
707
if(z > $B.min_int && z < $B.max_int){return z}
708
else{return value}
709
}
Sep 5, 2014
710
Mar 10, 2018
711
base = $B.$GetInt(base)
712
function invalid(value, base){
713
throw _b_.ValueError.$factory("invalid literal for int() with base " +
714
base + ": '" + _b_.str.$factory(value) + "'")
715
}
Sep 5, 2014
716
717
if(_b_.isinstance(value, _b_.str)){value = value.valueOf()}
Mar 10, 2018
718
if(typeof value == "string") {
719
var _value = value.trim() // remove leading/trailing whitespace
720
if(_value.length == 2 && base == 0 &&
721
(_value == "0b" || _value == "0o" || _value == "0x")){
722
throw _b_.ValueError.$factory("invalid value")
723
}
724
if(_value.length >2) {
725
var _pre = _value.substr(0, 2).toUpperCase()
726
if(base == 0){
727
if(_pre == "0B"){base = 2}
728
if(_pre == "0O"){base = 8}
729
if(_pre == "0X"){base = 16}
730
}else if(_pre == "0X" && base != 16){invalid(_value, base)}
731
else if(_pre == "0O" && base != 8){invalid(_value, base)}
732
if((_pre == "0B" && base == 2) || _pre == "0O" || _pre == "0X"){
Mar 10, 2018
733
_value = _value.substr(2)
734
while(_value.startsWith("_")){
735
_value = _value.substr(1)
736
}
Mar 10, 2018
737
}
738
}else if(base == 0){
739
// eg int("1\n", 0)
740
base = 10
Mar 10, 2018
741
}
742
var _digits = $valid_digits(base),
743
_re = new RegExp("^[+-]?[" + _digits + "]" +
744
"[" + _digits + "_]*$", "i"),
745
match = _re.exec(_value)
746
if(match === null){
747
invalid(value, base)
748
}else{
749
value = _value.replace(/_/g, "")
Mar 10, 2018
750
}
751
if(base <= 10 && ! isFinite(value)){invalid(_value, base)}
752
var res = parseInt(value, base)
Mar 10, 2018
753
if(res < $B.min_int || res > $B.max_int){
754
return $B.long_int.$factory(value, base)
Mar 10, 2018
755
}
756
return res
Sep 5, 2014
757
}
759
if(_b_.isinstance(value, [_b_.bytes, _b_.bytearray])){
760
return int.$factory($B.$getattr(value, "decode")("latin-1"), base)
761
}
763
var num_value = $B.to_num(value, ["__int__", "__index__", "__trunc__"])
764
if(num_value === null){
765
throw _b_.TypeError.$factory(
766
"int() argument must be a string, a bytes-like " +
767
"object or a number, not '" + $B.class_name(value) + "'")
768
}
769
return num_value
Sep 5, 2014
770
}
771
772
$B.set_func_names(int, "builtins")
Sep 5, 2014
774
_b_.int = int
775
Feb 11, 2018
777
$B.$bool = function(obj){ // return true or false
Mar 10, 2018
778
if(obj === null || obj === undefined ){ return false}
779
switch(typeof obj){
780
case "boolean":
781
return obj
782
case "number":
783
case "string":
784
if(obj){return true}
785
return false
786
default:
787
if(obj.$is_class){return true}
788
var klass = obj.__class__ || $B.get_class(obj),
789
missing = {},
790
bool_method = $B.$getattr(klass, "__bool__", missing)
791
if(bool_method === missing){
792
try{return _b_.len(obj) > 0}
Mar 10, 2018
793
catch(err){return true}
795
var res = $B.$call(bool_method)(obj)
796
if(res !== true && res !== false){
797
throw _b_.TypeError.$factory("__bool__ should return " +
798
"bool, returned " + $B.class_name(res))
799
}
800
return res
Mar 10, 2018
801
}
802
}
Feb 11, 2018
803
}
804
805
var bool = {
806
__bases__: [int],
Feb 11, 2018
807
__class__: _b_.type,
808
__mro__: [int, _b_.object],
809
$infos:{
810
__name__: "bool",
811
__module__: "builtins"
812
},
Feb 11, 2018
813
$is_class: true,
814
$native: true
815
}
Feb 22, 2019
817
var methods = $B.op2method.subset("operations", "binary", "comparisons",
818
"boolean")
819
for(var op in methods){
820
var method = "__" + methods[op] + "__"
821
bool[method] = (function(op){
822
return function(self, other){
823
var value = self ? 1 : 0
824
if(int[op] !== undefined){
825
return int[op](value, other)
826
}
827
}
828
})(method)
Feb 11, 2018
831
bool.__and__ = function(self, other){
832
if(_b_.isinstance(other, bool)){
833
return self && other
834
}else if(_b_.isinstance(other, int)){
835
return int.__and__(bool.__index__(self), int.__index__(other))
836
}
837
return _b_.NotImplemented
Mar 10, 2018
840
bool.__hash__ = bool.__index__ = bool.__int__ = function(self){
841
if(self.valueOf()) return 1
842
return 0
843
}
844
Feb 11, 2018
845
bool.__neg__ = function(self){return -$B.int_or_bool(self)}
Feb 11, 2018
847
bool.__or__ = function(self, other){
848
if(_b_.isinstance(other, bool)){
849
return self || other
850
}else if(_b_.isinstance(other, int)){
851
return int.__or__(bool.__index__(self), int.__index__(other))
852
}
853
return _b_.NotImplemented
Feb 11, 2018
856
bool.__pos__ = $B.int_or_bool
Feb 11, 2018
858
bool.__repr__ = bool.__str__ = function(self){
859
return self ? "True" : "False"
Feb 11, 2018
862
bool.__setattr__ = function(self, attr){
863
if(_b_.dir(self).indexOf(attr) > -1){
864
var msg = "attribute '" + attr + "' of 'int' objects is not writable"
865
}else{
866
var msg = "'bool' object has no attribute '" + attr + "'"
867
}
868
throw _b_.AttributeError.$factory(msg)
Feb 11, 2018
871
bool.__xor__ = function(self, other) {
872
if(_b_.isinstance(other, bool)){
873
return self ^ other ? true : false
874
}else if(_b_.isinstance(other, int)){
875
return int.__xor__(bool.__index__(self), int.__index__(other))
876
}
877
return _b_.NotImplemented
Feb 11, 2018
880
bool.$factory = function(){
881
// Calls $B.$bool, which is used inside the generated JS code and skips
882
// arguments control.
Mar 10, 2018
883
var $ = $B.args("bool", 1, {x: null}, ["x"],
884
arguments,{x: false}, null, null)
Feb 11, 2018
885
return $B.$bool($.x)
886
}
887
888
_b_.bool = bool
Feb 11, 2018
890
$B.set_func_names(bool, "builtins")
Sep 5, 2014
892
})(__BRYTHON__)