Skip to content
Permalink
Newer
Older
100644 585 lines (504 sloc) 18.2 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,
20
'denominator':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__ = [$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.__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(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(typeof self=="number"){
306
if($IntDict[attr]===undefined){
307
throw _b_.AttributeError("'int' object has no attribute '"+attr+"'")
308
}else{
309
throw _b_.AttributeError("'int' object attribute '"+attr+"' is read-only")
310
}
Sep 5, 2014
311
}
312
// subclasses of int can have attributes set
313
self[attr] = value
Sep 5, 2014
315
}
316
317
$IntDict.__str__ = $IntDict.__repr__
318
319
$IntDict.__truediv__ = function(self,other){
320
if(isinstance(other,int)){
321
if(other==0) throw ZeroDivisionError('division by zero')
322
if(other.__class__==$B.LongInt.$dict){return new Number(self/parseInt(other.value))}
323
return new Number(self/other)
Sep 5, 2014
324
}
325
if(isinstance(other,_b_.float)){
326
if(!other.valueOf()) throw ZeroDivisionError('division by zero')
327
return new Number(self/other)
Sep 5, 2014
328
}
329
if(isinstance(other,_b_.complex)){
330
var cmod = other.real*other.real+other.imag*other.imag
331
if(cmod==0) throw ZeroDivisionError('division by zero')
332
return _b_.complex(self*other.real/cmod,-self*other.imag/cmod)
333
}
334
if(hasattr(other,'__rtruediv__')) return getattr(other,'__rtruediv__')(self)
335
$err("/",other)
336
}
337
338
//$IntDict.__xor__ = function(self,other){return self ^ other} // bitwise XOR
339
340
$IntDict.bit_length = function(self){
341
s = bin(self)
342
s = getattr(s,'lstrip')('-0b') // remove leading zeros and minus sign
343
return s.length // len('100101') --> 6
344
}
345
346
// descriptors
347
$IntDict.numerator = function(self){return self}
348
$IntDict.denominator = function(self){return int(1)}
349
$IntDict.imag = function(self){return int(0)}
350
$IntDict.real = function(self){return self}
351
353
$B.max_int32= (1<<30) * 2 - 1
354
$B.min_int32= - $B.max_int32
355
356
// code for operands & | ^
Sep 5, 2014
357
var $op_func = function(self,other){
Jun 7, 2015
358
if(isinstance(other,int)) {
359
if(other.__class__===$B.LongInt.$dict){
360
return $B.LongInt.$dict.__sub__($B.LongInt(self), $B.LongInt(other))
361
}
362
if (self > $B.max_int32 || self < $B.min_int32 ||
363
other > $B.max_int32 || other < $B.min_int32) {
364
return $B.LongInt.$dict.__sub__($B.LongInt(self), $B.LongInt(other))
365
}
366
return self-other
Jun 7, 2015
367
}
Sep 5, 2014
368
if(isinstance(other,_b_.bool)) return self-other
369
if(hasattr(other,'__rsub__')) return getattr(other,'__rsub__')(self)
370
$err("-",other)
371
}
372
373
$op_func += '' // source code
374
var $ops = {'&':'and','|':'or','^':'xor'}
Sep 5, 2014
375
for(var $op in $ops){
376
var opf = $op_func.replace(/-/gm,$op)
377
opf = opf.replace(new RegExp('sub','gm'),$ops[$op])
378
eval('$IntDict.__'+$ops[$op]+'__ = '+opf)
379
}
380
381
// code for + and -
382
var $op_func = function(self,other){
Sep 5, 2014
384
if(isinstance(other,int)){
385
if(typeof other=='number'){
386
var res = self.valueOf()-other.valueOf()
387
if(res>=$B.min_int && res<=$B.max_int){return res}
388
else{return $B.LongInt.$dict.__sub__($B.LongInt(self),
389
$B.LongInt(other))}
390
}else{
391
return $B.LongInt.$dict.__sub__($B.LongInt(self),
392
$B.LongInt(other))
393
}
Sep 5, 2014
394
}
395
if(isinstance(other,_b_.float)){
396
return new Number(self-other)
Sep 5, 2014
397
}
398
if(isinstance(other,_b_.complex)){
399
return _b_.complex(self-other.real,-other.imag)
400
}
401
if(isinstance(other,_b_.bool)){
402
var bool_value=0;
403
if(other.valueOf()) bool_value=1;
Sep 5, 2014
405
}
406
if(isinstance(other,_b_.complex)){
407
return _b_.complex(self.valueOf() - other.real, other.imag)
408
}
409
if(hasattr(other,'__rsub__')) return getattr(other,'__rsub__')(self)
410
throw $err('-',other)
411
}
412
$op_func += '' // source code
413
var $ops = {'+':'add','-':'sub'}
414
for(var $op in $ops){
415
var opf = $op_func.replace(/-/gm,$op)
416
opf = opf.replace(new RegExp('sub','gm'),$ops[$op])
417
eval('$IntDict.__'+$ops[$op]+'__ = '+opf)
418
}
419
420
// comparison methods
421
var $comp_func = function(self,other){
422
if (other.__class__ === $B.LongInt.$dict) return $B.LongInt.$dict.__gt__($B.LongInt(self), other)
Sep 5, 2014
423
if(isinstance(other,int)) return self.valueOf() > other.valueOf()
424
if(isinstance(other,_b_.float)) return self.valueOf() > other.valueOf()
Sep 5, 2014
425
if(isinstance(other,_b_.bool)) {
426
return self.valueOf() > _b_.bool.$dict.__hash__(other)
427
}
428
if (hasattr(other, '__int__') || hasattr(other, '__index__')) {
429
return $IntDict.__gt__(self, $B.$GetInt(other))
430
}
Sep 5, 2014
431
throw _b_.TypeError(
432
"unorderable types: int() > "+$B.get_class(other).__name__+"()")
Sep 5, 2014
433
}
434
$comp_func += '' // source codevar $comps = {'>':'gt','>=':'ge','<':'lt','<=':'le'}
435
for(var $op in $B.$comps){
436
eval("$IntDict.__"+$B.$comps[$op]+'__ = '+
437
$comp_func.replace(/>/gm,$op).replace(/__gt__/gm,'__'+$B.$comps[$op]+'__'))
Sep 5, 2014
438
}
439
440
// add "reflected" methods
441
$B.make_rmethods($IntDict)
442
443
var $valid_digits=function(base) {
444
var digits=''
445
if (base === 0) return '0'
446
if (base < 10) {
447
for (var i=0; i < base; i++) digits+=String.fromCharCode(i+48)
448
return digits
449
}
450
451
var digits='0123456789'
452
// A = 65 (10 + 55)
453
for (var i=10; i < base; i++) digits+=String.fromCharCode(i+55)
454
return digits
455
}
456
Dec 26, 2014
457
var int = function(value, base){
458
// int() with no argument returns 0
459
if(value===undefined){return 0}
460
461
// int() of an integer returns the integer if base is undefined
462
if(typeof value=='number' &&
463
(base===undefined || base==10)){return parseInt(value)}
464
Dec 28, 2014
465
if(base!==undefined){
466
if(!isinstance(value,[_b_.str,_b_.bytes,_b_.bytearray])){
467
throw TypeError("int() can't convert non-string with explicit base")
468
}
469
}
470
471
if(isinstance(value,_b_.complex)){
472
throw TypeError("can't convert complex to int")
473
}
474
475
var $ns=$B.args('int',2,{x:null,base:null},['x','base'],arguments,
476
{'base':10},'null','null')
477
var value = $ns['x']
478
var base = $ns['base']
479
480
if(isinstance(value, _b_.float) && base===10){
481
if(value<$B.min_int || value>$B.max_int){
482
return $B.LongInt.$dict.$from_float(value)
483
}
484
else{return value>0 ? Math.floor(value) : Math.ceil(value)}
Sep 5, 2014
486
Dec 26, 2014
487
if (!(base >=2 && base <= 36)) {
488
// throw error (base must be 0, or 2-36)
489
if (base != 0) throw _b_.ValueError("invalid base")
490
}
491
492
if (typeof value == 'number'){
493
494
if(base==10){
495
if(value < $B.min_int || value > $B.max_int) return $B.LongInt(value)
496
return value
497
}else if(value.toString().search('e')>-1){
Dec 26, 2014
498
// can't convert to another base if value is too big
499
throw _b_.OverflowError("can't convert to base "+base)
500
}else{
501
var res=parseInt(value, base)
502
if(res < $B.min_int || res > $B.max_int) return $B.LongInt(value,base)
503
return res
Dec 26, 2014
504
}
505
}
Sep 5, 2014
506
507
if(value===true) return Number(1)
508
if(value===false) return Number(0)
509
if(value.__class__===$B.LongInt.$dict){
510
var z = parseInt(value.value)
511
if(z>$B.min_int && z<$B.max_int){return z}
512
else{return value}
513
}
Sep 5, 2014
514
Jan 22, 2015
515
base=$B.$GetInt(base)
Sep 5, 2014
516
517
if(isinstance(value, _b_.str)) value=value.valueOf()
518
if(typeof value=="string") {
519
var _value=value.trim() // remove leading/trailing whitespace
520
if (_value.length == 2 && base==0 && (_value=='0b' || _value=='0o' || _value=='0x')) {
Sep 5, 2014
521
throw _b_.ValueError('invalid value')
522
}
523
if (_value.length >2) {
524
var _pre=_value.substr(0,2).toUpperCase()
Sep 5, 2014
525
if (base == 0) {
526
if (_pre == '0B') base=2
527
if (_pre == '0O') base=8
528
if (_pre == '0X') base=16
529
}
530
if (_pre=='0B' || _pre=='0O' || _pre=='0X') {
Sep 5, 2014
532
}
533
}
534
var _digits=$valid_digits(base)
535
var _re=new RegExp('^[+-]?['+_digits+']+$', 'i')
Sep 5, 2014
537
throw _b_.ValueError(
538
"invalid literal for int() with base "+base +": '"+_b_.str(value)+"'")
Sep 5, 2014
539
}
540
if(base <= 10 && !isFinite(value)) {
541
throw _b_.ValueError(
542
"invalid literal for int() with base "+base +": '"+_b_.str(value)+"'")
Sep 5, 2014
543
}
544
var res=parseInt(_value, base)
545
if(res < $B.min_int || res > $B.max_int) return $B.LongInt(_value, base)
546
return res
Sep 5, 2014
547
}
548
549
if(isinstance(value,[_b_.bytes,_b_.bytearray])){
550
var _digits = $valid_digits(base)
551
for(var i=0;i<value.source.length;i++){
552
if(_digits.indexOf(String.fromCharCode(value.source[i]))==-1){
553
throw _b_.ValueError("invalid literal for int() with base "+
554
base +": "+_b_.repr(value))
555
}
556
}
557
return Number(parseInt(getattr(value,'decode')('latin-1'), base))
558
}
Sep 5, 2014
559
560
if(hasattr(value, '__int__')) return getattr(value,'__int__')()
561
if(hasattr(value, '__index__')) return getattr(value,'__index__')()
562
if(hasattr(value, '__trunc__')) {
563
var res = getattr(value,'__trunc__')(),
564
int_func = _b_.getattr(res, '__int__', null)
565
if(int_func===null){
566
throw TypeError('__trunc__ returned non-Integral (type '+
567
$B.get_class(res).__name__+')')
568
}
569
var res=int_func()
570
if(isinstance(res, int)){return res}
571
throw TypeError('__trunc__ returned non-Integral (type '+
572
$B.get_class(res).__name__+')')
573
}
Sep 5, 2014
574
575
throw _b_.ValueError(
576
"invalid literal for int() with base "+base +": '"+_b_.str(value)+"'")
Sep 5, 2014
577
}
578
int.$dict = $IntDict
579
int.__class__ = $B.$factory
580
$IntDict.$factory = int
581
582
_b_.int = int
583
Sep 5, 2014
585
})(__BRYTHON__)