Skip to content
Permalink
Newer
Older
100644 876 lines (779 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,
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
}
153
return _b_.NotImplemented
Sep 5, 2014
154
}
155
156
int.__float__ = function(self){
157
return new Number(self)
158
}
159
160
function preformat(self, fmt){
str
Feb 10, 2018
161
if(fmt.empty){return _b_.str.$factory(self)}
Mar 10, 2018
162
if(fmt.type && 'bcdoxXn'.indexOf(fmt.type) == -1){
163
throw _b_.ValueError.$factory("Unknown format code '" + fmt.type +
164
"' for object of type 'int'")
165
}
167
switch(fmt.type){
168
case undefined:
Mar 10, 2018
169
case "d":
170
res = self.toString()
171
break
Mar 10, 2018
172
case "b":
173
res = (fmt.alternate ? "0b" : "") + self.toString(2)
174
break
Mar 10, 2018
175
case "c":
176
res = _b_.chr(self)
177
break
Mar 10, 2018
178
case "o":
179
res = (fmt.alternate ? "0o" : "") + self.toString(8)
180
break
Mar 10, 2018
181
case "x":
182
res = (fmt.alternate ? "0x" : "") + self.toString(16)
183
break
Mar 10, 2018
184
case "X":
185
res = (fmt.alternate ? "0X" : "") + self.toString(16).toUpperCase()
186
break
Mar 10, 2018
187
case "n":
188
return self // fix me
189
}
191
if(fmt.sign !== undefined){
192
if((fmt.sign == " " || fmt.sign == "+" ) && self >= 0){
193
res = fmt.sign + res
194
}
195
}
196
return res
197
}
198
199
Mar 10, 2018
200
int.__format__ = function(self, format_spec){
201
var fmt = new $B.parse_format_spec(format_spec)
Mar 10, 2018
202
if(fmt.type && 'eEfFgG%'.indexOf(fmt.type) != -1){
203
// Call __format__ on float(self)
204
return _b_.float.__format__(self, format_spec)
Mar 10, 2018
206
fmt.align = fmt.align || ">"
207
var res = preformat(self, fmt)
208
if(fmt.comma){
Mar 10, 2018
209
var sign = res[0] == "-" ? "-" : "",
210
rest = res.substr(sign.length),
211
len = rest.length,
212
nb = Math.ceil(rest.length/3),
213
chunks = []
Mar 10, 2018
214
for(var i = 0; i < nb; i++){
215
chunks.push(rest.substring(len - 3 * i - 3, len - 3 * i))
216
}
217
chunks.reverse()
Mar 10, 2018
218
res = sign + chunks.join(",")
219
}
220
return $B.format_width(res, fmt)
Sep 5, 2014
221
}
222
223
int.__floordiv__ = function(self,other){
224
if(other.__class__ == $B.long_int){
225
return $B.long_int.__floordiv__($B.long_int.$factory(self), other)
226
}
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){
254
return int_value(self)
255
}
Sep 5, 2014
256
257
int.__init__ = function(self, value){
Mar 10, 2018
258
if(value === undefined){value = 0}
Sep 5, 2014
259
self.toString = function(){return value}
Sep 5, 2014
261
}
262
263
int.__int__ = function(self){return self}
Sep 5, 2014
264
265
int.__invert__ = function(self){return ~self}
Sep 5, 2014
266
Mar 10, 2018
268
int.__lshift__ = function(self, other){
269
if(isinstance(other, int)){
Mar 10, 2018
271
return int.$factory($B.long_int.__lshift__($B.long_int.$factory(self),
272
$B.long_int.$factory(other)))
Mar 10, 2018
274
var rlshift = getattr(other, "__rlshift__", None)
275
if(rlshift !== None){return rlshift(self)}
276
$err("<<", other)
Mar 10, 2018
279
int.__mod__ = function(self, other) {
Sep 5, 2014
280
// can't use Javascript % because it works differently for negative numbers
Mar 10, 2018
281
if(isinstance(other,_b_.tuple) && other.length == 1){other = other[0]}
282
if(other.__class__ === $B.long_int){
283
return $B.long_int.__mod__($B.long_int.$factory(self), other)
284
}
Mar 10, 2018
285
if(isinstance(other, [int, _b_.float, bool])){
Mar 10, 2018
287
if(other === false){other = 0}
288
else if(other === true){other = 1}
289
if(other == 0){throw _b_.ZeroDivisionError.$factory(
290
"integer division or modulo by zero")}
Mar 10, 2018
291
return (self % other + other) % other
Sep 5, 2014
292
}
Mar 10, 2018
293
if(hasattr(other, "__rmod__")){return getattr(other, "__rmod__")(self)}
294
$err("%", other)
Sep 5, 2014
295
}
296
297
int.__mro__ = [object]
Sep 5, 2014
298
Mar 10, 2018
299
int.__mul__ = function(self, other){
300
Sep 5, 2014
301
var val = self.valueOf()
Jan 22, 2015
302
303
// this will be quick check, so lets do it early.
Mar 10, 2018
304
if(typeof other === "string") {
Jan 22, 2015
305
return other.repeat(val)
306
}
307
Mar 10, 2018
308
if(isinstance(other, int)){
Mar 10, 2018
310
var res = self * other
311
if(res > $B.min_int && res < $B.max_int){return res}
312
else{
313
return int.$factory($B.long_int.__mul__($B.long_int.$factory(self),
314
$B.long_int.$factory(other)))
315
}
Mar 10, 2018
317
if(isinstance(other, _b_.float)){
318
return new Number(self * other)
Mar 10, 2018
320
if(isinstance(other, _b_.bool)){
321
if(other.valueOf()){return self}
322
return int.$factory(0)
Sep 5, 2014
323
}
Mar 10, 2018
324
if(isinstance(other, _b_.complex)){
325
return $B.make_complex(int.__mul__(self, other.$real),
326
int.__mul__(self, other.$imag))
Sep 5, 2014
327
}
Mar 10, 2018
328
if(isinstance(other, [_b_.list, _b_.tuple])){
Sep 5, 2014
329
var res = []
330
// make temporary copy of list
Mar 10, 2018
331
var $temp = other.slice(0, other.length)
332
for(var i = 0; i < val; i++){res = res.concat($temp)}
333
if(isinstance(other, _b_.tuple)){res = _b_.tuple.$factory(res)}
Sep 5, 2014
334
return res
335
}
Mar 10, 2018
336
if(hasattr(other, "__rmul__")){return getattr(other, "__rmul__")(self)}
337
$err("*", other)
Sep 5, 2014
338
}
339
340
int.__neg__ = function(self){return -self}
Sep 5, 2014
341
342
int.__new__ = function(cls, value){
Mar 10, 2018
343
if(cls === undefined){
344
throw _b_.TypeError.$factory("int.__new__(): not enough arguments")
345
}else if(! isinstance(cls, _b_.type)){
346
throw _b_.TypeError.$factory("int.__new__(X): X is not a type object")
347
}
348
if(cls === int){return int.$factory(value)}
349
return {
350
__class__: cls,
351
__dict__: _b_.dict.$factory(),
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))
Sep 5, 2014
586
}
Mar 10, 2018
587
$comp_func += "" // source code
Sep 5, 2014
589
for(var $op in $B.$comps){
Mar 10, 2018
590
eval("int.__"+$B.$comps[$op] + "__ = " +
591
$comp_func.replace(/>/gm, $op).
592
replace(/__gt__/gm,"__" + $B.$comps[$op] + "__").
593
replace(/__lt__/, "__" + $B.$inv_comps[$op] + "__"))
Sep 5, 2014
594
}
595
596
// add "reflected" methods
597
$B.make_rmethods(int)
Sep 5, 2014
598
Mar 10, 2018
599
var $valid_digits = function(base) {
600
var digits = ""
601
if(base === 0){return "0"}
602
if(base < 10){
Mar 21, 2018
603
for(var i = 0; i < base; i++){digits += String.fromCharCode(i + 48)}
Sep 5, 2014
604
return digits
605
}
606
Mar 10, 2018
607
var digits = "0123456789"
Sep 5, 2014
608
// A = 65 (10 + 55)
Mar 21, 2018
609
for (var i = 10; i < base; i++) {digits += String.fromCharCode(i + 55)}
Sep 5, 2014
610
return digits
611
}
612
613
int.$factory = function(value, base){
614
// int() with no argument returns 0
Mar 10, 2018
615
if(value === undefined){return 0}
617
// int() of an integer returns the integer if base is undefined
Mar 10, 2018
618
if(typeof value == "number" &&
619
(base === undefined || base == 10)){return parseInt(value)}
Mar 10, 2018
621
if(base !== undefined){
622
if(! isinstance(value, [_b_.str, _b_.bytes, _b_.bytearray])){
623
throw TypeError.$factory(
624
"int() can't convert non-string with explicit base")
Dec 28, 2014
625
}
626
}
627
Mar 10, 2018
628
if(isinstance(value, _b_.complex)){
629
throw TypeError.$factory("can't convert complex to int")
Dec 28, 2014
630
}
Mar 10, 2018
631
var $ns = $B.args("int", 2, {x:null, base:null}, ["x", "base"], arguments,
632
{"base": 10}, null, null),
633
value = $ns["x"],
634
base = $ns["base"]
Mar 10, 2018
636
if(isinstance(value, _b_.float) && base == 10){
637
if(value < $B.min_int || value > $B.max_int){
Feb 11, 2018
638
return $B.long_int.$from_float(value)
Mar 10, 2018
640
else{return value > 0 ? Math.floor(value) : Math.ceil(value)}
Sep 5, 2014
642
Mar 10, 2018
643
if(! (base >=2 && base <= 36)){
Dec 26, 2014
644
// throw error (base must be 0, or 2-36)
Mar 10, 2018
645
if(base != 0){throw _b_.ValueError.$factory("invalid base")}
Dec 26, 2014
646
}
647
Mar 10, 2018
648
if(typeof value == "number"){
Mar 10, 2018
650
if(base == 10){
651
if(value < $B.min_int || value > $B.max_int){
652
return $B.long_int.$factory(value)
653
}
Mar 10, 2018
655
}else if(value.toString().search("e") > -1){
Dec 26, 2014
656
// can't convert to another base if value is too big
Mar 10, 2018
657
throw _b_.OverflowError.$factory("can't convert to base " + base)
Dec 26, 2014
658
}else{
Mar 10, 2018
659
var res = parseInt(value, base)
660
if(value < $B.min_int || value > $B.max_int){
661
return $B.long_int.$factory(value, base)
662
}
Dec 26, 2014
664
}
665
}
Sep 5, 2014
666
Mar 10, 2018
667
if(value === true){return Number(1)}
668
if(value === false){return Number(0)}
669
if(value.__class__ === $B.long_int){
670
var z = parseInt(value.value)
Mar 10, 2018
671
if(z > $B.min_int && z < $B.max_int){return z}
672
else{return value}
673
}
Sep 5, 2014
674
Mar 10, 2018
675
base = $B.$GetInt(base)
676
function invalid(value, base){
677
throw _b_.ValueError.$factory("invalid literal for int() with base " +
678
base + ": '" + _b_.str.$factory(value) + "'")
679
}
Sep 5, 2014
680
Mar 10, 2018
681
if(isinstance(value, _b_.str)){value = value.valueOf()}
682
if(typeof value == "string") {
683
var _value = value.trim() // remove leading/trailing whitespace
684
if(_value.length == 2 && base == 0 &&
685
(_value == "0b" || _value == "0o" || _value == "0x")){
686
throw _b_.ValueError.$factory("invalid value")
687
}
688
if(_value.length >2) {
689
var _pre = _value.substr(0, 2).toUpperCase()
690
if(base == 0){
691
if(_pre == "0B"){base = 2}
692
if(_pre == "0O"){base = 8}
693
if(_pre == "0X"){base = 16}
694
}else if(_pre == "0X" && base != 16){invalid(_value, base)}
695
else if(_pre == "0O" && base != 8){invalid(_value, base)}
696
else if(_pre == "0B" && base != 2){invalid(_value, base)
Mar 10, 2018
697
}
698
if(_pre == "0B" || _pre == "0O" || _pre == "0X"){
699
_value = _value.substr(2)
700
while(_value.startsWith("_")){
701
_value = _value.substr(1)
702
}
Mar 10, 2018
703
}
704
}
705
var _digits = $valid_digits(base),
706
_re = new RegExp("^[+-]?[" + _digits + "]" +
707
"[" + _digits + "_]*$", "i"),
708
match = _re.exec(_value)
709
if(match === null){invalid(value, base)}
710
else{
711
value = _value.replace(/_/g, "")
Mar 10, 2018
712
}
713
if(base <= 10 && ! isFinite(value)){invalid(_value, base)}
714
var res = parseInt(value, base)
Mar 10, 2018
715
if(res < $B.min_int || res > $B.max_int){
716
return $B.long_int.$factory(value, base)
Mar 10, 2018
717
}
718
return res
Sep 5, 2014
719
}
Mar 10, 2018
721
if(isinstance(value, [_b_.bytes, _b_.bytearray])){
722
var _digits = $valid_digits(base)
Mar 10, 2018
723
for(var i = 0; i < value.source.length; i++){
724
if(_digits.indexOf(String.fromCharCode(value.source[i])) == -1){
Mar 10, 2018
728
return Number(parseInt(getattr(value, "decode")("latin-1"), base))
Sep 5, 2014
730
Mar 10, 2018
731
if(hasattr(value, "__int__")){return getattr(value, "__int__")()}
732
if(hasattr(value, "__index__")){return getattr(value, "__index__")()}
733
if(hasattr(value, "__trunc__")){
734
var res = getattr(value, "__trunc__")(),
735
int_func = _b_.getattr(res, "__int__", null)
736
if(int_func === null){
737
throw TypeError.$factory("__trunc__ returned non-Integral (type "+
Mar 21, 2018
738
$B.get_class(res).__name__ + ")")
Mar 10, 2018
740
var res = int_func()
741
if(isinstance(res, int)){return int_value(res)}
Mar 10, 2018
742
throw TypeError.$factory("__trunc__ returned non-Integral (type "+
Mar 21, 2018
743
$B.get_class(res).__name__ + ")")
Mar 10, 2018
745
throw _b_.TypeError.$factory(
746
"int() argument must be a string, a bytes-like " +
747
"object or a number, not '" + $B.get_class(value).__name__ + "'")
Sep 5, 2014
748
}
749
750
$B.set_func_names(int, "builtins")
Sep 5, 2014
752
_b_.int = int
753
Feb 11, 2018
755
$B.$bool = function(obj){ // return true or false
Mar 10, 2018
756
if(obj === null || obj === undefined ){ return false}
757
switch(typeof obj){
758
case "boolean":
759
return obj
760
case "number":
761
case "string":
762
if(obj){return true}
763
return false
764
default:
765
var missing = {},
766
bool_func = $B.$getattr(obj, "__bool__", missing)
767
if(bool_func === missing){
Mar 21, 2018
768
try{return getattr(obj, "__len__")() > 0}
Mar 10, 2018
769
catch(err){return true}
770
}else{
771
return bool_func()
Mar 10, 2018
772
}
773
}
Feb 11, 2018
774
}
775
776
var bool = {
777
__bases__: [int],
Feb 11, 2018
778
__class__: _b_.type,
Feb 11, 2018
779
__module__: "builtins",
780
__mro__: [int, object],
781
__name__: "bool",
782
$is_class: true,
783
$native: true
784
}
Feb 11, 2018
786
bool.__add__ = function(self,other){
Mar 10, 2018
787
return (other ? 1 : 0) + (self ? 1 : 0)
Feb 11, 2018
790
bool.__and__ = function(self, other){
791
return $B.$bool(int.__and__(self, other))
794
bool.__eq__ = function(self, other){
795
if(other === self){return True}
796
else if(typeof other == "number"){
797
return self ? other == 1 : other == 0
798
}else if(isinstance(other, _b_.int)){
799
return self ? other.$value == 1 : other.$value == 0
800
}else if(other instanceof Number){
801
return self ? other == 1 : other == 0
802
}else{
803
return false
804
}
805
//return self ? $B.$bool(other) : !$B.$bool(other)
Feb 11, 2018
808
bool.__ne__ = function(self,other){
809
return ! bool.__eq__(self, other)
Feb 11, 2018
812
bool.__ge__ = function(self,other){
813
return _b_.int.__ge__(bool.__hash__(self),other)
Feb 11, 2018
816
bool.__gt__ = function(self,other){
817
return _b_.int.__gt__(bool.__hash__(self),other)
Mar 10, 2018
820
bool.__hash__ = bool.__index__ = bool.__int__ = function(self){
821
if(self.valueOf()) return 1
822
return 0
823
}
824
Mar 10, 2018
825
bool.__le__ = function(self, other){return ! bool.__gt__(self, other)}
Mar 10, 2018
827
bool.__lshift__ = function(self, other){return self.valueOf() << other}
Mar 10, 2018
829
bool.__lt__ = function(self, other){return ! bool.__ge__(self, other)}
Mar 10, 2018
831
bool.__mul__ = function(self, other){
Feb 11, 2018
835
bool.__neg__ = function(self){return -$B.int_or_bool(self)}
Feb 11, 2018
837
bool.__or__ = function(self, other){
838
return $B.$bool(int.__or__(self, other))
Feb 11, 2018
841
bool.__pos__ = $B.int_or_bool
Feb 11, 2018
843
bool.__repr__ = bool.__str__ = function(self){
844
return self ? "True" : "False"
Feb 11, 2018
847
bool.__setattr__ = function(self, attr){
848
if(_b_.dir(self).indexOf(attr) > -1){
849
var msg = "attribute '" + attr + "' of 'int' objects is not writable"
850
}else{
851
var msg = "'bool' object has no attribute '" + attr + "'"
852
}
853
throw _b_.AttributeError.$factory(msg)
Feb 11, 2018
856
bool.__sub__ = function(self,other){
857
return (self ? 1 : 0) - (other ? 1 : 0)
Feb 11, 2018
860
bool.__xor__ = function(self, other) {
861
return self.valueOf() != other.valueOf()
862
}
863
Feb 11, 2018
864
bool.$factory = function(){
865
// Calls $B.$bool, which is used inside the generated JS code and skips
866
// arguments control.
Mar 10, 2018
867
var $ = $B.args("bool", 1, {x: null}, ["x"],
868
arguments,{x: false}, null, null)
Feb 11, 2018
869
return $B.$bool($.x)
870
}
871
872
_b_.bool = bool
Feb 11, 2018
874
$B.set_func_names(bool, "builtins")
Sep 5, 2014
876
})(__BRYTHON__)