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