Skip to content
Permalink
Newer
Older
100644 577 lines (496 sloc) 18 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'},
18
$native:true
19
}
20
21
$IntDict.from_bytes = function() {
22
var $=$B.args("from_bytes", 3,
23
{bytes:null, byteorder:null, signed:null}, ['bytes', 'byteorder', 'signed'],
24
arguments, {signed:False}, null, null)
Sep 5, 2014
25
26
var x = $.bytes,
27
byteorder = $.byteorder,
28
signed = $.signed
29
var _bytes, _len
30
if (isinstance(x, [_b_.list, _b_.tuple])) {
31
_bytes=x
32
_len=len(x)
Jan 14, 2015
33
} else if (isinstance(x, [_b_.bytes, _b_.bytearray])) {
34
_bytes=x.source
35
_len=x.source.length
Jan 14, 2015
36
} else {
37
_b_.TypeError("Error! " + _b_.type(x) + " is not supported in int.from_bytes. fix me!")
Sep 5, 2014
38
}
39
40
switch(byteorder) {
41
case 'big':
42
var num = _bytes[_len - 1];
43
var _mult=256
44
for (var i = (_len - 2); i >= 0; i--) {
45
// For operations, use the functions that can take or return
46
// big integers
47
num = $B.add($B.mul(_mult, _bytes[i]), num)
48
_mult = $B.mul(_mult,256)
Jan 14, 2015
50
if (!signed) return num
51
if (_bytes[0] < 128) return num
52
return $B.sub(num, _mult)
53
case 'little':
54
var num = _bytes[0]
55
if (num >= 128) num = num - 256
56
var _mult=256
57
for (var i = 1; i < _len; i++) {
58
num = $B.add($B.mul(_mult, _bytes[i]), num)
59
_mult = $B.mul(_mult,256)
Jan 14, 2015
61
if (!signed) return num
62
if (_bytes[_len - 1] < 128) return num
63
return $B.sub(num, _mult)
Sep 5, 2014
64
}
65
66
throw _b_.ValueError("byteorder must be either 'little' or 'big'");
67
}
68
69
$IntDict.to_bytes = function(length, byteorder, star) {
70
//var len = x.length
71
throw _b_.NotImplementedError("int.to_bytes is not implemented yet")
72
}
73
74
75
//$IntDict.__and__ = function(self,other){return self & other} // bitwise AND
76
77
$IntDict.__abs__ = function(self){return abs(self)}
78
Sep 5, 2014
79
$IntDict.__bool__ = function(self){return new Boolean(self.valueOf())}
80
81
$IntDict.__ceil__ = function(self){return Math.ceil(self)}
82
Sep 5, 2014
83
//is this a duplicate?
84
$IntDict.__class__ = $B.$type
85
86
$IntDict.__divmod__ = function(self, other){return divmod(self, other)}
87
Sep 5, 2014
88
$IntDict.__eq__ = function(self,other){
89
// compare object "self" to class "int"
90
if(other===undefined) return self===int
91
if(isinstance(other,int)) return self.valueOf()==other.valueOf()
92
if(isinstance(other,_b_.float)) return self.valueOf()==other.valueOf()
Sep 5, 2014
93
if(isinstance(other,_b_.complex)){
94
if (other.imag != 0) return False
95
return self.valueOf() == other.real
96
}
97
98
if (hasattr(other, '__eq__')) return getattr(other, '__eq__')(self)
99
Sep 5, 2014
100
return self.valueOf()===other
101
}
102
103
function preformat(self, fmt){
104
if(fmt.empty){return _b_.str(self)}
105
if(fmt.type && 'bcdoxXn'.indexOf(fmt.type)==-1){
106
throw _b_.ValueError("Unknown format code '"+fmt.type+
107
"' for object of type 'int'")
108
}
109
110
switch(fmt.type){
111
case undefined:
112
case 'd':
113
return self.toString()
114
case 'b':
115
return (fmt.alternate ? '0b' : '') + self.toString(2)
116
case 'c':
117
return _b_.chr(self)
118
case 'o':
119
return (fmt.alternate ? '0o' : '') + self.toString(8)
121
return (fmt.alternate ? '0x' : '') + self.toString(16)
123
return (fmt.alternate ? '0X' : '') + self.toString(16).toUpperCase()
124
case 'n':
125
return self // fix me
126
}
127
128
return res
129
}
130
131
Sep 5, 2014
132
$IntDict.__format__ = function(self,format_spec){
133
var fmt = new $B.parse_format_spec(format_spec)
134
if(fmt.type && 'eEfFgG%'.indexOf(fmt.type)!=-1){
135
// Call __format__ on float(self)
136
return _b_.float.$dict.__format__(self, format_spec)
137
}
138
fmt.align = fmt.align || '>'
139
var res = preformat(self, fmt)
140
if(fmt.comma){
141
var len = res.length, nb = Math.ceil(res.length/3), chunks = []
142
for(var i=0;i<nb;i++){
143
chunks.push(res.substring(len-3*i-3, len-3*i))
144
}
145
chunks.reverse()
146
res = chunks.join(',')
147
}
148
return $B.format_width(res, fmt)
Sep 5, 2014
149
}
150
151
//$IntDict.__float__ = function(self){return float(self)}
152
Sep 5, 2014
153
$IntDict.__floordiv__ = function(self,other){
154
if(isinstance(other,int)){
155
if(other==0) throw ZeroDivisionError('division by zero')
156
return Math.floor(self/other)
157
}
158
if(isinstance(other,_b_.float)){
159
if(!other.valueOf()) throw ZeroDivisionError('division by zero')
160
return Math.floor(self/other)
Sep 5, 2014
161
}
162
if(hasattr(other,'__rfloordiv__')){
163
return getattr(other,'__rfloordiv__')(self)
164
}
165
$err("//",other)
166
}
167
168
$IntDict.__getitem__ = function(){
169
throw _b_.TypeError("'int' object is not subscriptable")
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__ = [$IntDict,$ObjectDict]
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.__or__ = function(self,other){return self | other} // bitwise OR
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(res>$B.min_int && res<$B.max_int){return res}
279
else{return int($B.LongInt.$dict.__pow__($B.LongInt(self),
280
$B.LongInt(other)))}
Sep 5, 2014
281
}
282
if(isinstance(other, _b_.float)) {
283
return new Number(Math.pow(self.valueOf(), other.valueOf()))
Sep 5, 2014
284
}
285
if(hasattr(other,'__rpow__')) return getattr(other,'__rpow__')(self)
286
$err("**",other)
287
}
288
289
$IntDict.__repr__ = function(self){
290
if(self===int) return "<class 'int'>"
291
return self.toString()
292
}
293
294
// bitwise right shift
295
$IntDict.__rshift__ = function(self,other){
296
if(isinstance(other, int)){
297
return int($B.LongInt.$dict.__rshift__($B.LongInt(self), $B.LongInt(other)))
298
}
299
var rrshift = getattr(other, '__rrshift__', null)
300
if(rrshift!==null){return rrshift(self)}
301
$err('>>', other)
302
}
Sep 5, 2014
303
304
$IntDict.__setattr__ = function(self,attr,value){
305
if(self.__class__===$IntDict){
306
throw _b_.AttributeError("'int' object has no attribute "+attr+"'")
307
}
308
// subclasses of int can have attributes set
309
self[attr] = value
Sep 5, 2014
311
}
312
313
$IntDict.__str__ = $IntDict.__repr__
314
315
$IntDict.__truediv__ = function(self,other){
316
if(isinstance(other,int)){
317
if(other==0) throw ZeroDivisionError('division by zero')
318
if(other.__class__==$B.LongInt.$dict){return new Number(self/parseInt(other.value))}
319
return new Number(self/other)
Sep 5, 2014
320
}
321
if(isinstance(other,_b_.float)){
322
if(!other.valueOf()) throw ZeroDivisionError('division by zero')
323
return new Number(self/other)
Sep 5, 2014
324
}
325
if(isinstance(other,_b_.complex)){
326
var cmod = other.real*other.real+other.imag*other.imag
327
if(cmod==0) throw ZeroDivisionError('division by zero')
328
return _b_.complex(self*other.real/cmod,-self*other.imag/cmod)
329
}
330
if(hasattr(other,'__rtruediv__')) return getattr(other,'__rtruediv__')(self)
331
$err("/",other)
332
}
333
334
//$IntDict.__xor__ = function(self,other){return self ^ other} // bitwise XOR
335
336
$IntDict.bit_length = function(self){
337
s = bin(self)
338
s = getattr(s,'lstrip')('-0b') // remove leading zeros and minus sign
339
return s.length // len('100101') --> 6
340
}
341
342
$IntDict.numerator = function(self){return self}
343
$IntDict.denominator = function(self){return int(1)}
344
345
$B.max_int32= (1<<30) * 2 - 1
346
$B.min_int32= - $B.max_int32
347
348
// code for operands & | ^
Sep 5, 2014
349
var $op_func = function(self,other){
Jun 7, 2015
350
if(isinstance(other,int)) {
351
if(other.__class__===$B.LongInt.$dict){
352
return $B.LongInt.$dict.__sub__($B.LongInt(self), $B.LongInt(other))
353
}
354
if (self > $B.max_int32 || self < $B.min_int32 ||
355
other > $B.max_int32 || other < $B.min_int32) {
356
return $B.LongInt.$dict.__sub__($B.LongInt(self), $B.LongInt(other))
357
}
358
return self-other
Jun 7, 2015
359
}
Sep 5, 2014
360
if(isinstance(other,_b_.bool)) return self-other
361
if(hasattr(other,'__rsub__')) return getattr(other,'__rsub__')(self)
362
$err("-",other)
363
}
364
365
$op_func += '' // source code
366
var $ops = {'&':'and','|':'or','^':'xor'}
Sep 5, 2014
367
for(var $op in $ops){
368
var opf = $op_func.replace(/-/gm,$op)
369
opf = opf.replace(new RegExp('sub','gm'),$ops[$op])
370
eval('$IntDict.__'+$ops[$op]+'__ = '+opf)
371
}
372
373
// code for + and -
374
var $op_func = function(self,other){
Sep 5, 2014
376
if(isinstance(other,int)){
377
if(typeof other=='number'){
378
var res = self.valueOf()-other.valueOf()
379
if(res>=$B.min_int && res<=$B.max_int){return res}
380
else{return $B.LongInt.$dict.__sub__($B.LongInt(self),
381
$B.LongInt(other))}
382
}else{
383
return $B.LongInt.$dict.__sub__($B.LongInt(self),
384
$B.LongInt(other))
385
}
Sep 5, 2014
386
}
387
if(isinstance(other,_b_.float)){
388
return new Number(self-other)
Sep 5, 2014
389
}
390
if(isinstance(other,_b_.complex)){
391
return _b_.complex(self-other.real,-other.imag)
392
}
393
if(isinstance(other,_b_.bool)){
394
var bool_value=0;
395
if(other.valueOf()) bool_value=1;
Sep 5, 2014
397
}
398
if(isinstance(other,_b_.complex)){
399
return _b_.complex(self.valueOf() - other.real, other.imag)
400
}
401
if(hasattr(other,'__rsub__')) return getattr(other,'__rsub__')(self)
402
throw $err('-',other)
403
}
404
$op_func += '' // source code
405
var $ops = {'+':'add','-':'sub'}
406
for(var $op in $ops){
407
var opf = $op_func.replace(/-/gm,$op)
408
opf = opf.replace(new RegExp('sub','gm'),$ops[$op])
409
eval('$IntDict.__'+$ops[$op]+'__ = '+opf)
410
}
411
412
// comparison methods
413
var $comp_func = function(self,other){
414
if (other.__class__ === $B.LongInt.$dict) return $B.LongInt.$dict.__gt__($B.LongInt(self), other)
Sep 5, 2014
415
if(isinstance(other,int)) return self.valueOf() > other.valueOf()
416
if(isinstance(other,_b_.float)) return self.valueOf() > other.valueOf()
Sep 5, 2014
417
if(isinstance(other,_b_.bool)) {
418
return self.valueOf() > _b_.bool.$dict.__hash__(other)
419
}
420
if (hasattr(other, '__int__') || hasattr(other, '__index__')) {
421
return $IntDict.__gt__(self, $B.$GetInt(other))
422
}
Sep 5, 2014
423
throw _b_.TypeError(
424
"unorderable types: int() > "+$B.get_class(other).__name__+"()")
Sep 5, 2014
425
}
426
$comp_func += '' // source codevar $comps = {'>':'gt','>=':'ge','<':'lt','<=':'le'}
427
for(var $op in $B.$comps){
428
eval("$IntDict.__"+$B.$comps[$op]+'__ = '+
429
$comp_func.replace(/>/gm,$op).replace(/__gt__/gm,'__'+$B.$comps[$op]+'__'))
Sep 5, 2014
430
}
431
432
// add "reflected" methods
433
$B.make_rmethods($IntDict)
434
435
var $valid_digits=function(base) {
436
var digits=''
437
if (base === 0) return '0'
438
if (base < 10) {
439
for (var i=0; i < base; i++) digits+=String.fromCharCode(i+48)
440
return digits
441
}
442
443
var digits='0123456789'
444
// A = 65 (10 + 55)
445
for (var i=10; i < base; i++) digits+=String.fromCharCode(i+55)
446
return digits
447
}
448
Dec 26, 2014
449
var int = function(value, base){
450
// int() with no argument returns 0
451
if(value===undefined){return 0}
452
453
// int() of an integer returns the integer if base is undefined
454
if(typeof value=='number' &&
455
(base===undefined || base==10)){return parseInt(value)}
456
Dec 28, 2014
457
if(base!==undefined){
458
if(!isinstance(value,[_b_.str,_b_.bytes,_b_.bytearray])){
459
throw TypeError("int() can't convert non-string with explicit base")
460
}
461
}
462
463
if(isinstance(value,_b_.complex)){
464
throw TypeError("can't convert complex to int")
465
}
466
467
var $ns=$B.args('int',2,{x:null,base:null},['x','base'],arguments,
468
{'base':10},'null','null')
469
var value = $ns['x']
470
var base = $ns['base']
471
472
if(isinstance(value, _b_.float) && base===10){
473
if(value<$B.min_int || value>$B.max_int){
474
return $B.LongInt.$dict.$from_float(value)
475
}
476
else{return value>0 ? Math.floor(value) : Math.ceil(value)}
Sep 5, 2014
478
Dec 26, 2014
479
if (!(base >=2 && base <= 36)) {
480
// throw error (base must be 0, or 2-36)
481
if (base != 0) throw _b_.ValueError("invalid base")
482
}
483
484
if (typeof value == 'number'){
485
486
if(base==10){
487
if(value < $B.min_int || value > $B.max_int) return $B.LongInt(value)
488
return value
489
}else if(value.toString().search('e')>-1){
Dec 26, 2014
490
// can't convert to another base if value is too big
491
throw _b_.OverflowError("can't convert to base "+base)
492
}else{
493
var res=parseInt(value, base)
494
if(res < $B.min_int || res > $B.max_int) return $B.LongInt(value,base)
495
return res
Dec 26, 2014
496
}
497
}
Sep 5, 2014
498
499
if(value===true) return Number(1)
500
if(value===false) return Number(0)
501
if(value.__class__===$B.LongInt.$dict){
502
var z = parseInt(value.value)
503
if(z>$B.min_int && z<$B.max_int){return z}
504
else{return value}
505
}
Sep 5, 2014
506
Jan 22, 2015
507
base=$B.$GetInt(base)
Sep 5, 2014
508
509
if(isinstance(value, _b_.str)) value=value.valueOf()
510
if(typeof value=="string") {
511
var _value=value.trim() // remove leading/trailing whitespace
512
if (_value.length == 2 && base==0 && (_value=='0b' || _value=='0o' || _value=='0x')) {
Sep 5, 2014
513
throw _b_.ValueError('invalid value')
514
}
515
if (_value.length >2) {
516
var _pre=_value.substr(0,2).toUpperCase()
Sep 5, 2014
517
if (base == 0) {
518
if (_pre == '0B') base=2
519
if (_pre == '0O') base=8
520
if (_pre == '0X') base=16
521
}
522
if (_pre=='0B' || _pre=='0O' || _pre=='0X') {
Sep 5, 2014
524
}
525
}
526
var _digits=$valid_digits(base)
527
var _re=new RegExp('^[+-]?['+_digits+']+$', 'i')
Sep 5, 2014
529
throw _b_.ValueError(
530
"invalid literal for int() with base "+base +": '"+_b_.str(value)+"'")
Sep 5, 2014
531
}
532
if(base <= 10 && !isFinite(value)) {
533
throw _b_.ValueError(
534
"invalid literal for int() with base "+base +": '"+_b_.str(value)+"'")
Sep 5, 2014
535
}
536
var res=parseInt(_value, base)
537
if(res < $B.min_int || res > $B.max_int) return $B.LongInt(_value, base)
538
return res
Sep 5, 2014
539
}
540
541
if(isinstance(value,[_b_.bytes,_b_.bytearray])){
542
var _digits = $valid_digits(base)
543
for(var i=0;i<value.source.length;i++){
544
if(_digits.indexOf(String.fromCharCode(value.source[i]))==-1){
545
throw _b_.ValueError("invalid literal for int() with base "+
546
base +": "+_b_.repr(value))
547
}
548
}
549
return Number(parseInt(getattr(value,'decode')('latin-1'), base))
550
}
Sep 5, 2014
551
552
if(hasattr(value, '__int__')) return getattr(value,'__int__')()
553
if(hasattr(value, '__index__')) return getattr(value,'__index__')()
554
if(hasattr(value, '__trunc__')) {
555
var res = getattr(value,'__trunc__')(),
556
int_func = _b_.getattr(res, '__int__', null)
557
if(int_func===null){
558
throw TypeError('__trunc__ returned non-Integral (type '+
559
$B.get_class(res).__name__+')')
560
}
561
var res=int_func()
562
if(isinstance(res, int)){return res}
563
throw TypeError('__trunc__ returned non-Integral (type '+
564
$B.get_class(res).__name__+')')
565
}
Sep 5, 2014
566
567
throw _b_.ValueError(
568
"invalid literal for int() with base "+base +": '"+_b_.str(value)+"'")
Sep 5, 2014
569
}
570
int.$dict = $IntDict
571
int.__class__ = $B.$factory
572
$IntDict.$factory = int
573
574
_b_.int = int
575
Sep 5, 2014
577
})(__BRYTHON__)