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