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