Skip to content
Permalink
Newer
Older
100644 858 lines (758 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.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,
Mar 10, 2018
23
__name__: "int",
24
__dir__: object.__dir__,
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.from_bytes = function() {
Mar 10, 2018
36
var $ = $B.args("from_bytes", 3,
37
{bytes:null, byteorder:null, signed:null},
Mar 10, 2018
38
["bytes", "byteorder", "signed"],
39
arguments, {signed: False}, null, null)
Sep 5, 2014
40
41
var x = $.bytes,
42
byteorder = $.byteorder,
Mar 10, 2018
43
signed = $.signed,
44
_bytes, _len
45
if(isinstance(x, [_b_.bytes, _b_.bytearray])){
46
_bytes = x.source
47
_len = x.source.length
48
}else{
49
_bytes = _b_.list.$factory(x)
50
_len = _bytes.length
Mar 10, 2018
51
for(var i = 0; i < _len; i++){
52
_b_.bytes.$factory([_bytes[i]])
53
}
Sep 5, 2014
54
}
Mar 10, 2018
56
case "big":
57
var num = _bytes[_len - 1]
58
var _mult = 256
59
for(var i = _len - 2; i >= 0; i--){
60
// For operations, use the functions that can take or return
61
// big integers
62
num = $B.add($B.mul(_mult, _bytes[i]), num)
63
_mult = $B.mul(_mult,256)
64
}
65
if(! signed){return num}
66
if(_bytes[0] < 128){return num}
67
return $B.sub(num, _mult)
68
case "little":
69
var num = _bytes[0]
70
if(num >= 128){num = num - 256}
71
var _mult = 256
72
for(var i = 1; i < _len; i++){
73
num = $B.add($B.mul(_mult, _bytes[i]), num)
74
_mult = $B.mul(_mult, 256)
75
}
76
if(! signed){return num}
77
if(_bytes[_len - 1] < 128){return num}
78
return $B.sub(num, _mult)
Sep 5, 2014
79
}
80
Mar 10, 2018
81
throw _b_.ValueError.$factory("byteorder must be either 'little' or 'big'")
Sep 5, 2014
82
}
83
84
int.to_bytes = function(){
85
var $ = $B.args("to_bytes", 3,
86
{self: null, len: null, byteorder: null},
87
["self", "len", "byteorder"],
88
arguments, {}, "args", "kw"),
89
self = $.self,
90
len = $.len,
91
byteorder = $.byteorder,
92
kwargs = $.kw
93
if(! _b_.isinstance(len, _b_.int)){
94
throw _b_.TypeError.$factory("integer argument expected, got " +
95
$B.get_class(len).__name__)
96
}
97
if(["little", "big"].indexOf(byteorder) == -1){
98
throw _b_.ValueError.$factory("byteorder must be either 'little' or 'big'")
99
}
100
var signed = kwargs.$string_dict["signed"] || false,
101
res = []
102
103
if(self < 0){
104
if(! signed){
105
throw _b_.OverflowError.$factory("can't convert negative int to unsigned")
106
}
107
self = Math.pow(256, len) + self
108
}
109
var value = self
110
while(true){
111
var quotient = Math.floor(value / 256),
112
rest = value - 256 * quotient
113
res.push(rest)
114
if(quotient == 0){
115
break
116
}
117
value = quotient
118
}
119
if(res.length > len){
120
throw _b_.OverflowError.$factory("int too big to convert")
121
}
122
if(byteorder == "big"){res = res.reverse()}
123
return {
124
__class__: _b_.bytes,
125
source: res
126
}
Sep 5, 2014
127
}
128
129
130
//int.__and__ = function(self,other){return self & other} // bitwise AND
Sep 5, 2014
131
132
int.__abs__ = function(self){return abs(self)}
134
int.__bool__ = function(self){
135
return int_value(self).valueOf() == 0 ? false : true
136
}
Sep 5, 2014
137
138
int.__ceil__ = function(self){return Math.ceil(int_value(self))}
140
int.__divmod__ = function(self, other){return divmod(self, other)}
Mar 10, 2018
142
int.__eq__ = function(self, other){
Sep 5, 2014
143
// compare object "self" to class "int"
Mar 10, 2018
144
if(other === undefined){return self === int}
145
if(isinstance(other, int)){
146
return self.valueOf() == int_value(other).valueOf()
147
}
Mar 10, 2018
148
if(isinstance(other, _b_.float)){return self.valueOf() == other.valueOf()}
149
if(isinstance(other, _b_.complex)){
150
if(other.$imag != 0){return False}
151
return self.valueOf() == other.$real
Sep 5, 2014
152
}
Mar 10, 2018
154
if(hasattr(other, "__eq__")){return getattr(other, "__eq__")(self)}
Mar 10, 2018
156
return self.valueOf() === other
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){
Mar 10, 2018
227
if(isinstance(other, int)){
Mar 10, 2018
229
if(other == 0){throw ZeroDivisionError.$factory("division by zero")}
230
return Math.floor(self / other)
Sep 5, 2014
231
}
Mar 10, 2018
232
if(isinstance(other, _b_.float)){
233
if(!other.valueOf()){
234
throw ZeroDivisionError.$factory("division by zero")
235
}
236
return Math.floor(self / other)
Sep 5, 2014
237
}
Mar 10, 2018
238
if(hasattr(other, "__rfloordiv__")){
239
return getattr(other, "__rfloordiv__")(self)
Sep 5, 2014
240
}
Mar 10, 2018
241
$err("//", other)
Sep 5, 2014
242
}
243
244
int.__hash__ = function(self){
Mar 23, 2018
245
if(self === undefined){
246
return int.__hashvalue__ || $B.$py_next_hash-- // for hash of int type (not instance of int)
247
}
248
return self.valueOf()
249
}
Sep 5, 2014
250
251
//int.__ior__ = function(self,other){return self | other} // bitwise OR
Sep 5, 2014
252
253
int.__index__ = function(self){return self}
Sep 5, 2014
254
255
int.__init__ = function(self,value){
Mar 10, 2018
256
if(value === undefined){value = 0}
Sep 5, 2014
257
self.toString = function(){return value}
Sep 5, 2014
259
}
260
261
int.__int__ = function(self){return self}
Sep 5, 2014
262
263
int.__invert__ = function(self){return ~self}
Sep 5, 2014
264
Mar 10, 2018
266
int.__lshift__ = function(self, other){
267
if(isinstance(other, int)){
Mar 10, 2018
269
return int.$factory($B.long_int.__lshift__($B.long_int.$factory(self),
270
$B.long_int.$factory(other)))
Mar 10, 2018
272
var rlshift = getattr(other, "__rlshift__", None)
273
if(rlshift !== None){return rlshift(self)}
274
$err("<<", other)
Mar 10, 2018
277
int.__mod__ = function(self, other) {
Sep 5, 2014
278
// can't use Javascript % because it works differently for negative numbers
Mar 10, 2018
279
if(isinstance(other,_b_.tuple) && other.length == 1){other = other[0]}
280
if(isinstance(other, [int, _b_.float, bool])){
Mar 10, 2018
282
if(other === false){other = 0}
283
else if(other === true){other = 1}
284
if(other == 0){throw _b_.ZeroDivisionError.$factory(
285
"integer division or modulo by zero")}
Mar 10, 2018
286
return (self % other + other) % other
Sep 5, 2014
287
}
Mar 10, 2018
288
if(hasattr(other, "__rmod__")){return getattr(other, "__rmod__")(self)}
289
$err("%", other)
Sep 5, 2014
290
}
291
292
int.__mro__ = [object]
Sep 5, 2014
293
Mar 10, 2018
294
int.__mul__ = function(self, other){
295
Sep 5, 2014
296
var val = self.valueOf()
Jan 22, 2015
297
298
// this will be quick check, so lets do it early.
Mar 10, 2018
299
if(typeof other === "string") {
Jan 22, 2015
300
return other.repeat(val)
301
}
302
Mar 10, 2018
303
if(isinstance(other, int)){
Mar 10, 2018
305
var res = self * other
306
if(res > $B.min_int && res < $B.max_int){return res}
307
else{
308
return int.$factory($B.long_int.__mul__($B.long_int.$factory(self),
309
$B.long_int.$factory(other)))
310
}
Mar 10, 2018
312
if(isinstance(other, _b_.float)){
313
return new Number(self * other)
Mar 10, 2018
315
if(isinstance(other, _b_.bool)){
316
if(other.valueOf()){return self}
317
return int.$factory(0)
Sep 5, 2014
318
}
Mar 10, 2018
319
if(isinstance(other, _b_.complex)){
320
return $B.make_complex(int.__mul__(self, other.$real),
321
int.__mul__(self, other.$imag))
Sep 5, 2014
322
}
Mar 10, 2018
323
if(isinstance(other, [_b_.list, _b_.tuple])){
Sep 5, 2014
324
var res = []
325
// make temporary copy of list
Mar 10, 2018
326
var $temp = other.slice(0, other.length)
327
for(var i = 0; i < val; i++){res = res.concat($temp)}
328
if(isinstance(other, _b_.tuple)){res = _b_.tuple.$factory(res)}
Sep 5, 2014
329
return res
330
}
Mar 10, 2018
331
if(hasattr(other, "__rmul__")){return getattr(other, "__rmul__")(self)}
332
$err("*", other)
Sep 5, 2014
333
}
334
335
int.__neg__ = function(self){return -self}
Sep 5, 2014
336
337
int.__new__ = function(cls, value){
Mar 10, 2018
338
if(cls === undefined){
339
throw _b_.TypeError.$factory("int.__new__(): not enough arguments")
340
}else if(! isinstance(cls, _b_.type)){
341
throw _b_.TypeError.$factory("int.__new__(X): X is not a type object")
342
}
343
if(cls === int){return int.$factory(value)}
344
return {
345
__class__: cls,
346
$value: value || 0
Mar 10, 2018
347
}
Sep 5, 2014
348
}
349
350
int.__pos__ = function(self){return self}
Sep 5, 2014
351
Mar 10, 2018
352
int.__pow__ = function(self, other, z){
353
if(isinstance(other, int)){
354
other = int_value(other)
355
switch(other.valueOf()) {
356
case 0:
357
return int.$factory(1)
358
case 1:
359
return int.$factory(self.valueOf())
Feb 9, 2015
360
}
May 19, 2017
361
if(z !== undefined && z !== null){
362
// If z is provided, the algorithm is faster than computing
363
// self ** other then applying the modulo z
364
if(z == 1){return 0}
365
var result = 1,
366
base = self % z,
367
exponent = other,
368
long_int = $B.long_int
369
while(exponent > 0){
370
if(exponent % 2 == 1){
371
if(result * base > $B.max_int){
372
result = long_int.__mul__(
373
long_int.$factory(result),
374
long_int.$factory(base))
375
result = long_int.__mod__(result, z)
376
}else{
377
result = (result * base) % z
378
}
379
}
380
exponent = exponent >> 1
381
if(base * base > $B.max_int){
382
base = long_int.__mul__(long_int.$factory(base),
383
long_int.$factory(base))
384
base = long_int.__mod__(base, z)
385
}else{
386
base = (base * base) % z
387
}
May 19, 2017
388
}
May 19, 2017
390
}
Mar 10, 2018
391
var res = Math.pow(self.valueOf(), other.valueOf())
392
if(res > $B.min_int && res < $B.max_int){return res}
May 19, 2017
393
else if(res !== Infinity && !isFinite(res)){return res}
Feb 11, 2018
395
return int.$factory($B.long_int.__pow__($B.long_int.$factory(self),
396
$B.long_int.$factory(other)))
May 19, 2017
397
}
Sep 5, 2014
398
}
399
if(isinstance(other, _b_.float)) {
Mar 10, 2018
400
if(self >= 0){return new Number(Math.pow(self, other.valueOf()))}
401
else{
402
// use complex power
403
return _b_.complex.__pow__($B.make_complex(self, 0), other)
405
}else if(isinstance(other, _b_.complex)){
Mar 10, 2018
406
var preal = Math.pow(self, other.$real),
407
ln = Math.log(self)
Mar 10, 2018
408
return $B.make_complex(preal * Math.cos(ln), preal * Math.sin(ln))
Sep 5, 2014
409
}
Mar 10, 2018
410
if(hasattr(other, "__rpow__")){return getattr(other, "__rpow__")(self)}
411
$err("**", other)
Sep 5, 2014
412
}
413
414
int.__repr__ = function(self){
Mar 10, 2018
415
if(self === int){return "<class 'int'>"}
Sep 5, 2014
416
return self.toString()
417
}
418
419
// bitwise right shift
Mar 10, 2018
420
int.__rshift__ = function(self, other){
421
if(isinstance(other, int)){
Feb 11, 2018
423
return int.$factory($B.long_int.__rshift__($B.long_int.$factory(self),
424
$B.long_int.$factory(other)))
Mar 10, 2018
426
var rrshift = getattr(other, "__rrshift__", None)
427
if(rrshift !== None){return rrshift(self)}
428
$err('>>', other)
429
}
Sep 5, 2014
430
431
int.__setattr__ = function(self,attr,value){
Mar 10, 2018
432
if(typeof self == "number"){
433
if(int.$factory[attr] === undefined){
434
throw _b_.AttributeError.$factory(
435
"'int' object has no attribute '" + attr + "'")
Mar 10, 2018
437
throw _b_.AttributeError.$factory(
438
"'int' object attribute '" + attr + "' is read-only")
Sep 5, 2014
440
}
441
// subclasses of int can have attributes set
442
self[attr] = value
Sep 5, 2014
444
}
445
446
int.__str__ = int.__repr__
Sep 5, 2014
447
Mar 10, 2018
448
int.__truediv__ = function(self, other){
449
if(isinstance(other, int)){
Mar 10, 2018
451
if(other == 0){throw ZeroDivisionError.$factory("division by zero")}
452
if(other.__class__ === $B.long_int){
453
return new Number(self / parseInt(other.value))
454
}
455
return new Number(self / other)
Sep 5, 2014
456
}
Mar 10, 2018
457
if(isinstance(other, _b_.float)){
458
if(!other.valueOf()){
459
throw ZeroDivisionError.$factory("division by zero")
460
}
461
return new Number(self / other)
Sep 5, 2014
462
}
Mar 10, 2018
463
if(isinstance(other, _b_.complex)){
464
var cmod = other.$real * other.$real + other.$imag * other.$imag
465
if(cmod == 0){throw ZeroDivisionError.$factory("division by zero")}
466
return $B.make_complex(self * other.$real / cmod,
467
-self * other.$imag / cmod)
Sep 5, 2014
468
}
Mar 10, 2018
469
if(hasattr(other, "__rtruediv__")){
470
return getattr(other, "__rtruediv__")(self)
471
}
472
$err("/", other)
Sep 5, 2014
473
}
474
475
//int.__xor__ = function(self,other){return self ^ other} // bitwise XOR
Sep 5, 2014
476
477
int.bit_length = function(self){
Sep 5, 2014
478
s = bin(self)
Mar 10, 2018
479
s = getattr(s, "lstrip")("-0b") // remove leading zeros and minus sign
Sep 5, 2014
480
return s.length // len('100101') --> 6
481
}
482
483
// descriptors
484
int.numerator = function(self){return self}
485
int.denominator = function(self){return int.$factory(1)}
486
int.imag = function(self){return int.$factory(0)}
487
int.real = function(self){return self}
488
Mar 10, 2018
489
$B.max_int32 = (1 << 30) * 2 - 1
490
$B.min_int32 = - $B.max_int32
492
// code for operands & | ^
Mar 10, 2018
493
var $op_func = function(self, other){
494
if(isinstance(other, int)) {
495
if(other.__class__ === $B.long_int){
496
return $B.long_int.__sub__($B.long_int.$factory(self),
497
$B.long_int.$factory(other))
Mar 23, 2018
500
if(self > $B.max_int32 || self < $B.min_int32 ||
501
other > $B.max_int32 || other < $B.min_int32){
Mar 10, 2018
502
return $B.long_int.__sub__($B.long_int.$factory(self),
503
$B.long_int.$factory(other))
Mar 21, 2018
505
return self - other
Jun 7, 2015
506
}
Mar 10, 2018
507
if(isinstance(other, _b_.bool)){return self - other}
508
if(hasattr(other, "__rsub__")){return getattr(other, "__rsub__")(self)}
509
$err("-", other)
Sep 5, 2014
510
}
511
Mar 10, 2018
512
$op_func += "" // source code
513
var $ops = {"&": "and", "|": "or", "^": "xor"}
Sep 5, 2014
514
for(var $op in $ops){
Mar 10, 2018
515
var opf = $op_func.replace(/-/gm, $op)
516
opf = opf.replace(new RegExp("sub", "gm"), $ops[$op])
517
eval("int.__" + $ops[$op] + "__ = " + opf)
Sep 5, 2014
518
}
519
520
// code for + and -
Mar 10, 2018
521
var $op_func = function(self, other){
522
if(isinstance(other, int)){
Mar 10, 2018
524
if(typeof other == "number"){
525
var res = self.valueOf() - other.valueOf()
526
if(res > $B.min_int && res < $B.max_int){return res}
Feb 11, 2018
527
else{return $B.long_int.__sub__($B.long_int.$factory(self),
528
$B.long_int.$factory(other))}
Mar 10, 2018
529
}else if(typeof other == "boolean"){
Mar 21, 2018
530
return other ? self - 1 : self
531
}else{
Feb 11, 2018
532
return $B.long_int.__sub__($B.long_int.$factory(self),
533
$B.long_int.$factory(other))
Sep 5, 2014
535
}
Mar 10, 2018
536
if(isinstance(other, _b_.float)){
537
return new Number(self - other)
Sep 5, 2014
538
}
Mar 10, 2018
539
if(isinstance(other, _b_.complex)){
540
return $B.make_complex(self - other.$real, -other.$imag)
Sep 5, 2014
541
}
Mar 10, 2018
542
if(isinstance(other, _b_.bool)){
543
var bool_value = 0;
544
if(other.valueOf()){bool_value = 1}
545
return self - bool_value
Sep 5, 2014
546
}
Mar 10, 2018
547
if(isinstance(other, _b_.complex)){
548
return $B.make_complex(self.valueOf() - other.$real, other.$imag)
Sep 5, 2014
549
}
Mar 10, 2018
550
var rsub = $B.$getattr(other, "__rsub__", None)
551
if(rsub !== None){return rsub(self)}
552
throw $err("-", other)
Sep 5, 2014
553
}
Mar 10, 2018
554
$op_func += "" // source code
555
var $ops = {"+": "add", "-": "sub"}
Sep 5, 2014
556
for(var $op in $ops){
Mar 10, 2018
557
var opf = $op_func.replace(/-/gm, $op)
558
opf = opf.replace(new RegExp("sub", "gm"), $ops[$op])
559
eval("int.__" + $ops[$op] + "__ = " + opf)
Sep 5, 2014
560
}
561
562
// comparison methods
Mar 10, 2018
563
var $comp_func = function(self, other){
Mar 23, 2018
564
if(other.__class__ === $B.long_int){
Feb 11, 2018
565
return $B.long_int.__lt__(other, $B.long_int.$factory(self))
567
if(isinstance(other, int)){
568
other = int_value(other)
569
return self.valueOf() > other.valueOf()
570
}else if(isinstance(other, _b_.float)){
571
return self.valueOf() > other.valueOf()
572
}else if(isinstance(other, _b_.bool)) {
Feb 11, 2018
573
return self.valueOf() > _b_.bool.__hash__(other)
Sep 5, 2014
574
}
Mar 10, 2018
575
if(hasattr(other, "__int__") || hasattr(other, "__index__")){
576
return int.__gt__(self, $B.$GetInt(other))
579
// See if other has the opposite operator, eg < for >
Mar 10, 2018
580
var inv_op = $B.$getattr(other, "__lt__", None)
581
if(inv_op !== None){return inv_op(self)}
583
throw _b_.TypeError.$factory(
Mar 21, 2018
584
"unorderable types: int() > " + $B.get_class(other).__name__ + "()")
Sep 5, 2014
585
}
Mar 10, 2018
586
$comp_func += "" // source code
Sep 5, 2014
588
for(var $op in $B.$comps){
Mar 10, 2018
589
eval("int.__"+$B.$comps[$op] + "__ = " +
590
$comp_func.replace(/>/gm, $op).
591
replace(/__gt__/gm,"__" + $B.$comps[$op] + "__").
592
replace(/__lt__/, "__" + $B.$inv_comps[$op] + "__"))
Sep 5, 2014
593
}
594
595
// add "reflected" methods
596
$B.make_rmethods(int)
Sep 5, 2014
597
Mar 10, 2018
598
var $valid_digits = function(base) {
599
var digits = ""
600
if(base === 0){return "0"}
601
if(base < 10){
Mar 21, 2018
602
for(var i = 0; i < base; i++){digits += String.fromCharCode(i + 48)}
Sep 5, 2014
603
return digits
604
}
605
Mar 10, 2018
606
var digits = "0123456789"
Sep 5, 2014
607
// A = 65 (10 + 55)
Mar 21, 2018
608
for (var i = 10; i < base; i++) {digits += String.fromCharCode(i + 55)}
Sep 5, 2014
609
return digits
610
}
611
612
int.$factory = function(value, base){
613
// int() with no argument returns 0
Mar 10, 2018
614
if(value === undefined){return 0}
616
// int() of an integer returns the integer if base is undefined
Mar 10, 2018
617
if(typeof value == "number" &&
618
(base === undefined || base == 10)){return parseInt(value)}
Mar 10, 2018
620
if(base !== undefined){
621
if(! isinstance(value, [_b_.str, _b_.bytes, _b_.bytearray])){
622
throw TypeError.$factory(
623
"int() can't convert non-string with explicit base")
Dec 28, 2014
624
}
625
}
626
Mar 10, 2018
627
if(isinstance(value, _b_.complex)){
628
throw TypeError.$factory("can't convert complex to int")
Dec 28, 2014
629
}
Mar 10, 2018
630
var $ns = $B.args("int", 2, {x:null, base:null}, ["x", "base"], arguments,
631
{"base": 10}, null, null),
632
value = $ns["x"],
633
base = $ns["base"]
Mar 10, 2018
635
if(isinstance(value, _b_.float) && base == 10){
636
if(value < $B.min_int || value > $B.max_int){
Feb 11, 2018
637
return $B.long_int.$from_float(value)
Mar 10, 2018
639
else{return value > 0 ? Math.floor(value) : Math.ceil(value)}
Sep 5, 2014
641
Mar 10, 2018
642
if(! (base >=2 && base <= 36)){
Dec 26, 2014
643
// throw error (base must be 0, or 2-36)
Mar 10, 2018
644
if(base != 0){throw _b_.ValueError.$factory("invalid base")}
Dec 26, 2014
645
}
646
Mar 10, 2018
647
if(typeof value == "number"){
Mar 10, 2018
649
if(base == 10){
650
if(value < $B.min_int || value > $B.max_int){
651
return $B.long_int.$factory(value)
652
}
Mar 10, 2018
654
}else if(value.toString().search("e") > -1){
Dec 26, 2014
655
// can't convert to another base if value is too big
Mar 10, 2018
656
throw _b_.OverflowError.$factory("can't convert to base " + base)
Dec 26, 2014
657
}else{
Mar 10, 2018
658
var res = parseInt(value, base)
659
if(value < $B.min_int || value > $B.max_int){
660
return $B.long_int.$factory(value, base)
661
}
Dec 26, 2014
663
}
664
}
Sep 5, 2014
665
Mar 10, 2018
666
if(value === true){return Number(1)}
667
if(value === false){return Number(0)}
668
if(value.__class__ === $B.long_int){
669
var z = parseInt(value.value)
Mar 10, 2018
670
if(z > $B.min_int && z < $B.max_int){return z}
671
else{return value}
672
}
Sep 5, 2014
673
Mar 10, 2018
674
base = $B.$GetInt(base)
Sep 5, 2014
675
Mar 10, 2018
676
if(isinstance(value, _b_.str)){value = value.valueOf()}
677
if(typeof value == "string") {
678
var _value = value.trim() // remove leading/trailing whitespace
679
if(_value.length == 2 && base == 0 &&
680
(_value == "0b" || _value == "0o" || _value == "0x")){
681
throw _b_.ValueError.$factory("invalid value")
682
}
683
if(_value.length >2) {
684
var _pre = _value.substr(0, 2).toUpperCase()
685
if(base == 0){
686
if(_pre == "0B"){base = 2}
687
if(_pre == "0O"){base = 8}
688
if(_pre == "0X"){base = 16}
689
}
690
if(_pre == "0B" || _pre == "0O" || _pre == "0X"){
691
_value = _value.substr(2)
692
while(_value.startsWith("_")){
693
_value = _value.substr(1)
694
}
Mar 10, 2018
695
}
696
}
697
var _digits = $valid_digits(base),
698
_re = new RegExp("^[+-]?[" + _digits + "]" +
699
"[" + _digits + "_]*$", "i"),
700
match = _re.exec(_value)
701
if(match === null){
Mar 10, 2018
702
throw _b_.ValueError.$factory(
703
"invalid literal for int() with base " + base + ": '" +
704
_b_.str.$factory(value) + "'")
705
}else{
706
value = _value.replace(/_/g, "")
Mar 10, 2018
707
}
708
if(base <= 10 && ! isFinite(value)){
709
throw _b_.ValueError.$factory(
710
"invalid literal for int() with base " + base + ": '" +
711
_b_.str.$factory(value) + "'")
712
}
713
var res = parseInt(value, base)
Mar 10, 2018
714
if(res < $B.min_int || res > $B.max_int){
715
return $B.long_int.$factory(value, base)
Mar 10, 2018
716
}
717
return res
Sep 5, 2014
718
}
Mar 10, 2018
720
if(isinstance(value, [_b_.bytes, _b_.bytearray])){
721
var _digits = $valid_digits(base)
Mar 10, 2018
722
for(var i = 0; i < value.source.length; i++){
723
if(_digits.indexOf(String.fromCharCode(value.source[i])) == -1){
724
throw _b_.ValueError.$factory(
725
"invalid literal for int() with base " + base + ": " +
726
_b_.repr(value))
Mar 10, 2018
729
return Number(parseInt(getattr(value, "decode")("latin-1"), base))
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
try{return getattr(obj, "__bool__")()}
767
catch(err){
Mar 21, 2018
768
try{return getattr(obj, "__len__")() > 0}
Mar 10, 2018
769
catch(err){return true}
770
}
771
}
Feb 11, 2018
772
}
773
774
var bool = {
Feb 11, 2018
775
__class__: _b_.type,
Feb 11, 2018
776
__module__: "builtins",
777
__mro__: [int, object],
778
__name__: "bool",
779
$is_class: true,
780
$native: true
781
}
Feb 11, 2018
783
bool.__add__ = function(self,other){
Mar 10, 2018
784
return (other ? 1 : 0) + (self ? 1 : 0)
Feb 11, 2018
787
bool.__and__ = function(self, other){
788
return $B.$bool(int.__and__(self, other))
Feb 11, 2018
791
bool.__eq__ = function(self,other){
792
return self ? $B.$bool(other) : !$B.$bool(other)
Feb 11, 2018
795
bool.__ne__ = function(self,other){
796
return self ? !$B.$bool(other) : $B.$bool(other)
Feb 11, 2018
799
bool.__ge__ = function(self,other){
800
return _b_.int.__ge__(bool.__hash__(self),other)
Feb 11, 2018
803
bool.__gt__ = function(self,other){
804
return _b_.int.__gt__(bool.__hash__(self),other)
Mar 10, 2018
807
bool.__hash__ = bool.__index__ = bool.__int__ = function(self){
808
if(self.valueOf()) return 1
809
return 0
810
}
811
Mar 10, 2018
812
bool.__le__ = function(self, other){return ! bool.__gt__(self, other)}
Mar 10, 2018
814
bool.__lshift__ = function(self, other){return self.valueOf() << other}
Mar 10, 2018
816
bool.__lt__ = function(self, other){return ! bool.__ge__(self, other)}
Mar 10, 2018
818
bool.__mul__ = function(self, other){
Feb 11, 2018
822
bool.__neg__ = function(self){return -$B.int_or_bool(self)}
Feb 11, 2018
824
bool.__or__ = function(self, other){
825
return $B.$bool(int.__or__(self, other))
Feb 11, 2018
828
bool.__pos__ = $B.int_or_bool
Feb 11, 2018
830
bool.__repr__ = bool.__str__ = function(self){
831
return self ? "True" : "False"
Feb 11, 2018
834
bool.__setattr__ = function(self, attr){
835
return no_set_attr(bool, attr)
Feb 11, 2018
838
bool.__sub__ = function(self,other){
839
return (self ? 1 : 0) - (other ? 1 : 0)
Feb 11, 2018
842
bool.__xor__ = function(self, other) {
843
return self.valueOf() != other.valueOf()
844
}
845
Feb 11, 2018
846
bool.$factory = function(){
847
// Calls $B.$bool, which is used inside the generated JS code and skips
848
// arguments control.
Mar 10, 2018
849
var $ = $B.args("bool", 1, {x: null}, ["x"],
850
arguments,{x: false}, null, null)
Feb 11, 2018
851
return $B.$bool($.x)
852
}
853
854
_b_.bool = bool
Feb 11, 2018
856
$B.set_func_names(bool, "builtins")
Sep 5, 2014
858
})(__BRYTHON__)