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