Skip to content
Permalink
Newer
Older
100644 446 lines (371 sloc) 13.7 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
//var res = ''
172
//for(var i=0;i<val;i++) res+=other
173
//return res
174
}
175
176
other = $B.$GetInt(other) // check for int, __int__, __index__
177
Sep 5, 2014
178
if(isinstance(other,int)) return self*other
179
if(isinstance(other,_b_.float)) return _b_.float(self*other.value)
180
if(isinstance(other,_b_.bool)){
181
//var bool_value=0
Jan 22, 2015
182
if (other.valueOf()) return self //bool_value=1
183
//return self*bool_value
184
return int(0)
Sep 5, 2014
185
}
186
if(isinstance(other,_b_.complex)){
187
return _b_.complex(self.valueOf()*other.real, self.valueOf()*other.imag)
188
}
189
if(isinstance(other,[_b_.list,_b_.tuple])){
190
var res = []
191
// make temporary copy of list
192
var $temp = other.slice(0,other.length)
193
for(var i=0;i<val;i++) res=res.concat($temp)
194
if(isinstance(other,_b_.tuple)) res=_b_.tuple(res)
195
return res
196
}
197
if(hasattr(other,'__rmul__')) return getattr(other,'__rmul__')(self)
198
$err("*",other)
199
}
200
201
$IntDict.__name__ = 'int'
202
203
$IntDict.__ne__ = function(self,other){return !$IntDict.__eq__(self,other)}
204
205
$IntDict.__neg__ = function(self){return -self}
206
207
$IntDict.__new__ = function(cls){
208
if(cls===undefined){throw _b_.TypeError('int.__new__(): not enough arguments')}
209
return {__class__:cls.$dict}
210
}
211
212
//$IntDict.__or__ = function(self,other){return self | other} // bitwise OR
213
214
$IntDict.__pow__ = function(self,other){
215
if(isinstance(other, int)) {
216
if (other.valueOf() >= 0) return int(Math.pow(self.valueOf(),other.valueOf()))
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
// code for operands & | ^ << >>
270
var $op_func = function(self,other){
271
if(isinstance(other,int)) return self-other
272
if(isinstance(other,_b_.bool)) return self-other
273
if(hasattr(other,'__rsub__')) return getattr(other,'__rsub__')(self)
274
$err("-",other)
275
}
276
277
$op_func += '' // source code
278
var $ops = {'&':'and','|':'or','<<':'lshift','>>':'rshift','^':'xor'}
279
for(var $op in $ops){
280
var opf = $op_func.replace(/-/gm,$op)
281
opf = opf.replace(new RegExp('sub','gm'),$ops[$op])
282
eval('$IntDict.__'+$ops[$op]+'__ = '+opf)
283
}
284
285
// code for + and -
286
var $op_func = function(self,other){
287
if(isinstance(other,int)){
288
var res = self.valueOf()-other.valueOf()
289
if(isinstance(res,int)) return res
290
return _b_.float(res)
291
}
292
if(isinstance(other,_b_.float)){
293
return _b_.float(self.valueOf()-other.value)
294
}
295
if(isinstance(other,_b_.complex)){
296
return _b_.complex(self-other.real,-other.imag)
297
}
298
if(isinstance(other,_b_.bool)){
299
var bool_value=0;
300
if(other.valueOf()) bool_value=1;
301
return self.valueOf()-bool_value
302
}
303
if(isinstance(other,_b_.complex)){
304
return _b_.complex(self.valueOf() - other.real, other.imag)
305
}
306
if(hasattr(other,'__rsub__')) return getattr(other,'__rsub__')(self)
307
throw $err('-',other)
308
}
309
$op_func += '' // source code
310
var $ops = {'+':'add','-':'sub'}
311
for(var $op in $ops){
312
var opf = $op_func.replace(/-/gm,$op)
313
opf = opf.replace(new RegExp('sub','gm'),$ops[$op])
314
eval('$IntDict.__'+$ops[$op]+'__ = '+opf)
315
}
316
317
// comparison methods
318
var $comp_func = function(self,other){
319
if(isinstance(other,int)) return self.valueOf() > other.valueOf()
320
if(isinstance(other,_b_.float)) return self.valueOf() > other.value
321
if(isinstance(other,_b_.bool)) {
322
return self.valueOf() > _b_.bool.$dict.__hash__(other)
323
}
324
throw _b_.TypeError(
325
"unorderable types: int() > "+$B.get_class(other).__name__+"()")
Sep 5, 2014
326
}
327
$comp_func += '' // source codevar $comps = {'>':'gt','>=':'ge','<':'lt','<=':'le'}
328
for(var $op in $B.$comps){
329
eval("$IntDict.__"+$B.$comps[$op]+'__ = '+$comp_func.replace(/>/gm,$op))
330
}
331
332
// add "reflected" methods
333
$B.make_rmethods($IntDict)
334
335
var $valid_digits=function(base) {
336
var digits=''
337
if (base === 0) return '0'
338
if (base < 10) {
339
for (var i=0; i < base; i++) digits+=String.fromCharCode(i+48)
340
return digits
341
}
342
343
var digits='0123456789'
344
// A = 65 (10 + 55)
345
for (var i=10; i < base; i++) digits+=String.fromCharCode(i+55)
346
return digits
347
}
348
Dec 26, 2014
349
var int = function(value, base){
Dec 28, 2014
350
// most simple case
Jan 22, 2015
351
Dec 28, 2014
352
if(typeof value=='number' && base===undefined){return value}
353
354
if(base!==undefined){
355
if(!isinstance(value,[_b_.str,_b_.bytes,_b_.bytearray])){
356
throw TypeError("int() can't convert non-string with explicit base")
357
}
358
}
359
360
if(isinstance(value,_b_.float)){
361
var v = value.value
362
return v >= 0 ? Math.floor(v) : Math.ceil(v)
363
}
364
if(isinstance(value,_b_.complex)){
365
throw TypeError("can't convert complex to int")
366
}
367
Sep 5, 2014
368
var $ns=$B.$MakeArgs('int',arguments,[],[],'args','kw')
369
var value = $ns['args'][0]
370
var base = $ns['args'][1]
371
372
if (value === undefined) value = _b_.dict.$dict.get($ns['kw'],'x', 0)
373
if (base === undefined) base = _b_.dict.$dict.get($ns['kw'],'base',10)
374
Dec 26, 2014
375
if (!(base >=2 && base <= 36)) {
376
// throw error (base must be 0, or 2-36)
377
if (base != 0) throw _b_.ValueError("invalid base")
378
}
379
380
if (typeof value == 'number'){
Dec 28, 2014
381
if(base==10){return value}
Dec 26, 2014
382
else if(value.toString().search('e')>-1){
383
// can't convert to another base if value is too big
384
throw _b_.OverflowError("can't convert to base "+base)
385
}else{
386
return parseInt(value, base)
387
}
388
}
Sep 5, 2014
389
390
if(value===true) return Number(1)
391
if(value===false) return Number(0)
392
Jan 22, 2015
393
base=$B.$GetInt(base)
394
//if(!isinstance(base, _b_.int)) {
395
// if (hasattr(base, '__int__')) {base = Number(getattr(base,'__int__')())
396
// }else if (hasattr(base, '__index__')) {base = Number(getattr(base,'__index__')())}
397
//}
Sep 5, 2014
398
399
if(isinstance(value, _b_.str)) value=value.valueOf()
400
401
if(typeof value=="string") {
402
value=value.trim() // remove leading/trailing whitespace
403
if (value.length == 2 && base==0 && (value=='0b' || value=='0o' || value=='0x')) {
404
throw _b_.ValueError('invalid value')
405
}
406
if (value.length >2) {
407
var _pre=value.substr(0,2).toUpperCase()
408
if (base == 0) {
409
if (_pre == '0B') base=2
410
if (_pre == '0O') base=8
411
if (_pre == '0X') base=16
412
}
413
if (_pre=='0B' || _pre=='0O' || _pre=='0X') {
414
value=value.substr(2)
415
}
416
}
417
var _digits=$valid_digits(base)
418
var _re=new RegExp('^[+-]?['+_digits+']+$', 'i')
419
if(!_re.test(value)) {
420
throw _b_.ValueError(
421
"Invalid literal for int() with base "+base +": '"+_b_.str(value)+"'")
422
}
423
if(base <= 10 && !isFinite(value)) {
424
throw _b_.ValueError(
425
"Invalid literal for int() with base "+base +": '"+_b_.str(value)+"'")
426
}
427
return Number(parseInt(value, base))
428
}
Dec 28, 2014
429
Sep 5, 2014
430
431
if(isinstance(value,[_b_.bytes,_b_.bytearray])) return Number(parseInt(getattr(value,'decode')('latin-1'), base))
432
433
if(hasattr(value, '__int__')) return Number(getattr(value,'__int__')())
434
if(hasattr(value, '__index__')) return Number(getattr(value,'__index__')())
Sep 5, 2014
435
if(hasattr(value, '__trunc__')) return Number(getattr(value,'__trunc__')())
436
437
throw _b_.ValueError(
438
"Invalid literal for int() with base "+base +": '"+_b_.str(value)+"'")
439
}
440
int.$dict = $IntDict
441
int.__class__ = $B.$factory
442
$IntDict.$factory = int
443
444
_b_.int = int
445
446
})(__BRYTHON__)