Skip to content
Permalink
Newer
Older
100644 865 lines (765 sloc) 26.3 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){
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){return self}
Sep 5, 2014
257
258
int.__init__ = function(self,value){
Mar 10, 2018
259
if(value === undefined){value = 0}
Sep 5, 2014
260
self.toString = function(){return value}
Sep 5, 2014
262
}
263
264
int.__int__ = function(self){return self}
Sep 5, 2014
265
266
int.__invert__ = function(self){return ~self}
Sep 5, 2014
267
Mar 10, 2018
269
int.__lshift__ = function(self, other){
270
if(isinstance(other, int)){
Mar 10, 2018
272
return int.$factory($B.long_int.__lshift__($B.long_int.$factory(self),
273
$B.long_int.$factory(other)))
Mar 10, 2018
275
var rlshift = getattr(other, "__rlshift__", None)
276
if(rlshift !== None){return rlshift(self)}
277
$err("<<", other)
Mar 10, 2018
280
int.__mod__ = function(self, other) {
Sep 5, 2014
281
// can't use Javascript % because it works differently for negative numbers
Mar 10, 2018
282
if(isinstance(other,_b_.tuple) && other.length == 1){other = other[0]}
283
if(other.__class__ === $B.long_int){
284
return $B.long_int.__mod__($B.long_int.$factory(self), other)
285
}
Mar 10, 2018
286
if(isinstance(other, [int, _b_.float, bool])){
Mar 10, 2018
288
if(other === false){other = 0}
289
else if(other === true){other = 1}
290
if(other == 0){throw _b_.ZeroDivisionError.$factory(
291
"integer division or modulo by zero")}
Mar 10, 2018
292
return (self % other + other) % other
Sep 5, 2014
293
}
Mar 10, 2018
294
if(hasattr(other, "__rmod__")){return getattr(other, "__rmod__")(self)}
295
$err("%", other)
Sep 5, 2014
296
}
297
298
int.__mro__ = [object]
Sep 5, 2014
299
Mar 10, 2018
300
int.__mul__ = function(self, other){
301
Sep 5, 2014
302
var val = self.valueOf()
Jan 22, 2015
303
304
// this will be quick check, so lets do it early.
Mar 10, 2018
305
if(typeof other === "string") {
Jan 22, 2015
306
return other.repeat(val)
307
}
308
Mar 10, 2018
309
if(isinstance(other, int)){
Mar 10, 2018
311
var res = self * other
312
if(res > $B.min_int && res < $B.max_int){return res}
313
else{
314
return int.$factory($B.long_int.__mul__($B.long_int.$factory(self),
315
$B.long_int.$factory(other)))
316
}
Mar 10, 2018
318
if(isinstance(other, _b_.float)){
319
return new Number(self * other)
Mar 10, 2018
321
if(isinstance(other, _b_.bool)){
322
if(other.valueOf()){return self}
323
return int.$factory(0)
Sep 5, 2014
324
}
Mar 10, 2018
325
if(isinstance(other, _b_.complex)){
326
return $B.make_complex(int.__mul__(self, other.$real),
327
int.__mul__(self, other.$imag))
Sep 5, 2014
328
}
Mar 10, 2018
329
if(isinstance(other, [_b_.list, _b_.tuple])){
Sep 5, 2014
330
var res = []
331
// make temporary copy of list
Mar 10, 2018
332
var $temp = other.slice(0, other.length)
333
for(var i = 0; i < val; i++){res = res.concat($temp)}
334
if(isinstance(other, _b_.tuple)){res = _b_.tuple.$factory(res)}
Sep 5, 2014
335
return res
336
}
Mar 10, 2018
337
if(hasattr(other, "__rmul__")){return getattr(other, "__rmul__")(self)}
338
$err("*", other)
Sep 5, 2014
339
}
340
341
int.__neg__ = function(self){return -self}
Sep 5, 2014
342
343
int.__new__ = function(cls, value){
Mar 10, 2018
344
if(cls === undefined){
345
throw _b_.TypeError.$factory("int.__new__(): not enough arguments")
346
}else if(! isinstance(cls, _b_.type)){
347
throw _b_.TypeError.$factory("int.__new__(X): X is not a type object")
348
}
349
if(cls === int){return int.$factory(value)}
350
return {
351
__class__: cls,
352
$value: value || 0
Mar 10, 2018
353
}
Sep 5, 2014
354
}
355
356
int.__pos__ = function(self){return self}
Sep 5, 2014
357
Mar 10, 2018
358
int.__pow__ = function(self, other, z){
359
if(isinstance(other, int)){
360
other = int_value(other)
361
switch(other.valueOf()) {
362
case 0:
363
return int.$factory(1)
364
case 1:
365
return int.$factory(self.valueOf())
Feb 9, 2015
366
}
May 19, 2017
367
if(z !== undefined && z !== null){
368
// If z is provided, the algorithm is faster than computing
369
// self ** other then applying the modulo z
370
if(z == 1){return 0}
371
var result = 1,
372
base = self % z,
373
exponent = other,
374
long_int = $B.long_int
375
while(exponent > 0){
376
if(exponent % 2 == 1){
377
if(result * base > $B.max_int){
378
result = long_int.__mul__(
379
long_int.$factory(result),
380
long_int.$factory(base))
381
result = long_int.__mod__(result, z)
382
}else{
383
result = (result * base) % z
384
}
385
}
386
exponent = exponent >> 1
387
if(base * base > $B.max_int){
388
base = long_int.__mul__(long_int.$factory(base),
389
long_int.$factory(base))
390
base = long_int.__mod__(base, z)
391
}else{
392
base = (base * base) % z
393
}
May 19, 2017
394
}
May 19, 2017
396
}
Mar 10, 2018
397
var res = Math.pow(self.valueOf(), other.valueOf())
398
if(res > $B.min_int && res < $B.max_int){return res}
May 19, 2017
399
else if(res !== Infinity && !isFinite(res)){return res}
Feb 11, 2018
401
return int.$factory($B.long_int.__pow__($B.long_int.$factory(self),
402
$B.long_int.$factory(other)))
May 19, 2017
403
}
Sep 5, 2014
404
}
405
if(isinstance(other, _b_.float)) {
Mar 10, 2018
406
if(self >= 0){return new Number(Math.pow(self, other.valueOf()))}
407
else{
408
// use complex power
409
return _b_.complex.__pow__($B.make_complex(self, 0), other)
411
}else if(isinstance(other, _b_.complex)){
Mar 10, 2018
412
var preal = Math.pow(self, other.$real),
413
ln = Math.log(self)
Mar 10, 2018
414
return $B.make_complex(preal * Math.cos(ln), preal * Math.sin(ln))
Sep 5, 2014
415
}
Mar 10, 2018
416
if(hasattr(other, "__rpow__")){return getattr(other, "__rpow__")(self)}
417
$err("**", other)
Sep 5, 2014
418
}
419
420
int.__repr__ = function(self){
Mar 10, 2018
421
if(self === int){return "<class 'int'>"}
Sep 5, 2014
422
return self.toString()
423
}
424
425
// bitwise right shift
Mar 10, 2018
426
int.__rshift__ = function(self, other){
427
if(isinstance(other, int)){
Feb 11, 2018
429
return int.$factory($B.long_int.__rshift__($B.long_int.$factory(self),
430
$B.long_int.$factory(other)))
Mar 10, 2018
432
var rrshift = getattr(other, "__rrshift__", None)
433
if(rrshift !== None){return rrshift(self)}
434
$err('>>', other)
435
}
Sep 5, 2014
436
437
int.__setattr__ = function(self,attr,value){
Mar 10, 2018
438
if(typeof self == "number"){
439
if(int.$factory[attr] === undefined){
440
throw _b_.AttributeError.$factory(
441
"'int' object has no attribute '" + attr + "'")
Mar 10, 2018
443
throw _b_.AttributeError.$factory(
444
"'int' object attribute '" + attr + "' is read-only")
Sep 5, 2014
446
}
447
// subclasses of int can have attributes set
448
self[attr] = value
Sep 5, 2014
450
}
451
452
int.__str__ = int.__repr__
Sep 5, 2014
453
Mar 10, 2018
454
int.__truediv__ = function(self, other){
455
if(isinstance(other, int)){
Mar 10, 2018
457
if(other == 0){throw ZeroDivisionError.$factory("division by zero")}
458
if(other.__class__ === $B.long_int){
459
return new Number(self / parseInt(other.value))
460
}
461
return new Number(self / other)
Sep 5, 2014
462
}
Mar 10, 2018
463
if(isinstance(other, _b_.float)){
464
if(!other.valueOf()){
465
throw ZeroDivisionError.$factory("division by zero")
466
}
467
return new Number(self / other)
Sep 5, 2014
468
}
Mar 10, 2018
469
if(isinstance(other, _b_.complex)){
470
var cmod = other.$real * other.$real + other.$imag * other.$imag
471
if(cmod == 0){throw ZeroDivisionError.$factory("division by zero")}
472
return $B.make_complex(self * other.$real / cmod,
473
-self * other.$imag / cmod)
Sep 5, 2014
474
}
Mar 10, 2018
475
if(hasattr(other, "__rtruediv__")){
476
return getattr(other, "__rtruediv__")(self)
477
}
478
$err("/", other)
Sep 5, 2014
479
}
480
481
//int.__xor__ = function(self,other){return self ^ other} // bitwise XOR
Sep 5, 2014
482
483
int.bit_length = function(self){
Sep 5, 2014
484
s = bin(self)
Mar 10, 2018
485
s = getattr(s, "lstrip")("-0b") // remove leading zeros and minus sign
Sep 5, 2014
486
return s.length // len('100101') --> 6
487
}
488
489
// descriptors
490
int.numerator = function(self){return self}
491
int.denominator = function(self){return int.$factory(1)}
492
int.imag = function(self){return int.$factory(0)}
493
int.real = function(self){return self}
494
Mar 10, 2018
495
$B.max_int32 = (1 << 30) * 2 - 1
496
$B.min_int32 = - $B.max_int32
498
// code for operands & | ^
Mar 10, 2018
499
var $op_func = function(self, other){
500
if(isinstance(other, int)) {
501
if(other.__class__ === $B.long_int){
502
return $B.long_int.__sub__($B.long_int.$factory(self),
503
$B.long_int.$factory(other))
Mar 23, 2018
506
if(self > $B.max_int32 || self < $B.min_int32 ||
507
other > $B.max_int32 || other < $B.min_int32){
Mar 10, 2018
508
return $B.long_int.__sub__($B.long_int.$factory(self),
509
$B.long_int.$factory(other))
Mar 21, 2018
511
return self - other
Jun 7, 2015
512
}
Mar 10, 2018
513
if(isinstance(other, _b_.bool)){return self - other}
514
if(hasattr(other, "__rsub__")){return getattr(other, "__rsub__")(self)}
515
$err("-", other)
Sep 5, 2014
516
}
517
Mar 10, 2018
518
$op_func += "" // source code
519
var $ops = {"&": "and", "|": "or", "^": "xor"}
Sep 5, 2014
520
for(var $op in $ops){
Mar 10, 2018
521
var opf = $op_func.replace(/-/gm, $op)
522
opf = opf.replace(new RegExp("sub", "gm"), $ops[$op])
523
eval("int.__" + $ops[$op] + "__ = " + opf)
Sep 5, 2014
524
}
525
526
// code for + and -
Mar 10, 2018
527
var $op_func = function(self, other){
528
if(isinstance(other, int)){
Mar 10, 2018
530
if(typeof other == "number"){
531
var res = self.valueOf() - other.valueOf()
532
if(res > $B.min_int && res < $B.max_int){return res}
Feb 11, 2018
533
else{return $B.long_int.__sub__($B.long_int.$factory(self),
534
$B.long_int.$factory(other))}
Mar 10, 2018
535
}else if(typeof other == "boolean"){
Mar 21, 2018
536
return other ? self - 1 : self
537
}else{
Feb 11, 2018
538
return $B.long_int.__sub__($B.long_int.$factory(self),
539
$B.long_int.$factory(other))
Sep 5, 2014
541
}
Mar 10, 2018
542
if(isinstance(other, _b_.float)){
543
return new Number(self - other)
Sep 5, 2014
544
}
Mar 10, 2018
545
if(isinstance(other, _b_.complex)){
546
return $B.make_complex(self - other.$real, -other.$imag)
Sep 5, 2014
547
}
Mar 10, 2018
548
if(isinstance(other, _b_.bool)){
549
var bool_value = 0;
550
if(other.valueOf()){bool_value = 1}
551
return self - bool_value
Sep 5, 2014
552
}
Mar 10, 2018
553
if(isinstance(other, _b_.complex)){
554
return $B.make_complex(self.valueOf() - other.$real, other.$imag)
Sep 5, 2014
555
}
Mar 10, 2018
556
var rsub = $B.$getattr(other, "__rsub__", None)
557
if(rsub !== None){return rsub(self)}
558
throw $err("-", other)
Sep 5, 2014
559
}
Mar 10, 2018
560
$op_func += "" // source code
561
var $ops = {"+": "add", "-": "sub"}
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
// comparison methods
Mar 10, 2018
569
var $comp_func = function(self, other){
Mar 23, 2018
570
if(other.__class__ === $B.long_int){
Feb 11, 2018
571
return $B.long_int.__lt__(other, $B.long_int.$factory(self))
573
if(isinstance(other, int)){
574
other = int_value(other)
575
return self.valueOf() > other.valueOf()
576
}else if(isinstance(other, _b_.float)){
577
return self.valueOf() > other.valueOf()
578
}else if(isinstance(other, _b_.bool)) {
Feb 11, 2018
579
return self.valueOf() > _b_.bool.__hash__(other)
Sep 5, 2014
580
}
Mar 10, 2018
581
if(hasattr(other, "__int__") || hasattr(other, "__index__")){
582
return int.__gt__(self, $B.$GetInt(other))
585
// See if other has the opposite operator, eg < for >
Mar 10, 2018
586
var inv_op = $B.$getattr(other, "__lt__", None)
587
if(inv_op !== None){return inv_op(self)}
589
throw _b_.TypeError.$factory(
Mar 21, 2018
590
"unorderable types: int() > " + $B.get_class(other).__name__ + "()")
Sep 5, 2014
591
}
Mar 10, 2018
592
$comp_func += "" // source code
Sep 5, 2014
594
for(var $op in $B.$comps){
Mar 10, 2018
595
eval("int.__"+$B.$comps[$op] + "__ = " +
596
$comp_func.replace(/>/gm, $op).
597
replace(/__gt__/gm,"__" + $B.$comps[$op] + "__").
598
replace(/__lt__/, "__" + $B.$inv_comps[$op] + "__"))
Sep 5, 2014
599
}
600
601
// add "reflected" methods
602
$B.make_rmethods(int)
Sep 5, 2014
603
Mar 10, 2018
604
var $valid_digits = function(base) {
605
var digits = ""
606
if(base === 0){return "0"}
607
if(base < 10){
Mar 21, 2018
608
for(var i = 0; i < base; i++){digits += String.fromCharCode(i + 48)}
Sep 5, 2014
609
return digits
610
}
611
Mar 10, 2018
612
var digits = "0123456789"
Sep 5, 2014
613
// A = 65 (10 + 55)
Mar 21, 2018
614
for (var i = 10; i < base; i++) {digits += String.fromCharCode(i + 55)}
Sep 5, 2014
615
return digits
616
}
617
618
int.$factory = function(value, base){
619
// int() with no argument returns 0
Mar 10, 2018
620
if(value === undefined){return 0}
622
// int() of an integer returns the integer if base is undefined
Mar 10, 2018
623
if(typeof value == "number" &&
624
(base === undefined || base == 10)){return parseInt(value)}
Mar 10, 2018
626
if(base !== undefined){
627
if(! isinstance(value, [_b_.str, _b_.bytes, _b_.bytearray])){
628
throw TypeError.$factory(
629
"int() can't convert non-string with explicit base")
Dec 28, 2014
630
}
631
}
632
Mar 10, 2018
633
if(isinstance(value, _b_.complex)){
634
throw TypeError.$factory("can't convert complex to int")
Dec 28, 2014
635
}
Mar 10, 2018
636
var $ns = $B.args("int", 2, {x:null, base:null}, ["x", "base"], arguments,
637
{"base": 10}, null, null),
638
value = $ns["x"],
639
base = $ns["base"]
Mar 10, 2018
641
if(isinstance(value, _b_.float) && base == 10){
642
if(value < $B.min_int || value > $B.max_int){
Feb 11, 2018
643
return $B.long_int.$from_float(value)
Mar 10, 2018
645
else{return value > 0 ? Math.floor(value) : Math.ceil(value)}
Sep 5, 2014
647
Mar 10, 2018
648
if(! (base >=2 && base <= 36)){
Dec 26, 2014
649
// throw error (base must be 0, or 2-36)
Mar 10, 2018
650
if(base != 0){throw _b_.ValueError.$factory("invalid base")}
Dec 26, 2014
651
}
652
Mar 10, 2018
653
if(typeof value == "number"){
Mar 10, 2018
655
if(base == 10){
656
if(value < $B.min_int || value > $B.max_int){
657
return $B.long_int.$factory(value)
658
}
Mar 10, 2018
660
}else if(value.toString().search("e") > -1){
Dec 26, 2014
661
// can't convert to another base if value is too big
Mar 10, 2018
662
throw _b_.OverflowError.$factory("can't convert to base " + base)
Dec 26, 2014
663
}else{
Mar 10, 2018
664
var res = parseInt(value, base)
665
if(value < $B.min_int || value > $B.max_int){
666
return $B.long_int.$factory(value, base)
667
}
Dec 26, 2014
669
}
670
}
Sep 5, 2014
671
Mar 10, 2018
672
if(value === true){return Number(1)}
673
if(value === false){return Number(0)}
674
if(value.__class__ === $B.long_int){
675
var z = parseInt(value.value)
Mar 10, 2018
676
if(z > $B.min_int && z < $B.max_int){return z}
677
else{return value}
678
}
Sep 5, 2014
679
Mar 10, 2018
680
base = $B.$GetInt(base)
Sep 5, 2014
681
Mar 10, 2018
682
if(isinstance(value, _b_.str)){value = value.valueOf()}
683
if(typeof value == "string") {
684
var _value = value.trim() // remove leading/trailing whitespace
685
if(_value.length == 2 && base == 0 &&
686
(_value == "0b" || _value == "0o" || _value == "0x")){
687
throw _b_.ValueError.$factory("invalid value")
688
}
689
if(_value.length >2) {
690
var _pre = _value.substr(0, 2).toUpperCase()
691
if(base == 0){
692
if(_pre == "0B"){base = 2}
693
if(_pre == "0O"){base = 8}
694
if(_pre == "0X"){base = 16}
695
}
696
if(_pre == "0B" || _pre == "0O" || _pre == "0X"){
697
_value = _value.substr(2)
698
while(_value.startsWith("_")){
699
_value = _value.substr(1)
700
}
Mar 10, 2018
701
}
702
}
703
var _digits = $valid_digits(base),
704
_re = new RegExp("^[+-]?[" + _digits + "]" +
705
"[" + _digits + "_]*$", "i"),
706
match = _re.exec(_value)
707
if(match === null){
Mar 10, 2018
708
throw _b_.ValueError.$factory(
709
"invalid literal for int() with base " + base + ": '" +
710
_b_.str.$factory(value) + "'")
711
}else{
712
value = _value.replace(/_/g, "")
Mar 10, 2018
713
}
714
if(base <= 10 && ! isFinite(value)){
715
throw _b_.ValueError.$factory(
716
"invalid literal for int() with base " + base + ": '" +
717
_b_.str.$factory(value) + "'")
718
}
719
var res = parseInt(value, base)
Mar 10, 2018
720
if(res < $B.min_int || res > $B.max_int){
721
return $B.long_int.$factory(value, base)
Mar 10, 2018
722
}
723
return res
Sep 5, 2014
724
}
Mar 10, 2018
726
if(isinstance(value, [_b_.bytes, _b_.bytearray])){
727
var _digits = $valid_digits(base)
Mar 10, 2018
728
for(var i = 0; i < value.source.length; i++){
729
if(_digits.indexOf(String.fromCharCode(value.source[i])) == -1){
730
throw _b_.ValueError.$factory(
731
"invalid literal for int() with base " + base + ": " +
732
_b_.repr(value))
Mar 10, 2018
735
return Number(parseInt(getattr(value, "decode")("latin-1"), base))
Sep 5, 2014
737
Mar 10, 2018
738
if(hasattr(value, "__int__")){return getattr(value, "__int__")()}
739
if(hasattr(value, "__index__")){return getattr(value, "__index__")()}
740
if(hasattr(value, "__trunc__")){
741
var res = getattr(value, "__trunc__")(),
742
int_func = _b_.getattr(res, "__int__", null)
743
if(int_func === null){
744
throw TypeError.$factory("__trunc__ returned non-Integral (type "+
Mar 21, 2018
745
$B.get_class(res).__name__ + ")")
Mar 10, 2018
747
var res = int_func()
748
if(isinstance(res, int)){return int_value(res)}
Mar 10, 2018
749
throw TypeError.$factory("__trunc__ returned non-Integral (type "+
Mar 21, 2018
750
$B.get_class(res).__name__ + ")")
Mar 10, 2018
752
throw _b_.TypeError.$factory(
753
"int() argument must be a string, a bytes-like " +
754
"object or a number, not '" + $B.get_class(value).__name__ + "'")
Sep 5, 2014
755
}
756
757
$B.set_func_names(int, "builtins")
Sep 5, 2014
759
_b_.int = int
760
Feb 11, 2018
762
$B.$bool = function(obj){ // return true or false
Mar 10, 2018
763
if(obj === null || obj === undefined ){ return false}
764
switch(typeof obj){
765
case "boolean":
766
return obj
767
case "number":
768
case "string":
769
if(obj){return true}
770
return false
771
default:
772
try{return getattr(obj, "__bool__")()}
773
catch(err){
Mar 21, 2018
774
try{return getattr(obj, "__len__")() > 0}
Mar 10, 2018
775
catch(err){return true}
776
}
777
}
Feb 11, 2018
778
}
779
780
var bool = {
781
__bases__: [int],
Feb 11, 2018
782
__class__: _b_.type,
Feb 11, 2018
783
__module__: "builtins",
784
__mro__: [int, object],
785
__name__: "bool",
786
$is_class: true,
787
$native: true
788
}
Feb 11, 2018
790
bool.__add__ = function(self,other){
Mar 10, 2018
791
return (other ? 1 : 0) + (self ? 1 : 0)
Feb 11, 2018
794
bool.__and__ = function(self, other){
795
return $B.$bool(int.__and__(self, other))
Feb 11, 2018
798
bool.__eq__ = function(self,other){
799
return self ? $B.$bool(other) : !$B.$bool(other)
Feb 11, 2018
802
bool.__ne__ = function(self,other){
803
return self ? !$B.$bool(other) : $B.$bool(other)
Feb 11, 2018
806
bool.__ge__ = function(self,other){
807
return _b_.int.__ge__(bool.__hash__(self),other)
Feb 11, 2018
810
bool.__gt__ = function(self,other){
811
return _b_.int.__gt__(bool.__hash__(self),other)
Mar 10, 2018
814
bool.__hash__ = bool.__index__ = bool.__int__ = function(self){
815
if(self.valueOf()) return 1
816
return 0
817
}
818
Mar 10, 2018
819
bool.__le__ = function(self, other){return ! bool.__gt__(self, other)}
Mar 10, 2018
821
bool.__lshift__ = function(self, other){return self.valueOf() << other}
Mar 10, 2018
823
bool.__lt__ = function(self, other){return ! bool.__ge__(self, other)}
Mar 10, 2018
825
bool.__mul__ = function(self, other){
Feb 11, 2018
829
bool.__neg__ = function(self){return -$B.int_or_bool(self)}
Feb 11, 2018
831
bool.__or__ = function(self, other){
832
return $B.$bool(int.__or__(self, other))
Feb 11, 2018
835
bool.__pos__ = $B.int_or_bool
Feb 11, 2018
837
bool.__repr__ = bool.__str__ = function(self){
838
return self ? "True" : "False"
Feb 11, 2018
841
bool.__setattr__ = function(self, attr){
842
return no_set_attr(bool, attr)
Feb 11, 2018
845
bool.__sub__ = function(self,other){
846
return (self ? 1 : 0) - (other ? 1 : 0)
Feb 11, 2018
849
bool.__xor__ = function(self, other) {
850
return self.valueOf() != other.valueOf()
851
}
852
Feb 11, 2018
853
bool.$factory = function(){
854
// Calls $B.$bool, which is used inside the generated JS code and skips
855
// arguments control.
Mar 10, 2018
856
var $ = $B.args("bool", 1, {x: null}, ["x"],
857
arguments,{x: false}, null, null)
Feb 11, 2018
858
return $B.$bool($.x)
859
}
860
861
_b_.bool = bool
Feb 11, 2018
863
$B.set_func_names(bool, "builtins")
Sep 5, 2014
865
})(__BRYTHON__)