Skip to content
Permalink
Newer
Older
100644 879 lines (793 sloc) 27 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.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(_b_.isinstance(x, [_b_.bytes, _b_.bytearray])){
Mar 10, 2018
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 " +
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
}else{
122
while(res.length < len){
123
res = res.concat([0])
124
}
125
}
126
if(byteorder == "big"){res = res.reverse()}
127
return {
128
__class__: _b_.bytes,
129
source: res
130
}
Sep 5, 2014
131
}
132
133
int.__abs__ = function(self){return _b_.abs(self)}
135
int.__bool__ = function(self){
136
return int_value(self).valueOf() == 0 ? false : true
137
}
Sep 5, 2014
138
139
int.__ceil__ = function(self){return Math.ceil(int_value(self))}
141
int.__divmod__ = function(self, other){return _b_.divmod(self, other)}
Mar 10, 2018
143
int.__eq__ = function(self, other){
Sep 5, 2014
144
// compare object "self" to class "int"
Mar 10, 2018
145
if(other === undefined){return self === int}
146
if(_b_.isinstance(other, int)){
147
return self.valueOf() == int_value(other).valueOf()
148
}
149
if(_b_.isinstance(other, _b_.float)){return self.valueOf() == other.valueOf()}
150
if(_b_.isinstance(other, _b_.complex)){
Mar 10, 2018
151
if(other.$imag != 0){return False}
152
return self.valueOf() == other.$real
Sep 5, 2014
153
}
154
return _b_.NotImplemented
Sep 5, 2014
155
}
156
157
int.__float__ = function(self){
158
return new Number(self)
159
}
160
161
function preformat(self, fmt){
str
Feb 10, 2018
162
if(fmt.empty){return _b_.str.$factory(self)}
Mar 10, 2018
163
if(fmt.type && 'bcdoxXn'.indexOf(fmt.type) == -1){
164
throw _b_.ValueError.$factory("Unknown format code '" + fmt.type +
165
"' for object of type 'int'")
166
}
168
switch(fmt.type){
169
case undefined:
Mar 10, 2018
170
case "d":
171
res = self.toString()
172
break
Mar 10, 2018
173
case "b":
174
res = (fmt.alternate ? "0b" : "") + self.toString(2)
175
break
Mar 10, 2018
176
case "c":
177
res = _b_.chr(self)
178
break
Mar 10, 2018
179
case "o":
180
res = (fmt.alternate ? "0o" : "") + self.toString(8)
181
break
Mar 10, 2018
182
case "x":
183
res = (fmt.alternate ? "0x" : "") + self.toString(16)
184
break
Mar 10, 2018
185
case "X":
186
res = (fmt.alternate ? "0X" : "") + self.toString(16).toUpperCase()
187
break
Mar 10, 2018
188
case "n":
189
return self // fix me
190
}
192
if(fmt.sign !== undefined){
193
if((fmt.sign == " " || fmt.sign == "+" ) && self >= 0){
194
res = fmt.sign + res
195
}
196
}
197
return res
198
}
199
200
Mar 10, 2018
201
int.__format__ = function(self, format_spec){
202
var fmt = new $B.parse_format_spec(format_spec)
Mar 10, 2018
203
if(fmt.type && 'eEfFgG%'.indexOf(fmt.type) != -1){
204
// Call __format__ on float(self)
205
return _b_.float.__format__(self, format_spec)
Mar 10, 2018
207
fmt.align = fmt.align || ">"
208
var res = preformat(self, fmt)
209
if(fmt.comma){
Mar 10, 2018
210
var sign = res[0] == "-" ? "-" : "",
211
rest = res.substr(sign.length),
212
len = rest.length,
213
nb = Math.ceil(rest.length/3),
214
chunks = []
Mar 10, 2018
215
for(var i = 0; i < nb; i++){
216
chunks.push(rest.substring(len - 3 * i - 3, len - 3 * i))
217
}
218
chunks.reverse()
Mar 10, 2018
219
res = sign + chunks.join(",")
220
}
221
return $B.format_width(res, fmt)
Sep 5, 2014
222
}
223
224
int.__floordiv__ = function(self, other){
225
if(other.__class__ === $B.long_int){
226
return $B.long_int.__floordiv__($B.long_int.$factory(self), other)
227
}
228
if(_b_.isinstance(other, int)){
230
if(other == 0){throw _b_.ZeroDivisionError.$factory("division by zero")}
Mar 10, 2018
231
return Math.floor(self / other)
Sep 5, 2014
232
}
233
if(_b_.isinstance(other, _b_.float)){
Mar 10, 2018
234
if(!other.valueOf()){
235
throw _b_.ZeroDivisionError.$factory("division by zero")
Mar 10, 2018
236
}
237
return Math.floor(self / other)
Sep 5, 2014
238
}
Mar 10, 2018
239
if(hasattr(other, "__rfloordiv__")){
240
return $B.$getattr(other, "__rfloordiv__")(self)
Sep 5, 2014
241
}
Mar 10, 2018
242
$err("//", other)
Sep 5, 2014
243
}
244
245
int.__hash__ = function(self){
Mar 23, 2018
246
if(self === undefined){
247
return int.__hashvalue__ || $B.$py_next_hash-- // for hash of int type (not instance of int)
248
}
249
return self.valueOf()
250
}
Sep 5, 2014
251
252
//int.__ior__ = function(self,other){return self | other} // bitwise OR
Sep 5, 2014
253
254
int.__index__ = function(self){
255
return int_value(self)
256
}
Sep 5, 2014
257
258
int.__init__ = function(self, value){
Mar 10, 2018
259
if(value === undefined){value = 0}
Sep 5, 2014
260
self.toString = function(){return value}
261
return _b_.None
Sep 5, 2014
262
}
263
264
int.__int__ = function(self){return self}
Sep 5, 2014
265
266
int.__invert__ = function(self){return ~self}
Sep 5, 2014
267
Mar 10, 2018
269
int.__lshift__ = function(self, other){
270
if(_b_.isinstance(other, int)){
Mar 10, 2018
272
return int.$factory($B.long_int.__lshift__($B.long_int.$factory(self),
273
$B.long_int.$factory(other)))
275
var rlshift = $B.$getattr(other, "__rlshift__", _b_.None)
276
if(rlshift !== _b_.None){return rlshift(self)}
Mar 10, 2018
277
$err("<<", other)
Mar 10, 2018
280
int.__mod__ = function(self, other) {
Sep 5, 2014
281
// can't use Javascript % because it works differently for negative numbers
282
if(_b_.isinstance(other,_b_.tuple) && other.length == 1){other = other[0]}
283
if(other.__class__ === $B.long_int){
284
return $B.long_int.__mod__($B.long_int.$factory(self), other)
285
}
286
if(_b_.isinstance(other, [int, _b_.float, bool])){
Mar 10, 2018
288
if(other === false){other = 0}
289
else if(other === true){other = 1}
290
if(other == 0){throw _b_.ZeroDivisionError.$factory(
291
"integer division or modulo by zero")}
Mar 10, 2018
292
return (self % other + other) % other
Sep 5, 2014
293
}
294
if(hasattr(other, "__rmod__")){return $B.$getattr(other, "__rmod__")(self)}
Mar 10, 2018
295
$err("%", other)
Sep 5, 2014
296
}
297
298
int.__mro__ = [_b_.object]
Sep 5, 2014
299
Mar 10, 2018
300
int.__mul__ = function(self, other){
301
Sep 5, 2014
302
var val = self.valueOf()
Jan 22, 2015
303
304
// this will be quick check, so lets do it early.
Mar 10, 2018
305
if(typeof other === "string") {
Jan 22, 2015
306
return other.repeat(val)
307
}
308
309
if(_b_.isinstance(other, int)){
Mar 10, 2018
311
var res = self * other
312
if(res > $B.min_int && res < $B.max_int){return res}
313
else{
314
return int.$factory($B.long_int.__mul__($B.long_int.$factory(self),
315
$B.long_int.$factory(other)))
316
}
318
if(_b_.isinstance(other, _b_.float)){
Mar 10, 2018
319
return new Number(self * other)
321
if(_b_.isinstance(other, _b_.bool)){
Mar 10, 2018
322
if(other.valueOf()){return self}
323
return int.$factory(0)
Sep 5, 2014
324
}
325
if(_b_.isinstance(other, _b_.complex)){
326
return $B.make_complex(int.__mul__(self, other.$real),
327
int.__mul__(self, other.$imag))
Sep 5, 2014
328
}
329
if(_b_.isinstance(other, [_b_.list, _b_.tuple])){
Sep 5, 2014
330
var res = []
331
// make temporary copy of list
Mar 10, 2018
332
var $temp = other.slice(0, other.length)
333
for(var i = 0; i < val; i++){res = res.concat($temp)}
334
if(_b_.isinstance(other, _b_.tuple)){res = _b_.tuple.$factory(res)}
Sep 5, 2014
335
return res
336
}
337
if(_b_.hasattr(other, "__rmul__")){
338
return $B.$getattr(other, "__rmul__")(self)
339
}
Mar 10, 2018
340
$err("*", other)
Sep 5, 2014
341
}
342
Feb 22, 2019
343
int.__ne__ = function(self, other){
344
var res = int.__eq__(self, other)
345
return (res === _b_.NotImplemented) ? res : !res
346
}
347
348
int.__neg__ = function(self){return -self}
Sep 5, 2014
349
350
int.__new__ = function(cls, value){
Mar 10, 2018
351
if(cls === undefined){
352
throw _b_.TypeError.$factory("int.__new__(): not enough arguments")
353
}else if(! _b_.isinstance(cls, _b_.type)){
354
throw _b_.TypeError.$factory("int.__new__(X): X is not a type object")
355
}
356
if(cls === int){return int.$factory(value)}
357
return {
358
__class__: cls,
359
__dict__: _b_.dict.$factory(),
Mar 10, 2018
361
}
Sep 5, 2014
362
}
363
364
int.__pos__ = function(self){return self}
Sep 5, 2014
365
Mar 10, 2018
366
int.__pow__ = function(self, other, z){
367
if(_b_.isinstance(other, int)){
368
other = int_value(other)
369
switch(other.valueOf()) {
370
case 0:
371
return int.$factory(1)
372
case 1:
373
return int.$factory(self.valueOf())
Feb 9, 2015
374
}
May 19, 2017
375
if(z !== undefined && z !== null){
376
// If z is provided, the algorithm is faster than computing
377
// self ** other then applying the modulo z
378
if(z == 1){return 0}
379
var result = 1,
380
base = self % z,
381
exponent = other,
382
long_int = $B.long_int
383
while(exponent > 0){
384
if(exponent % 2 == 1){
385
if(result * base > $B.max_int){
386
result = long_int.__mul__(
387
long_int.$factory(result),
388
long_int.$factory(base))
389
result = long_int.__mod__(result, z)
390
}else{
391
result = (result * base) % z
392
}
393
}
394
exponent = exponent >> 1
395
if(base * base > $B.max_int){
396
base = long_int.__mul__(long_int.$factory(base),
397
long_int.$factory(base))
398
base = long_int.__mod__(base, z)
399
}else{
400
base = (base * base) % z
401
}
May 19, 2017
402
}
May 19, 2017
404
}
Mar 10, 2018
405
var res = Math.pow(self.valueOf(), other.valueOf())
406
if(res > $B.min_int && res < $B.max_int){return res}
May 19, 2017
407
else if(res !== Infinity && !isFinite(res)){return res}
Feb 11, 2018
409
return int.$factory($B.long_int.__pow__($B.long_int.$factory(self),
410
$B.long_int.$factory(other)))
May 19, 2017
411
}
Sep 5, 2014
412
}
413
if(_b_.isinstance(other, _b_.float)) {
Mar 10, 2018
414
if(self >= 0){return new Number(Math.pow(self, other.valueOf()))}
415
else{
416
// use complex power
417
return _b_.complex.__pow__($B.make_complex(self, 0), other)
419
}else if(_b_.isinstance(other, _b_.complex)){
Mar 10, 2018
420
var preal = Math.pow(self, other.$real),
421
ln = Math.log(self)
Mar 10, 2018
422
return $B.make_complex(preal * Math.cos(ln), preal * Math.sin(ln))
Sep 5, 2014
423
}
424
if(hasattr(other, "__rpow__")){return $B.$getattr(other, "__rpow__")(self)}
Mar 10, 2018
425
$err("**", other)
Sep 5, 2014
426
}
427
428
int.__repr__ = function(self){
Mar 10, 2018
429
if(self === int){return "<class 'int'>"}
Sep 5, 2014
430
return self.toString()
431
}
432
433
// bitwise right shift
Mar 10, 2018
434
int.__rshift__ = function(self, other){
435
if(_b_.isinstance(other, int)){
Feb 11, 2018
437
return int.$factory($B.long_int.__rshift__($B.long_int.$factory(self),
438
$B.long_int.$factory(other)))
440
var rrshift = $B.$getattr(other, "__rrshift__", _b_.None)
441
if(rrshift !== _b_.None){return rrshift(self)}
442
$err('>>', other)
443
}
Sep 5, 2014
444
445
int.__setattr__ = function(self, attr, value){
Mar 10, 2018
446
if(typeof self == "number"){
447
if(int.$factory[attr] === undefined){
448
throw _b_.AttributeError.$factory(
449
"'int' object has no attribute '" + attr + "'")
Mar 10, 2018
451
throw _b_.AttributeError.$factory(
452
"'int' object attribute '" + attr + "' is read-only")
Sep 5, 2014
454
}
455
// subclasses of int can have attributes set
456
self.__dict__.$string_dict[attr] = value
457
return _b_.None
Sep 5, 2014
458
}
459
460
int.__str__ = int.__repr__
Sep 5, 2014
461
Mar 10, 2018
462
int.__truediv__ = function(self, other){
463
if(_b_.isinstance(other, int)){
465
if(other == 0){
466
throw _b_.ZeroDivisionError.$factory("division by zero")
467
}
Mar 10, 2018
468
if(other.__class__ === $B.long_int){
469
return new Number(self / parseInt(other.value))
470
}
471
return new Number(self / other)
Sep 5, 2014
472
}
473
if(_b_.isinstance(other, _b_.float)){
Mar 10, 2018
474
if(!other.valueOf()){
475
throw _b_.ZeroDivisionError.$factory("division by zero")
Mar 10, 2018
476
}
477
return new Number(self / other)
Sep 5, 2014
478
}
479
if(_b_.isinstance(other, _b_.complex)){
Mar 10, 2018
480
var cmod = other.$real * other.$real + other.$imag * other.$imag
481
if(cmod == 0){throw _b_.ZeroDivisionError.$factory("division by zero")}
Mar 10, 2018
482
return $B.make_complex(self * other.$real / cmod,
483
-self * other.$imag / cmod)
Sep 5, 2014
484
}
485
if(_b_.hasattr(other, "__rtruediv__")){
486
return $B.$getattr(other, "__rtruediv__")(self)
Mar 10, 2018
487
}
488
$err("/", other)
Sep 5, 2014
489
}
490
491
int.bit_length = function(self){
492
s = _b_.bin(self)
493
s = $B.$getattr(s, "lstrip")("-0b") // remove leading zeros and minus sign
Sep 5, 2014
494
return s.length // len('100101') --> 6
495
}
496
497
// descriptors
498
int.numerator = function(self){return self}
499
int.denominator = function(self){return int.$factory(1)}
500
int.imag = function(self){return int.$factory(0)}
501
int.real = function(self){return self}
502
Mar 10, 2018
503
$B.max_int32 = (1 << 30) * 2 - 1
504
$B.min_int32 = - $B.max_int32
506
// code for operands & | ^
Mar 10, 2018
507
var $op_func = function(self, other){
508
if(_b_.isinstance(other, int)) {
Mar 10, 2018
509
if(other.__class__ === $B.long_int){
510
return $B.long_int.__sub__($B.long_int.$factory(self),
511
$B.long_int.$factory(other))
Mar 23, 2018
514
if(self > $B.max_int32 || self < $B.min_int32 ||
515
other > $B.max_int32 || other < $B.min_int32){
Mar 10, 2018
516
return $B.long_int.__sub__($B.long_int.$factory(self),
517
$B.long_int.$factory(other))
Mar 21, 2018
519
return self - other
Jun 7, 2015
520
}
521
if(_b_.isinstance(other, _b_.bool)){return self - other}
522
var rsub = $B.$getattr(other, "__rsub__", _b_.None)
523
if(rsub !== _b_.None){return rsub(self)}
Mar 10, 2018
524
$err("-", other)
Sep 5, 2014
525
}
526
Mar 10, 2018
527
$op_func += "" // source code
528
var $ops = {"&": "and", "|": "or", "^": "xor"}
Sep 5, 2014
529
for(var $op in $ops){
Mar 10, 2018
530
var opf = $op_func.replace(/-/gm, $op)
531
opf = opf.replace(new RegExp("sub", "gm"), $ops[$op])
532
eval("int.__" + $ops[$op] + "__ = " + opf)
Sep 5, 2014
533
}
534
535
// code for + and -
Mar 10, 2018
536
var $op_func = function(self, other){
537
if(_b_.isinstance(other, int)){
Mar 10, 2018
539
if(typeof other == "number"){
540
var res = self.valueOf() - other.valueOf()
541
if(res > $B.min_int && res < $B.max_int){return res}
Feb 11, 2018
542
else{return $B.long_int.__sub__($B.long_int.$factory(self),
543
$B.long_int.$factory(other))}
Mar 10, 2018
544
}else if(typeof other == "boolean"){
Mar 21, 2018
545
return other ? self - 1 : self
546
}else{
Feb 11, 2018
547
return $B.long_int.__sub__($B.long_int.$factory(self),
548
$B.long_int.$factory(other))
Sep 5, 2014
550
}
551
if(_b_.isinstance(other, _b_.float)){
Mar 10, 2018
552
return new Number(self - other)
Sep 5, 2014
553
}
554
if(_b_.isinstance(other, _b_.complex)){
Mar 10, 2018
555
return $B.make_complex(self - other.$real, -other.$imag)
Sep 5, 2014
556
}
557
if(_b_.isinstance(other, _b_.bool)){
Mar 10, 2018
558
var bool_value = 0;
559
if(other.valueOf()){bool_value = 1}
560
return self - bool_value
Sep 5, 2014
561
}
562
if(_b_.isinstance(other, _b_.complex)){
563
return $B.make_complex(self.valueOf() - other.$real, other.$imag)
Sep 5, 2014
564
}
565
var rsub = $B.$getattr(other, "__rsub__", _b_.None)
566
if(rsub !== _b_.None){return rsub(self)}
Mar 10, 2018
567
throw $err("-", other)
Sep 5, 2014
568
}
Mar 10, 2018
569
$op_func += "" // source code
570
var $ops = {"+": "add", "-": "sub"}
Sep 5, 2014
571
for(var $op in $ops){
Mar 10, 2018
572
var opf = $op_func.replace(/-/gm, $op)
573
opf = opf.replace(new RegExp("sub", "gm"), $ops[$op])
574
eval("int.__" + $ops[$op] + "__ = " + opf)
Sep 5, 2014
575
}
576
577
// comparison methods
Mar 10, 2018
578
var $comp_func = function(self, other){
Mar 23, 2018
579
if(other.__class__ === $B.long_int){
Feb 11, 2018
580
return $B.long_int.__lt__(other, $B.long_int.$factory(self))
582
if(_b_.isinstance(other, int)){
583
other = int_value(other)
584
return self.valueOf() > other.valueOf()
585
}else if(_b_.isinstance(other, _b_.float)){
586
return self.valueOf() > other.valueOf()
587
}else if(_b_.isinstance(other, _b_.bool)) {
Feb 11, 2018
588
return self.valueOf() > _b_.bool.__hash__(other)
Sep 5, 2014
589
}
590
if(_b_.hasattr(other, "__int__") || _b_.hasattr(other, "__index__")){
591
return int.__gt__(self, $B.$GetInt(other))
Sep 5, 2014
595
}
Mar 10, 2018
596
$comp_func += "" // source code
Sep 5, 2014
598
for(var $op in $B.$comps){
Mar 10, 2018
599
eval("int.__"+$B.$comps[$op] + "__ = " +
600
$comp_func.replace(/>/gm, $op).
601
replace(/__gt__/gm,"__" + $B.$comps[$op] + "__").
602
replace(/__lt__/, "__" + $B.$inv_comps[$op] + "__"))
Sep 5, 2014
603
}
604
605
// add "reflected" methods
606
$B.make_rmethods(int)
Sep 5, 2014
607
Mar 10, 2018
608
var $valid_digits = function(base) {
609
var digits = ""
610
if(base === 0){return "0"}
611
if(base < 10){
Mar 21, 2018
612
for(var i = 0; i < base; i++){digits += String.fromCharCode(i + 48)}
Sep 5, 2014
613
return digits
614
}
615
Mar 10, 2018
616
var digits = "0123456789"
Sep 5, 2014
617
// A = 65 (10 + 55)
Mar 21, 2018
618
for (var i = 10; i < base; i++) {digits += String.fromCharCode(i + 55)}
Sep 5, 2014
619
return digits
620
}
621
622
int.$factory = function(value, base){
623
// int() with no argument returns 0
Mar 10, 2018
624
if(value === undefined){return 0}
626
// int() of an integer returns the integer if base is undefined
Mar 10, 2018
627
if(typeof value == "number" &&
628
(base === undefined || base == 10)){return parseInt(value)}
Mar 10, 2018
630
if(base !== undefined){
631
if(! _b_.isinstance(value, [_b_.str, _b_.bytes, _b_.bytearray])){
632
throw _b_.TypeError.$factory(
Mar 10, 2018
633
"int() can't convert non-string with explicit base")
Dec 28, 2014
634
}
635
}
636
637
if(_b_.isinstance(value, _b_.complex)){
638
throw _b_.TypeError.$factory("can't convert complex to int")
Dec 28, 2014
639
}
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
}
735
var $int = $B.$getattr(value, "__int__", _b_.None)
736
if($int !== _b_.None){return $int()}
737
738
var $index = $B.$getattr(value, "__index__", _b_.None)
739
if($index !== _b_.None){return $index()}
Sep 5, 2014
740
741
var $trunc = $B.$getattr(value, "__trunc__", _b_.None)
742
if($trunc !== _b_.None){
743
var res = $truc(),
744
int_func = $int
745
if(int_func === _b_.None){
746
throw _b_.TypeError.$factory("__trunc__ returned non-Integral (type "+
Mar 10, 2018
749
var res = int_func()
750
if(_b_.isinstance(res, int)){return int_value(res)}
751
throw _b_.TypeError.$factory("__trunc__ returned non-Integral (type "+
Mar 10, 2018
754
throw _b_.TypeError.$factory(
755
"int() argument must be a string, a bytes-like " +
756
"object or a number, not '" + $B.class_name(value) + "'")
Sep 5, 2014
757
}
758
759
$B.set_func_names(int, "builtins")
Sep 5, 2014
761
_b_.int = int
762
Feb 11, 2018
764
$B.$bool = function(obj){ // return true or false
Mar 10, 2018
765
if(obj === null || obj === undefined ){ return false}
766
switch(typeof obj){
767
case "boolean":
768
return obj
769
case "number":
770
case "string":
771
if(obj){return true}
772
return false
773
default:
774
if(obj.$is_class){return true}
775
var klass = obj.__class__ || $B.get_class(obj),
776
missing = {},
777
bool_method = $B.$getattr(klass, "__bool__", missing)
778
if(bool_method === missing){
779
try{return _b_.len(obj) > 0}
Mar 10, 2018
780
catch(err){return true}
782
var res = $B.$call(bool_method)(obj)
783
if(res !== true && res !== false){
784
throw _b_.TypeError.$factory("__bool__ should return " +
785
"bool, returned " + $B.class_name(res))
786
}
787
return res
Mar 10, 2018
788
}
789
}
Feb 11, 2018
790
}
791
792
var bool = {
793
__bases__: [int],
Feb 11, 2018
794
__class__: _b_.type,
795
__mro__: [int, _b_.object],
796
$infos:{
797
__name__: "bool",
798
__module__: "builtins"
799
},
Feb 11, 2018
800
$is_class: true,
801
$native: true
802
}
Feb 22, 2019
804
var methods = $B.op2method.subset("operations", "binary", "comparisons",
805
"boolean")
806
for(var op in methods){
807
var method = "__" + methods[op] + "__"
808
bool[method] = (function(op){
809
return function(self, other){
810
var value = self ? 1 : 0
811
if(int[op] !== undefined){
812
return int[op](value, other)
813
}
814
}
815
})(method)
Feb 11, 2018
818
bool.__and__ = function(self, other){
819
if(_b_.isinstance(other, bool)){
820
return self && other
821
}else if(_b_.isinstance(other, int)){
822
return int.__and__(bool.__index__(self), int.__index__(other))
823
}
824
return _b_.NotImplemented
Mar 10, 2018
827
bool.__hash__ = bool.__index__ = bool.__int__ = function(self){
828
if(self.valueOf()) return 1
829
return 0
830
}
831
Feb 11, 2018
832
bool.__neg__ = function(self){return -$B.int_or_bool(self)}
Feb 11, 2018
834
bool.__or__ = function(self, other){
835
if(_b_.isinstance(other, bool)){
836
return self || other
837
}else if(_b_.isinstance(other, int)){
838
return int.__or__(bool.__index__(self), int.__index__(other))
839
}
840
return _b_.NotImplemented
Feb 11, 2018
843
bool.__pos__ = $B.int_or_bool
Feb 11, 2018
845
bool.__repr__ = bool.__str__ = function(self){
846
return self ? "True" : "False"
Feb 11, 2018
849
bool.__setattr__ = function(self, attr){
850
if(_b_.dir(self).indexOf(attr) > -1){
851
var msg = "attribute '" + attr + "' of 'int' objects is not writable"
852
}else{
853
var msg = "'bool' object has no attribute '" + attr + "'"
854
}
855
throw _b_.AttributeError.$factory(msg)
Feb 11, 2018
858
bool.__xor__ = function(self, other) {
859
if(_b_.isinstance(other, bool)){
860
return self ^ other ? true : false
861
}else if(_b_.isinstance(other, int)){
862
return int.__xor__(bool.__index__(self), int.__index__(other))
863
}
864
return _b_.NotImplemented
Feb 11, 2018
867
bool.$factory = function(){
868
// Calls $B.$bool, which is used inside the generated JS code and skips
869
// arguments control.
Mar 10, 2018
870
var $ = $B.args("bool", 1, {x: null}, ["x"],
871
arguments,{x: false}, null, null)
Feb 11, 2018
872
return $B.$bool($.x)
873
}
874
875
_b_.bool = bool
Feb 11, 2018
877
$B.set_func_names(bool, "builtins")
Sep 5, 2014
879
})(__BRYTHON__)