Skip to content
Permalink
Newer
Older
100644 604 lines (521 sloc) 18.9 KB
Sep 5, 2014
1
;(function($B){
2
3
eval($B.InjectBuiltins())
4
5
var $ObjectDict = _b_.object.$dict, $N = _b_.None
Sep 5, 2014
6
7
function $err(op,other){
8
var msg = "unsupported operand type(s) for "+op
9
msg += ": 'int' and '"+$B.get_class(other).__name__+"'"
10
throw _b_.TypeError(msg)
11
}
12
13
// dictionary for built-in class 'int'
Sep 5, 2014
14
var $IntDict = {__class__:$B.$type,
15
__name__:'int',
16
__dir__:$ObjectDict.__dir__,
Sep 5, 2014
17
toString:function(){return '$IntDict'},
Dec 6, 2015
18
$native:true,
19
descriptors:{'numerator':true,
21
'imag':true,
22
'real':true}
Sep 5, 2014
23
}
24
25
$IntDict.from_bytes = function() {
26
var $=$B.args("from_bytes", 3,
27
{bytes:null, byteorder:null, signed:null}, ['bytes', 'byteorder', 'signed'],
28
arguments, {signed:False}, null, null)
Sep 5, 2014
29
30
var x = $.bytes,
31
byteorder = $.byteorder,
32
signed = $.signed
33
var _bytes, _len
34
if (isinstance(x, [_b_.list, _b_.tuple])) {
35
_bytes=x
36
_len=len(x)
Jan 14, 2015
37
} else if (isinstance(x, [_b_.bytes, _b_.bytearray])) {
38
_bytes=x.source
39
_len=x.source.length
Jan 14, 2015
40
} else {
41
_b_.TypeError("Error! " + _b_.type(x) + " is not supported in int.from_bytes. fix me!")
Sep 5, 2014
42
}
43
44
switch(byteorder) {
45
case 'big':
46
var num = _bytes[_len - 1];
47
var _mult=256
48
for (var i = (_len - 2); i >= 0; i--) {
49
// For operations, use the functions that can take or return
50
// big integers
51
num = $B.add($B.mul(_mult, _bytes[i]), num)
52
_mult = $B.mul(_mult,256)
Jan 14, 2015
54
if (!signed) return num
55
if (_bytes[0] < 128) return num
56
return $B.sub(num, _mult)
57
case 'little':
58
var num = _bytes[0]
59
if (num >= 128) num = num - 256
60
var _mult=256
61
for (var i = 1; i < _len; i++) {
62
num = $B.add($B.mul(_mult, _bytes[i]), num)
63
_mult = $B.mul(_mult,256)
Jan 14, 2015
65
if (!signed) return num
66
if (_bytes[_len - 1] < 128) return num
67
return $B.sub(num, _mult)
Sep 5, 2014
68
}
69
70
throw _b_.ValueError("byteorder must be either 'little' or 'big'");
71
}
72
73
$IntDict.to_bytes = function(length, byteorder, star) {
74
//var len = x.length
75
throw _b_.NotImplementedError("int.to_bytes is not implemented yet")
76
}
77
78
79
//$IntDict.__and__ = function(self,other){return self & other} // bitwise AND
80
81
$IntDict.__abs__ = function(self){return abs(self)}
82
Sep 5, 2014
83
$IntDict.__bool__ = function(self){return new Boolean(self.valueOf())}
84
85
$IntDict.__ceil__ = function(self){return Math.ceil(self)}
86
Sep 5, 2014
87
//is this a duplicate?
88
$IntDict.__class__ = $B.$type
89
90
$IntDict.__divmod__ = function(self, other){return divmod(self, other)}
91
Sep 5, 2014
92
$IntDict.__eq__ = function(self,other){
93
// compare object "self" to class "int"
94
if(other===undefined) return self===int
95
if(isinstance(other,int)) return self.valueOf()==other.valueOf()
96
if(isinstance(other,_b_.float)) return self.valueOf()==other.valueOf()
Sep 5, 2014
97
if(isinstance(other,_b_.complex)){
98
if (other.imag != 0) return False
99
return self.valueOf() == other.real
100
}
101
102
if (hasattr(other, '__eq__')) return getattr(other, '__eq__')(self)
103
Sep 5, 2014
104
return self.valueOf()===other
105
}
106
107
function preformat(self, fmt){
108
if(fmt.empty){return _b_.str(self)}
109
if(fmt.type && 'bcdoxXn'.indexOf(fmt.type)==-1){
110
throw _b_.ValueError("Unknown format code '"+fmt.type+
111
"' for object of type 'int'")
112
}
113
114
switch(fmt.type){
115
case undefined:
116
case 'd':
117
return self.toString()
118
case 'b':
119
return (fmt.alternate ? '0b' : '') + self.toString(2)
120
case 'c':
121
return _b_.chr(self)
122
case 'o':
123
return (fmt.alternate ? '0o' : '') + self.toString(8)
125
return (fmt.alternate ? '0x' : '') + self.toString(16)
127
return (fmt.alternate ? '0X' : '') + self.toString(16).toUpperCase()
128
case 'n':
129
return self // fix me
130
}
131
132
return res
133
}
134
135
Sep 5, 2014
136
$IntDict.__format__ = function(self,format_spec){
137
var fmt = new $B.parse_format_spec(format_spec)
138
if(fmt.type && 'eEfFgG%'.indexOf(fmt.type)!=-1){
139
// Call __format__ on float(self)
140
return _b_.float.$dict.__format__(self, format_spec)
141
}
142
fmt.align = fmt.align || '>'
143
var res = preformat(self, fmt)
144
if(fmt.comma){
145
var len = res.length, nb = Math.ceil(res.length/3), chunks = []
146
for(var i=0;i<nb;i++){
147
chunks.push(res.substring(len-3*i-3, len-3*i))
148
}
149
chunks.reverse()
150
res = chunks.join(',')
151
}
152
return $B.format_width(res, fmt)
Sep 5, 2014
153
}
154
155
//$IntDict.__float__ = function(self){return float(self)}
156
Sep 5, 2014
157
$IntDict.__floordiv__ = function(self,other){
158
if(isinstance(other,int)){
159
if(other==0) throw ZeroDivisionError('division by zero')
160
return Math.floor(self/other)
161
}
162
if(isinstance(other,_b_.float)){
163
if(!other.valueOf()) throw ZeroDivisionError('division by zero')
164
return Math.floor(self/other)
Sep 5, 2014
165
}
166
if(hasattr(other,'__rfloordiv__')){
167
return getattr(other,'__rfloordiv__')(self)
168
}
169
$err("//",other)
170
}
171
172
$IntDict.__hash__ = function(self){
173
if (self === undefined) {
174
return $IntDict.__hashvalue__ || $B.$py_next_hash-- // for hash of int type (not instance of int)
175
}
176
177
return self.valueOf()
178
}
Sep 5, 2014
179
180
//$IntDict.__ior__ = function(self,other){return self | other} // bitwise OR
181
182
$IntDict.__index__ = function(self){return self}
183
184
$IntDict.__init__ = function(self,value){
185
if(value===undefined){value=0}
186
self.toString = function(){return value}
187
//self.valueOf = function(){return value}
Sep 5, 2014
189
}
190
191
$IntDict.__int__ = function(self){return self}
192
193
$IntDict.__invert__ = function(self){return ~self}
194
195
// bitwise left shift
196
$IntDict.__lshift__ = function(self,other){
197
if(isinstance(other, int)){
198
return int($B.LongInt.$dict.__lshift__($B.LongInt(self), $B.LongInt(other)))
199
}
200
var rlshift = getattr(other, '__rlshift__', null)
201
if(rlshift!==null){return rlshift(self)}
202
$err('<<', other)
203
}
204
Sep 5, 2014
205
$IntDict.__mod__ = function(self,other) {
206
// can't use Javascript % because it works differently for negative numbers
207
if(isinstance(other,_b_.tuple) && other.length==1) other=other[0]
208
if(isinstance(other,[int, _b_.float, bool])){
209
if(other===false){other=0}else if(other===true){other=1}
210
if(other==0){throw _b_.ZeroDivisionError(
211
"integer division or modulo by zero")}
212
return (self%other+other)%other
Sep 5, 2014
213
}
214
if(hasattr(other,'__rmod__')) return getattr(other,'__rmod__')(self)
215
$err('%',other)
216
}
217
218
$IntDict.__mro__ = [$ObjectDict]
Sep 5, 2014
219
220
$IntDict.__mul__ = function(self,other){
221
Sep 5, 2014
222
var val = self.valueOf()
Jan 22, 2015
223
224
// this will be quick check, so lets do it early.
225
if(typeof other==="string") {
226
return other.repeat(val)
227
}
228
229
if(isinstance(other,int)){
230
var res = self*other
231
if(res>$B.min_int && res<$B.max_int){return res}
232
else{return int($B.LongInt.$dict.__mul__($B.LongInt(self),
233
$B.LongInt(other)))}
235
if(isinstance(other,_b_.float)){
236
return new Number(self*other)
Sep 5, 2014
238
if(isinstance(other,_b_.bool)){
239
if (other.valueOf()) return self
Jan 22, 2015
240
return int(0)
Sep 5, 2014
241
}
242
if(isinstance(other,_b_.complex)){
243
return _b_.complex($IntDict.__mul__(self, other.real),
244
$IntDict.__mul__(self, other.imag))
Sep 5, 2014
245
}
246
if(isinstance(other,[_b_.list,_b_.tuple])){
247
var res = []
248
// make temporary copy of list
249
var $temp = other.slice(0,other.length)
250
for(var i=0;i<val;i++) res=res.concat($temp)
251
if(isinstance(other,_b_.tuple)) res=_b_.tuple(res)
252
return res
253
}
254
if(hasattr(other,'__rmul__')) return getattr(other,'__rmul__')(self)
255
$err("*",other)
256
}
257
258
$IntDict.__name__ = 'int'
259
260
$IntDict.__neg__ = function(self){return -self}
261
262
$IntDict.__new__ = function(cls){
263
if(cls===undefined){throw _b_.TypeError('int.__new__(): not enough arguments')}
264
return {__class__:cls.$dict}
265
}
266
267
$IntDict.__pos__ = function(self){return self}
Sep 5, 2014
268
269
$IntDict.__pow__ = function(self,other){
270
if(isinstance(other, int)) {
Feb 9, 2015
271
switch(other.valueOf()) {
272
case 0:
273
return int(1)
274
case 1:
275
return int(self.valueOf())
276
}
277
var res = Math.pow(self.valueOf(),other.valueOf())
278
if(!isFinite(res)){return res}
279
if(res>$B.min_int && res<$B.max_int){return res}
280
else{
281
return int($B.LongInt.$dict.__pow__($B.LongInt(self),
282
$B.LongInt(other)))}
Sep 5, 2014
283
}
284
if(isinstance(other, _b_.float)) {
285
if(self>=0){return new Number(Math.pow(self, other.valueOf()))}
286
else{
287
// use complex power
288
return _b_.complex.$dict.__pow__(_b_.complex(self, 0), other)
289
}
290
}else if(isinstance(other, _b_.complex)){
291
var preal = Math.pow(self, other.real),
292
ln = Math.log(self)
293
return _b_.complex(preal*Math.cos(ln), preal*Math.sin(ln))
Sep 5, 2014
294
}
295
if(hasattr(other,'__rpow__')) return getattr(other,'__rpow__')(self)
296
$err("**",other)
297
}
298
299
$IntDict.__repr__ = function(self){
300
if(self===int) return "<class 'int'>"
301
return self.toString()
302
}
303
304
// bitwise right shift
305
$IntDict.__rshift__ = function(self,other){
306
if(isinstance(other, int)){
307
return int($B.LongInt.$dict.__rshift__($B.LongInt(self), $B.LongInt(other)))
308
}
309
var rrshift = getattr(other, '__rrshift__', null)
310
if(rrshift!==null){return rrshift(self)}
311
$err('>>', other)
312
}
Sep 5, 2014
313
314
$IntDict.__setattr__ = function(self,attr,value){
315
if(typeof self=="number"){
316
if($IntDict[attr]===undefined){
317
throw _b_.AttributeError("'int' object has no attribute '"+attr+"'")
318
}else{
319
throw _b_.AttributeError("'int' object attribute '"+attr+"' is read-only")
320
}
Sep 5, 2014
321
}
322
// subclasses of int can have attributes set
323
self[attr] = value
Sep 5, 2014
325
}
326
327
$IntDict.__str__ = $IntDict.__repr__
328
329
$IntDict.__truediv__ = function(self,other){
330
if(isinstance(other,int)){
331
if(other==0) throw ZeroDivisionError('division by zero')
332
if(other.__class__==$B.LongInt.$dict){return new Number(self/parseInt(other.value))}
333
return new Number(self/other)
Sep 5, 2014
334
}
335
if(isinstance(other,_b_.float)){
336
if(!other.valueOf()) throw ZeroDivisionError('division by zero')
337
return new Number(self/other)
Sep 5, 2014
338
}
339
if(isinstance(other,_b_.complex)){
340
var cmod = other.real*other.real+other.imag*other.imag
341
if(cmod==0) throw ZeroDivisionError('division by zero')
342
return _b_.complex(self*other.real/cmod,-self*other.imag/cmod)
343
}
344
if(hasattr(other,'__rtruediv__')) return getattr(other,'__rtruediv__')(self)
345
$err("/",other)
346
}
347
348
//$IntDict.__xor__ = function(self,other){return self ^ other} // bitwise XOR
349
350
$IntDict.bit_length = function(self){
351
s = bin(self)
352
s = getattr(s,'lstrip')('-0b') // remove leading zeros and minus sign
353
return s.length // len('100101') --> 6
354
}
355
356
// descriptors
357
$IntDict.numerator = function(self){return self}
358
$IntDict.denominator = function(self){return int(1)}
359
$IntDict.imag = function(self){return int(0)}
360
$IntDict.real = function(self){return self}
361
363
$B.max_int32= (1<<30) * 2 - 1
364
$B.min_int32= - $B.max_int32
365
366
// code for operands & | ^
Sep 5, 2014
367
var $op_func = function(self,other){
Jun 7, 2015
368
if(isinstance(other,int)) {
369
if(other.__class__===$B.LongInt.$dict){
370
return $B.LongInt.$dict.__sub__($B.LongInt(self), $B.LongInt(other))
371
}
372
if (self > $B.max_int32 || self < $B.min_int32 ||
373
other > $B.max_int32 || other < $B.min_int32) {
374
return $B.LongInt.$dict.__sub__($B.LongInt(self), $B.LongInt(other))
375
}
376
return self-other
Jun 7, 2015
377
}
Sep 5, 2014
378
if(isinstance(other,_b_.bool)) return self-other
379
if(hasattr(other,'__rsub__')) return getattr(other,'__rsub__')(self)
380
$err("-",other)
381
}
382
383
$op_func += '' // source code
384
var $ops = {'&':'and','|':'or','^':'xor'}
Sep 5, 2014
385
for(var $op in $ops){
386
var opf = $op_func.replace(/-/gm,$op)
387
opf = opf.replace(new RegExp('sub','gm'),$ops[$op])
388
eval('$IntDict.__'+$ops[$op]+'__ = '+opf)
389
}
390
391
// code for + and -
392
var $op_func = function(self,other){
393
if(isinstance(other,int)){
394
if(typeof other=='number'){
395
var res = self.valueOf()-other.valueOf()
396
if(res>=$B.min_int && res<=$B.max_int){return res}
397
else{return $B.LongInt.$dict.__sub__($B.LongInt(self),
398
$B.LongInt(other))}
399
}else if(typeof other=="boolean"){
400
return other ? self-1 : self
401
}else{
402
return $B.LongInt.$dict.__sub__($B.LongInt(self),
403
$B.LongInt(other))
404
}
Sep 5, 2014
405
}
406
if(isinstance(other,_b_.float)){
407
return new Number(self-other)
Sep 5, 2014
408
}
409
if(isinstance(other,_b_.complex)){
410
return _b_.complex(self-other.real,-other.imag)
411
}
412
if(isinstance(other,_b_.bool)){
413
var bool_value=0;
414
if(other.valueOf()) bool_value=1;
Sep 5, 2014
416
}
417
if(isinstance(other,_b_.complex)){
418
return _b_.complex(self.valueOf() - other.real, other.imag)
419
}
420
if(hasattr(other,'__rsub__')) return getattr(other,'__rsub__')(self)
421
throw $err('-',other)
422
}
423
$op_func += '' // source code
424
var $ops = {'+':'add','-':'sub'}
425
for(var $op in $ops){
426
var opf = $op_func.replace(/-/gm,$op)
427
opf = opf.replace(new RegExp('sub','gm'),$ops[$op])
428
eval('$IntDict.__'+$ops[$op]+'__ = '+opf)
429
}
430
431
// comparison methods
432
var $comp_func = function(self,other){
433
if (other.__class__ === $B.LongInt.$dict) return $B.LongInt.$dict.__gt__($B.LongInt(self), other)
Sep 5, 2014
434
if(isinstance(other,int)) return self.valueOf() > other.valueOf()
435
if(isinstance(other,_b_.float)) return self.valueOf() > other.valueOf()
Sep 5, 2014
436
if(isinstance(other,_b_.bool)) {
437
return self.valueOf() > _b_.bool.$dict.__hash__(other)
438
}
439
if (hasattr(other, '__int__') || hasattr(other, '__index__')) {
440
return $IntDict.__gt__(self, $B.$GetInt(other))
441
}
442
443
// See if other has the opposite operator, eg <= for >
444
var inv_op = getattr(other, '__le__', null)
445
if(inv_op !== null){return inv_op(self)}
446
Sep 5, 2014
447
throw _b_.TypeError(
448
"unorderable types: int() > "+$B.get_class(other).__name__+"()")
Sep 5, 2014
449
}
450
$comp_func += '' // source codevar $comps = {'>':'gt','>=':'ge','<':'lt','<=':'le'}
Sep 5, 2014
452
for(var $op in $B.$comps){
453
eval("$IntDict.__"+$B.$comps[$op]+'__ = '+
454
$comp_func.replace(/>/gm,$op).
455
replace(/__gt__/gm,'__'+$B.$comps[$op]+'__').
456
replace(/__le__/, '__'+$B.$inv_comps[$op]+'__'))
Sep 5, 2014
457
}
458
459
// add "reflected" methods
460
$B.make_rmethods($IntDict)
461
462
var $valid_digits=function(base) {
463
var digits=''
464
if (base === 0) return '0'
465
if (base < 10) {
466
for (var i=0; i < base; i++) digits+=String.fromCharCode(i+48)
467
return digits
468
}
469
470
var digits='0123456789'
471
// A = 65 (10 + 55)
472
for (var i=10; i < base; i++) digits+=String.fromCharCode(i+55)
473
return digits
474
}
475
Dec 26, 2014
476
var int = function(value, base){
477
// int() with no argument returns 0
478
if(value===undefined){return 0}
479
480
// int() of an integer returns the integer if base is undefined
481
if(typeof value=='number' &&
482
(base===undefined || base==10)){return parseInt(value)}
483
Dec 28, 2014
484
if(base!==undefined){
485
if(!isinstance(value,[_b_.str,_b_.bytes,_b_.bytearray])){
486
throw TypeError("int() can't convert non-string with explicit base")
487
}
488
}
489
490
if(isinstance(value,_b_.complex)){
491
throw TypeError("can't convert complex to int")
492
}
493
494
var $ns=$B.args('int',2,{x:null,base:null},['x','base'],arguments,
495
{'base':10},'null','null')
496
var value = $ns['x']
497
var base = $ns['base']
498
499
if(isinstance(value, _b_.float) && base===10){
500
if(value<$B.min_int || value>$B.max_int){
501
return $B.LongInt.$dict.$from_float(value)
502
}
503
else{return value>0 ? Math.floor(value) : Math.ceil(value)}
Sep 5, 2014
505
Dec 26, 2014
506
if (!(base >=2 && base <= 36)) {
507
// throw error (base must be 0, or 2-36)
508
if (base != 0) throw _b_.ValueError("invalid base")
509
}
510
511
if (typeof value == 'number'){
512
513
if(base==10){
514
if(value < $B.min_int || value > $B.max_int) return $B.LongInt(value)
515
return value
516
}else if(value.toString().search('e')>-1){
Dec 26, 2014
517
// can't convert to another base if value is too big
518
throw _b_.OverflowError("can't convert to base "+base)
519
}else{
520
var res=parseInt(value, base)
521
if(res < $B.min_int || res > $B.max_int) return $B.LongInt(value,base)
522
return res
Dec 26, 2014
523
}
524
}
Sep 5, 2014
525
526
if(value===true) return Number(1)
527
if(value===false) return Number(0)
528
if(value.__class__===$B.LongInt.$dict){
529
var z = parseInt(value.value)
530
if(z>$B.min_int && z<$B.max_int){return z}
531
else{return value}
532
}
Sep 5, 2014
533
Jan 22, 2015
534
base=$B.$GetInt(base)
Sep 5, 2014
535
536
if(isinstance(value, _b_.str)) value=value.valueOf()
537
if(typeof value=="string") {
538
var _value=value.trim() // remove leading/trailing whitespace
539
if (_value.length == 2 && base==0 && (_value=='0b' || _value=='0o' || _value=='0x')) {
Sep 5, 2014
540
throw _b_.ValueError('invalid value')
541
}
542
if (_value.length >2) {
543
var _pre=_value.substr(0,2).toUpperCase()
Sep 5, 2014
544
if (base == 0) {
545
if (_pre == '0B') base=2
546
if (_pre == '0O') base=8
547
if (_pre == '0X') base=16
548
}
549
if (_pre=='0B' || _pre=='0O' || _pre=='0X') {
Sep 5, 2014
551
}
552
}
553
var _digits=$valid_digits(base)
554
var _re=new RegExp('^[+-]?['+_digits+']+$', 'i')
Sep 5, 2014
556
throw _b_.ValueError(
557
"invalid literal for int() with base "+base +": '"+_b_.str(value)+"'")
Sep 5, 2014
558
}
559
if(base <= 10 && !isFinite(value)) {
560
throw _b_.ValueError(
561
"invalid literal for int() with base "+base +": '"+_b_.str(value)+"'")
Sep 5, 2014
562
}
563
var res=parseInt(_value, base)
564
if(res < $B.min_int || res > $B.max_int) return $B.LongInt(_value, base)
565
return res
Sep 5, 2014
566
}
567
568
if(isinstance(value,[_b_.bytes,_b_.bytearray])){
569
var _digits = $valid_digits(base)
570
for(var i=0;i<value.source.length;i++){
571
if(_digits.indexOf(String.fromCharCode(value.source[i]))==-1){
572
throw _b_.ValueError("invalid literal for int() with base "+
573
base +": "+_b_.repr(value))
574
}
575
}
576
return Number(parseInt(getattr(value,'decode')('latin-1'), base))
577
}
Sep 5, 2014
578
579
if(hasattr(value, '__int__')) return getattr(value,'__int__')()
580
if(hasattr(value, '__index__')) return getattr(value,'__index__')()
581
if(hasattr(value, '__trunc__')) {
582
var res = getattr(value,'__trunc__')(),
583
int_func = _b_.getattr(res, '__int__', null)
584
if(int_func===null){
585
throw TypeError('__trunc__ returned non-Integral (type '+
586
$B.get_class(res).__name__+')')
587
}
588
var res=int_func()
589
if(isinstance(res, int)){return res}
590
throw TypeError('__trunc__ returned non-Integral (type '+
591
$B.get_class(res).__name__+')')
592
}
Sep 5, 2014
593
594
throw _b_.ValueError(
595
"invalid literal for int() with base "+base +": '"+_b_.str(value)+"'")
Sep 5, 2014
596
}
597
int.$dict = $IntDict
598
int.__class__ = $B.$factory
599
$IntDict.$factory = int
600
601
_b_.int = int
602
Sep 5, 2014
604
})(__BRYTHON__)