Skip to content
Permalink
Newer
Older
100644 393 lines (330 sloc) 12.3 KB
Sep 5, 2014
1
;(function($B){
2
var _b_ = $B.builtins
3
4
var $s=[]
5
for(var $b in _b_) $s.push('var ' + $b +'=_b_["'+$b+'"]')
6
eval($s.join(';'))
7
//for(var $py_builtin in _b_){eval("var "+$py_builtin+"=_b_[$py_builtin]")}
8
var $ObjectDict = _b_.object.$dict
9
10
function $err(op,other){
11
var msg = "unsupported operand type(s) for "+op
12
msg += ": 'int' and '"+$B.get_class(other).__name__+"'"
13
throw _b_.TypeError(msg)
14
}
15
16
var $IntDict = {__class__:$B.$type,
17
__name__:'int',
18
toString:function(){return '$IntDict'},
19
$native:true
20
}
21
// Pierre, this probably isn't correct, but may work for now.
22
// do we need to create a $IntDict, like what we did for Float?
23
$IntDict.from_bytes = function(x, byteorder) {
24
var len = x.source.length
25
26
if (byteorder == 'little') {
27
var num = x.source[len - 1];
28
29
if (num >= 128) num = num - 256;
30
31
for (var i = (len - 2); i >= 0; i--) {
32
num = 256 * num + x.source[i];
33
}
34
return num;
35
}
36
37
if (byteorder === 'big') {
38
var num = x.source[0];
39
40
if (num >= 128) num = num - 256;
41
42
for (var i = 1; i < len; i++) {
43
num = 256 * num + x.source[i];
44
}
45
if (num < 0) return -num // fixme.. alg above shouldn't return a negative
46
return num;
47
}
48
49
throw _b_.ValueError("byteorder must be either 'little' or 'big'");
50
}
51
52
$IntDict.to_bytes = function(length, byteorder, star) {
53
//var len = x.length
54
throw _b_.NotImplementedError("int.to_bytes is not implemented yet")
55
}
56
57
58
//$IntDict.__and__ = function(self,other){return self & other} // bitwise AND
59
60
$IntDict.__bool__ = function(self){return new Boolean(self.valueOf())}
61
62
//is this a duplicate?
63
$IntDict.__class__ = $B.$type
64
65
$IntDict.__eq__ = function(self,other){
66
// compare object "self" to class "int"
67
if(other===undefined) return self===int
68
if(isinstance(other,int)) return self.valueOf()==other.valueOf()
69
if(isinstance(other,_b_.float)) return self.valueOf()==other.value
70
if(isinstance(other,_b_.complex)){
71
if (other.imag != 0) return False
72
return self.valueOf() == other.real
73
}
74
return self.valueOf()===other
75
}
76
77
$IntDict.__format__ = function(self,format_spec){
78
if (format_spec == '') format_spec='d'
79
return _b_.str.$dict.__mod__('%'+format_spec, self)
80
}
81
82
$IntDict.__floordiv__ = function(self,other){
83
if(isinstance(other,int)){
84
if(other==0) throw ZeroDivisionError('division by zero')
85
return Math.floor(self/other)
86
}
87
if(isinstance(other,_b_.float)){
88
if(!other.value) throw ZeroDivisionError('division by zero')
89
return _b_.float(Math.floor(self/other.value))
90
}
91
if(hasattr(other,'__rfloordiv__')){
92
return getattr(other,'__rfloordiv__')(self)
93
}
94
$err("//",other)
95
}
96
97
$IntDict.__getitem__ = function(){
98
throw _b_.TypeError("'int' object is not subscriptable")
99
}
100
101
$IntDict.__hash__ = function(self){return self.valueOf()}
102
103
//$IntDict.__ior__ = function(self,other){return self | other} // bitwise OR
104
105
$IntDict.__index__ = function(self){return self}
106
107
$IntDict.__init__ = function(self,value){
108
if(value===undefined){value=0}
109
self.toString = function(){return value}
110
//self.valueOf = function(){return value}
111
}
112
113
$IntDict.__int__ = function(self){return self}
114
115
$IntDict.__invert__ = function(self){return ~self}
116
117
$IntDict.__mod__ = function(self,other) {
118
// can't use Javascript % because it works differently for negative numbers
119
if(isinstance(other,_b_.tuple) && other.length==1) other=other[0]
120
if(isinstance(other,int)) return (self%other+other)%other
121
if(isinstance(other,_b_.float)) return ((self%other)+other)%other
122
if(isinstance(other,bool)){
123
var bool_value=0;
124
if (other.valueOf()) bool_value=1;
125
return (self%bool_value+bool_value)%bool_value
126
}
127
if(hasattr(other,'__rmod__')) return getattr(other,'__rmod__')(self)
128
$err('%',other)
129
}
130
131
$IntDict.__mro__ = [$IntDict,$ObjectDict]
132
133
$IntDict.__mul__ = function(self,other){
134
var val = self.valueOf()
135
if(isinstance(other,int)) return self*other
136
if(isinstance(other,_b_.float)) return _b_.float(self*other.value)
137
if(isinstance(other,_b_.bool)){
138
var bool_value=0
139
if (other.valueOf()) bool_value=1
140
return self*bool_value
141
}
142
if(isinstance(other,_b_.complex)){
143
return _b_.complex(self.valueOf()*other.real, self.valueOf()*other.imag)
144
}
145
if(typeof other==="string") {
146
var res = ''
147
for(var i=0;i<val;i++) res+=other
148
return res
149
}
150
if(isinstance(other,[_b_.list,_b_.tuple])){
151
var res = []
152
// make temporary copy of list
153
var $temp = other.slice(0,other.length)
154
for(var i=0;i<val;i++) res=res.concat($temp)
155
if(isinstance(other,_b_.tuple)) res=_b_.tuple(res)
156
return res
157
}
158
if(hasattr(other,'__rmul__')) return getattr(other,'__rmul__')(self)
159
$err("*",other)
160
}
161
162
$IntDict.__name__ = 'int'
163
164
$IntDict.__ne__ = function(self,other){return !$IntDict.__eq__(self,other)}
165
166
$IntDict.__neg__ = function(self){return -self}
167
168
$IntDict.__new__ = function(cls){
169
if(cls===undefined){throw _b_.TypeError('int.__new__(): not enough arguments')}
170
return {__class__:cls.$dict}
171
}
172
173
//$IntDict.__or__ = function(self,other){return self | other} // bitwise OR
174
175
$IntDict.__pow__ = function(self,other){
176
if(isinstance(other, int)) {
177
if (other.valueOf() >= 0) return int(Math.pow(self.valueOf(),other.valueOf()))
178
return Math.pow(self.valueOf(),other.valueOf())
179
}
180
if(isinstance(other, _b_.float)) {
181
return _b_.float(Math.pow(self.valueOf(), other.valueOf()))
182
}
183
if(hasattr(other,'__rpow__')) return getattr(other,'__rpow__')(self)
184
$err("**",other)
185
}
186
187
$IntDict.__repr__ = function(self){
188
if(self===int) return "<class 'int'>"
189
return self.toString()
190
}
191
192
//$IntDict.__rshift__ = function(self,other){return self >> other} // bitwise right shift
193
194
$IntDict.__setattr__ = function(self,attr,value){
195
if(self.__class__===$IntDict){
196
throw _b_.AttributeError("'int' object has no attribute "+attr+"'")
197
}
198
// subclasses of int can have attributes set
199
self[attr] = value
200
}
201
202
$IntDict.__str__ = $IntDict.__repr__
203
204
$IntDict.__truediv__ = function(self,other){
205
if(isinstance(other,int)){
206
if(other==0) throw ZeroDivisionError('division by zero')
207
return _b_.float(self/other)
208
}
209
if(isinstance(other,_b_.float)){
210
if(!other.value) throw ZeroDivisionError('division by zero')
211
return _b_.float(self/other.value)
212
}
213
if(isinstance(other,_b_.complex)){
214
var cmod = other.real*other.real+other.imag*other.imag
215
if(cmod==0) throw ZeroDivisionError('division by zero')
216
return _b_.complex(self*other.real/cmod,-self*other.imag/cmod)
217
}
218
if(hasattr(other,'__rtruediv__')) return getattr(other,'__rtruediv__')(self)
219
$err("/",other)
220
}
221
222
//$IntDict.__xor__ = function(self,other){return self ^ other} // bitwise XOR
223
224
$IntDict.bit_length = function(self){
225
s = bin(self)
226
s = getattr(s,'lstrip')('-0b') // remove leading zeros and minus sign
227
return s.length // len('100101') --> 6
228
}
229
230
// code for operands & | ^ << >>
231
var $op_func = function(self,other){
232
if(isinstance(other,int)) return self-other
233
if(isinstance(other,_b_.bool)) return self-other
234
if(hasattr(other,'__rsub__')) return getattr(other,'__rsub__')(self)
235
$err("-",other)
236
}
237
238
$op_func += '' // source code
239
var $ops = {'&':'and','|':'or','<<':'lshift','>>':'rshift','^':'xor'}
240
for(var $op in $ops){
241
var opf = $op_func.replace(/-/gm,$op)
242
opf = opf.replace(new RegExp('sub','gm'),$ops[$op])
243
eval('$IntDict.__'+$ops[$op]+'__ = '+opf)
244
}
245
246
// code for + and -
247
var $op_func = function(self,other){
248
if(isinstance(other,int)){
249
var res = self.valueOf()-other.valueOf()
250
if(isinstance(res,int)) return res
251
return _b_.float(res)
252
}
253
if(isinstance(other,_b_.float)){
254
return _b_.float(self.valueOf()-other.value)
255
}
256
if(isinstance(other,_b_.complex)){
257
return _b_.complex(self-other.real,-other.imag)
258
}
259
if(isinstance(other,_b_.bool)){
260
var bool_value=0;
261
if(other.valueOf()) bool_value=1;
262
return self.valueOf()-bool_value
263
}
264
if(isinstance(other,_b_.complex)){
265
return _b_.complex(self.valueOf() - other.real, other.imag)
266
}
267
if(hasattr(other,'__rsub__')) return getattr(other,'__rsub__')(self)
268
throw $err('-',other)
269
}
270
$op_func += '' // source code
271
var $ops = {'+':'add','-':'sub'}
272
for(var $op in $ops){
273
var opf = $op_func.replace(/-/gm,$op)
274
opf = opf.replace(new RegExp('sub','gm'),$ops[$op])
275
eval('$IntDict.__'+$ops[$op]+'__ = '+opf)
276
}
277
278
// comparison methods
279
var $comp_func = function(self,other){
280
if(isinstance(other,int)) return self.valueOf() > other.valueOf()
281
if(isinstance(other,_b_.float)) return self.valueOf() > other.value
282
if(isinstance(other,_b_.bool)) {
283
return self.valueOf() > _b_.bool.$dict.__hash__(other)
284
}
285
throw _b_.TypeError(
286
"unorderable types: int() > "+$B.get_class(other).__name__+"()")
Sep 5, 2014
287
}
288
$comp_func += '' // source codevar $comps = {'>':'gt','>=':'ge','<':'lt','<=':'le'}
289
for(var $op in $B.$comps){
290
eval("$IntDict.__"+$B.$comps[$op]+'__ = '+$comp_func.replace(/>/gm,$op))
291
}
292
293
// add "reflected" methods
294
$B.make_rmethods($IntDict)
295
296
var $valid_digits=function(base) {
297
var digits=''
298
if (base === 0) return '0'
299
if (base < 10) {
300
for (var i=0; i < base; i++) digits+=String.fromCharCode(i+48)
301
return digits
302
}
303
304
var digits='0123456789'
305
// A = 65 (10 + 55)
306
for (var i=10; i < base; i++) digits+=String.fromCharCode(i+55)
307
return digits
308
}
309
Dec 26, 2014
310
var int = function(value, base){
311
// most usual case
312
if(typeof value=='number' && base===undefined){return Math.floor(value)}
313
Sep 5, 2014
314
var $ns=$B.$MakeArgs('int',arguments,[],[],'args','kw')
315
//console.log($ns)
316
var value = $ns['args'][0]
317
var base = $ns['args'][1]
318
319
if (value === undefined) value = _b_.dict.$dict.get($ns['kw'],'x', 0)
320
if (base === undefined) base = _b_.dict.$dict.get($ns['kw'],'base',10)
321
Dec 26, 2014
322
if (!(base >=2 && base <= 36)) {
323
// throw error (base must be 0, or 2-36)
324
if (base != 0) throw _b_.ValueError("invalid base")
325
}
326
327
if (typeof value == 'number'){
328
if(base==10){return Math.floor(value)}
329
else if(value.toString().search('e')>-1){
330
// can't convert to another base if value is too big
331
throw _b_.OverflowError("can't convert to base "+base)
332
}else{
333
return parseInt(value, base)
334
}
335
}
Sep 5, 2014
336
337
if(value===true) return Number(1)
338
if(value===false) return Number(0)
339
340
if(!isinstance(base, _b_.int)) {
341
if (hasattr(base, '__int__')) {base = Number(getattr(base,'__int__')())
342
}else if (hasattr(base, '__index__')) {base = Number(getattr(base,'__index__')())}
343
}
344
345
if(isinstance(value, _b_.str)) value=value.valueOf()
346
347
if(typeof value=="string") {
348
value=value.trim() // remove leading/trailing whitespace
349
if (value.length == 2 && base==0 && (value=='0b' || value=='0o' || value=='0x')) {
350
throw _b_.ValueError('invalid value')
351
}
352
if (value.length >2) {
353
var _pre=value.substr(0,2).toUpperCase()
354
if (base == 0) {
355
if (_pre == '0B') base=2
356
if (_pre == '0O') base=8
357
if (_pre == '0X') base=16
358
}
359
if (_pre=='0B' || _pre=='0O' || _pre=='0X') {
360
value=value.substr(2)
361
}
362
}
363
var _digits=$valid_digits(base)
364
var _re=new RegExp('^[+-]?['+_digits+']+$', 'i')
365
if(!_re.test(value)) {
366
throw _b_.ValueError(
367
"Invalid literal for int() with base "+base +": '"+_b_.str(value)+"'")
368
}
369
if(base <= 10 && !isFinite(value)) {
370
throw _b_.ValueError(
371
"Invalid literal for int() with base "+base +": '"+_b_.str(value)+"'")
372
}
373
return Number(parseInt(value, base))
374
}
375
if(isinstance(value,_b_.float)) return Number(parseInt(value.value,base))
376
377
if(isinstance(value,[_b_.bytes,_b_.bytearray])) return Number(parseInt(getattr(value,'decode')('latin-1'), base))
378
379
//if(isinstance(value, int)) return self
380
381
if(hasattr(value, '__int__')) return Number(getattr(value,'__int__')())
382
if(hasattr(value, '__trunc__')) return Number(getattr(value,'__trunc__')())
383
384
throw _b_.ValueError(
385
"Invalid literal for int() with base "+base +": '"+_b_.str(value)+"'")
386
}
387
int.$dict = $IntDict
388
int.__class__ = $B.$factory
389
$IntDict.$factory = int
390
391
_b_.int = int
392
393
})(__BRYTHON__)