Skip to content
Permalink
Newer
Older
100644 855 lines (766 sloc) 26 KB
Sep 5, 2014
1
;(function($B){
2
3
var bltns = $B.InjectBuiltins()
4
eval(bltns)
Mar 10, 2018
6
var object = _b_.object,
7
$N = _b_.None
Sep 5, 2014
8
Mar 10, 2018
9
function $err(op, other){
10
var msg = "unsupported operand type(s) for " + op +
11
": 'int' and '" + $B.class_name(other) + "'"
12
throw _b_.TypeError.$factory(msg)
Sep 5, 2014
13
}
14
15
function int_value(obj){
16
// Instances of int subclasses that call int.__new__(cls, value)
17
// have an attribute $value set
18
return obj.$value !== undefined ? obj.$value : obj
19
}
20
21
// dictionary for built-in class 'int'
Feb 11, 2018
22
var int = {__class__: _b_.type,
23
__dir__: object.__dir__,
24
$infos: {
25
__module__: "builtins",
26
__name__: "int"
27
},
28
$is_class: true,
29
$native: true,
30
$descriptors: {
Mar 10, 2018
31
"numerator": true,
32
"denominator": true,
33
"imag": true,
34
"real": true
Sep 5, 2014
36
}
37
38
int.from_bytes = function() {
Mar 10, 2018
39
var $ = $B.args("from_bytes", 3,
40
{bytes:null, byteorder:null, signed:null},
Mar 10, 2018
41
["bytes", "byteorder", "signed"],
42
arguments, {signed: False}, null, null)
Sep 5, 2014
43
44
var x = $.bytes,
45
byteorder = $.byteorder,
Mar 10, 2018
46
signed = $.signed,
47
_bytes, _len
48
if(isinstance(x, [_b_.bytes, _b_.bytearray])){
49
_bytes = x.source
50
_len = x.source.length
51
}else{
52
_bytes = _b_.list.$factory(x)
53
_len = _bytes.length
Mar 10, 2018
54
for(var i = 0; i < _len; i++){
55
_b_.bytes.$factory([_bytes[i]])
56
}
Sep 5, 2014
57
}
Mar 10, 2018
59
case "big":
60
var num = _bytes[_len - 1]
61
var _mult = 256
62
for(var i = _len - 2; i >= 0; i--){
63
// For operations, use the functions that can take or return
64
// big integers
65
num = $B.add($B.mul(_mult, _bytes[i]), num)
66
_mult = $B.mul(_mult,256)
67
}
68
if(! signed){return num}
69
if(_bytes[0] < 128){return num}
70
return $B.sub(num, _mult)
71
case "little":
72
var num = _bytes[0]
73
if(num >= 128){num = num - 256}
74
var _mult = 256
75
for(var i = 1; i < _len; i++){
76
num = $B.add($B.mul(_mult, _bytes[i]), num)
77
_mult = $B.mul(_mult, 256)
78
}
79
if(! signed){return num}
80
if(_bytes[_len - 1] < 128){return num}
81
return $B.sub(num, _mult)
Sep 5, 2014
82
}
83
Mar 10, 2018
84
throw _b_.ValueError.$factory("byteorder must be either 'little' or 'big'")
Sep 5, 2014
85
}
86
87
int.to_bytes = function(){
88
var $ = $B.args("to_bytes", 3,
89
{self: null, len: null, byteorder: null},
90
["self", "len", "byteorder"],
91
arguments, {}, "args", "kw"),
92
self = $.self,
93
len = $.len,
94
byteorder = $.byteorder,
95
kwargs = $.kw
96
if(! _b_.isinstance(len, _b_.int)){
97
throw _b_.TypeError.$factory("integer argument expected, got " +
99
}
100
if(["little", "big"].indexOf(byteorder) == -1){
101
throw _b_.ValueError.$factory("byteorder must be either 'little' or 'big'")
102
}
103
var signed = kwargs.$string_dict["signed"] || false,
104
res = []
105
106
if(self < 0){
107
if(! signed){
108
throw _b_.OverflowError.$factory("can't convert negative int to unsigned")
109
}
110
self = Math.pow(256, len) + self
111
}
112
var value = self
113
while(true){
114
var quotient = Math.floor(value / 256),
115
rest = value - 256 * quotient
116
res.push(rest)
117
if(quotient == 0){
118
break
119
}
120
value = quotient
121
}
122
if(res.length > len){
123
throw _b_.OverflowError.$factory("int too big to convert")
124
}
125
if(byteorder == "big"){res = res.reverse()}
126
return {
127
__class__: _b_.bytes,
128
source: res
129
}
Sep 5, 2014
130
}
131
132
133
//int.__and__ = function(self,other){return self & other} // bitwise AND
Sep 5, 2014
134
135
int.__abs__ = function(self){return abs(self)}
137
int.__bool__ = function(self){
138
return int_value(self).valueOf() == 0 ? false : true
139
}
Sep 5, 2014
140
141
int.__ceil__ = function(self){return Math.ceil(int_value(self))}
143
int.__divmod__ = function(self, other){return divmod(self, other)}
Mar 10, 2018
145
int.__eq__ = function(self, other){
Sep 5, 2014
146
// compare object "self" to class "int"
Mar 10, 2018
147
if(other === undefined){return self === int}
148
if(isinstance(other, int)){
149
return self.valueOf() == int_value(other).valueOf()
150
}
Mar 10, 2018
151
if(isinstance(other, _b_.float)){return self.valueOf() == other.valueOf()}
152
if(isinstance(other, _b_.complex)){
153
if(other.$imag != 0){return False}
154
return self.valueOf() == other.$real
Sep 5, 2014
155
}
156
return _b_.NotImplemented
Sep 5, 2014
157
}
158
159
int.__float__ = function(self){
160
return new Number(self)
161
}
162
163
function preformat(self, fmt){
str
Feb 10, 2018
164
if(fmt.empty){return _b_.str.$factory(self)}
Mar 10, 2018
165
if(fmt.type && 'bcdoxXn'.indexOf(fmt.type) == -1){
166
throw _b_.ValueError.$factory("Unknown format code '" + fmt.type +
167
"' for object of type 'int'")
168
}
170
switch(fmt.type){
171
case undefined:
Mar 10, 2018
172
case "d":
173
res = self.toString()
174
break
Mar 10, 2018
175
case "b":
176
res = (fmt.alternate ? "0b" : "") + self.toString(2)
177
break
Mar 10, 2018
178
case "c":
179
res = _b_.chr(self)
180
break
Mar 10, 2018
181
case "o":
182
res = (fmt.alternate ? "0o" : "") + self.toString(8)
183
break
Mar 10, 2018
184
case "x":
185
res = (fmt.alternate ? "0x" : "") + self.toString(16)
186
break
Mar 10, 2018
187
case "X":
188
res = (fmt.alternate ? "0X" : "") + self.toString(16).toUpperCase()
189
break
Mar 10, 2018
190
case "n":
191
return self // fix me
192
}
194
if(fmt.sign !== undefined){
195
if((fmt.sign == " " || fmt.sign == "+" ) && self >= 0){
196
res = fmt.sign + res
197
}
198
}
199
return res
200
}
201
202
Mar 10, 2018
203
int.__format__ = function(self, format_spec){
204
var fmt = new $B.parse_format_spec(format_spec)
Mar 10, 2018
205
if(fmt.type && 'eEfFgG%'.indexOf(fmt.type) != -1){
206
// Call __format__ on float(self)
207
return _b_.float.__format__(self, format_spec)
Mar 10, 2018
209
fmt.align = fmt.align || ">"
210
var res = preformat(self, fmt)
211
if(fmt.comma){
Mar 10, 2018
212
var sign = res[0] == "-" ? "-" : "",
213
rest = res.substr(sign.length),
214
len = rest.length,
215
nb = Math.ceil(rest.length/3),
216
chunks = []
Mar 10, 2018
217
for(var i = 0; i < nb; i++){
218
chunks.push(rest.substring(len - 3 * i - 3, len - 3 * i))
219
}
220
chunks.reverse()
Mar 10, 2018
221
res = sign + chunks.join(",")
222
}
223
return $B.format_width(res, fmt)
Sep 5, 2014
224
}
225
226
int.__floordiv__ = function(self,other){
227
if(other.__class__ == $B.long_int){
228
return $B.long_int.__floordiv__($B.long_int.$factory(self), other)
229
}
Mar 10, 2018
230
if(isinstance(other, int)){
Mar 10, 2018
232
if(other == 0){throw ZeroDivisionError.$factory("division by zero")}
233
return Math.floor(self / other)
Sep 5, 2014
234
}
Mar 10, 2018
235
if(isinstance(other, _b_.float)){
236
if(!other.valueOf()){
237
throw ZeroDivisionError.$factory("division by zero")
238
}
239
return Math.floor(self / other)
Sep 5, 2014
240
}
Mar 10, 2018
241
if(hasattr(other, "__rfloordiv__")){
242
return getattr(other, "__rfloordiv__")(self)
Sep 5, 2014
243
}
Mar 10, 2018
244
$err("//", other)
Sep 5, 2014
245
}
246
247
int.__hash__ = function(self){
Mar 23, 2018
248
if(self === undefined){
249
return int.__hashvalue__ || $B.$py_next_hash-- // for hash of int type (not instance of int)
250
}
251
return self.valueOf()
252
}
Sep 5, 2014
253
254
//int.__ior__ = function(self,other){return self | other} // bitwise OR
Sep 5, 2014
255
256
int.__index__ = function(self){
257
return int_value(self)
258
}
Sep 5, 2014
259
260
int.__init__ = function(self, value){
Mar 10, 2018
261
if(value === undefined){value = 0}
Sep 5, 2014
262
self.toString = function(){return value}
Sep 5, 2014
264
}
265
266
int.__int__ = function(self){return self}
Sep 5, 2014
267
268
int.__invert__ = function(self){return ~self}
Sep 5, 2014
269
Mar 10, 2018
271
int.__lshift__ = function(self, other){
272
if(isinstance(other, int)){
Mar 10, 2018
274
return int.$factory($B.long_int.__lshift__($B.long_int.$factory(self),
275
$B.long_int.$factory(other)))
Mar 10, 2018
277
var rlshift = getattr(other, "__rlshift__", None)
278
if(rlshift !== None){return rlshift(self)}
279
$err("<<", other)
Mar 10, 2018
282
int.__mod__ = function(self, other) {
Sep 5, 2014
283
// can't use Javascript % because it works differently for negative numbers
Mar 10, 2018
284
if(isinstance(other,_b_.tuple) && other.length == 1){other = other[0]}
285
if(other.__class__ === $B.long_int){
286
return $B.long_int.__mod__($B.long_int.$factory(self), other)
287
}
Mar 10, 2018
288
if(isinstance(other, [int, _b_.float, bool])){
Mar 10, 2018
290
if(other === false){other = 0}
291
else if(other === true){other = 1}
292
if(other == 0){throw _b_.ZeroDivisionError.$factory(
293
"integer division or modulo by zero")}
Mar 10, 2018
294
return (self % other + other) % other
Sep 5, 2014
295
}
Mar 10, 2018
296
if(hasattr(other, "__rmod__")){return getattr(other, "__rmod__")(self)}
297
$err("%", other)
Sep 5, 2014
298
}
299
300
int.__mro__ = [object]
Sep 5, 2014
301
Mar 10, 2018
302
int.__mul__ = function(self, other){
303
Sep 5, 2014
304
var val = self.valueOf()
Jan 22, 2015
305
306
// this will be quick check, so lets do it early.
Mar 10, 2018
307
if(typeof other === "string") {
Jan 22, 2015
308
return other.repeat(val)
309
}
310
Mar 10, 2018
311
if(isinstance(other, int)){
Mar 10, 2018
313
var res = self * other
314
if(res > $B.min_int && res < $B.max_int){return res}
315
else{
316
return int.$factory($B.long_int.__mul__($B.long_int.$factory(self),
317
$B.long_int.$factory(other)))
318
}
Mar 10, 2018
320
if(isinstance(other, _b_.float)){
321
return new Number(self * other)
Mar 10, 2018
323
if(isinstance(other, _b_.bool)){
324
if(other.valueOf()){return self}
325
return int.$factory(0)
Sep 5, 2014
326
}
Mar 10, 2018
327
if(isinstance(other, _b_.complex)){
328
return $B.make_complex(int.__mul__(self, other.$real),
329
int.__mul__(self, other.$imag))
Sep 5, 2014
330
}
Mar 10, 2018
331
if(isinstance(other, [_b_.list, _b_.tuple])){
Sep 5, 2014
332
var res = []
333
// make temporary copy of list
Mar 10, 2018
334
var $temp = other.slice(0, other.length)
335
for(var i = 0; i < val; i++){res = res.concat($temp)}
336
if(isinstance(other, _b_.tuple)){res = _b_.tuple.$factory(res)}
Sep 5, 2014
337
return res
338
}
Mar 10, 2018
339
if(hasattr(other, "__rmul__")){return getattr(other, "__rmul__")(self)}
340
$err("*", other)
Sep 5, 2014
341
}
342
Feb 22, 2019
343
int.__ne__ = function(self, other){
344
var res = int.__eq__(self, other)
345
return (res === _b_.NotImplemented) ? res : !res
346
}
347
348
int.__neg__ = function(self){return -self}
Sep 5, 2014
349
350
int.__new__ = function(cls, value){
Mar 10, 2018
351
if(cls === undefined){
352
throw _b_.TypeError.$factory("int.__new__(): not enough arguments")
353
}else if(! isinstance(cls, _b_.type)){
354
throw _b_.TypeError.$factory("int.__new__(X): X is not a type object")
355
}
356
if(cls === int){return int.$factory(value)}
357
return {
358
__class__: cls,
359
__dict__: _b_.dict.$factory(),
Mar 10, 2018
361
}
Sep 5, 2014
362
}
363
364
int.__pos__ = function(self){return self}
Sep 5, 2014
365
Mar 10, 2018
366
int.__pow__ = function(self, other, z){
367
if(isinstance(other, int)){
368
other = int_value(other)
369
switch(other.valueOf()) {
370
case 0:
371
return int.$factory(1)
372
case 1:
373
return int.$factory(self.valueOf())
Feb 9, 2015
374
}
May 19, 2017
375
if(z !== undefined && z !== null){
376
// If z is provided, the algorithm is faster than computing
377
// self ** other then applying the modulo z
378
if(z == 1){return 0}
379
var result = 1,
380
base = self % z,
381
exponent = other,
382
long_int = $B.long_int
383
while(exponent > 0){
384
if(exponent % 2 == 1){
385
if(result * base > $B.max_int){
386
result = long_int.__mul__(
387
long_int.$factory(result),
388
long_int.$factory(base))
389
result = long_int.__mod__(result, z)
390
}else{
391
result = (result * base) % z
392
}
393
}
394
exponent = exponent >> 1
395
if(base * base > $B.max_int){
396
base = long_int.__mul__(long_int.$factory(base),
397
long_int.$factory(base))
398
base = long_int.__mod__(base, z)
399
}else{
400
base = (base * base) % z
401
}
May 19, 2017
402
}
May 19, 2017
404
}
Mar 10, 2018
405
var res = Math.pow(self.valueOf(), other.valueOf())
406
if(res > $B.min_int && res < $B.max_int){return res}
May 19, 2017
407
else if(res !== Infinity && !isFinite(res)){return res}
Feb 11, 2018
409
return int.$factory($B.long_int.__pow__($B.long_int.$factory(self),
410
$B.long_int.$factory(other)))
May 19, 2017
411
}
Sep 5, 2014
412
}
413
if(isinstance(other, _b_.float)) {
Mar 10, 2018
414
if(self >= 0){return new Number(Math.pow(self, other.valueOf()))}
415
else{
416
// use complex power
417
return _b_.complex.__pow__($B.make_complex(self, 0), other)
419
}else if(isinstance(other, _b_.complex)){
Mar 10, 2018
420
var preal = Math.pow(self, other.$real),
421
ln = Math.log(self)
Mar 10, 2018
422
return $B.make_complex(preal * Math.cos(ln), preal * Math.sin(ln))
Sep 5, 2014
423
}
Mar 10, 2018
424
if(hasattr(other, "__rpow__")){return getattr(other, "__rpow__")(self)}
425
$err("**", other)
Sep 5, 2014
426
}
427
428
int.__repr__ = function(self){
Mar 10, 2018
429
if(self === int){return "<class 'int'>"}
Sep 5, 2014
430
return self.toString()
431
}
432
433
// bitwise right shift
Mar 10, 2018
434
int.__rshift__ = function(self, other){
435
if(isinstance(other, int)){
Feb 11, 2018
437
return int.$factory($B.long_int.__rshift__($B.long_int.$factory(self),
438
$B.long_int.$factory(other)))
Mar 10, 2018
440
var rrshift = getattr(other, "__rrshift__", None)
441
if(rrshift !== None){return rrshift(self)}
442
$err('>>', other)
443
}
Sep 5, 2014
444
445
int.__setattr__ = function(self,attr,value){
Mar 10, 2018
446
if(typeof self == "number"){
447
if(int.$factory[attr] === undefined){
448
throw _b_.AttributeError.$factory(
449
"'int' object has no attribute '" + attr + "'")
Mar 10, 2018
451
throw _b_.AttributeError.$factory(
452
"'int' object attribute '" + attr + "' is read-only")
Sep 5, 2014
454
}
455
// subclasses of int can have attributes set
456
self[attr] = value
Sep 5, 2014
458
}
459
460
int.__str__ = int.__repr__
Sep 5, 2014
461
Mar 10, 2018
462
int.__truediv__ = function(self, other){
463
if(isinstance(other, int)){
Mar 10, 2018
465
if(other == 0){throw ZeroDivisionError.$factory("division by zero")}
466
if(other.__class__ === $B.long_int){
467
return new Number(self / parseInt(other.value))
468
}
469
return new Number(self / other)
Sep 5, 2014
470
}
Mar 10, 2018
471
if(isinstance(other, _b_.float)){
472
if(!other.valueOf()){
473
throw ZeroDivisionError.$factory("division by zero")
474
}
475
return new Number(self / other)
Sep 5, 2014
476
}
Mar 10, 2018
477
if(isinstance(other, _b_.complex)){
478
var cmod = other.$real * other.$real + other.$imag * other.$imag
479
if(cmod == 0){throw ZeroDivisionError.$factory("division by zero")}
480
return $B.make_complex(self * other.$real / cmod,
481
-self * other.$imag / cmod)
Sep 5, 2014
482
}
Mar 10, 2018
483
if(hasattr(other, "__rtruediv__")){
484
return getattr(other, "__rtruediv__")(self)
485
}
486
$err("/", other)
Sep 5, 2014
487
}
488
489
//int.__xor__ = function(self,other){return self ^ other} // bitwise XOR
Sep 5, 2014
490
491
int.bit_length = function(self){
Sep 5, 2014
492
s = bin(self)
Mar 10, 2018
493
s = getattr(s, "lstrip")("-0b") // remove leading zeros and minus sign
Sep 5, 2014
494
return s.length // len('100101') --> 6
495
}
496
497
// descriptors
498
int.numerator = function(self){return self}
499
int.denominator = function(self){return int.$factory(1)}
500
int.imag = function(self){return int.$factory(0)}
501
int.real = function(self){return self}
502
Mar 10, 2018
503
$B.max_int32 = (1 << 30) * 2 - 1
504
$B.min_int32 = - $B.max_int32
506
// code for operands & | ^
Mar 10, 2018
507
var $op_func = function(self, other){
508
if(isinstance(other, int)) {
509
if(other.__class__ === $B.long_int){
510
return $B.long_int.__sub__($B.long_int.$factory(self),
511
$B.long_int.$factory(other))
Mar 23, 2018
514
if(self > $B.max_int32 || self < $B.min_int32 ||
515
other > $B.max_int32 || other < $B.min_int32){
Mar 10, 2018
516
return $B.long_int.__sub__($B.long_int.$factory(self),
517
$B.long_int.$factory(other))
Mar 21, 2018
519
return self - other
Jun 7, 2015
520
}
Mar 10, 2018
521
if(isinstance(other, _b_.bool)){return self - other}
522
if(hasattr(other, "__rsub__")){return getattr(other, "__rsub__")(self)}
523
$err("-", other)
Sep 5, 2014
524
}
525
Mar 10, 2018
526
$op_func += "" // source code
527
var $ops = {"&": "and", "|": "or", "^": "xor"}
Sep 5, 2014
528
for(var $op in $ops){
Mar 10, 2018
529
var opf = $op_func.replace(/-/gm, $op)
530
opf = opf.replace(new RegExp("sub", "gm"), $ops[$op])
531
eval("int.__" + $ops[$op] + "__ = " + opf)
Sep 5, 2014
532
}
533
534
// code for + and -
Mar 10, 2018
535
var $op_func = function(self, other){
536
if(isinstance(other, int)){
Mar 10, 2018
538
if(typeof other == "number"){
539
var res = self.valueOf() - other.valueOf()
540
if(res > $B.min_int && res < $B.max_int){return res}
Feb 11, 2018
541
else{return $B.long_int.__sub__($B.long_int.$factory(self),
542
$B.long_int.$factory(other))}
Mar 10, 2018
543
}else if(typeof other == "boolean"){
Mar 21, 2018
544
return other ? self - 1 : self
545
}else{
Feb 11, 2018
546
return $B.long_int.__sub__($B.long_int.$factory(self),
547
$B.long_int.$factory(other))
Sep 5, 2014
549
}
Mar 10, 2018
550
if(isinstance(other, _b_.float)){
551
return new Number(self - other)
Sep 5, 2014
552
}
Mar 10, 2018
553
if(isinstance(other, _b_.complex)){
554
return $B.make_complex(self - other.$real, -other.$imag)
Sep 5, 2014
555
}
Mar 10, 2018
556
if(isinstance(other, _b_.bool)){
557
var bool_value = 0;
558
if(other.valueOf()){bool_value = 1}
559
return self - bool_value
Sep 5, 2014
560
}
Mar 10, 2018
561
if(isinstance(other, _b_.complex)){
562
return $B.make_complex(self.valueOf() - other.$real, other.$imag)
Sep 5, 2014
563
}
Mar 10, 2018
564
var rsub = $B.$getattr(other, "__rsub__", None)
565
if(rsub !== None){return rsub(self)}
566
throw $err("-", other)
Sep 5, 2014
567
}
Mar 10, 2018
568
$op_func += "" // source code
569
var $ops = {"+": "add", "-": "sub"}
Sep 5, 2014
570
for(var $op in $ops){
Mar 10, 2018
571
var opf = $op_func.replace(/-/gm, $op)
572
opf = opf.replace(new RegExp("sub", "gm"), $ops[$op])
573
eval("int.__" + $ops[$op] + "__ = " + opf)
Sep 5, 2014
574
}
575
576
// comparison methods
Mar 10, 2018
577
var $comp_func = function(self, other){
Mar 23, 2018
578
if(other.__class__ === $B.long_int){
Feb 11, 2018
579
return $B.long_int.__lt__(other, $B.long_int.$factory(self))
581
if(isinstance(other, int)){
582
other = int_value(other)
583
return self.valueOf() > other.valueOf()
584
}else if(isinstance(other, _b_.float)){
585
return self.valueOf() > other.valueOf()
586
}else if(isinstance(other, _b_.bool)) {
Feb 11, 2018
587
return self.valueOf() > _b_.bool.__hash__(other)
Sep 5, 2014
588
}
Mar 10, 2018
589
if(hasattr(other, "__int__") || hasattr(other, "__index__")){
590
return int.__gt__(self, $B.$GetInt(other))
Sep 5, 2014
594
}
Mar 10, 2018
595
$comp_func += "" // source code
Sep 5, 2014
597
for(var $op in $B.$comps){
Mar 10, 2018
598
eval("int.__"+$B.$comps[$op] + "__ = " +
599
$comp_func.replace(/>/gm, $op).
600
replace(/__gt__/gm,"__" + $B.$comps[$op] + "__").
601
replace(/__lt__/, "__" + $B.$inv_comps[$op] + "__"))
Sep 5, 2014
602
}
603
604
// add "reflected" methods
605
$B.make_rmethods(int)
Sep 5, 2014
606
Mar 10, 2018
607
var $valid_digits = function(base) {
608
var digits = ""
609
if(base === 0){return "0"}
610
if(base < 10){
Mar 21, 2018
611
for(var i = 0; i < base; i++){digits += String.fromCharCode(i + 48)}
Sep 5, 2014
612
return digits
613
}
614
Mar 10, 2018
615
var digits = "0123456789"
Sep 5, 2014
616
// A = 65 (10 + 55)
Mar 21, 2018
617
for (var i = 10; i < base; i++) {digits += String.fromCharCode(i + 55)}
Sep 5, 2014
618
return digits
619
}
620
621
int.$factory = function(value, base){
622
// int() with no argument returns 0
Mar 10, 2018
623
if(value === undefined){return 0}
625
// int() of an integer returns the integer if base is undefined
Mar 10, 2018
626
if(typeof value == "number" &&
627
(base === undefined || base == 10)){return parseInt(value)}
Mar 10, 2018
629
if(base !== undefined){
630
if(! isinstance(value, [_b_.str, _b_.bytes, _b_.bytearray])){
631
throw TypeError.$factory(
632
"int() can't convert non-string with explicit base")
Dec 28, 2014
633
}
634
}
635
Mar 10, 2018
636
if(isinstance(value, _b_.complex)){
637
throw TypeError.$factory("can't convert complex to int")
Dec 28, 2014
638
}
Mar 10, 2018
639
var $ns = $B.args("int", 2, {x:null, base:null}, ["x", "base"], arguments,
640
{"base": 10}, null, null),
641
value = $ns["x"],
642
base = $ns["base"]
Mar 10, 2018
644
if(isinstance(value, _b_.float) && base == 10){
645
if(value < $B.min_int || value > $B.max_int){
Feb 11, 2018
646
return $B.long_int.$from_float(value)
Mar 10, 2018
648
else{return value > 0 ? Math.floor(value) : Math.ceil(value)}
Sep 5, 2014
650
Mar 10, 2018
651
if(! (base >=2 && base <= 36)){
Dec 26, 2014
652
// throw error (base must be 0, or 2-36)
Mar 10, 2018
653
if(base != 0){throw _b_.ValueError.$factory("invalid base")}
Dec 26, 2014
654
}
655
Mar 10, 2018
656
if(typeof value == "number"){
Mar 10, 2018
658
if(base == 10){
659
if(value < $B.min_int || value > $B.max_int){
660
return $B.long_int.$factory(value)
661
}
Mar 10, 2018
663
}else if(value.toString().search("e") > -1){
Dec 26, 2014
664
// can't convert to another base if value is too big
Mar 10, 2018
665
throw _b_.OverflowError.$factory("can't convert to base " + base)
Dec 26, 2014
666
}else{
Mar 10, 2018
667
var res = parseInt(value, base)
668
if(value < $B.min_int || value > $B.max_int){
669
return $B.long_int.$factory(value, base)
670
}
Dec 26, 2014
672
}
673
}
Sep 5, 2014
674
Mar 10, 2018
675
if(value === true){return Number(1)}
676
if(value === false){return Number(0)}
677
if(value.__class__ === $B.long_int){
678
var z = parseInt(value.value)
Mar 10, 2018
679
if(z > $B.min_int && z < $B.max_int){return z}
680
else{return value}
681
}
Sep 5, 2014
682
Mar 10, 2018
683
base = $B.$GetInt(base)
684
function invalid(value, base){
685
throw _b_.ValueError.$factory("invalid literal for int() with base " +
686
base + ": '" + _b_.str.$factory(value) + "'")
687
}
Sep 5, 2014
688
Mar 10, 2018
689
if(isinstance(value, _b_.str)){value = value.valueOf()}
690
if(typeof value == "string") {
691
var _value = value.trim() // remove leading/trailing whitespace
692
if(_value.length == 2 && base == 0 &&
693
(_value == "0b" || _value == "0o" || _value == "0x")){
694
throw _b_.ValueError.$factory("invalid value")
695
}
696
if(_value.length >2) {
697
var _pre = _value.substr(0, 2).toUpperCase()
698
if(base == 0){
699
if(_pre == "0B"){base = 2}
700
if(_pre == "0O"){base = 8}
701
if(_pre == "0X"){base = 16}
702
}else if(_pre == "0X" && base != 16){invalid(_value, base)}
703
else if(_pre == "0O" && base != 8){invalid(_value, base)}
704
else if(_pre == "0B" && base != 2){invalid(_value, base)
Mar 10, 2018
705
}
706
if(_pre == "0B" || _pre == "0O" || _pre == "0X"){
707
_value = _value.substr(2)
708
while(_value.startsWith("_")){
709
_value = _value.substr(1)
710
}
Mar 10, 2018
711
}
712
}else if(base == 0){
713
// eg int("1\n", 0)
714
base = 10
Mar 10, 2018
715
}
716
var _digits = $valid_digits(base),
717
_re = new RegExp("^[+-]?[" + _digits + "]" +
718
"[" + _digits + "_]*$", "i"),
719
match = _re.exec(_value)
720
if(match === null){
721
invalid(value, base)
722
}else{
723
value = _value.replace(/_/g, "")
Mar 10, 2018
724
}
725
if(base <= 10 && ! isFinite(value)){invalid(_value, base)}
726
var res = parseInt(value, base)
Mar 10, 2018
727
if(res < $B.min_int || res > $B.max_int){
728
return $B.long_int.$factory(value, base)
Mar 10, 2018
729
}
730
return res
Sep 5, 2014
731
}
Mar 10, 2018
733
if(isinstance(value, [_b_.bytes, _b_.bytearray])){
734
return int.$factory($B.$getattr(value, "decode")("latin-1"), base)
735
}
Sep 5, 2014
736
Mar 10, 2018
737
if(hasattr(value, "__int__")){return getattr(value, "__int__")()}
738
if(hasattr(value, "__index__")){return getattr(value, "__index__")()}
739
if(hasattr(value, "__trunc__")){
740
var res = getattr(value, "__trunc__")(),
741
int_func = _b_.getattr(res, "__int__", null)
742
if(int_func === null){
743
throw TypeError.$factory("__trunc__ returned non-Integral (type "+
Mar 10, 2018
746
var res = int_func()
747
if(isinstance(res, int)){return int_value(res)}
Mar 10, 2018
748
throw TypeError.$factory("__trunc__ returned non-Integral (type "+
Mar 10, 2018
751
throw _b_.TypeError.$factory(
752
"int() argument must be a string, a bytes-like " +
753
"object or a number, not '" + $B.class_name(value) + "'")
Sep 5, 2014
754
}
755
756
$B.set_func_names(int, "builtins")
Sep 5, 2014
758
_b_.int = int
759
Feb 11, 2018
761
$B.$bool = function(obj){ // return true or false
Mar 10, 2018
762
if(obj === null || obj === undefined ){ return false}
763
switch(typeof obj){
764
case "boolean":
765
return obj
766
case "number":
767
case "string":
768
if(obj){return true}
769
return false
770
default:
771
if(obj.$is_class){return true}
772
var missing = {},
773
bool_func = $B.$getattr(obj, "__bool__", missing)
774
if(bool_func === missing){
Mar 21, 2018
775
try{return getattr(obj, "__len__")() > 0}
Mar 10, 2018
776
catch(err){return true}
777
}else{
778
return bool_func()
Mar 10, 2018
779
}
780
}
Feb 11, 2018
781
}
782
783
var bool = {
784
__bases__: [int],
Feb 11, 2018
785
__class__: _b_.type,
Feb 11, 2018
786
__mro__: [int, object],
787
$infos:{
788
__name__: "bool",
789
__module__: "builtins"
790
},
Feb 11, 2018
791
$is_class: true,
792
$native: true
793
}
Feb 22, 2019
795
var methods = $B.op2method.subset("operations", "binary", "comparisons",
796
"boolean")
797
for(var op in methods){
798
var method = "__" + methods[op] + "__"
799
bool[method] = (function(op){
800
return function(self, other){
801
var value = self ? 1 : 0
802
if(int[op] !== undefined){
803
return int[op](value, other)
804
}
805
}
806
})(method)
Feb 11, 2018
809
bool.__and__ = function(self, other){
810
return $B.$bool(int.__and__(self, other))
Mar 10, 2018
813
bool.__hash__ = bool.__index__ = bool.__int__ = function(self){
814
if(self.valueOf()) return 1
815
return 0
816
}
817
Feb 11, 2018
818
bool.__neg__ = function(self){return -$B.int_or_bool(self)}
Feb 11, 2018
820
bool.__or__ = function(self, other){
821
return $B.$bool(int.__or__(self, other))
Feb 11, 2018
824
bool.__pos__ = $B.int_or_bool
Feb 11, 2018
826
bool.__repr__ = bool.__str__ = function(self){
827
return self ? "True" : "False"
Feb 11, 2018
830
bool.__setattr__ = function(self, attr){
831
if(_b_.dir(self).indexOf(attr) > -1){
832
var msg = "attribute '" + attr + "' of 'int' objects is not writable"
833
}else{
834
var msg = "'bool' object has no attribute '" + attr + "'"
835
}
836
throw _b_.AttributeError.$factory(msg)
Feb 11, 2018
839
bool.__xor__ = function(self, other) {
840
return self.valueOf() != other.valueOf()
841
}
842
Feb 11, 2018
843
bool.$factory = function(){
844
// Calls $B.$bool, which is used inside the generated JS code and skips
845
// arguments control.
Mar 10, 2018
846
var $ = $B.args("bool", 1, {x: null}, ["x"],
847
arguments,{x: false}, null, null)
Feb 11, 2018
848
return $B.$bool($.x)
849
}
850
851
_b_.bool = bool
Feb 11, 2018
853
$B.set_func_names(bool, "builtins")
Sep 5, 2014
855
})(__BRYTHON__)