Skip to content
Permalink
Newer
Older
100644 879 lines (782 sloc) 26.6 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.get_class(other).__name__ + "'"
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 " +
98
$B.get_class(len).__name__)
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
343
int.__neg__ = function(self){return -self}
Sep 5, 2014
344
345
int.__new__ = function(cls, value){
Mar 10, 2018
346
if(cls === undefined){
347
throw _b_.TypeError.$factory("int.__new__(): not enough arguments")
348
}else if(! isinstance(cls, _b_.type)){
349
throw _b_.TypeError.$factory("int.__new__(X): X is not a type object")
350
}
351
if(cls === int){return int.$factory(value)}
352
return {
353
__class__: cls,
354
__dict__: _b_.dict.$factory(),
Mar 10, 2018
356
}
Sep 5, 2014
357
}
358
359
int.__pos__ = function(self){return self}
Sep 5, 2014
360
Mar 10, 2018
361
int.__pow__ = function(self, other, z){
362
if(isinstance(other, int)){
363
other = int_value(other)
364
switch(other.valueOf()) {
365
case 0:
366
return int.$factory(1)
367
case 1:
368
return int.$factory(self.valueOf())
Feb 9, 2015
369
}
May 19, 2017
370
if(z !== undefined && z !== null){
371
// If z is provided, the algorithm is faster than computing
372
// self ** other then applying the modulo z
373
if(z == 1){return 0}
374
var result = 1,
375
base = self % z,
376
exponent = other,
377
long_int = $B.long_int
378
while(exponent > 0){
379
if(exponent % 2 == 1){
380
if(result * base > $B.max_int){
381
result = long_int.__mul__(
382
long_int.$factory(result),
383
long_int.$factory(base))
384
result = long_int.__mod__(result, z)
385
}else{
386
result = (result * base) % z
387
}
388
}
389
exponent = exponent >> 1
390
if(base * base > $B.max_int){
391
base = long_int.__mul__(long_int.$factory(base),
392
long_int.$factory(base))
393
base = long_int.__mod__(base, z)
394
}else{
395
base = (base * base) % z
396
}
May 19, 2017
397
}
May 19, 2017
399
}
Mar 10, 2018
400
var res = Math.pow(self.valueOf(), other.valueOf())
401
if(res > $B.min_int && res < $B.max_int){return res}
May 19, 2017
402
else if(res !== Infinity && !isFinite(res)){return res}
Feb 11, 2018
404
return int.$factory($B.long_int.__pow__($B.long_int.$factory(self),
405
$B.long_int.$factory(other)))
May 19, 2017
406
}
Sep 5, 2014
407
}
408
if(isinstance(other, _b_.float)) {
Mar 10, 2018
409
if(self >= 0){return new Number(Math.pow(self, other.valueOf()))}
410
else{
411
// use complex power
412
return _b_.complex.__pow__($B.make_complex(self, 0), other)
414
}else if(isinstance(other, _b_.complex)){
Mar 10, 2018
415
var preal = Math.pow(self, other.$real),
416
ln = Math.log(self)
Mar 10, 2018
417
return $B.make_complex(preal * Math.cos(ln), preal * Math.sin(ln))
Sep 5, 2014
418
}
Mar 10, 2018
419
if(hasattr(other, "__rpow__")){return getattr(other, "__rpow__")(self)}
420
$err("**", other)
Sep 5, 2014
421
}
422
423
int.__repr__ = function(self){
Mar 10, 2018
424
if(self === int){return "<class 'int'>"}
Sep 5, 2014
425
return self.toString()
426
}
427
428
// bitwise right shift
Mar 10, 2018
429
int.__rshift__ = function(self, other){
430
if(isinstance(other, int)){
Feb 11, 2018
432
return int.$factory($B.long_int.__rshift__($B.long_int.$factory(self),
433
$B.long_int.$factory(other)))
Mar 10, 2018
435
var rrshift = getattr(other, "__rrshift__", None)
436
if(rrshift !== None){return rrshift(self)}
437
$err('>>', other)
438
}
Sep 5, 2014
439
440
int.__setattr__ = function(self,attr,value){
Mar 10, 2018
441
if(typeof self == "number"){
442
if(int.$factory[attr] === undefined){
443
throw _b_.AttributeError.$factory(
444
"'int' object has no attribute '" + attr + "'")
Mar 10, 2018
446
throw _b_.AttributeError.$factory(
447
"'int' object attribute '" + attr + "' is read-only")
Sep 5, 2014
449
}
450
// subclasses of int can have attributes set
451
self[attr] = value
Sep 5, 2014
453
}
454
455
int.__str__ = int.__repr__
Sep 5, 2014
456
Mar 10, 2018
457
int.__truediv__ = function(self, other){
458
if(isinstance(other, int)){
Mar 10, 2018
460
if(other == 0){throw ZeroDivisionError.$factory("division by zero")}
461
if(other.__class__ === $B.long_int){
462
return new Number(self / parseInt(other.value))
463
}
464
return new Number(self / other)
Sep 5, 2014
465
}
Mar 10, 2018
466
if(isinstance(other, _b_.float)){
467
if(!other.valueOf()){
468
throw ZeroDivisionError.$factory("division by zero")
469
}
470
return new Number(self / other)
Sep 5, 2014
471
}
Mar 10, 2018
472
if(isinstance(other, _b_.complex)){
473
var cmod = other.$real * other.$real + other.$imag * other.$imag
474
if(cmod == 0){throw ZeroDivisionError.$factory("division by zero")}
475
return $B.make_complex(self * other.$real / cmod,
476
-self * other.$imag / cmod)
Sep 5, 2014
477
}
Mar 10, 2018
478
if(hasattr(other, "__rtruediv__")){
479
return getattr(other, "__rtruediv__")(self)
480
}
481
$err("/", other)
Sep 5, 2014
482
}
483
484
//int.__xor__ = function(self,other){return self ^ other} // bitwise XOR
Sep 5, 2014
485
486
int.bit_length = function(self){
Sep 5, 2014
487
s = bin(self)
Mar 10, 2018
488
s = getattr(s, "lstrip")("-0b") // remove leading zeros and minus sign
Sep 5, 2014
489
return s.length // len('100101') --> 6
490
}
491
492
// descriptors
493
int.numerator = function(self){return self}
494
int.denominator = function(self){return int.$factory(1)}
495
int.imag = function(self){return int.$factory(0)}
496
int.real = function(self){return self}
497
Mar 10, 2018
498
$B.max_int32 = (1 << 30) * 2 - 1
499
$B.min_int32 = - $B.max_int32
501
// code for operands & | ^
Mar 10, 2018
502
var $op_func = function(self, other){
503
if(isinstance(other, int)) {
504
if(other.__class__ === $B.long_int){
505
return $B.long_int.__sub__($B.long_int.$factory(self),
506
$B.long_int.$factory(other))
Mar 23, 2018
509
if(self > $B.max_int32 || self < $B.min_int32 ||
510
other > $B.max_int32 || other < $B.min_int32){
Mar 10, 2018
511
return $B.long_int.__sub__($B.long_int.$factory(self),
512
$B.long_int.$factory(other))
Mar 21, 2018
514
return self - other
Jun 7, 2015
515
}
Mar 10, 2018
516
if(isinstance(other, _b_.bool)){return self - other}
517
if(hasattr(other, "__rsub__")){return getattr(other, "__rsub__")(self)}
518
$err("-", other)
Sep 5, 2014
519
}
520
Mar 10, 2018
521
$op_func += "" // source code
522
var $ops = {"&": "and", "|": "or", "^": "xor"}
Sep 5, 2014
523
for(var $op in $ops){
Mar 10, 2018
524
var opf = $op_func.replace(/-/gm, $op)
525
opf = opf.replace(new RegExp("sub", "gm"), $ops[$op])
526
eval("int.__" + $ops[$op] + "__ = " + opf)
Sep 5, 2014
527
}
528
529
// code for + and -
Mar 10, 2018
530
var $op_func = function(self, other){
531
if(isinstance(other, int)){
Mar 10, 2018
533
if(typeof other == "number"){
534
var res = self.valueOf() - other.valueOf()
535
if(res > $B.min_int && res < $B.max_int){return res}
Feb 11, 2018
536
else{return $B.long_int.__sub__($B.long_int.$factory(self),
537
$B.long_int.$factory(other))}
Mar 10, 2018
538
}else if(typeof other == "boolean"){
Mar 21, 2018
539
return other ? self - 1 : self
540
}else{
Feb 11, 2018
541
return $B.long_int.__sub__($B.long_int.$factory(self),
542
$B.long_int.$factory(other))
Sep 5, 2014
544
}
Mar 10, 2018
545
if(isinstance(other, _b_.float)){
546
return new Number(self - other)
Sep 5, 2014
547
}
Mar 10, 2018
548
if(isinstance(other, _b_.complex)){
549
return $B.make_complex(self - other.$real, -other.$imag)
Sep 5, 2014
550
}
Mar 10, 2018
551
if(isinstance(other, _b_.bool)){
552
var bool_value = 0;
553
if(other.valueOf()){bool_value = 1}
554
return self - bool_value
Sep 5, 2014
555
}
Mar 10, 2018
556
if(isinstance(other, _b_.complex)){
557
return $B.make_complex(self.valueOf() - other.$real, other.$imag)
Sep 5, 2014
558
}
Mar 10, 2018
559
var rsub = $B.$getattr(other, "__rsub__", None)
560
if(rsub !== None){return rsub(self)}
561
throw $err("-", other)
Sep 5, 2014
562
}
Mar 10, 2018
563
$op_func += "" // source code
564
var $ops = {"+": "add", "-": "sub"}
Sep 5, 2014
565
for(var $op in $ops){
Mar 10, 2018
566
var opf = $op_func.replace(/-/gm, $op)
567
opf = opf.replace(new RegExp("sub", "gm"), $ops[$op])
568
eval("int.__" + $ops[$op] + "__ = " + opf)
Sep 5, 2014
569
}
570
571
// comparison methods
Mar 10, 2018
572
var $comp_func = function(self, other){
Mar 23, 2018
573
if(other.__class__ === $B.long_int){
Feb 11, 2018
574
return $B.long_int.__lt__(other, $B.long_int.$factory(self))
576
if(isinstance(other, int)){
577
other = int_value(other)
578
return self.valueOf() > other.valueOf()
579
}else if(isinstance(other, _b_.float)){
580
return self.valueOf() > other.valueOf()
581
}else if(isinstance(other, _b_.bool)) {
Feb 11, 2018
582
return self.valueOf() > _b_.bool.__hash__(other)
Sep 5, 2014
583
}
Mar 10, 2018
584
if(hasattr(other, "__int__") || hasattr(other, "__index__")){
585
return int.__gt__(self, $B.$GetInt(other))
Sep 5, 2014
589
}
Mar 10, 2018
590
$comp_func += "" // source code
Sep 5, 2014
592
for(var $op in $B.$comps){
Mar 10, 2018
593
eval("int.__"+$B.$comps[$op] + "__ = " +
594
$comp_func.replace(/>/gm, $op).
595
replace(/__gt__/gm,"__" + $B.$comps[$op] + "__").
596
replace(/__lt__/, "__" + $B.$inv_comps[$op] + "__"))
Sep 5, 2014
597
}
598
599
// add "reflected" methods
600
$B.make_rmethods(int)
Sep 5, 2014
601
Mar 10, 2018
602
var $valid_digits = function(base) {
603
var digits = ""
604
if(base === 0){return "0"}
605
if(base < 10){
Mar 21, 2018
606
for(var i = 0; i < base; i++){digits += String.fromCharCode(i + 48)}
Sep 5, 2014
607
return digits
608
}
609
Mar 10, 2018
610
var digits = "0123456789"
Sep 5, 2014
611
// A = 65 (10 + 55)
Mar 21, 2018
612
for (var i = 10; i < base; i++) {digits += String.fromCharCode(i + 55)}
Sep 5, 2014
613
return digits
614
}
615
616
int.$factory = function(value, base){
617
// int() with no argument returns 0
Mar 10, 2018
618
if(value === undefined){return 0}
620
// int() of an integer returns the integer if base is undefined
Mar 10, 2018
621
if(typeof value == "number" &&
622
(base === undefined || base == 10)){return parseInt(value)}
Mar 10, 2018
624
if(base !== undefined){
625
if(! isinstance(value, [_b_.str, _b_.bytes, _b_.bytearray])){
626
throw TypeError.$factory(
627
"int() can't convert non-string with explicit base")
Dec 28, 2014
628
}
629
}
630
Mar 10, 2018
631
if(isinstance(value, _b_.complex)){
632
throw TypeError.$factory("can't convert complex to int")
Dec 28, 2014
633
}
Mar 10, 2018
634
var $ns = $B.args("int", 2, {x:null, base:null}, ["x", "base"], arguments,
635
{"base": 10}, null, null),
636
value = $ns["x"],
637
base = $ns["base"]
Mar 10, 2018
639
if(isinstance(value, _b_.float) && base == 10){
640
if(value < $B.min_int || value > $B.max_int){
Feb 11, 2018
641
return $B.long_int.$from_float(value)
Mar 10, 2018
643
else{return value > 0 ? Math.floor(value) : Math.ceil(value)}
Sep 5, 2014
645
Mar 10, 2018
646
if(! (base >=2 && base <= 36)){
Dec 26, 2014
647
// throw error (base must be 0, or 2-36)
Mar 10, 2018
648
if(base != 0){throw _b_.ValueError.$factory("invalid base")}
Dec 26, 2014
649
}
650
Mar 10, 2018
651
if(typeof value == "number"){
Mar 10, 2018
653
if(base == 10){
654
if(value < $B.min_int || value > $B.max_int){
655
return $B.long_int.$factory(value)
656
}
Mar 10, 2018
658
}else if(value.toString().search("e") > -1){
Dec 26, 2014
659
// can't convert to another base if value is too big
Mar 10, 2018
660
throw _b_.OverflowError.$factory("can't convert to base " + base)
Dec 26, 2014
661
}else{
Mar 10, 2018
662
var res = parseInt(value, base)
663
if(value < $B.min_int || value > $B.max_int){
664
return $B.long_int.$factory(value, base)
665
}
Dec 26, 2014
667
}
668
}
Sep 5, 2014
669
Mar 10, 2018
670
if(value === true){return Number(1)}
671
if(value === false){return Number(0)}
672
if(value.__class__ === $B.long_int){
673
var z = parseInt(value.value)
Mar 10, 2018
674
if(z > $B.min_int && z < $B.max_int){return z}
675
else{return value}
676
}
Sep 5, 2014
677
Mar 10, 2018
678
base = $B.$GetInt(base)
679
function invalid(value, base){
680
throw _b_.ValueError.$factory("invalid literal for int() with base " +
681
base + ": '" + _b_.str.$factory(value) + "'")
682
}
Sep 5, 2014
683
Mar 10, 2018
684
if(isinstance(value, _b_.str)){value = value.valueOf()}
685
if(typeof value == "string") {
686
var _value = value.trim() // remove leading/trailing whitespace
687
if(_value.length == 2 && base == 0 &&
688
(_value == "0b" || _value == "0o" || _value == "0x")){
689
throw _b_.ValueError.$factory("invalid value")
690
}
691
if(_value.length >2) {
692
var _pre = _value.substr(0, 2).toUpperCase()
693
if(base == 0){
694
if(_pre == "0B"){base = 2}
695
if(_pre == "0O"){base = 8}
696
if(_pre == "0X"){base = 16}
697
}else if(_pre == "0X" && base != 16){invalid(_value, base)}
698
else if(_pre == "0O" && base != 8){invalid(_value, base)}
699
else if(_pre == "0B" && base != 2){invalid(_value, base)
Mar 10, 2018
700
}
701
if(_pre == "0B" || _pre == "0O" || _pre == "0X"){
702
_value = _value.substr(2)
703
while(_value.startsWith("_")){
704
_value = _value.substr(1)
705
}
Mar 10, 2018
706
}
707
}else if(base == 0){
708
// eg int("1\n", 0)
709
base = 10
Mar 10, 2018
710
}
711
var _digits = $valid_digits(base),
712
_re = new RegExp("^[+-]?[" + _digits + "]" +
713
"[" + _digits + "_]*$", "i"),
714
match = _re.exec(_value)
715
if(match === null){
716
invalid(value, base)
717
}else{
718
value = _value.replace(/_/g, "")
Mar 10, 2018
719
}
720
if(base <= 10 && ! isFinite(value)){invalid(_value, base)}
721
var res = parseInt(value, base)
Mar 10, 2018
722
if(res < $B.min_int || res > $B.max_int){
723
return $B.long_int.$factory(value, base)
Mar 10, 2018
724
}
725
return res
Sep 5, 2014
726
}
Mar 10, 2018
728
if(isinstance(value, [_b_.bytes, _b_.bytearray])){
729
return int.$factory($B.$getattr(value, "decode")("latin-1"), base)
730
}
Sep 5, 2014
731
Mar 10, 2018
732
if(hasattr(value, "__int__")){return getattr(value, "__int__")()}
733
if(hasattr(value, "__index__")){return getattr(value, "__index__")()}
734
if(hasattr(value, "__trunc__")){
735
var res = getattr(value, "__trunc__")(),
736
int_func = _b_.getattr(res, "__int__", null)
737
if(int_func === null){
738
throw TypeError.$factory("__trunc__ returned non-Integral (type "+
Mar 21, 2018
739
$B.get_class(res).__name__ + ")")
Mar 10, 2018
741
var res = int_func()
742
if(isinstance(res, int)){return int_value(res)}
Mar 10, 2018
743
throw TypeError.$factory("__trunc__ returned non-Integral (type "+
Mar 21, 2018
744
$B.get_class(res).__name__ + ")")
Mar 10, 2018
746
throw _b_.TypeError.$factory(
747
"int() argument must be a string, a bytes-like " +
748
"object or a number, not '" + $B.get_class(value).__name__ + "'")
Sep 5, 2014
749
}
750
751
$B.set_func_names(int, "builtins")
Sep 5, 2014
753
_b_.int = int
754
Feb 11, 2018
756
$B.$bool = function(obj){ // return true or false
Mar 10, 2018
757
if(obj === null || obj === undefined ){ return false}
758
switch(typeof obj){
759
case "boolean":
760
return obj
761
case "number":
762
case "string":
763
if(obj){return true}
764
return false
765
default:
766
var missing = {},
767
bool_func = $B.$getattr(obj, "__bool__", missing)
768
if(bool_func === missing){
Mar 21, 2018
769
try{return getattr(obj, "__len__")() > 0}
Mar 10, 2018
770
catch(err){return true}
771
}else{
772
return bool_func()
Mar 10, 2018
773
}
774
}
Feb 11, 2018
775
}
776
777
var bool = {
778
__bases__: [int],
Feb 11, 2018
779
__class__: _b_.type,
Feb 11, 2018
780
__mro__: [int, object],
781
$infos:{
782
__name__: "bool",
783
__module__: "builtins"
784
},
Feb 11, 2018
785
$is_class: true,
786
$native: true
787
}
Feb 11, 2018
789
bool.__add__ = function(self,other){
Mar 10, 2018
790
return (other ? 1 : 0) + (self ? 1 : 0)
Feb 11, 2018
793
bool.__and__ = function(self, other){
794
return $B.$bool(int.__and__(self, other))
797
bool.__eq__ = function(self, other){
798
if(other === self){return True}
799
else if(typeof other == "number"){
800
return self ? other == 1 : other == 0
801
}else if(isinstance(other, _b_.int)){
802
return self ? other.$value == 1 : other.$value == 0
803
}else if(other instanceof Number){
804
return self ? other == 1 : other == 0
805
}else{
806
return false
807
}
808
//return self ? $B.$bool(other) : !$B.$bool(other)
Feb 11, 2018
811
bool.__ne__ = function(self,other){
812
return ! bool.__eq__(self, other)
Feb 11, 2018
815
bool.__ge__ = function(self,other){
816
return _b_.int.__ge__(bool.__hash__(self),other)
Feb 11, 2018
819
bool.__gt__ = function(self,other){
820
return _b_.int.__gt__(bool.__hash__(self),other)
Mar 10, 2018
823
bool.__hash__ = bool.__index__ = bool.__int__ = function(self){
824
if(self.valueOf()) return 1
825
return 0
826
}
827
Mar 10, 2018
828
bool.__le__ = function(self, other){return ! bool.__gt__(self, other)}
Mar 10, 2018
830
bool.__lshift__ = function(self, other){return self.valueOf() << other}
Mar 10, 2018
832
bool.__lt__ = function(self, other){return ! bool.__ge__(self, other)}
Mar 10, 2018
834
bool.__mul__ = function(self, other){
Feb 11, 2018
838
bool.__neg__ = function(self){return -$B.int_or_bool(self)}
Feb 11, 2018
840
bool.__or__ = function(self, other){
841
return $B.$bool(int.__or__(self, other))
Feb 11, 2018
844
bool.__pos__ = $B.int_or_bool
Feb 11, 2018
846
bool.__repr__ = bool.__str__ = function(self){
847
return self ? "True" : "False"
Feb 11, 2018
850
bool.__setattr__ = function(self, attr){
851
if(_b_.dir(self).indexOf(attr) > -1){
852
var msg = "attribute '" + attr + "' of 'int' objects is not writable"
853
}else{
854
var msg = "'bool' object has no attribute '" + attr + "'"
855
}
856
throw _b_.AttributeError.$factory(msg)
Feb 11, 2018
859
bool.__sub__ = function(self,other){
860
return (self ? 1 : 0) - (other ? 1 : 0)
Feb 11, 2018
863
bool.__xor__ = function(self, other) {
864
return self.valueOf() != other.valueOf()
865
}
866
Feb 11, 2018
867
bool.$factory = function(){
868
// Calls $B.$bool, which is used inside the generated JS code and skips
869
// arguments control.
Mar 10, 2018
870
var $ = $B.args("bool", 1, {x: null}, ["x"],
871
arguments,{x: false}, null, null)
Feb 11, 2018
872
return $B.$bool($.x)
873
}
874
875
_b_.bool = bool
Feb 11, 2018
877
$B.set_func_names(bool, "builtins")
Sep 5, 2014
879
})(__BRYTHON__)