Skip to content
Permalink
Newer
Older
100644 529 lines (451 sloc) 16.6 KB
Sep 5, 2014
1
;(function($B){
2
3
eval($B.InjectBuiltins())
4
Sep 5, 2014
5
var $ObjectDict = _b_.object.$dict
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}
146
}
147
148
$IntDict.__int__ = function(self){return self}
149
150
$IntDict.__invert__ = function(self){return ~self}
151
152
// bitwise left shift
153
$IntDict.__lshift__ = function(self,other){
154
if(isinstance(other, int)){
155
return int($B.LongInt.$dict.__lshift__($B.LongInt(self), $B.LongInt(other)))
156
}
157
var rlshift = getattr(other, '__rlshift__', null)
158
if(rlshift!==null){return rlshift(self)}
159
$err('<<', other)
160
}
161
Sep 5, 2014
162
$IntDict.__mod__ = function(self,other) {
163
// can't use Javascript % because it works differently for negative numbers
164
if(isinstance(other,_b_.tuple) && other.length==1) other=other[0]
165
if(isinstance(other,int)) return (self%other+other)%other
166
if(isinstance(other,_b_.float)) return ((self%other)+other)%other
167
if(isinstance(other,bool)){
168
var bool_value=0;
169
if (other.valueOf()) bool_value=1;
170
return (self%bool_value+bool_value)%bool_value
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
268
}
269
270
$IntDict.__str__ = $IntDict.__repr__
271
272
$IntDict.__truediv__ = function(self,other){
273
if(isinstance(other,int)){
274
if(other==0) throw ZeroDivisionError('division by zero')
275
if(other.__class__==$B.LongInt.$dict){return new Number(self/parseInt(other.value))}
276
return new Number(self/other)
Sep 5, 2014
277
}
278
if(isinstance(other,_b_.float)){
279
if(!other.valueOf()) throw ZeroDivisionError('division by zero')
280
return new Number(self/other)
Sep 5, 2014
281
}
282
if(isinstance(other,_b_.complex)){
283
var cmod = other.real*other.real+other.imag*other.imag
284
if(cmod==0) throw ZeroDivisionError('division by zero')
285
return _b_.complex(self*other.real/cmod,-self*other.imag/cmod)
286
}
287
if(hasattr(other,'__rtruediv__')) return getattr(other,'__rtruediv__')(self)
288
$err("/",other)
289
}
290
291
//$IntDict.__xor__ = function(self,other){return self ^ other} // bitwise XOR
292
293
$IntDict.bit_length = function(self){
294
s = bin(self)
295
s = getattr(s,'lstrip')('-0b') // remove leading zeros and minus sign
296
return s.length // len('100101') --> 6
297
}
298
299
$IntDict.numerator = function(self){return self}
300
$IntDict.denominator = function(self){return int(1)}
301
302
$B.max_int32= (1<<30) * 2 - 1
303
$B.min_int32= - $B.max_int32
304
305
// code for operands & | ^
Sep 5, 2014
306
var $op_func = function(self,other){
Jun 7, 2015
307
if(isinstance(other,int)) {
308
if (self > $B.max_int32 || self < $B.min_int32 || other > $B.max_int32 || other < $B.min_int32) {
Jun 7, 2015
309
return $B.LongInt.$dict.__sub__($B.LongInt(self), $B.LongInt(other))
310
}
311
return self-other
312
}
Sep 5, 2014
313
if(isinstance(other,_b_.bool)) return self-other
314
if(hasattr(other,'__rsub__')) return getattr(other,'__rsub__')(self)
315
$err("-",other)
316
}
317
318
$op_func += '' // source code
319
var $ops = {'&':'and','|':'or','^':'xor'}
Sep 5, 2014
320
for(var $op in $ops){
321
var opf = $op_func.replace(/-/gm,$op)
322
opf = opf.replace(new RegExp('sub','gm'),$ops[$op])
323
eval('$IntDict.__'+$ops[$op]+'__ = '+opf)
324
}
325
326
// code for + and -
327
var $op_func = function(self,other){
Sep 5, 2014
329
if(isinstance(other,int)){
330
if(typeof other=='number'){
331
var res = self.valueOf()-other.valueOf()
332
if(res>=$B.min_int && res<=$B.max_int){return res}
333
else{return $B.LongInt.$dict.__sub__($B.LongInt(self),
334
$B.LongInt(other))}
335
}else{
336
return $B.LongInt.$dict.__sub__($B.LongInt(self),
337
$B.LongInt(other))
338
}
Sep 5, 2014
339
}
340
if(isinstance(other,_b_.float)){
341
return new Number(self-other)
Sep 5, 2014
342
}
343
if(isinstance(other,_b_.complex)){
344
return _b_.complex(self-other.real,-other.imag)
345
}
346
if(isinstance(other,_b_.bool)){
347
var bool_value=0;
348
if(other.valueOf()) bool_value=1;
Sep 5, 2014
350
}
351
if(isinstance(other,_b_.complex)){
352
return _b_.complex(self.valueOf() - other.real, other.imag)
353
}
354
if(hasattr(other,'__rsub__')) return getattr(other,'__rsub__')(self)
355
throw $err('-',other)
356
}
357
$op_func += '' // source code
358
var $ops = {'+':'add','-':'sub'}
359
for(var $op in $ops){
360
var opf = $op_func.replace(/-/gm,$op)
361
opf = opf.replace(new RegExp('sub','gm'),$ops[$op])
362
eval('$IntDict.__'+$ops[$op]+'__ = '+opf)
363
}
364
365
// comparison methods
366
var $comp_func = function(self,other){
367
if (other.__class__ === $B.LongInt.$dict) return $B.LongInt.$dict.__gt__($B.LongInt(self), other)
Sep 5, 2014
368
if(isinstance(other,int)) return self.valueOf() > other.valueOf()
369
if(isinstance(other,_b_.float)) return self.valueOf() > other.valueOf()
Sep 5, 2014
370
if(isinstance(other,_b_.bool)) {
371
return self.valueOf() > _b_.bool.$dict.__hash__(other)
372
}
373
if (hasattr(other, '__int__') || hasattr(other, '__index__')) {
374
return $IntDict.__gt__(self, $B.$GetInt(other))
375
}
Sep 5, 2014
376
throw _b_.TypeError(
377
"unorderable types: int() > "+$B.get_class(other).__name__+"()")
Sep 5, 2014
378
}
379
$comp_func += '' // source codevar $comps = {'>':'gt','>=':'ge','<':'lt','<=':'le'}
380
for(var $op in $B.$comps){
381
eval("$IntDict.__"+$B.$comps[$op]+'__ = '+
382
$comp_func.replace(/>/gm,$op).replace(/__gt__/gm,'__'+$B.$comps[$op]+'__'))
Sep 5, 2014
383
}
384
385
// add "reflected" methods
386
$B.make_rmethods($IntDict)
387
388
var $valid_digits=function(base) {
389
var digits=''
390
if (base === 0) return '0'
391
if (base < 10) {
392
for (var i=0; i < base; i++) digits+=String.fromCharCode(i+48)
393
return digits
394
}
395
396
var digits='0123456789'
397
// A = 65 (10 + 55)
398
for (var i=10; i < base; i++) digits+=String.fromCharCode(i+55)
399
return digits
400
}
401
Dec 26, 2014
402
var int = function(value, base){
403
// int() with no argument returns 0
404
if(value===undefined){return 0}
405
406
// int() of an integer returns the integer if base is undefined
407
if(typeof value=='number' &&
408
(base===undefined || base==10)){return parseInt(value)}
409
Dec 28, 2014
410
if(base!==undefined){
411
if(!isinstance(value,[_b_.str,_b_.bytes,_b_.bytearray])){
412
throw TypeError("int() can't convert non-string with explicit base")
413
}
414
}
415
416
if(isinstance(value,_b_.complex)){
417
throw TypeError("can't convert complex to int")
418
}
419
420
var $ns=$B.$MakeArgs1('int',2,{x:null,base:null},['x','base'],arguments,
421
{'base':10},'null','null')
422
var value = $ns['x']
423
var base = $ns['base']
424
425
if(isinstance(value, _b_.float) && base===10){
426
var res = parseInt(value)
427
if(res<$B.min_int || res>$B.max_int){return $B.LongInt(res+'')}
428
else{return res}
429
}
Sep 5, 2014
430
Dec 26, 2014
431
if (!(base >=2 && base <= 36)) {
432
// throw error (base must be 0, or 2-36)
433
if (base != 0) throw _b_.ValueError("invalid base")
434
}
435
436
if (typeof value == 'number'){
437
438
if(base==10){
439
if(value < $B.min_int || value > $B.max_int) return $B.LongInt(value)
440
return value
441
}else if(value.toString().search('e')>-1){
Dec 26, 2014
442
// can't convert to another base if value is too big
443
throw _b_.OverflowError("can't convert to base "+base)
444
}else{
445
var res=parseInt(value, base)
446
if(res < $B.min_int || res > $B.max_int) return $B.LongInt(value,base)
447
return res
Dec 26, 2014
448
}
449
}
Sep 5, 2014
450
451
if(value===true) return Number(1)
452
if(value===false) return Number(0)
453
if(value.__class__===$B.LongInt.$dict){
454
var z = parseInt(value.value)
455
if(z>$B.min_int && z<$B.max_int){return z}
456
else{return value}
457
}
Sep 5, 2014
458
Jan 22, 2015
459
base=$B.$GetInt(base)
Sep 5, 2014
460
461
if(isinstance(value, _b_.str)) value=value.valueOf()
462
if(typeof value=="string") {
463
var _value=value.trim() // remove leading/trailing whitespace
464
if (_value.length == 2 && base==0 && (_value=='0b' || _value=='0o' || _value=='0x')) {
Sep 5, 2014
465
throw _b_.ValueError('invalid value')
466
}
467
if (_value.length >2) {
468
var _pre=_value.substr(0,2).toUpperCase()
Sep 5, 2014
469
if (base == 0) {
470
if (_pre == '0B') base=2
471
if (_pre == '0O') base=8
472
if (_pre == '0X') base=16
473
}
474
if (_pre=='0B' || _pre=='0O' || _pre=='0X') {
Sep 5, 2014
476
}
477
}
478
var _digits=$valid_digits(base)
479
var _re=new RegExp('^[+-]?['+_digits+']+$', 'i')
Sep 5, 2014
481
throw _b_.ValueError(
482
"invalid literal for int() with base "+base +": '"+_b_.str(value)+"'")
Sep 5, 2014
483
}
484
if(base <= 10 && !isFinite(value)) {
485
throw _b_.ValueError(
486
"invalid literal for int() with base "+base +": '"+_b_.str(value)+"'")
Sep 5, 2014
487
}
488
var res=parseInt(_value, base)
489
if(res < $B.min_int || res > $B.max_int) return $B.LongInt(_value, base)
490
return res
Sep 5, 2014
491
}
492
493
if(isinstance(value,[_b_.bytes,_b_.bytearray])){
494
var _digits = $valid_digits(base)
495
for(var i=0;i<value.source.length;i++){
496
if(_digits.indexOf(String.fromCharCode(value.source[i]))==-1){
497
throw _b_.ValueError("invalid literal for int() with base "+
498
base +": "+_b_.repr(value))
499
}
500
}
501
return Number(parseInt(getattr(value,'decode')('latin-1'), base))
502
}
Sep 5, 2014
503
504
if(hasattr(value, '__int__')) return getattr(value,'__int__')()
505
if(hasattr(value, '__index__')) return getattr(value,'__index__')()
506
if(hasattr(value, '__trunc__')) {
507
var res = getattr(value,'__trunc__')(),
508
int_func = _b_.getattr(res, '__int__', null)
509
if(int_func===null){
510
throw TypeError('__trunc__ returned non-Integral (type '+
511
$B.get_class(res).__name__+')')
512
}
513
var res=int_func()
514
if(isinstance(res, int)){return res}
515
throw TypeError('__trunc__ returned non-Integral (type '+
516
$B.get_class(res).__name__+')')
517
}
Sep 5, 2014
518
519
throw _b_.ValueError(
520
"invalid literal for int() with base "+base +": '"+_b_.str(value)+"'")
Sep 5, 2014
521
}
522
int.$dict = $IntDict
523
int.__class__ = $B.$factory
524
$IntDict.$factory = int
525
526
_b_.int = int
527
Sep 5, 2014
529
})(__BRYTHON__)