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