Skip to content
Permalink
Newer
Older
100644 870 lines (784 sloc) 26.5 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
}
245
if(_b_.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(_b_.hasattr(other, "__rmod__")){
301
return $B.$getattr(other, "__rmod__")(self)
302
}
Mar 10, 2018
303
$err("%", other)
Sep 5, 2014
304
}
305
306
int.__mro__ = [_b_.object]
Sep 5, 2014
307
Mar 10, 2018
308
int.__mul__ = function(self, other){
309
Sep 5, 2014
310
var val = self.valueOf()
Jan 22, 2015
311
312
// this will be quick check, so lets do it early.
Mar 10, 2018
313
if(typeof other === "string") {
Jan 22, 2015
314
return other.repeat(val)
315
}
316
317
if(_b_.isinstance(other, int)){
Mar 10, 2018
319
var res = self * other
320
if(res > $B.min_int && res < $B.max_int){return res}
321
else{
322
return int.$factory($B.long_int.__mul__($B.long_int.$factory(self),
323
$B.long_int.$factory(other)))
324
}
326
if(_b_.isinstance(other, _b_.float)){
Mar 10, 2018
327
return new Number(self * other)
329
if(_b_.isinstance(other, _b_.bool)){
Mar 10, 2018
330
if(other.valueOf()){return self}
331
return int.$factory(0)
Sep 5, 2014
332
}
333
if(_b_.isinstance(other, _b_.complex)){
334
return $B.make_complex(int.__mul__(self, other.$real),
335
int.__mul__(self, other.$imag))
Sep 5, 2014
336
}
337
if(_b_.isinstance(other, [_b_.list, _b_.tuple])){
Sep 5, 2014
338
var res = []
339
// make temporary copy of list
Mar 10, 2018
340
var $temp = other.slice(0, other.length)
341
for(var i = 0; i < val; i++){res = res.concat($temp)}
342
if(_b_.isinstance(other, _b_.tuple)){res = _b_.tuple.$factory(res)}
Sep 5, 2014
343
return res
344
}
345
if(_b_.hasattr(other, "__rmul__")){
346
return $B.$getattr(other, "__rmul__")(self)
347
}
Mar 10, 2018
348
$err("*", other)
Sep 5, 2014
349
}
350
Feb 22, 2019
351
int.__ne__ = function(self, other){
352
var res = int.__eq__(self, other)
353
return (res === _b_.NotImplemented) ? res : !res
354
}
355
356
int.__neg__ = function(self){return -self}
Sep 5, 2014
357
358
int.__new__ = function(cls, value){
Mar 10, 2018
359
if(cls === undefined){
360
throw _b_.TypeError.$factory("int.__new__(): not enough arguments")
361
}else if(! _b_.isinstance(cls, _b_.type)){
362
throw _b_.TypeError.$factory("int.__new__(X): X is not a type object")
363
}
364
if(cls === int){return int.$factory(value)}
365
return {
366
__class__: cls,
367
__dict__: _b_.dict.$factory(),
Mar 10, 2018
369
}
Sep 5, 2014
370
}
371
372
int.__pos__ = function(self){return self}
Sep 5, 2014
373
Mar 10, 2018
374
int.__pow__ = function(self, other, z){
375
if(_b_.isinstance(other, int)){
376
other = int_value(other)
377
switch(other.valueOf()) {
378
case 0:
379
return int.$factory(1)
380
case 1:
381
return int.$factory(self.valueOf())
Feb 9, 2015
382
}
383
if(z !== undefined && z !== _b_.None){
May 19, 2017
384
// If z is provided, the algorithm is faster than computing
385
// self ** other then applying the modulo z
386
if(z == 1){return 0}
387
var result = 1,
388
base = self % z,
389
exponent = other,
390
long_int = $B.long_int
391
while(exponent > 0){
392
if(exponent % 2 == 1){
393
if(result * base > $B.max_int){
394
result = long_int.__mul__(
395
long_int.$factory(result),
396
long_int.$factory(base))
397
result = long_int.__mod__(result, z)
398
}else{
399
result = (result * base) % z
400
}
401
}
402
exponent = exponent >> 1
403
if(base * base > $B.max_int){
404
base = long_int.__mul__(long_int.$factory(base),
405
long_int.$factory(base))
406
base = long_int.__mod__(base, z)
407
}else{
408
base = (base * base) % z
409
}
May 19, 2017
410
}
May 19, 2017
412
}
Mar 10, 2018
413
var res = Math.pow(self.valueOf(), other.valueOf())
414
if(res > $B.min_int && res < $B.max_int){return res}
May 19, 2017
415
else if(res !== Infinity && !isFinite(res)){return res}
Feb 11, 2018
417
return int.$factory($B.long_int.__pow__($B.long_int.$factory(self),
418
$B.long_int.$factory(other)))
May 19, 2017
419
}
Sep 5, 2014
420
}
421
if(_b_.isinstance(other, _b_.float)) {
Mar 10, 2018
422
if(self >= 0){return new Number(Math.pow(self, other.valueOf()))}
423
else{
424
// use complex power
425
return _b_.complex.__pow__($B.make_complex(self, 0), other)
427
}else if(_b_.isinstance(other, _b_.complex)){
Mar 10, 2018
428
var preal = Math.pow(self, other.$real),
429
ln = Math.log(self)
Mar 10, 2018
430
return $B.make_complex(preal * Math.cos(ln), preal * Math.sin(ln))
Sep 5, 2014
431
}
432
var rpow = $B.$getattr(other, "__rpow__", _b_.None)
433
if(rpow !== _b_.None){
434
return rpow(self)
435
}
Mar 10, 2018
436
$err("**", other)
Sep 5, 2014
437
}
438
439
int.__repr__ = function(self){
Mar 10, 2018
440
if(self === int){return "<class 'int'>"}
Sep 5, 2014
441
return self.toString()
442
}
443
444
// bitwise right shift
Mar 10, 2018
445
int.__rshift__ = function(self, other){
446
if(_b_.isinstance(other, int)){
Feb 11, 2018
448
return int.$factory($B.long_int.__rshift__($B.long_int.$factory(self),
449
$B.long_int.$factory(other)))
451
var rrshift = $B.$getattr(other, "__rrshift__", _b_.None)
452
if(rrshift !== _b_.None){return rrshift(self)}
453
$err('>>', other)
454
}
Sep 5, 2014
455
456
int.__setattr__ = function(self, attr, value){
Mar 10, 2018
457
if(typeof self == "number"){
458
if(int.$factory[attr] === undefined){
459
throw _b_.AttributeError.$factory(
460
"'int' object has no attribute '" + attr + "'")
Mar 10, 2018
462
throw _b_.AttributeError.$factory(
463
"'int' object attribute '" + attr + "' is read-only")
Sep 5, 2014
465
}
466
// subclasses of int can have attributes set
467
_b_.dict.$setitem(self.__dict__, attr, value)
468
return _b_.None
Sep 5, 2014
469
}
470
471
int.__str__ = int.__repr__
Sep 5, 2014
472
Mar 10, 2018
473
int.__truediv__ = function(self, other){
474
if(_b_.isinstance(other, int)){
476
if(other == 0){
477
throw _b_.ZeroDivisionError.$factory("division by zero")
478
}
Mar 10, 2018
479
if(other.__class__ === $B.long_int){
480
return new Number(self / parseInt(other.value))
481
}
482
return new Number(self / other)
Sep 5, 2014
483
}
484
if(_b_.isinstance(other, _b_.float)){
Mar 10, 2018
485
if(!other.valueOf()){
486
throw _b_.ZeroDivisionError.$factory("division by zero")
Mar 10, 2018
487
}
488
return new Number(self / other)
Sep 5, 2014
489
}
490
if(_b_.isinstance(other, _b_.complex)){
Mar 10, 2018
491
var cmod = other.$real * other.$real + other.$imag * other.$imag
492
if(cmod == 0){throw _b_.ZeroDivisionError.$factory("division by zero")}
Mar 10, 2018
493
return $B.make_complex(self * other.$real / cmod,
494
-self * other.$imag / cmod)
Sep 5, 2014
495
}
496
if(_b_.hasattr(other, "__rtruediv__")){
497
return $B.$getattr(other, "__rtruediv__")(self)
Mar 10, 2018
498
}
499
$err("/", other)
Sep 5, 2014
500
}
501
502
int.bit_length = function(self){
503
s = _b_.bin(self)
504
s = $B.$getattr(s, "lstrip")("-0b") // remove leading zeros and minus sign
Sep 5, 2014
505
return s.length // len('100101') --> 6
506
}
507
508
// descriptors
509
int.numerator = function(self){return self}
510
int.denominator = function(self){return int.$factory(1)}
511
int.imag = function(self){return int.$factory(0)}
512
int.real = function(self){return self}
513
Mar 10, 2018
514
$B.max_int32 = (1 << 30) * 2 - 1
515
$B.min_int32 = - $B.max_int32
517
// code for operands & | ^
Mar 10, 2018
518
var $op_func = function(self, other){
519
if(_b_.isinstance(other, int)) {
Mar 10, 2018
520
if(other.__class__ === $B.long_int){
521
return $B.long_int.__sub__($B.long_int.$factory(self),
522
$B.long_int.$factory(other))
Mar 23, 2018
525
if(self > $B.max_int32 || self < $B.min_int32 ||
526
other > $B.max_int32 || other < $B.min_int32){
Mar 10, 2018
527
return $B.long_int.__sub__($B.long_int.$factory(self),
528
$B.long_int.$factory(other))
Mar 21, 2018
530
return self - other
Jun 7, 2015
531
}
532
if(_b_.isinstance(other, _b_.bool)){return self - other}
533
var rsub = $B.$getattr(other, "__rsub__", _b_.None)
534
if(rsub !== _b_.None){return rsub(self)}
Mar 10, 2018
535
$err("-", other)
Sep 5, 2014
536
}
537
Mar 10, 2018
538
$op_func += "" // source code
539
var $ops = {"&": "and", "|": "or", "^": "xor"}
Sep 5, 2014
540
for(var $op in $ops){
Mar 10, 2018
541
var opf = $op_func.replace(/-/gm, $op)
542
opf = opf.replace(new RegExp("sub", "gm"), $ops[$op])
543
eval("int.__" + $ops[$op] + "__ = " + opf)
Sep 5, 2014
544
}
545
546
// code for + and -
Mar 10, 2018
547
var $op_func = function(self, other){
548
if(_b_.isinstance(other, int)){
Mar 10, 2018
550
if(typeof other == "number"){
551
var res = self.valueOf() - other.valueOf()
552
if(res > $B.min_int && res < $B.max_int){return res}
Feb 11, 2018
553
else{return $B.long_int.__sub__($B.long_int.$factory(self),
554
$B.long_int.$factory(other))}
Mar 10, 2018
555
}else if(typeof other == "boolean"){
Mar 21, 2018
556
return other ? self - 1 : self
557
}else{
Feb 11, 2018
558
return $B.long_int.__sub__($B.long_int.$factory(self),
559
$B.long_int.$factory(other))
Sep 5, 2014
561
}
562
if(_b_.isinstance(other, _b_.float)){
Mar 10, 2018
563
return new Number(self - other)
Sep 5, 2014
564
}
565
if(_b_.isinstance(other, _b_.complex)){
Mar 10, 2018
566
return $B.make_complex(self - other.$real, -other.$imag)
Sep 5, 2014
567
}
568
if(_b_.isinstance(other, _b_.bool)){
Mar 10, 2018
569
var bool_value = 0;
570
if(other.valueOf()){bool_value = 1}
571
return self - bool_value
Sep 5, 2014
572
}
573
if(_b_.isinstance(other, _b_.complex)){
574
return $B.make_complex(self.valueOf() - other.$real, other.$imag)
Sep 5, 2014
575
}
576
var rsub = $B.$getattr(other, "__rsub__", _b_.None)
577
if(rsub !== _b_.None){return rsub(self)}
Mar 10, 2018
578
throw $err("-", other)
Sep 5, 2014
579
}
Mar 10, 2018
580
$op_func += "" // source code
581
var $ops = {"+": "add", "-": "sub"}
Sep 5, 2014
582
for(var $op in $ops){
Mar 10, 2018
583
var opf = $op_func.replace(/-/gm, $op)
584
opf = opf.replace(new RegExp("sub", "gm"), $ops[$op])
585
eval("int.__" + $ops[$op] + "__ = " + opf)
Sep 5, 2014
586
}
587
588
// comparison methods
Mar 10, 2018
589
var $comp_func = function(self, other){
Mar 23, 2018
590
if(other.__class__ === $B.long_int){
Feb 11, 2018
591
return $B.long_int.__lt__(other, $B.long_int.$factory(self))
593
if(_b_.isinstance(other, int)){
594
other = int_value(other)
595
return self.valueOf() > other.valueOf()
596
}else if(_b_.isinstance(other, _b_.float)){
597
return self.valueOf() > other.valueOf()
598
}else if(_b_.isinstance(other, _b_.bool)) {
Feb 11, 2018
599
return self.valueOf() > _b_.bool.__hash__(other)
Sep 5, 2014
600
}
601
if(_b_.hasattr(other, "__int__") || _b_.hasattr(other, "__index__")){
602
return int.__gt__(self, $B.$GetInt(other))
Sep 5, 2014
606
}
Mar 10, 2018
607
$comp_func += "" // source code
Sep 5, 2014
609
for(var $op in $B.$comps){
Mar 10, 2018
610
eval("int.__"+$B.$comps[$op] + "__ = " +
611
$comp_func.replace(/>/gm, $op).
612
replace(/__gt__/gm,"__" + $B.$comps[$op] + "__").
613
replace(/__lt__/, "__" + $B.$inv_comps[$op] + "__"))
Sep 5, 2014
614
}
615
616
// add "reflected" methods
617
$B.make_rmethods(int)
Sep 5, 2014
618
Mar 10, 2018
619
var $valid_digits = function(base) {
620
var digits = ""
621
if(base === 0){return "0"}
622
if(base < 10){
Mar 21, 2018
623
for(var i = 0; i < base; i++){digits += String.fromCharCode(i + 48)}
Sep 5, 2014
624
return digits
625
}
626
Mar 10, 2018
627
var digits = "0123456789"
Sep 5, 2014
628
// A = 65 (10 + 55)
Mar 21, 2018
629
for (var i = 10; i < base; i++) {digits += String.fromCharCode(i + 55)}
Sep 5, 2014
630
return digits
631
}
632
633
int.$factory = function(value, base){
634
// int() with no argument returns 0
Mar 10, 2018
635
if(value === undefined){return 0}
637
// int() of an integer returns the integer if base is undefined
Mar 10, 2018
638
if(typeof value == "number" &&
639
(base === undefined || base == 10)){return parseInt(value)}
641
if(_b_.isinstance(value, _b_.complex)){
642
throw _b_.TypeError.$factory("can't convert complex to int")
Dec 28, 2014
643
}
Mar 10, 2018
645
var $ns = $B.args("int", 2, {x:null, base:null}, ["x", "base"], arguments,
646
{"base": 10}, null, null),
647
value = $ns["x"],
648
base = $ns["base"]
650
if(_b_.isinstance(value, _b_.float) && base == 10){
Mar 10, 2018
651
if(value < $B.min_int || value > $B.max_int){
Feb 11, 2018
652
return $B.long_int.$from_float(value)
Mar 10, 2018
654
else{return value > 0 ? Math.floor(value) : Math.ceil(value)}
Sep 5, 2014
656
Mar 10, 2018
657
if(! (base >=2 && base <= 36)){
Dec 26, 2014
658
// throw error (base must be 0, or 2-36)
Mar 10, 2018
659
if(base != 0){throw _b_.ValueError.$factory("invalid base")}
Dec 26, 2014
660
}
661
Mar 10, 2018
662
if(typeof value == "number"){
Mar 10, 2018
664
if(base == 10){
665
if(value < $B.min_int || value > $B.max_int){
666
return $B.long_int.$factory(value)
667
}
Mar 10, 2018
669
}else if(value.toString().search("e") > -1){
Dec 26, 2014
670
// can't convert to another base if value is too big
Mar 10, 2018
671
throw _b_.OverflowError.$factory("can't convert to base " + base)
Dec 26, 2014
672
}else{
Mar 10, 2018
673
var res = parseInt(value, base)
674
if(value < $B.min_int || value > $B.max_int){
675
return $B.long_int.$factory(value, base)
676
}
Dec 26, 2014
678
}
679
}
Sep 5, 2014
680
Mar 10, 2018
681
if(value === true){return Number(1)}
682
if(value === false){return Number(0)}
683
if(value.__class__ === $B.long_int){
684
var z = parseInt(value.value)
Mar 10, 2018
685
if(z > $B.min_int && z < $B.max_int){return z}
686
else{return value}
687
}
Sep 5, 2014
688
Mar 10, 2018
689
base = $B.$GetInt(base)
690
function invalid(value, base){
691
throw _b_.ValueError.$factory("invalid literal for int() with base " +
692
base + ": '" + _b_.str.$factory(value) + "'")
693
}
Sep 5, 2014
694
695
if(_b_.isinstance(value, _b_.str)){value = value.valueOf()}
Mar 10, 2018
696
if(typeof value == "string") {
697
var _value = value.trim() // remove leading/trailing whitespace
698
if(_value.length == 2 && base == 0 &&
699
(_value == "0b" || _value == "0o" || _value == "0x")){
700
throw _b_.ValueError.$factory("invalid value")
701
}
702
if(_value.length >2) {
703
var _pre = _value.substr(0, 2).toUpperCase()
704
if(base == 0){
705
if(_pre == "0B"){base = 2}
706
if(_pre == "0O"){base = 8}
707
if(_pre == "0X"){base = 16}
708
}else if(_pre == "0X" && base != 16){invalid(_value, base)}
709
else if(_pre == "0O" && base != 8){invalid(_value, base)}
710
if((_pre == "0B" && base == 2) || _pre == "0O" || _pre == "0X"){
Mar 10, 2018
711
_value = _value.substr(2)
712
while(_value.startsWith("_")){
713
_value = _value.substr(1)
714
}
Mar 10, 2018
715
}
716
}else if(base == 0){
717
// eg int("1\n", 0)
718
base = 10
Mar 10, 2018
719
}
720
var _digits = $valid_digits(base),
721
_re = new RegExp("^[+-]?[" + _digits + "]" +
722
"[" + _digits + "_]*$", "i"),
723
match = _re.exec(_value)
724
if(match === null){
725
invalid(value, base)
726
}else{
727
value = _value.replace(/_/g, "")
Mar 10, 2018
728
}
729
if(base <= 10 && ! isFinite(value)){invalid(_value, base)}
730
var res = parseInt(value, base)
Mar 10, 2018
731
if(res < $B.min_int || res > $B.max_int){
732
return $B.long_int.$factory(value, base)
Mar 10, 2018
733
}
734
return res
Sep 5, 2014
735
}
737
if(_b_.isinstance(value, [_b_.bytes, _b_.bytearray])){
738
return int.$factory($B.$getattr(value, "decode")("latin-1"), base)
739
}
741
var num_value = $B.to_num(value, ["__int__", "__index__", "__trunc__"])
742
if(num_value === null){
743
throw _b_.TypeError.$factory(
744
"int() argument must be a string, a bytes-like " +
745
"object or a number, not '" + $B.class_name(value) + "'")
746
}
747
return num_value
Sep 5, 2014
748
}
749
750
$B.set_func_names(int, "builtins")
Sep 5, 2014
752
_b_.int = int
753
Feb 11, 2018
755
$B.$bool = function(obj){ // return true or false
Mar 10, 2018
756
if(obj === null || obj === undefined ){ return false}
757
switch(typeof obj){
758
case "boolean":
759
return obj
760
case "number":
761
case "string":
762
if(obj){return true}
763
return false
764
default:
765
if(obj.$is_class){return true}
766
var klass = obj.__class__ || $B.get_class(obj),
767
missing = {},
768
bool_method = $B.$getattr(klass, "__bool__", missing)
769
if(bool_method === missing){
770
try{return _b_.len(obj) > 0}
Mar 10, 2018
771
catch(err){return true}
773
var res = $B.$call(bool_method)(obj)
774
if(res !== true && res !== false){
775
throw _b_.TypeError.$factory("__bool__ should return " +
776
"bool, returned " + $B.class_name(res))
777
}
778
return res
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
if(_b_.isinstance(other, bool)){
811
return self && other
812
}else if(_b_.isinstance(other, int)){
813
return int.__and__(bool.__index__(self), int.__index__(other))
814
}
815
return _b_.NotImplemented
Mar 10, 2018
818
bool.__hash__ = bool.__index__ = bool.__int__ = function(self){
819
if(self.valueOf()) return 1
820
return 0
821
}
822
Feb 11, 2018
823
bool.__neg__ = function(self){return -$B.int_or_bool(self)}
Feb 11, 2018
825
bool.__or__ = function(self, other){
826
if(_b_.isinstance(other, bool)){
827
return self || other
828
}else if(_b_.isinstance(other, int)){
829
return int.__or__(bool.__index__(self), int.__index__(other))
830
}
831
return _b_.NotImplemented
Feb 11, 2018
834
bool.__pos__ = $B.int_or_bool
Feb 11, 2018
836
bool.__repr__ = bool.__str__ = function(self){
837
return self ? "True" : "False"
Feb 11, 2018
840
bool.__setattr__ = function(self, attr){
841
if(_b_.dir(self).indexOf(attr) > -1){
842
var msg = "attribute '" + attr + "' of 'int' objects is not writable"
843
}else{
844
var msg = "'bool' object has no attribute '" + attr + "'"
845
}
846
throw _b_.AttributeError.$factory(msg)
Feb 11, 2018
849
bool.__xor__ = function(self, other) {
850
if(_b_.isinstance(other, bool)){
851
return self ^ other ? true : false
852
}else if(_b_.isinstance(other, int)){
853
return int.__xor__(bool.__index__(self), int.__index__(other))
854
}
855
return _b_.NotImplemented
Feb 11, 2018
858
bool.$factory = function(){
859
// Calls $B.$bool, which is used inside the generated JS code and skips
860
// arguments control.
Mar 10, 2018
861
var $ = $B.args("bool", 1, {x: null}, ["x"],
862
arguments,{x: false}, null, null)
Feb 11, 2018
863
return $B.$bool($.x)
864
}
865
866
_b_.bool = bool
Feb 11, 2018
868
$B.set_func_names(bool, "builtins")
Sep 5, 2014
870
})(__BRYTHON__)