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