PageRenderTime 48ms CodeModel.GetById 22ms RepoModel.GetById 0ms app.codeStats 0ms

/brython.js

https://bitbucket.org/olemis/brython-git
JavaScript | 5400 lines | 5397 code | 0 blank | 3 comment | 721 complexity | 2b3b992a411831b336b4d525699e7589 MD5 | raw file
Possible License(s): BSD-3-Clause
  1. // brython.js www.brython.info
  2. // version 1.1.20130319-232656
  3. // version compiled from commented, indented source files at http://code.google.com/p/brython/
  4. __BRYTHON__=new Object()
  5. __BRYTHON__.__getattr__=function(attr){return this[attr]}
  6. __BRYTHON__.date=function(){
  7. if(arguments.length===0){return JSObject(new Date())}
  8. else if(arguments.length===1){return JSObject(new Date(arguments[0]))}
  9. else if(arguments.length===7){return JSObject(new Date(arguments[0],
  10. arguments[1]-1,arguments[2],arguments[3],
  11. arguments[4],arguments[5],arguments[6]))}
  12. }
  13. __BRYTHON__.has_local_storage=typeof(Storage)!=="undefined"
  14. if(__BRYTHON__.has_local_storage){
  15. __BRYTHON__.local_storage=function(){return JSObject(localStorage)}
  16. }
  17. __BRYTHON__.has_json=typeof(JSON)!=="undefined"
  18. __BRYTHON__.version_info=[1,1,"20130319-232656"]
  19. __BRYTHON__.path=[]
  20. function abs(obj){
  21. if(isinstance(obj,int)){return int(Math.abs(obj))}
  22. else if(isinstance(obj,float)){return float(Math.abs(obj.value))}
  23. else if('__abs__' in obj){return obj.__abs__()}
  24. else{throw TypeError("Bad operand type for abs(): '"+str(obj.__class__)+"'")}
  25. }
  26. function $alert(src){alert(str(src))}
  27. function all(iterable){
  28. while(true){
  29. try{
  30. var elt=next(iterable)
  31. if(!bool(elt)){return False}
  32. }catch(err){return True}
  33. }
  34. }
  35. function any(iterable){
  36. if(iterable.__item__===undefined){
  37. throw TypeError("'"+iterable.__class__.__name__+"' object is not iterable")
  38. }
  39. while(true){
  40. try{
  41. var elt=next(iterable)
  42. if(bool(elt)){return True}
  43. }catch(err){return False}
  44. }
  45. }
  46. function assert_raises(){
  47. var $ns=$MakeArgs('assert_raises',arguments,['exc','func'],{},'args','kw')
  48. var args=$ns['args']
  49. try{$ns['func'].apply(this,args)}
  50. catch(err){
  51. if(err.name!==$ns['exc']){
  52. throw AssertionError(
  53. "exception raised '"+err.name+"', expected '"+$ns['exc']+"'")
  54. }
  55. return
  56. }
  57. throw AssertionError("no exception raised, expected '"+$ns['exc']+"'")
  58. }
  59. function bool(obj){
  60. if(obj===null){return False}
  61. else if(obj===undefined){return False}
  62. else if(isinstance(obj,dict)){return obj.keys.length>0}
  63. else if(isinstance(obj,tuple)){return obj.length>0}
  64. else if(typeof obj==="boolean"){return obj}
  65. else if(typeof obj==="number" || typeof obj==="string"){
  66. if(obj){return true}else{return false}
  67. }else if('__bool__' in obj){return obj.__bool__()}
  68. else if('__len__' in obj){return obj.__len__()>0}
  69. return true
  70. }
  71. bool.__class__=$type
  72. bool.__name__='bool'
  73. bool.__str__=function(){return "<class 'bool'>"}
  74. bool.toString=bool.__str__
  75. bool.__hash__=function(){
  76. if(this.valueOf())return 1
  77. return 0
  78. }
  79. function $class(obj,info){
  80. this.obj=obj
  81. this.info=info
  82. this.__class__=Object
  83. this.toString=function(){return "<class '"+info+"'>"}
  84. }
  85. function $confirm(src){return confirm(src)}
  86. function $DictClass($keys,$values){
  87. var x=null
  88. var i=null
  89. this.iter=null
  90. this.__class__=dict
  91. this.$keys=$keys
  92. this.$values=$values
  93. }
  94. function dict(){
  95. if(arguments.length==0){return new $DictClass([],[])}
  96. else if(arguments.length===1 && isinstance(arguments[0],dict)){
  97. return arguments[0]
  98. }
  99. var $ns=$MakeArgs('dict',arguments,[],{},'args','kw')
  100. var args=$ns['args']
  101. var kw=$ns['kw']
  102. if(args.length>0){
  103. var iterable=args[0]
  104. var obj=new $DictClass([],[])
  105. for(var i=0;i<iterable.__len__();i++){
  106. var elt=iterable.__item__(i)
  107. obj.__setitem__(elt.__item__(0),elt.__item__(1))
  108. }
  109. return obj
  110. }else if(kw.$keys.length>0){
  111. return kw
  112. }
  113. }
  114. dict.__name__='dict'
  115. dict.toString=function(){return "<class 'dict'>"}
  116. dict.__add__=function(self,other){
  117. var msg="unsupported operand types for +:'dict' and "
  118. throw TypeError(msg+"'"+(str(other.__class__)|| typeof other)+"'")
  119. }
  120. dict.__class__=$type
  121. dict.__contains__=function(self,item){
  122. return self.$keys.__contains__(item)
  123. }
  124. dict.__delitem__=function(self,arg){
  125. for(var i=0;i<self.$keys.length;i++){
  126. if(arg.__eq__(self.$keys[i])){
  127. self.$keys.splice(i,1)
  128. self.$values.splice(i,1)
  129. return
  130. }
  131. }
  132. throw KeyError(str(arg))
  133. }
  134. dict.__eq__=function(self,other){
  135. if(other===undefined){
  136. return self===dict
  137. }
  138. if(!isinstance(other,dict)){return False}
  139. if(other.$keys.length!==self.$keys.length){return False}
  140. for(var i=0;i<self.$keys.length;i++){
  141. var key=self.$keys[i]
  142. for(j=0;j<other.$keys.length;j++){
  143. try{
  144. if(other.$keys[j].__eq__(key)){
  145. if(!other.$values[j].__eq__(self.$values[i])){
  146. return False
  147. }
  148. }
  149. }catch(err){void(0)}
  150. }
  151. }
  152. return True
  153. }
  154. dict.__getattr__=function(attr){
  155. if(this[attr]!==undefined){return this[attr]}
  156. else{throw AttributeError("'dict' object has no attribute '"+attr+"'")}
  157. }
  158. dict.__getitem__=function(self,arg){
  159. for(var i=0;i<self.$keys.length;i++){
  160. if(arg.__eq__(self.$keys[i])){return self.$values[i]}
  161. }
  162. throw KeyError(str(arg))
  163. }
  164. dict.__hash__=function(self){throw TypeError("unhashable type: 'dict'");}
  165. dict.__in__=function(self,item){return item.__contains__(self)}
  166. dict.__item__=function(self,i){return self.$keys[i]}
  167. dict.__len__=function(self){return self.$keys.length}
  168. dict.__ne__=function(self,other){return !dict.__eq__(self,other)}
  169. dict.__next__=function(self){
  170. if(self.iter==null){self.iter==0}
  171. if(self.iter<self.$keys.length){
  172. self.iter++
  173. return self.$keys[self.iter-1]
  174. }else{
  175. self.iter=null
  176. throw StopIteration()
  177. }
  178. }
  179. dict.__not_in__=function(self,item){return !(item.__contains__(self))}
  180. dict.__setitem__=function(self,key,value){
  181. for(var i=0;i<self.$keys.length;i++){
  182. try{
  183. if(key.__eq__(self.$keys[i])){
  184. self.$values[i]=value
  185. return
  186. }
  187. }catch(err){
  188. void(0)
  189. }
  190. }
  191. self.$keys.push(key)
  192. self.$values.push(value)
  193. }
  194. dict.__str__=function(self){
  195. if(self===undefined){return "<class 'dict'>"}
  196. if(self.$keys.length==0){return '{}'}
  197. var res="{",key=null,value=null,i=null
  198. var qesc=new RegExp('"',"g")
  199. for(var i=0;i<self.$keys.length;i++){
  200. if(typeof self.$keys[i]==="string"){key='"'+$escape_dq(self.$keys[i])+'"'}
  201. else{key=str(self.$keys[i])}
  202. if(typeof self.$values[i]==="string"){value='"'+$escape_dq(self.$values[i])+'"'}
  203. else{value=str(self.$values[i])}
  204. res +=key+':'+value+','
  205. }
  206. return res.substr(0,res.length-1)+'}'
  207. }
  208. dict.items=function(self){
  209. return new $iterator(zip(self.$keys,self.$values),"dict_items")
  210. }
  211. dict.keys=function(self){
  212. return new $iterator(self.$keys,"dict keys")
  213. }
  214. dict.update=function(self){
  215. var params=[]
  216. for(var i=1;i<arguments.length;i++){params.push(arguments[i])}
  217. var $ns=$MakeArgs('dict.update',params,[],{},'args','kw')
  218. var args=$ns['args']
  219. if(args.length>0 && isinstance(args[0],dict)){
  220. var other=args[0]
  221. for(var i=0;i<other.$keys.length;i++){
  222. dict.__setitem__(self,other.$keys[i],other.$values[i])
  223. }
  224. }
  225. var kw=$ns['kw']
  226. console.log('kw '+kw.__class__)
  227. var keys=list(kw.keys())
  228. for(var i=0;i<keys.__len__();i++){
  229. dict.__setitem__(self,keys[i],kw.__getitem__(keys[i]))
  230. }
  231. }
  232. dict.values=function(self){
  233. return new $iterator(self.$values,"dict values")
  234. }
  235. $DictClass.prototype.__class__=dict
  236. $DictClass.prototype.__getattr__=function(attr){
  237. if(attr==='__class__'){return this.__class__}
  238. if(dict[attr]===undefined){throw AttributeError("'dict' object has no attribute '"+attr+"'")}
  239. var obj=this
  240. var res=function(){
  241. var args=[obj]
  242. for(var i=0;i<arguments.length;i++){args.push(arguments[i])}
  243. return dict[attr].apply(obj,args)
  244. }
  245. res.__str__=function(){return "<built-in method "+attr+" of dict object>"}
  246. return res
  247. }
  248. for(var attr in dict){
  249. if($DictClass.prototype[attr]===undefined){
  250. $DictClass.prototype[attr]=(function(attr){
  251. return function(){
  252. var args=[this]
  253. for(var i=0;i<arguments.length;i++){args.push(arguments[i])}
  254. return dict[attr].apply(this,args)
  255. }
  256. })(attr)
  257. }
  258. }
  259. function dir(obj){
  260. var res=[]
  261. for(var attr in obj){res.push(attr)}
  262. res.sort()
  263. return res
  264. }
  265. function enumerate(iterator){
  266. var res=[]
  267. for(var i=0;i<iterator.__len__();i++){
  268. res.push([i,iterator.__item__(i)])
  269. }
  270. return res
  271. }
  272. function $eval(src){
  273. if(src===""){throw SyntaxError("unexpected EOF while parsing")}
  274. try{return eval(__BRYTHON__.py2js(src).to_js())}
  275. catch(err){
  276. if(err.py_error===undefined){throw RuntimeError(err.message)}
  277. if(document.$stderr){document.$stderr.__getattr__('write')(document.$stderr_buff+'\n')}
  278. else{err.message +=err.info;throw(err)}
  279. }
  280. }
  281. function exec(src){
  282. try{eval(__BRYTHON__.py2js(src).to_js())}
  283. catch(err){
  284. console.log(err)
  285. if(err.py_error===undefined){err=RuntimeError(err+'')}
  286. var trace=err.__name__+': '+err.message
  287. if(err.__name__=='SyntaxError'||err.__name__==='IndentationError'){
  288. trace +=err.info
  289. }
  290. if(document.$stderr){document.$stderr.__getattr__('write')(trace)}
  291. else{err.message +=err.info}
  292. throw err
  293. }
  294. }
  295. function filter(){
  296. if(arguments.length!=2){throw TypeError(
  297. "filter expected 2 arguments, got "+arguments.length)}
  298. var func=arguments[0],iterable=arguments[1]
  299. var res=[]
  300. for(var i=0;i<iterable.__len__();i++){
  301. if(func(iterable.__item__(i))){
  302. res.push(iterable.__item__(i))
  303. }
  304. }
  305. return res
  306. }
  307. function float(value){
  308. if(value===undefined){return new $FloatClass(0.0)}
  309. if(typeof value=="number" ||(typeof value=="string" && !isNaN(value))){
  310. return new $FloatClass(parseFloat(value))
  311. }
  312. if(isinstance(value,float))return value
  313. if(value=='inf')return new $FloatClass(Infinity)
  314. if(value=='-inf')return new $FloatClass(-Infinity)
  315. if(typeof value=='string' && value.toLowerCase()=='nan')return new $FloatClass(Number.NaN)
  316. throw ValueError("Could not convert to float(): '"+str(value)+"'")
  317. }
  318. float.__class__=$type
  319. float.__name__='float'
  320. float.toString=function(){return "<class 'float'>"}
  321. float.__hash__=function(){
  322. frexp=function(re){
  323. var ex=Math.floor(Math.log(re)/ Math.log(2))+ 1
  324. var frac=re / Math.pow(2, ex)
  325. return[frac, ex]
  326. }
  327. if(this.value===Infinity || this.value===-Infinity){
  328. if(this.value < 0.0)return -271828
  329. return 314159
  330. }else if(isNaN(this.value)){
  331. return 0
  332. }
  333. var r=frexp(this.value)
  334. r[0]*=Math.pow(2,31)
  335. hipart=int(r[0])
  336. r[0]=(r[0]- hipart)* Math.pow(2,31)
  337. var x=hipart + int(r[0])+(r[1]<< 15)
  338. return x & 0xFFFFFFFF
  339. }
  340. function $FloatClass(value){
  341. this.value=value
  342. this.__class__=float
  343. this.__hash__=float.__hash__
  344. }
  345. $FloatClass.prototype.toString=function(){
  346. var res=this.value+''
  347. if(res.indexOf('.')==-1){res+='.0'}
  348. return str(res)
  349. }
  350. $FloatClass.prototype.__class__=float
  351. $FloatClass.prototype.__bool__=function(){return bool(this.value)}
  352. $FloatClass.prototype.__floordiv__=function(other){
  353. if(isinstance(other,int)){
  354. if(other===0){throw ZeroDivisionError('division by zero')}
  355. else{return float(Math.floor(this.value/other))}
  356. }else if(isinstance(other,float)){
  357. if(!other.value){throw ZeroDivisionError('division by zero')}
  358. else{return float(Math.floor(this.value/other.value))}
  359. }else{throw TypeError(
  360. "unsupported operand type(s) for //: 'int' and '"+other.__class__+"'")
  361. }
  362. }
  363. $FloatClass.prototype.__getattr__=function(attr){
  364. if(this[attr]!==undefined){return this[attr]}
  365. else{throw AttributeError("'float' object has no attribute '"+attr+"'")}
  366. }
  367. $FloatClass.prototype.__hash__=float.__hash__
  368. $FloatClass.prototype.__in__=function(item){return item.__contains__(this)}
  369. $FloatClass.prototype.__not_in__=function(item){return !(item.__contains__(this))}
  370. $FloatClass.prototype.__str__=$FloatClass.prototype.toString
  371. $FloatClass.prototype.__truediv__=function(other){
  372. if(isinstance(other,int)){
  373. if(other===0){throw ZeroDivisionError('division by zero')}
  374. else{return float(this.value/other)}
  375. }else if(isinstance(other,float)){
  376. if(!other.value){throw ZeroDivisionError('division by zero')}
  377. else{return float(this.value/other.value)}
  378. }else{throw TypeError(
  379. "unsupported operand type(s) for //: 'int' and '"+other.__class__+"'")
  380. }
  381. }
  382. var $op_func=function(other){
  383. if(isinstance(other,int)){return float(this.value-other)}
  384. else if(isinstance(other,float)){return float(this.value-other.value)}
  385. else if(isinstance(other,bool)){
  386. var bool_value=0;
  387. if(other.valueOf())bool_value=1
  388. return float(this.value-bool_value)}
  389. else{throw TypeError(
  390. "unsupported operand type(s) for -: "+this.value+" (float) and '"+other.__class__+"'")
  391. }
  392. }
  393. $op_func +=''
  394. var $ops={'+':'add','-':'sub','*':'mul','%':'mod'}
  395. for($op in $ops){
  396. eval('$FloatClass.prototype.__'+$ops[$op]+'__ = '+$op_func.replace(/-/gm,$op))
  397. }
  398. var $comp_func=function(other){
  399. if(isinstance(other,int)){return this.value > other.valueOf()}
  400. else if(isinstance(other,float)){return this.value > other.value}
  401. else{throw TypeError(
  402. "unorderable types: "+this.__class__+'() > '+other.__class__+"()")
  403. }
  404. }
  405. $comp_func +=''
  406. var $comps={'>':'gt','>=':'ge','<':'lt','<=':'le','==':'eq','!=':'ne'}
  407. for($op in $comps){
  408. eval("$FloatClass.prototype.__"+$comps[$op]+'__ = '+$comp_func.replace(/>/gm,$op))
  409. }
  410. var $notimplemented=function(other){
  411. throw TypeError(
  412. "unsupported operand types for OPERATOR: '"+this.__class__+"' and '"+other.__class__+"'")
  413. }
  414. $notimplemented +=''
  415. for($op in $operators){
  416. var $opfunc='__'+$operators[$op]+'__'
  417. if(!($opfunc in $FloatClass.prototype)){
  418. eval('$FloatClass.prototype.'+$opfunc+"="+$notimplemented.replace(/OPERATOR/gm,$op))
  419. }
  420. }
  421. function getattr(obj,attr,_default){
  422. if(obj.__getattr__!==undefined &&
  423. obj.__getattr__(attr)!==undefined){
  424. return obj.__getattr__(attr)
  425. }
  426. else if(_default !==undefined){return _default}
  427. else{throw AttributeError(
  428. "'"+str(obj.__class__)+"' object has no attribute '"+attr+"'")}
  429. }
  430. function hasattr(obj,attr){
  431. try{getattr(obj,attr);return True}
  432. catch(err){return False}
  433. }
  434. function hash(obj){
  435. if(isinstance(obj, int)){return obj.valueOf();}
  436. if(isinstance(obj, bool)){return int(obj);}
  437. if(obj.__hashvalue__ !==undefined){return obj.__hashvalue__;}
  438. if(obj.__hash__ !==undefined){
  439. obj.__hashvalue__=obj.__hash__()
  440. return obj.__hashvalue__
  441. }else{
  442. throw AttributeError(
  443. "'"+str(obj.__class__)+"' object has no attribute '__hash__'")
  444. }
  445. }
  446. function input(src){
  447. return prompt(src)
  448. }
  449. function int(value){
  450. if(value===undefined){return 0}
  451. else if(isinstance(value,int)){return value}
  452. else if(value===True){return 1}
  453. else if(value===False){return 0}
  454. else if(typeof value=="number" ||
  455. (typeof value=="string" && parseInt(value)!=NaN)){
  456. return parseInt(value)
  457. }else if(isinstance(value,float)){
  458. return parseInt(value.value)
  459. }else{throw ValueError(
  460. "Invalid literal for int() with base 10: '"+str(value)+"'"+value.__class__)
  461. }
  462. }
  463. int.__class__=$type
  464. int.__name__='int'
  465. int.toString=function(){return "<class 'int'>"}
  466. Number.prototype.__class__=int
  467. Number.prototype.__floordiv__=function(other){
  468. if(isinstance(other,int)){
  469. if(other==0){throw ZeroDivisionError('division by zero')}
  470. else{return Math.floor(this/other)}
  471. }else if(isinstance(other,float)){
  472. if(!other.value){throw ZeroDivisionError('division by zero')}
  473. else{return float(Math.floor(this/other.value))}
  474. }else{$UnsupportedOpType("//","int",other.__class__)}
  475. }
  476. Number.prototype.__getattr__=function(attr){
  477. if(this[attr]!==undefined){return this[attr]}
  478. throw AttributeError("'int' object has no attribute '"+attr+"'")
  479. }
  480. Number.prototype.__hash__=function(){return this.valueOf()}
  481. Number.prototype.__in__=function(item){return item.__contains__(this)}
  482. Number.prototype.__int__=function(){return this}
  483. Number.prototype.__mul__=function(other){
  484. var val=this.valueOf()
  485. if(isinstance(other,int)){return this*other}
  486. else if(isinstance(other,float)){return float(this*other.value)}
  487. else if(isinstance(other,bool)){
  488. var bool_value=0
  489. if(other.valueOf())bool_value=1
  490. return this*bool_value}
  491. else if(typeof other==="string"){
  492. var res=''
  493. for(var i=0;i<val;i++){res+=other}
  494. return res
  495. }else if(isinstance(other,[list,tuple])){
  496. var res=[]
  497. var $temp=other.slice(0,other.length)
  498. for(var i=0;i<val;i++){res=res.concat($temp)}
  499. if(isinstance(other,tuple)){res=tuple.apply(this,res)}
  500. return res
  501. }else{$UnsupportedOpType("*",int,other)}
  502. }
  503. Number.prototype.__not_in__=function(item){
  504. res=item.__contains__(this)
  505. return !res
  506. }
  507. Number.prototype.__pow__=function(other){
  508. if(typeof other==="number"){return int(Math.pow(this.valueOf(),other.valueOf()))}
  509. else{$UnsupportedOpType("//",int,other.__class__)}
  510. }
  511. Number.prototype.__setattr__=function(attr,value){throw AttributeError(
  512. "'int' object has no attribute "+attr+"'")}
  513. Number.prototype.__str__=function(){return this.toString()}
  514. Number.prototype.__truediv__=function(other){
  515. if(isinstance(other,int)){
  516. if(other==0){throw ZeroDivisionError('division by zero')}
  517. else{return float(this/other)}
  518. }else if(isinstance(other,float)){
  519. if(!other.value){throw ZeroDivisionError('division by zero')}
  520. else{return float(this/other.value)}
  521. }else{$UnsupportedOpType("//","int",other.__class__)}
  522. }
  523. var $op_func=function(other){
  524. if(isinstance(other,int)){
  525. var res=this.valueOf()-other.valueOf()
  526. if(isinstance(res,int)){return res}
  527. else{return float(res)}
  528. }
  529. else if(isinstance(other,float)){return float(this.valueOf()-other.value)}
  530. else if(isinstance(other,bool)){
  531. var bool_value=0
  532. if(other.valueOf())bool_value=1
  533. return this.valueOf()-bool_value}
  534. else{throw TypeError(
  535. "unsupported operand type(s) for -: "+this.value+" (float) and '"+str(other.__class__)+"'")
  536. }
  537. }
  538. $op_func +=''
  539. var $ops={'+':'add','-':'sub','%':'mod'}
  540. for($op in $ops){
  541. eval('Number.prototype.__'+$ops[$op]+'__ = '+$op_func.replace(/-/gm,$op))
  542. }
  543. var $comp_func=function(other){
  544. if(isinstance(other,int)){return this.valueOf()> other.valueOf()}
  545. else if(isinstance(other,float)){return this.valueOf()> other.value}
  546. else{throw TypeError(
  547. "unorderable types: "+str(this.__class__)+'() > '+str(other.__class__)+"()")}
  548. }
  549. $comp_func +=''
  550. var $comps={'>':'gt','>=':'ge','<':'lt','<=':'le','==':'eq','!=':'ne'}
  551. for($op in $comps){
  552. eval("Number.prototype.__"+$comps[$op]+'__ = '+$comp_func.replace(/>/gm,$op))
  553. }
  554. var $notimplemented=function(other){
  555. throw TypeError(
  556. "unsupported operand types for OPERATOR: '"+str(this.__class__)+"' and '"+str(other.__class__)+"'")
  557. }
  558. $notimplemented +=''
  559. for($op in $operators){
  560. var $opfunc='__'+$operators[$op]+'__'
  561. if(!($opfunc in Number.prototype)){
  562. eval('Number.prototype.'+$opfunc+"="+$notimplemented.replace(/OPERATOR/gm,$op))
  563. }
  564. }
  565. function isinstance(obj,arg){
  566. if(obj===null){return arg===None}
  567. if(obj===undefined){return false}
  568. if(arg.constructor===Array){
  569. for(var i=0;i<arg.length;i++){
  570. if(isinstance(obj,arg[i])){return true}
  571. }
  572. return false
  573. }else{
  574. if(arg===int){
  575. return((typeof obj)=="number"||obj.constructor===Number)&&(obj.valueOf()%1===0)
  576. }
  577. if(arg===float){
  578. return((typeof obj=="number" && obj.valueOf()%1!==0))||
  579. (obj.__class__===float)
  580. }
  581. if(arg===str){return(typeof obj=="string")}
  582. if(arg===list){return(obj.constructor===Array)}
  583. if(obj.__class__!==undefined){return obj.__class__===arg}
  584. return obj.constructor===arg
  585. }
  586. }
  587. function iter(obj){
  588. if('__item__' in obj){
  589. obj.__counter__=0
  590. return obj
  591. }
  592. throw TypeError("'"+str(obj.__class__)+"' object is not iterable")
  593. }
  594. function $iterator(obj,info){
  595. this.__getattr__=function(attr){
  596. var res=this[attr]
  597. if(res===undefined){throw AttributeError(
  598. "'"+info+"' object has no attribute '"+attr+"'")}
  599. else{return res}
  600. }
  601. this.__len__=function(){return obj.__len__()}
  602. this.__item__=function(i){return obj.__item__(i)}
  603. this.__class__=new $class(this,info)
  604. this.toString=function(){return info+'('+obj.toString()+')'}
  605. }
  606. function len(obj){
  607. try{return obj.__len__()}
  608. catch(err){
  609. try{return obj.__getattr__('__len__')()}
  610. catch(err){
  611. throw TypeError("object of type '"+obj.__class__.__name__+"' has no len()")}
  612. }
  613. }
  614. function map(){
  615. var func=arguments[0],res=[],rank=0
  616. while(true){
  617. var args=[],flag=true
  618. for(var i=1;i<arguments.length;i++){
  619. var x=arguments[i].__item__(rank)
  620. if(x===undefined){flag=false;break}
  621. args.push(x)
  622. }
  623. if(!flag){break}
  624. res.push(func.apply(null,args))
  625. rank++
  626. }
  627. return res
  628. }
  629. function $extreme(args,op){
  630. if(op==='__gt__'){var $op_name="max"}
  631. else{var $op_name="min"}
  632. if(args.length==0){throw TypeError($op_name+" expected 1 argument, got 0")}
  633. var last_arg=args[args.length-1]
  634. var last_i=args.length-1
  635. var has_key=false
  636. if(isinstance(last_arg,$Kw)){
  637. if(last_arg.name==='key'){
  638. var func=last_arg.value
  639. has_key=true
  640. last_i--
  641. }else{throw TypeError($op_name+"() got an unexpected keyword argument")}
  642. }else{var func=function(x){return x}}
  643. if((has_key && args.length==2)||(!has_key && args.length==1)){
  644. var arg=args[0]
  645. var $iter=iter(arg)
  646. var res=null
  647. while(true){
  648. try{
  649. var x=next($iter)
  650. if(res===null || bool(func(x)[op](func(res)))){res=x}
  651. }catch(err){
  652. if(err.__name__=="StopIteration"){return res}
  653. throw err
  654. }
  655. }
  656. }else{
  657. var res=null
  658. for(var i=0;i<=last_i;i++){
  659. var x=args[i]
  660. if(res===null || bool(func(x)[op](func(res)))){res=x}
  661. }
  662. return res
  663. }
  664. }
  665. function max(){
  666. var args=[]
  667. for(var i=0;i<arguments.length;i++){args.push(arguments[i])}
  668. return $extreme(args,'__gt__')
  669. }
  670. function min(){
  671. var args=[]
  672. for(var i=0;i<arguments.length;i++){args.push(arguments[i])}
  673. return $extreme(args,'__lt__')
  674. }
  675. function next(obj){
  676. if('__item__' in obj){
  677. if(obj.__counter__===undefined){obj.__counter__=0}
  678. var res=obj.__item__(obj.__counter__)
  679. if(res!==undefined){obj.__counter__++;return res}
  680. throw StopIteration('')
  681. }
  682. throw TypeError("'"+str(obj.__class__)+"' object is not iterable")
  683. }
  684. function $not(obj){return !bool(obj)}
  685. function $ObjectClass(){
  686. this.__class__="<class 'object'>"
  687. }
  688. $ObjectClass.prototype.__getattr__=function(attr){
  689. if(attr in this){return this[attr]}
  690. else{throw AttributeError("object has no attribute '"+attr+"'")}
  691. }
  692. $ObjectClass.prototype.__delattr__=function(attr){delete this[attr]}
  693. $ObjectClass.prototype.__setattr__=function(attr,value){this[attr]=value}
  694. function object(){
  695. return new $ObjectClass()
  696. }
  697. object.__class__=$type
  698. object.__name__='object'
  699. object.__str__="<class 'object'>"
  700. object.__hash__=function(){
  701. document.$py_next_hash+=1;
  702. return document.$py_next_hash
  703. }
  704. $ObjectClass.prototype.__hash__=object.__hash__
  705. function $open(){
  706. var $ns=$MakeArgs('open',arguments,['file'],{'mode':'r','encoding':'utf-8'},'args','kw')
  707. for(var attr in $ns){eval('var '+attr+'=$ns["'+attr+'"]')}
  708. if(args.length>0){var mode=args[0]}
  709. if(args.length>1){var encoding=args[1]}
  710. if(isinstance(file,JSObject)){return new $OpenFile(file.js,mode,encoding)}
  711. }
  712. function $print(){
  713. var $ns=$MakeArgs('print',arguments,[],{},'args','kw')
  714. var args=$ns['args']
  715. var kw=$ns['kw']
  716. var end='\n'
  717. var res=''
  718. if(kw['end']!==undefined){end=kw['end']}
  719. for(var i=0;i<args.length;i++){
  720. res +=str(args[i])
  721. if(i<args.length-1){res +=' '}
  722. }
  723. res +=end
  724. document.$stdout.__getattr__('write')(res)
  725. }
  726. log=function(arg){console.log(arg)}
  727. function $prompt(text,fill){return prompt(text,fill || '')}
  728. function range(){
  729. var $ns=$MakeArgs('range',arguments,[],{},'args',null)
  730. var args=$ns['args']
  731. if(args.length>3){throw TypeError(
  732. "range expected at most 3 arguments, got "+args.length)
  733. }
  734. var start=0
  735. var stop=0
  736. var step=1
  737. if(args.length==1){stop=args[0]}
  738. else if(args.length>=2){
  739. start=args[0]
  740. stop=args[1]
  741. }
  742. if(args.length>=3){step=args[2]}
  743. if(step==0){throw ValueError("range() arg 3 must not be zero")}
  744. var res=[]
  745. if(step>0){
  746. for(var i=start;i<stop;i+=step){res.push(i)}
  747. }else if(step<0){
  748. for(var i=start;i>stop;i+=step){res.push(i)}
  749. }
  750. return res
  751. }
  752. function repr(obj){return obj.toString()}
  753. function reversed(seq){
  754. if(isinstance(seq,list)){seq.reverse();return seq}
  755. else if(isinstance(seq,str)){
  756. var res=''
  757. for(var i=seq.length-1;i>=0;i--){res+=seq.charAt(i)}
  758. return res
  759. }else{throw TypeError(
  760. "argument to reversed() must be a sequence")}
  761. }
  762. function round(arg,n){
  763. if(!isinstance(arg,[int,float])){
  764. throw TypeError("type "+str(arg.__class__)+" doesn't define __round__ method")
  765. }
  766. if(n===undefined){n=0}
  767. if(!isinstance(n,int)){throw TypeError(
  768. "'"+n.__class__+"' object cannot be interpreted as an integer")}
  769. var mult=Math.pow(10,n)
  770. var res=Number(Math.round(arg*mult)).__truediv__(mult)
  771. if(n==0){return int(res)}else{return float(res)}
  772. }
  773. function set(){
  774. var i=0
  775. if(arguments.length==0){return new $SetClass()}
  776. else if(arguments.length==1){
  777. var arg=arguments[0]
  778. if(isinstance(arg,set)){return arg}
  779. var obj=new $SetClass()
  780. try{
  781. for(var i=0;i<arg.__len__();i++){
  782. obj.items.push(arg.__getitem__(i))
  783. }
  784. return obj
  785. }catch(err){
  786. throw TypeError("'"+arg.__class__.__name__+"' object is not iterable")
  787. }
  788. }else{
  789. throw TypeError("set expected at most 1 argument, got "+arguments.length)
  790. }
  791. }
  792. set.__class__=$type
  793. set.__name__='set'
  794. set.toString=function(){return "<class 'set'>"}
  795. set.__hash__=function(){throw TypeError("unhashable type: 'set'");}
  796. function $SetClass(){
  797. var x=null
  798. var i=null
  799. this.iter=null
  800. this.__class__=set
  801. this.items=[]
  802. }
  803. $SetClass.prototype.toString=function(){
  804. var res="{"
  805. for(var i=0;i<this.items.length;i++){
  806. var x=this.items[i]
  807. if(isinstance(x,str)){res +="'"+x+"'"}
  808. else{res +=x.toString()}
  809. if(i<this.items.length-1){res +=','}
  810. }
  811. return res+'}'
  812. }
  813. $SetClass.prototype.__add__=function(other){
  814. return set(this.items.concat(other.items))
  815. }
  816. $SetClass.prototype.__class__=set
  817. $SetClass.prototype.__contains__=function(item){
  818. for(var i=0;i<this.items.length;i++){
  819. try{if(this.items[i].__eq__(item)){return True}
  820. }catch(err){void(0)}
  821. }
  822. return False
  823. }
  824. $SetClass.prototype.__eq__=function(other){
  825. if(isinstance(other,set)){
  826. if(other.items.length==this.items.length){
  827. for(var i=0;i<this.items.length;i++){
  828. if(this.__contains__(other.items[i])===False){
  829. return False
  830. }
  831. }
  832. return True
  833. }
  834. }
  835. return False
  836. }
  837. $SetClass.prototype.__getattr__=function(attr){
  838. if(this[attr]!==undefined){return this[attr]}
  839. else{throw AttributeError("'set' object has no attribute '"+attr+"'")}
  840. }
  841. $SetClass.prototype.__hash__=set.__hash__
  842. $SetClass.prototype.__in__=function(item){return item.__contains__(this)}
  843. $SetClass.prototype.__len__=function(){return int(this.items.length)}
  844. $SetClass.prototype.__item__=function(i){return this.items[i]}
  845. $SetClass.prototype.__ne__=function(other){return !(this.__eq__(other))}
  846. $SetClass.prototype.__not_in__=function(item){return !(item.__contains__(this))}
  847. $SetClass.prototype.__str__=$SetClass.prototype.toString
  848. $SetClass.prototype.add=function(item){
  849. var i=0
  850. for(i=0;i<this.items.length;i++){
  851. try{if(item.__eq__(this.items[i])){return}}
  852. catch(err){void(0)}
  853. }
  854. this.items.push(item)
  855. }
  856. function setattr(obj,attr,value){
  857. if(!isinstance(attr,str)){throw TypeError("setattr(): attribute name must be string")}
  858. obj[attr]=value
  859. }
  860. function $SliceClass(start,stop,step){
  861. this.__class__=slice
  862. this.start=start
  863. this.stop=stop
  864. this.step=step
  865. }
  866. function slice(){
  867. var $ns=$MakeArgs('slice',arguments,[],{},'args',null)
  868. var args=$ns['args']
  869. if(args.length>3){throw TypeError(
  870. "slice expected at most 3 arguments, got "+args.length)
  871. }
  872. var start=0
  873. var stop=0
  874. var step=1
  875. if(args.length==1){stop=args[0]}
  876. else if(args.length>=2){
  877. start=args[0]
  878. stop=args[1]
  879. }
  880. if(args.length>=3){step=args[2]}
  881. if(step==0){throw ValueError("slice step must not be zero")}
  882. return new $SliceClass(start,stop,step)
  883. }
  884. function sum(iterable,start){
  885. if(start===undefined){start=0}
  886. var res=0
  887. for(var i=start;i<iterable.__len__();i++){
  888. res=res.__add__(iterable.__item__(i))
  889. }
  890. return res
  891. }
  892. function $tuple(arg){return arg}
  893. function tuple(){
  894. var args=new Array(),i=0
  895. for(i=0;i<arguments.length;i++){args.push(arguments[i])}
  896. var obj=list(args)
  897. obj.__class__=tuple
  898. obj.toString=function(){
  899. var res=args.__str__()
  900. res='('+res.substr(1,res.length-2)
  901. if(obj.length===1){res+=','}
  902. return res+')'
  903. }
  904. obj.__hash__=function(){
  905. var x=0x345678
  906. for(var i=0;i < args.length;i++){
  907. var y=args[i].__hash__()
  908. x=(1000003 * x)^ y & 0xFFFFFFFF
  909. }
  910. return x
  911. }
  912. obj.__str__=obj.toString
  913. return obj
  914. }
  915. tuple.__class__=$type
  916. tuple.__name__='tuple'
  917. tuple.__str__=function(){return "<class 'tuple'>"}
  918. tuple.toString=tuple.__str__
  919. function zip(){
  920. var $ns=$MakeArgs('zip',arguments,[],{},'args','kw')
  921. var args=$ns['args']
  922. var kw=$ns['kw']
  923. var rank=0,res=[]
  924. while(true){
  925. var line=[],flag=true
  926. for(var i=0;i<args.length;i++){
  927. var x=args[i].__item__(rank)
  928. if(x===undefined){flag=false;break}
  929. line.push(x)
  930. }
  931. if(!flag){return res}
  932. res.push(line)
  933. rank++
  934. }
  935. }
  936. True=true
  937. False=false
  938. Boolean.prototype.__class__=bool
  939. Boolean.prototype.__eq__=function(other){
  940. if(this.valueOf()){return !!other}else{return !other}
  941. }
  942. Boolean.prototype.__getattr__=function(attr){
  943. if(this[attr]!==undefined){return this[attr]}
  944. else{throw AttributeError("'bool' object has no attribute '"+attr+"'")}
  945. }
  946. Boolean.prototype.__hash__=function(){
  947. if(this.valueOf())return 1
  948. return 0
  949. }
  950. Boolean.prototype.__mul__=function(other){
  951. if(this.valueOf())return other
  952. return 0
  953. }
  954. Boolean.prototype.__add__=function(other){
  955. if(this.valueOf())return other + 1
  956. return other
  957. }
  958. Boolean.prototype.toString=function(){
  959. if(this.valueOf())return "True"
  960. return "False"
  961. }
  962. Boolean.prototype.__str__=Boolean.prototype.toString
  963. function $NoneClass(){
  964. this.__class__=new $class(this,"NoneType")
  965. this.value=null
  966. this.__bool__=function(){return False}
  967. this.__eq__=function(other){return other===None}
  968. this.__getattr__=function(attr){
  969. if(this[attr]!==undefined){return this[attr]}
  970. else{throw AttributeError("'NoneType' object has no attribute '"+attr+"'")}
  971. }
  972. this.__hash__=function(){return 0}
  973. this.__ne__=function(other){return other!==None}
  974. this.__str__=function(){return 'None'}
  975. var comp_ops=['ge','gt','le','lt']
  976. for(var key in $comps){
  977. if(comp_ops.indexOf($comps[key])>-1){
  978. this['__'+$comps[key]+'__']=(function(k){
  979. return function(other){
  980. throw TypeError("unorderable types: NoneType() "+$comps[k]+" "+
  981. other.__class__.__name__)}
  982. })(key)
  983. }
  984. }
  985. for(var func in this){
  986. if(typeof this[func]==='function'){
  987. this[func].__str__=(function(f){
  988. return function(){return "<mthod-wrapper "+f+" of NoneType object>"}
  989. })(func)
  990. }
  991. }
  992. }
  993. None=new $NoneClass()
  994. Exception=function(msg){
  995. var err=Error()
  996. err.info=''
  997. if(document.$debug && msg.split('\n').length==1){
  998. var module=document.$line_info[1]
  999. var line_num=document.$line_info[0]
  1000. var lines=document.$py_src[module].split('\n')
  1001. err.info +="\nmodule '"+module+"' line "+line_num
  1002. err.info +='\n'+lines[line_num-1]
  1003. }
  1004. err.message=msg + err.info
  1005. err.args=tuple(msg.split('\n')[0])
  1006. err.__str__=function(){return msg}
  1007. err.toString=err.__str__
  1008. err.__getattr__=function(attr){return this[attr]}
  1009. err.__name__='Exception'
  1010. err.__class__=Exception
  1011. err.py_error=true
  1012. __BRYTHON__.exception_stack.push(err)
  1013. return err
  1014. }
  1015. Exception.__str__=function(){return "<class 'Exception'>"}
  1016. Exception.__class__=$type
  1017. function $make_exc(name){
  1018. var $exc=(Exception+'').replace(/Exception/g,name)
  1019. eval(name+'='+$exc)
  1020. eval(name+'.__str__ = function(){return "<class '+"'"+name+"'"+'>"}')
  1021. eval(name+'.__class__=$type')
  1022. }
  1023. var $errors=['AssertionError','AttributeError','EOFError','FloatingPointError',
  1024. 'GeneratorExit','ImportError','IndexError','KeyError','KeyboardInterrupt',
  1025. 'NameError','NotImplementedError','OSError','OverflowError','ReferenceError',
  1026. 'RuntimeError','StopIteration','SyntaxError','IndentationError','TabError',
  1027. 'SystemError','SystemExit','TypeError','UnboundLocalError','ValueError',
  1028. 'ZeroDivisionError','IOError']
  1029. for(var i=0;i<$errors.length;i++){$make_exc($errors[i])}
  1030. list=function(){
  1031. function $list(){
  1032. var args=new Array()
  1033. for(var i=0;i<arguments.length;i++){args.push(arguments[i])}
  1034. return new $ListClass(args)
  1035. }
  1036. function list(){
  1037. if(arguments.length===0){return[]}
  1038. else if(arguments.length>1){
  1039. throw TypeError("list() takes at most 1 argument ("+arguments.length+" given)")
  1040. }
  1041. var res=[]
  1042. list.__init__(res,arguments[0])
  1043. return res
  1044. }
  1045. list.__add__=function(self,other){
  1046. var res=self.valueOf().concat(other.valueOf())
  1047. if(isinstance(self,tuple)){res=tuple.apply(self,res)}
  1048. return res
  1049. }
  1050. list.__class__=$type
  1051. list.__contains__=function(self,item){
  1052. for(var i=0;i<self.length;i++){
  1053. try{if(self[i].__eq__(item)){return true}
  1054. }catch(err){void(0)}
  1055. }
  1056. return false
  1057. }
  1058. list.__delitem__=function(self,arg){
  1059. if(isinstance(arg,int)){
  1060. var pos=arg
  1061. if(arg<0){pos=self.length+pos}
  1062. if(pos>=0 && pos<self.length){
  1063. self.splice(pos,1)
  1064. return
  1065. }
  1066. else{throw IndexError('list index out of range')}
  1067. }else if(isinstance(arg,slice)){
  1068. var start=arg.start || 0
  1069. var stop=arg.stop || self.length
  1070. var step=arg.step || 1
  1071. if(start<0){start=self.length+start}
  1072. if(stop<0){stop=self.length+stop}
  1073. var res=[],i=null
  1074. if(step>0){
  1075. if(stop>start){
  1076. for(i=start;i<stop;i+=step){
  1077. if(self[i]!==undefined){res.push(i)}
  1078. }
  1079. }
  1080. }else{
  1081. if(stop<start){
  1082. for(i=start;i>stop;i+=step.value){
  1083. if(self[i]!==undefined){res.push(i)}
  1084. }
  1085. res.reverse()
  1086. }
  1087. }
  1088. for(var i=res.length-1;i>=0;i--){
  1089. self.splice(res[i],1)
  1090. }
  1091. return
  1092. }else{
  1093. throw TypeError('list indices must be integer, not '+str(arg.__class__))
  1094. }
  1095. }
  1096. list.__eq__=function(self,other){
  1097. if(other===undefined){
  1098. return self===list
  1099. }
  1100. if(isinstance(other,self.__class__)){
  1101. if(other.length==self.length){
  1102. for(var i=0;i<self.length;i++){
  1103. if(!self[i].__eq__(other[i])){return False}
  1104. }
  1105. return True
  1106. }
  1107. }
  1108. return False
  1109. }
  1110. list.__getattr__=function(attr){
  1111. switch(attr){
  1112. case '__class__':
  1113. var res=function(){return list}
  1114. res.__str__=list.__str__
  1115. return res
  1116. case '__name__':
  1117. var res=function(){
  1118. throw AttributeError(" 'list' object has no attribute '__name__'")
  1119. }
  1120. res.__str__=function(){return 'list'}
  1121. return res
  1122. default:
  1123. return list[attr]
  1124. }
  1125. }
  1126. list.__getitem__=function(self,arg){
  1127. if(isinstance(arg,int)){
  1128. var items=self.valueOf()
  1129. var pos=arg
  1130. if(arg<0){pos=items.length+pos}
  1131. if(pos>=0 && pos<items.length){return items[pos]}
  1132. else{
  1133. throw IndexError('list index out of range')
  1134. }
  1135. }else if(isinstance(arg,slice)){
  1136. var step=arg.step===None ? 1 : arg.step
  1137. if(step>0){
  1138. var start=arg.start===None ? 0 : arg.start
  1139. var stop=arg.stop===None ? self.__len__(): arg.stop
  1140. }else{
  1141. var start=arg.start===None ? self.__len__()-1 : arg.start
  1142. var stop=arg.stop===None ? 0 : arg.stop
  1143. }
  1144. if(start<0){start=int(self.length+start)}
  1145. if(stop<0){stop=self.length+stop}
  1146. var res=[],i=null,items=self.valueOf()
  1147. if(step>0){
  1148. if(stop<=start){return res}
  1149. else{
  1150. for(i=start;i<stop;i+=step){
  1151. if(items[i]!==undefined){res.push(items[i])}
  1152. }
  1153. return res
  1154. }
  1155. }else{
  1156. if(stop>=start){return res}
  1157. else{
  1158. for(i=start;i>=stop;i+=step){
  1159. if(items[i]!==undefined){res.push(items[i])}
  1160. }
  1161. return res
  1162. }
  1163. }
  1164. }else if(isinstance(arg,bool)){
  1165. return self.__getitem__(int(arg))
  1166. }else{
  1167. throw TypeError('list indices must be integer, not '+str(arg.__class__))
  1168. }
  1169. }
  1170. list.__hash__=function(self){throw TypeError("unhashable type: 'list'")}
  1171. list.__in__=function(self,item){return item.__contains__(self)}
  1172. list.__init__=function(self){
  1173. while(self.__len__()>0){self.pop()}
  1174. if(arguments.length===1){return}
  1175. var arg=arguments[1]
  1176. for(var i=0;i<arg.__len__();i++){self.push(arg.__item__(i))}
  1177. }
  1178. list.__item__=function(self,i){return self[i]}
  1179. list.__len__=function(self){return self.length}
  1180. list.__mul__=function(self,other){
  1181. if(isinstance(other,int)){return other.__mul__(self)}
  1182. else{throw TypeError("can't multiply sequence by non-int of type '"+other.__name+"'")}
  1183. }
  1184. list.__name__='list'
  1185. list.__ne__=function(self,other){return !self.__eq__(other)}
  1186. list.__next__=function(self){
  1187. if(self.iter===null){self.iter=0}
  1188. if(self.iter<self.valueOf().length){
  1189. self.iter++
  1190. return self.valueOf()[self.iter-1]
  1191. }else{
  1192. self.iter=null
  1193. throw StopIteration('')
  1194. }
  1195. }
  1196. list.__not_in__=function(self,item){return !item.__contains__(self)}
  1197. list.__setitem__=function(self,arg,value){
  1198. if(isinstance(arg,int)){
  1199. var pos=arg
  1200. if(arg<0){pos=self.length+pos}
  1201. if(pos>=0 && pos<self.length){self[pos]=value}
  1202. else{throw IndexError('list index out of range')}
  1203. }else if(isinstance(arg,slice)){
  1204. var start=arg.start===None ? 0 : arg.start
  1205. var stop=arg.stop===None ? self.__len__(): arg.stop
  1206. var step=arg.step===None ? 1 : arg.step
  1207. if(start<0){start=self.length+start}
  1208. if(stop<0){stop=self.length+stop}
  1209. self.splice(start,stop-start)
  1210. if(hasattr(value,'__item__')){
  1211. var $temp=list(value)
  1212. for(var i=$temp.length-1;i>=0;i--){
  1213. self.splice(start,0,$temp[i])
  1214. }
  1215. }else{
  1216. throw TypeError("can only assign an iterable")
  1217. }
  1218. }else{
  1219. throw TypeError('list indices must be integer, not '+str(arg.__class__))
  1220. }
  1221. }
  1222. list.__str__=function(self){
  1223. if(self===undefined){return "<class 'list'>"}
  1224. var res="[",items=self.valueOf()
  1225. for(var i=0;i<self.length;i++){
  1226. var x=self[i]
  1227. if(isinstance(x,str)){res +="'"+x+"'"}
  1228. else if(x['__str__']!==undefined){res +=x.__str__()}
  1229. else{res +=x.toString()}
  1230. if(i<self.length-1){res +=','}
  1231. }
  1232. return res+']'
  1233. }
  1234. list.append=function(self,other){self.push(other)}
  1235. list.count=function(self,elt){
  1236. var res=0
  1237. for(var i=0;i<self.length;i++){
  1238. if(self[i].__eq__(elt)){res++}
  1239. }
  1240. return res
  1241. }
  1242. list.extend=function(self,other){
  1243. if(arguments.length!=2){throw TypeError(
  1244. "extend() takes exactly one argument ("+arguments.length+" given)")}
  1245. try{
  1246. for(var i=0;i<other.__len__();i++){self.push(other.__item__(i))}
  1247. }catch(err){
  1248. throw TypeError("object is not iterable")
  1249. }
  1250. }
  1251. list.index=function(self,elt){
  1252. for(var i=0;i<self.length;i++){
  1253. if(self[i].__eq__(elt)){return i}
  1254. }
  1255. throw ValueError(str(elt)+" is not in list")
  1256. }
  1257. list.insert=function(self,i,item){self.splice(i,0,item)}
  1258. list.remove=function(self,elt){
  1259. for(var i=0;i<self.length;i++){
  1260. if(self[i].__eq__(elt)){
  1261. self.splice(i,1)
  1262. return
  1263. }
  1264. }
  1265. throw ValueError(str(elt)+" is not in list")
  1266. }
  1267. list.pop=function(self,pos){
  1268. if(pos===undefined){
  1269. var res=self[self.length-1]
  1270. self.splice(self.length-1,1)
  1271. return res
  1272. }else if(arguments.length==2){
  1273. if(isinstance(pos,int)){
  1274. var res=self[pos]
  1275. self.splice(pos,1)
  1276. return res
  1277. }else{
  1278. throw TypeError(pos.__class__+" object cannot be interpreted as an integer")
  1279. }
  1280. }else{
  1281. throw TypeError("pop() takes at most 1 argument ("+(arguments.length-1)+' given)')
  1282. }
  1283. }
  1284. list.reverse=function(self){
  1285. for(var i=0;i<parseInt(self.length/2);i++){
  1286. var buf=self[i]
  1287. self[i]=self[self.length-i-1]
  1288. self[self.length-i-1]=buf
  1289. }
  1290. }
  1291. function $partition(arg,array,begin,end,pivot)
  1292. {
  1293. var piv=array[pivot]
  1294. array.swap(pivot, end-1)
  1295. var store=begin
  1296. for(var ix=begin;ix<end-1;++ix){
  1297. if(arg(array[ix]).__le__(arg(piv))){
  1298. array.swap(store, ix)
  1299. ++store
  1300. }
  1301. }
  1302. array.swap(end-1, store)
  1303. return store
  1304. }
  1305. Array.prototype.swap=function(a, b)
  1306. {
  1307. var tmp=this[a]
  1308. this[a]=this[b]
  1309. this[b]=tmp
  1310. }
  1311. function $qsort(arg,array, begin, end)
  1312. {
  1313. if(end-1>begin){
  1314. var pivot=begin+Math.floor(Math.random()*(end-begin))
  1315. pivot=$partition(arg,array, begin, end, pivot)
  1316. $qsort(arg,array, begin, pivot)
  1317. $qsort(arg,array, pivot+1, end)
  1318. }
  1319. }
  1320. list.sort=function(self){
  1321. var func=function(x){return x}
  1322. var reverse=false
  1323. for(var i=1;i<arguments.length;i++){
  1324. var arg=arguments[i]
  1325. if(isinstance(arg,$Kw)){
  1326. if(arg.name==='key'){func=arg.value}
  1327. else if(arg.name==='reverse'){reverse=arg.value}
  1328. }
  1329. }
  1330. if(self.length==0){return}
  1331. $qsort(func,self,0,self.length)
  1332. if(reverse){list.reverse(self)}
  1333. }
  1334. list.toString=list.__str__
  1335. function $ListClass(items){
  1336. var x=null,i=null
  1337. this.iter=null
  1338. this.__class__=list
  1339. this.items=items
  1340. }
  1341. for(var attr in list){
  1342. if(typeof list[attr]==='function'){list[attr].__str__=function(){return "<list method "+attr+">"}}
  1343. var func=(function(attr){
  1344. return function(){
  1345. var args=[this]
  1346. for(var i=0;i<arguments.length;i++){args.push(arguments[i])}
  1347. return list[attr].apply(this,args)
  1348. }
  1349. })(attr)
  1350. func.__str__=(function(attr){
  1351. return function(){return "<method-wrapper '"+attr+"' of list object>"}
  1352. })(attr)
  1353. Array.prototype[attr]=func
  1354. }
  1355. Array.prototype.__class__=list
  1356. Array.prototype.__getattr__=function(attr){
  1357. if(attr==='__class__'){return this.__class__}
  1358. if(list[attr]===undefined){
  1359. throw AttributeError("'"+this.__class__.__name__+"' object has no attribute '"+attr+"'")
  1360. }
  1361. var obj=this
  1362. var res=function(){
  1363. var args=[obj]
  1364. for(var i=0;i<arguments.length;i++){args.push(arguments[i])}
  1365. return list[attr].apply(obj,args)
  1366. }
  1367. res.__str__=function(){return "<built-in method "+attr+" of "+this.__class__.__name__+" object>"}
  1368. return res
  1369. }
  1370. return list
  1371. }()
  1372. str=function(){
  1373. function str(arg){
  1374. if(arg===undefined){return '<undefined>'}
  1375. else if(arg.__str__!==undefined){return arg.__str__()}
  1376. else if(arg.__getattr__('__str__')!==undefined){
  1377. return arg.__getattr__('__str__')()
  1378. }else{return arg.toString()}
  1379. }
  1380. str.__name__='str'
  1381. str.__str__=function(){return "<class 'str'>"}
  1382. str.toString=str.__str__
  1383. str.__add__=function(self,other){
  1384. if(!(typeof other==="string")){
  1385. try{return other.__radd__(self)}
  1386. catch(err){throw TypeError(
  1387. "Can't convert "+other.__class__+" to str implicitely")}
  1388. }else{
  1389. return self+other
  1390. }
  1391. }
  1392. str.__class__=$type
  1393. str.__contains__=function(self,item){
  1394. if(!(typeof item==="string")){throw TypeError(
  1395. "'in <string>' requires string as left operand, not "+item.__class__)}
  1396. var nbcar=item.length
  1397. for(var i=0;i<self.length;i++){
  1398. if(self.substr(i,nbcar)==item){return True}
  1399. }
  1400. return False
  1401. }
  1402. str.__eq__=function(self,other){
  1403. if(other===undefined){
  1404. return self===str
  1405. }
  1406. return other===self.valueOf()
  1407. }
  1408. str.__getattr__=function(attr){return this[attr]}
  1409. str.__getitem__=function(self,arg){
  1410. if(isinstance(arg,int)){
  1411. var pos=arg
  1412. if(arg<0){pos=self.length+pos}
  1413. if(pos>=0 && pos<self.length){return self.charAt(pos)}
  1414. else{throw IndexError('string index out of range')}
  1415. }else if(isinstance(arg,slice)){
  1416. var step=arg.step===None ? 1 : arg.step
  1417. if(step>0){
  1418. var start=arg.start===None ? 0 : arg.start
  1419. var stop=arg.stop===None ? self.__len__(): arg.stop
  1420. }else{
  1421. var start=arg.start===None ? self.__len__()-1 : arg.start
  1422. var stop=arg.stop===None ? 0 : arg.stop
  1423. }
  1424. if(start<0){start=self.length+start}
  1425. if(stop<0){stop=self.length+stop}
  1426. var res='',i=null
  1427. if(step>0){
  1428. if(stop<=start){return ''}
  1429. else{
  1430. for(i=start;i<stop;i+=step){
  1431. res +=self.charAt(i)
  1432. }
  1433. }
  1434. }else{
  1435. if(stop>=start){return ''}
  1436. else{
  1437. for(i=start;i>=stop;i+=step){
  1438. res +=self.charAt(i)
  1439. }
  1440. }
  1441. }
  1442. return res
  1443. }else if(isinstance(arg,bool)){
  1444. return self.__getitem__(int(arg))
  1445. }
  1446. }
  1447. str.__hash__=function(self){
  1448. var hash=1
  1449. for(var i=0;i < self.length;i++){
  1450. hash=(101*hash + self.charCodeAt(i))& 0xFFFFFFFF
  1451. }
  1452. return hash
  1453. }
  1454. str.__in__=function(self,item){return item.__contains__(self.valueOf())}
  1455. str.__item__=function(self,i){return self.charAt(i)}
  1456. str.__len__=function(self){return self.length}
  1457. str.__mod__=function(self,args){
  1458. var flags=$List2Dict('#','0','-',' ','+')
  1459. var ph=[]
  1460. function format(s){
  1461. var conv_flags='([#\\+\\- 0])*'
  1462. var conv_types='[diouxXeEfFgGcrsa%]'
  1463. var re=new RegExp('\\%(\\(.+\\))*'+conv_flags+'(\\*|\\d*)(\\.\\*|\\.\\d*)*(h|l|L)*('+conv_types+'){1}')
  1464. var res=re.exec(s)
  1465. this.is_format=true
  1466. if(!res){this.is_format=false;return}
  1467. this.src=res[0]
  1468. if(res[1]){this.mapping_key=str(res[1].substr(1,res[1].length-2))}
  1469. else{this.mapping_key=null}
  1470. this.flag=res[2]
  1471. this.min_width=res[3]
  1472. this.precision=res[4]
  1473. this.length_modifier=res[5]
  1474. this.type=res[6]
  1475. this.toString=function(){
  1476. var res='type '+this.type+' key '+this.mapping_key+' min width '+this.min_width
  1477. res +=' precision '+this.precision
  1478. return res
  1479. }
  1480. this.format=function(src){
  1481. if(this.mapping_key!==null){
  1482. if(!isinstance(src,dict)){throw TypeError("format requires a mapping")}
  1483. src=src.__getitem__(this.mapping_key)
  1484. }
  1485. if(this.type=="s"){return str(src)}
  1486. else if(this.type=="i" || this.type=="d"){
  1487. if(!isinstance(src,[int,float])){throw TypeError(
  1488. "%"+this.type+" format : a number is required, not "+str(src.__class__))}
  1489. return str(int(src))
  1490. }else if(this.type=="f" || this.type=="F"){
  1491. if(!isinstance(src,[int,float])){throw TypeError(
  1492. "%"+this.type+" format : a number is required, not "+str(src.__class__))}
  1493. return str(float(src))
  1494. }
  1495. }
  1496. }
  1497. var elts=[]
  1498. var pos=0, start=0, nb_repl=0
  1499. var val=self.valueOf()
  1500. while(pos<val.length){
  1501. if(val.charAt(pos)=='%'){
  1502. var f=new format(val.substr(pos))
  1503. if(f.is_format && f.type!=="%"){
  1504. elts.push(val.substring(start,pos))
  1505. elts.push(f)
  1506. start=pos+f.src.length
  1507. pos=start
  1508. nb_repl++
  1509. }else{pos++}
  1510. }else{pos++}
  1511. }
  1512. elts.push(val.substr(start))
  1513. if(!isinstance(args,tuple)){
  1514. if(nb_repl>1){throw TypeError('not enough arguments for format string')}
  1515. else{elts[1]=elts[1].format(args)}
  1516. }else{
  1517. if(nb_repl==args.length){
  1518. for(var i=0;i<args.length;i++){
  1519. var fmt=elts[1+2*i]
  1520. elts[1+2*i]=fmt.format(args[i])
  1521. }
  1522. }else if(nb_repl<args.length){throw TypeError(
  1523. "not all arguments converted during string formatting")
  1524. }else{throw TypeError('not enough arguments for format string')}
  1525. }
  1526. var res=''
  1527. for(var i=0;i<elts.length;i++){res+=elts[i]}
  1528. res=res.replace(/%%/g,'%')
  1529. return res
  1530. }
  1531. str.__mul__=function(self,other){
  1532. if(!isinstance(other,int)){throw TypeError(
  1533. "Can't multiply sequence by non-int of type '"+str(other.__class__)+"'")}
  1534. $res=''
  1535. for(var i=0;i<other;i++){$res+=self.valueOf()}
  1536. return $res
  1537. }
  1538. str.__ne__=function(self,other){return other!==self.valueOf()}
  1539. str.__next__=function(self){
  1540. if(self.iter==null){self.iter==0}
  1541. if(self.iter<self.value.length){
  1542. self.iter++
  1543. return str(self.value.charAt(self.iter-1))
  1544. }else{
  1545. self.iter=null
  1546. throw StopIteration()
  1547. }
  1548. }
  1549. str.__not_in__=function(self,item){return !item.__contains__(self.valueOf())}
  1550. str.__setattr__=function(self,attr,value){setattr(self,attr,value)}
  1551. self.__setitem__=function(self,attr,value){
  1552. throw TypeError("'str' object does not support item assignment")
  1553. }
  1554. str.__str__=function(self){
  1555. if(self===undefined){return "<class 'str'>"}
  1556. else{return self.toString()}
  1557. }
  1558. var $comp_func=function(self,other){
  1559. if(typeof other !=="string"){throw TypeError(
  1560. "unorderable types: 'str' > "+other.__class__+"()")}
  1561. return self > other
  1562. }
  1563. $comp_func +=''
  1564. var $comps={'>':'gt','>=':'ge','<':'lt','<=':'le'}
  1565. for($op in $comps){
  1566. eval("str.__"+$comps[$op]+'__ = '+$comp_func.replace(/>/gm,$op))
  1567. }
  1568. var $notimplemented=function(self,other){
  1569. throw TypeError(
  1570. "unsupported operand types for OPERATOR: '"+str(self.__class__)+"' and '"+str(other.__class__)+"'")
  1571. }
  1572. $notimplemented +=''
  1573. for($op in $operators){
  1574. var $opfunc='__'+$operators[$op]+'__'
  1575. if(!($opfunc in str)){
  1576. eval('str.'+$opfunc+"="+$notimplemented.replace(/OPERATOR/gm,$op))
  1577. }
  1578. }
  1579. str.capitalize=function(self){
  1580. if(self.length==0){return ''}
  1581. return self.charAt(0).toUpperCase()+self.substr(1).toLowerCase()
  1582. }
  1583. str.center=function(self,width,fillchar){
  1584. if(fillchar===undefined){fillchar=' '}else{fillchar=fillchar}
  1585. if(width<=self.length){return self}
  1586. else{
  1587. var pad=parseInt((width-self.length)/2)
  1588. res=''
  1589. for(var i=0;i<pad;i++){res+=fillchar}
  1590. res +=self
  1591. for(var i=0;i<pad;i++){res+=fillchar}
  1592. if(res.length<width){res +=fillchar}
  1593. return res
  1594. }
  1595. }
  1596. str.count=function(self,elt){
  1597. if(!(typeof elt==="string")){throw TypeError(
  1598. "Can't convert '"+str(elt.__class__)+"' object to str implicitly")}
  1599. var res=0
  1600. for(var i=0;i<self.length-elt.length+1;i++){
  1601. if(self.substr(i,elt.length)===elt){res++}
  1602. }
  1603. return res
  1604. }
  1605. str.endswith=function(self){
  1606. var args=[]
  1607. for(var i=1;i<arguments.length;i++){args.push(arguments[i])}
  1608. var $ns=$MakeArgs("str.endswith",args,['suffix'],
  1609. {'start':null,'end':null},null,null)
  1610. var suffixes=$ns['suffix']
  1611. if(!isinstance(suffixes,tuple)){suffixes=[suffixes]}
  1612. var start=$ns['start']|| 0
  1613. var end=$ns['end']|| self.length-1
  1614. var s=self.substr(start,end+1)
  1615. for(var i=0;i<suffixes.length;i++){
  1616. suffix=suffixes[i]
  1617. if(suffix.length<=s.length &&
  1618. s.substr(s.length-suffix.length)==suffix){return True}
  1619. }
  1620. return False
  1621. }
  1622. str.find=function(self){
  1623. var $ns=$MakeArgs("str.find",arguments,['self','sub'],
  1624. {'start':0,'end':self.length},null,null)
  1625. var sub=$ns['sub'],start=$ns['start'],end=$ns['end']
  1626. if(!isinstance(sub,str)){throw TypeError(
  1627. "Can't convert '"+str(sub.__class__)+"' object to str implicitly")}
  1628. if(!isinstance(start,int)||!isinstance(end,int)){throw TypeError(
  1629. "slice indices must be integers or None or have an __index__ method")}
  1630. var s=self.substring(start,end)
  1631. var escaped=list("[.*+?|()$^")
  1632. var esc_sub=''
  1633. for(var i=0;i<sub.length;i++){
  1634. if(escaped.indexOf(sub.charAt(i))>-1){esc_sub +='\\'}
  1635. esc_sub +=sub.charAt(i)
  1636. }
  1637. var res=s.search(esc_sub)
  1638. if(res==-1){return -1}
  1639. else{return start+res}
  1640. }
  1641. str.index=function(self){
  1642. var res=str.find.apply(self,arguments)
  1643. if(res===-1){throw ValueError("substring not found")}
  1644. else{return res}
  1645. }
  1646. str.join=function(self,iterable){
  1647. if(!'__item__' in iterable){throw TypeError(
  1648. "'"+str(iterable.__class__)+"' object is not iterable")}
  1649. var res='',count=0
  1650. for(var i=0;i<iterable.length;i++){
  1651. var obj2=iterable.__getitem__(i)
  1652. if(!isinstance(obj2,str)){throw TypeError(
  1653. "sequence item "+count+": expected str instance, "+obj2.__class__+"found")}
  1654. res +=obj2+self
  1655. count++
  1656. }
  1657. if(count==0){return ''}
  1658. res=res.substr(0,res.length-self.length)
  1659. return res
  1660. }
  1661. str.lower=function(self){return self.toLowerCase()}
  1662. str.lstrip=function(self,x){
  1663. var pattern=null
  1664. if(x==undefined){pattern="\\s*"}
  1665. else{pattern="["+x+"]*"}
  1666. var sp=new RegExp("^"+pattern)
  1667. return self.replace(sp,"")
  1668. }
  1669. function $re_escape(str)
  1670. {
  1671. var specials="[.*+?|()$^"
  1672. for(var i=0;i<specials.length;i++){
  1673. var re=new RegExp('\\'+specials.charAt(i),'g')
  1674. str=str.replace(re, "\\"+specials.charAt(i))
  1675. }
  1676. return str
  1677. }
  1678. str.replace=function(self,old,_new,count){
  1679. if(count!==undefined){
  1680. if(!isinstance(count,[int,float])){throw TypeError(
  1681. "'"+str(count.__class__)+"' object cannot be interpreted as an integer")}
  1682. var re=new RegExp($re_escape(old),'g')
  1683. var res=self.valueOf()
  1684. while(count>0){
  1685. if(self.search(re)==-1){return res}
  1686. res=res.replace(re,_new)
  1687. count--
  1688. }
  1689. return res
  1690. }else{
  1691. var re=new RegExp($re_escape(old),"g")
  1692. return self.replace(re,_new)
  1693. }
  1694. }
  1695. str.rfind=function(self){
  1696. var $ns=$MakeArgs("str.find",arguments,['self','sub'],
  1697. {'start':0,'end':self.length},null,null)
  1698. var sub=$ns['sub'],start=$ns['start'],end=$ns['end']
  1699. if(!isinstance(sub,str)){throw TypeError(
  1700. "Can't convert '"+str(sub.__class__)+"' object to str implicitly")}
  1701. if(!isinstance(start,int)||!isinstance(end,int)){throw TypeError(
  1702. "slice indices must be integers or None or have an __index__ method")}
  1703. var s=self.substring(start,end)
  1704. var reversed=''
  1705. for(var i=s.length-1;i>=0;i--){reversed +=s.charAt(i)}
  1706. var res=reversed.search(sub)
  1707. if(res==-1){return -1}
  1708. else{return start+s.length-1-res}
  1709. }
  1710. str.rindex=function(){
  1711. var res=str.rfind.apply(this,arguments)
  1712. if(res==-1){throw ValueError("substring not found")}
  1713. else{return res}
  1714. }
  1715. str.rstrip=function(self,x){
  1716. if(x==undefined){pattern="\\s*"}
  1717. else{pattern="["+x+"]*"}
  1718. sp=new RegExp(pattern+'$')
  1719. return str(self.replace(sp,""))
  1720. }
  1721. str.split=function(self){
  1722. var args=[]
  1723. for(var i=1;i<arguments.length;i++){args.push(arguments[i])}
  1724. var $ns=$MakeArgs("str.split",args,[],{},'args','kw')
  1725. var sep=null,maxsplit=-1
  1726. if($ns['args'].length>=1){sep=$ns['args'][0]}
  1727. if($ns['args'].length==2){maxsplit=$ns['args'][1]}
  1728. if(sep===null){var re=/\s/}
  1729. else{
  1730. var escaped=list('*.[]()|$^')
  1731. var esc_sep=''
  1732. for(var i=0;i<sep.length;i++){
  1733. if(escaped.indexOf(sep.charAt(i))>-1){esc_sep +='\\'}
  1734. esc_sep +=sep.charAt(i)
  1735. }
  1736. var re=new RegExp(esc_sep)
  1737. }
  1738. if(maxsplit==-1)return self.split(re,maxsplit)
  1739. var l=self.split(re,-1)
  1740. var a=l.splice(0, maxsplit)
  1741. var b=l.splice(maxsplit-1, l.length)
  1742. a.push(b.join(sep))
  1743. return a
  1744. }
  1745. str.splitlines=function(self){return str.split(self,'\n')}
  1746. str.startswith=function(self){
  1747. $ns=$MakeArgs("str.startswith",arguments,['self','prefix'],
  1748. {'start':null,'end':null},null,null)
  1749. var prefixes=$ns['prefix']
  1750. if(!isinstance(prefixes,tuple)){prefixes=[prefixes]}
  1751. var start=$ns['start']|| 0
  1752. var end=$ns['end']|| self.length-1
  1753. var s=self.substr(start,end+1)
  1754. for(var i=0;i<prefixes.length;i++){
  1755. prefix=prefixes[i]
  1756. if(prefix.length<=s.length &&
  1757. s.substr(0,prefix.length)==prefix){return True}
  1758. }
  1759. return False
  1760. }
  1761. str.strip=function(self,x){
  1762. if(x==undefined){x="\\s"}
  1763. pattern="["+x+"]"
  1764. return str.rstrip(str.lstrip(self,x),x)
  1765. }
  1766. str.upper=function(self){return self.toUpperCase()}
  1767. String.prototype.__class__=str
  1768. String.prototype.__getattr__=function(attr){
  1769. if(attr==='__class__'){return str}
  1770. if(str[attr]===undefined){throw AttributeError("'str' object has no attribute '"+attr+"'")}
  1771. var obj=this
  1772. var res=function(){
  1773. var args=[obj]
  1774. for(var i=0;i<arguments.length;i++){args.push(arguments[i])}
  1775. return str[attr].apply(obj,args)
  1776. }
  1777. res.__str__=function(){return "<built-in method "+attr+" of str object>"}
  1778. return res
  1779. }
  1780. for(var attr in str){
  1781. if(String.prototype[attr]===undefined){
  1782. String.prototype[attr]=(function(attr){
  1783. return function(){
  1784. var args=[this]
  1785. for(var i=0;i<arguments.length;i++){args.push(arguments[i])}
  1786. return str[attr].apply(this,args)
  1787. }
  1788. })(attr)
  1789. }
  1790. }
  1791. return str
  1792. }()
  1793. function $importer(){
  1794. if(window.XMLHttpRequest){
  1795. var $xmlhttp=new XMLHttpRequest()
  1796. }else{
  1797. var $xmlhttp=new ActiveXObject("Microsoft.XMLHTTP")
  1798. }
  1799. var fake_qs='?foo='+Math.random().toString(36).substr(2,8)
  1800. var timer=setTimeout(function(){
  1801. $xmlhttp.abort()
  1802. throw ImportError("No module named '"+module+"'")}, 5000)
  1803. return[$xmlhttp,fake_qs,timer]
  1804. }
  1805. function $import_js(module,alias,names){
  1806. var imp=$importer()
  1807. var $xmlhttp=imp[0],fake_qs=imp[1],timer=imp[2],res=null
  1808. $xmlhttp.onreadystatechange=function(){
  1809. if($xmlhttp.readyState==4){
  1810. window.clearTimeout(timer)
  1811. if($xmlhttp.status==200 || $xmlhttp.status==0){res=$xmlhttp.responseText}
  1812. else{
  1813. res=Error()
  1814. res.name='NotFoundError'
  1815. res.message="No module named '"+module+"'"
  1816. }
  1817. }
  1818. }
  1819. $xmlhttp.open('GET',__BRYTHON__.brython_path+'libs/'+module+'.js'+fake_qs,false)
  1820. if('overrideMimeType' in $xmlhttp){$xmlhttp.overrideMimeType("text/plain")}
  1821. $xmlhttp.send()
  1822. if(res.constructor===Error){throw res}
  1823. try{
  1824. eval(res)
  1825. if(eval('$module')===undefined){
  1826. throw ImportError("name '$module' is not defined in module")
  1827. }
  1828. if(names===undefined){
  1829. if(alias===undefined){alias=module}
  1830. eval(alias+'=$module')
  1831. eval(alias+'.__class__ = $type')
  1832. eval(alias+'.__str__ = function(){return "<module \''+module+"'>\"}")
  1833. eval(alias+'.__file__ = "' +__BRYTHON__.brython_path+'libs/'+ module + '.js"')
  1834. }else{
  1835. if(names.length===1 && names[0]==='*'){
  1836. for(var name in $module){
  1837. if(name.substr(0,1)==='_'){continue}
  1838. eval(name+'=$module[name]')
  1839. }
  1840. }else{
  1841. if(alias !==undefined){
  1842. for(var i=0;i<names.length;i++){
  1843. if(alias[i]!==undefined){
  1844. eval(alias[i]+'=$module[names[i]]')
  1845. }else{
  1846. eval(names[i]+'=$module[names[i]]')
  1847. }
  1848. }
  1849. }else{
  1850. for(var i=0;i<names.length;i++){
  1851. eval(names[i]+'=$module[names[i]]')
  1852. }
  1853. }
  1854. }
  1855. }
  1856. }catch(err){throw ImportError(err.message)}
  1857. }
  1858. function $import_py_search_path(module,alias,names){
  1859. var modnames=[module, '__init__']
  1860. for(var i=0;i<__BRYTHON__.path.length;i++){
  1861. for(var j=0;j < modnames.length;j++){
  1862. var path=__BRYTHON__.path[i]
  1863. if(modnames[j]=='__init__')path +='/' + module
  1864. try{
  1865. $import_py(module,alias,names,path)
  1866. return
  1867. }catch(err){
  1868. if(err.name!=='ImportError'){throw err}
  1869. }
  1870. }
  1871. }
  1872. throw ImportError("No module named '"+module+"'")
  1873. }
  1874. function $import_py(module,alias,names,path){
  1875. var imp=$importer()
  1876. var $xmlhttp=imp[0],fake_qs=imp[1],timer=imp[2],res=null
  1877. $xmlhttp.onreadystatechange=function(){
  1878. if($xmlhttp.readyState==4){
  1879. window.clearTimeout(timer)
  1880. if($xmlhttp.status==200 || $xmlhttp.status==0){res=$xmlhttp.responseText}
  1881. else{
  1882. res=Error('ImportError',"No module named '"+module+"'")
  1883. }
  1884. }
  1885. }
  1886. var module_path=path+'/'+module+'.py'
  1887. $xmlhttp.open('GET', module_path+fake_qs,false)
  1888. $xmlhttp.send()
  1889. if(res.constructor===Error){res.name='ImportError';throw res}
  1890. document.$py_module_path[module]=module_path
  1891. var root=__BRYTHON__.py2js(res,module)
  1892. var body=root.children
  1893. root.children=[]
  1894. var mod_node=new $Node('expression')
  1895. if(names!==undefined){alias='$module'}
  1896. new $NodeJSCtx(mod_node,alias+'=(function()')
  1897. root.insert(0,mod_node)
  1898. mod_node.children=body
  1899. var mod_names=[]
  1900. for(var i=1;i<mod_node.children.length;i++){
  1901. var node=mod_node.children[i]
  1902. var ctx=node.get_ctx().tree[0]
  1903. if(ctx.type==='def'||ctx.type==='class'){
  1904. if(mod_names.indexOf(ctx.name)===-1){mod_names.push(ctx.name)}
  1905. }else if(ctx.type==='assign'){
  1906. var left=ctx.tree[0]
  1907. if(left.type==='expr'&&left.tree[0].type==='id'&&left.tree[0].tree.length===0){
  1908. var id_name=left.tree[0].value
  1909. if(mod_names.indexOf(id_name)===-1){mod_names.push(id_name)}
  1910. }
  1911. }
  1912. }
  1913. var ret_code='return {'
  1914. for(var i=0;i<mod_names.length;i++){
  1915. ret_code +=mod_names[i]+':'+mod_names[i]+','
  1916. }
  1917. ret_code +='__getattr__:function(attr){return this[attr]},'
  1918. ret_code +='__setattr__:function(attr,value){this[attr]=value}'
  1919. ret_code +='}'
  1920. var ret_node=new $Node('expression')
  1921. new $NodeJSCtx(ret_node,ret_code)
  1922. mod_node.add(ret_node)
  1923. var ex_node=new $Node('expression')
  1924. new $NodeJSCtx(ex_node,')()')
  1925. root.add(ex_node)
  1926. if(names!==undefined){
  1927. if(names.length===1 && names[0]==='*'){
  1928. var new_node=new $Node('expression')
  1929. new $NodeJSCtx(new_node,'for(var $attr in $module)')
  1930. root.add(new_node)
  1931. var attr_node=new $Node('expression')
  1932. new $NodeJSCtx(attr_node,'if($attr.charAt(0)!=="_"){eval($attr+"=$module[$attr]")}')
  1933. new_node.add(attr_node)
  1934. }else{
  1935. if(alias !==undefined){
  1936. for(var i=0;i<names.length;i++){
  1937. var new_node=new $Node('expression')
  1938. new $NodeJSCtx(new_node,alias[i]+'=$module.'+names[i])
  1939. root.add(new_node)
  1940. }
  1941. }else{
  1942. for(var i=0;i<names.length;i++){
  1943. var new_node=new $Node('expression')
  1944. new $NodeJSCtx(new_node,names[i]+'=$module.'+names[i])
  1945. root.add(new_node)
  1946. }
  1947. }
  1948. }
  1949. }
  1950. try{
  1951. var js=root.to_js()
  1952. eval(js)
  1953. eval(alias+'.__class__ = $type')
  1954. eval(alias+'.__str__ = function(){return "<module \''+module+"'>\"}")
  1955. eval(alias+'.__file__ = "' + module_path + '"')
  1956. }catch(err){
  1957. eval('throw '+err.name+'(err.message)')
  1958. }
  1959. }
  1960. $import_funcs=[$import_js,$import_py_search_path]
  1961. function $import_single(name,alias,names){
  1962. for(var j=0;j<$import_funcs.length;j++){
  1963. try{$import_funcs[j](name,alias,names);return}
  1964. catch(err){
  1965. if(err.name==="NotFoundError"){
  1966. if(j==$import_funcs.length-1){
  1967. throw ImportError("no module named '"+name+"'")
  1968. }else{
  1969. continue
  1970. }
  1971. }else{throw(err)}
  1972. }
  1973. }
  1974. }
  1975. function $import_list(modules){
  1976. for(var i=0;i<modules.length;i++){
  1977. var module=modules[i][0]
  1978. $import_single(modules[i][0],modules[i][1])
  1979. document.$py_module_alias[modules[i][0]]=modules[i][1]
  1980. }
  1981. }
  1982. function $import_from(module,names,parent_module,alias){
  1983. var relpath
  1984. if(parent_module !==undefined){
  1985. relpath=document.$py_module_path[parent_module]
  1986. var i=relpath.lastIndexOf('/')
  1987. relpath=relpath.substring(0, i)
  1988. alias=document.$py_module_alias[parent_module]
  1989. }else if(alias !==undefined){
  1990. $import_single(module,alias,names)
  1991. }else{
  1992. $import_single(module,names,names)
  1993. }
  1994. }
  1995. var $operators={
  1996. "//=":"ifloordiv",">>=":"irshift","<<=":"ilshift",
  1997. "**=":"ipow","**":"pow","//":"floordiv","<<":"lshift",">>":"rshift",
  1998. "+=":"iadd","-=":"isub","*=":"imul","/=":"itruediv",
  1999. "%=":"imod","&=":"iand","|=":"ior",
  2000. "^=":"ipow","+":"add","-":"sub","*":"mul",
  2001. "/":"truediv","%":"mod","&":"and","|":"or",
  2002. "^":"pow","<":"lt",">":"gt",
  2003. "<=":"le",">=":"ge","==":"eq","!=":"ne",
  2004. "or":"or","and":"and", "in":"in",
  2005. "is":"is","not_in":"not_in","is_not":"is_not"
  2006. }
  2007. var $op_weight={
  2008. 'or':1,'and':2,
  2009. 'in':3,'not_in':3,
  2010. '<':4, '<=':4, '>':4, '>=':4, '!=':4, '==':4,'is':4,
  2011. '+':5,
  2012. '-':6,
  2013. '/':7,'//':7,'%':7,
  2014. '*':8,
  2015. '**':9
  2016. }
  2017. var $augmented_assigns={
  2018. "//=":"ifloordiv",">>=":"irshift","<<=":"ilshift",
  2019. "**=":"ipow","+=":"iadd","-=":"isub","*=":"imul","/=":"itruediv",
  2020. "%=":"imod","^=":"ipow"
  2021. }
  2022. function $_SyntaxError(C,msg,indent){
  2023. var ctx_node=C
  2024. while(ctx_node.type!=='node'){ctx_node=ctx_node.parent}
  2025. var tree_node=ctx_node.node
  2026. var module=tree_node.module
  2027. var line_num=tree_node.line_num
  2028. document.$line_info=[line_num,module]
  2029. if(indent===undefined){$SyntaxError(module,'invalid syntax',$pos)}
  2030. else{throw $IndentationError(module,msg,$pos)}
  2031. }
  2032. var $first_op_letter={}
  2033. for(op in $operators){$first_op_letter[op.charAt(0)]=0}
  2034. function $Node(type){
  2035. this.type=type
  2036. this.children=[]
  2037. this.add=function(child){
  2038. this.children.push(child)
  2039. child.parent=this
  2040. }
  2041. this.insert=function(pos,child){
  2042. this.children.splice(pos,0,child)
  2043. child.parent=this
  2044. }
  2045. this.toString=function(){return "<object 'Node'>"}
  2046. this.show=function(indent){
  2047. var res=''
  2048. if(this.type==='module'){
  2049. for(var i=0;i<this.children.length;i++){
  2050. res +=this.children[i].show(indent)
  2051. }
  2052. }else{
  2053. indent=indent || 0
  2054. for(var i=0;i<indent;i++){res+=' '}
  2055. res +=this.C
  2056. if(this.children.length>0){res +='{'}
  2057. res +='\n'
  2058. for(var i=0;i<this.children.length;i++){
  2059. res +='['+i+'] '+this.children[i].show(indent+4)
  2060. }
  2061. if(this.children.length>0){
  2062. for(var i=0;i<indent;i++){res+=' '}
  2063. res+='}\n'
  2064. }
  2065. }
  2066. return res
  2067. }
  2068. this.to_js=function(indent){
  2069. var res=''
  2070. if(this.type==='module'){
  2071. for(var i=0;i<this.children.length;i++){
  2072. res +=this.children[i].to_js(indent)
  2073. }
  2074. }else{
  2075. indent=indent || 0
  2076. var ctx_js=this.C.to_js(indent)
  2077. if(ctx_js){
  2078. for(var i=0;i<indent;i++){res+=' '}
  2079. res +=ctx_js
  2080. if(this.children.length>0){res +='{'}
  2081. res +='\n'
  2082. for(var i=0;i<this.children.length;i++){
  2083. res +=this.children[i].to_js(indent+4)
  2084. }
  2085. if(this.children.length>0){
  2086. for(var i=0;i<indent;i++){res+=' '}
  2087. res+='}\n'
  2088. }
  2089. }
  2090. }
  2091. return res
  2092. }
  2093. this.transform=function(rank){
  2094. var res=''
  2095. if(this.type==='module'){
  2096. var i=0
  2097. while(i<this.children.length){
  2098. var node=this.children[i]
  2099. this.children[i].transform(i)
  2100. i++
  2101. }
  2102. }else{
  2103. var elt=this.C.tree[0]
  2104. if(elt.transform !==undefined){
  2105. elt.transform(this,rank)
  2106. }
  2107. var i=0
  2108. while(i<this.children.length){
  2109. this.children[i].transform(i)
  2110. i++
  2111. }
  2112. }
  2113. }
  2114. this.get_ctx=function(){return this.C}
  2115. }
  2116. function $last(src){return src[src.length-1]}
  2117. var $loop_id=0
  2118. function $AbstractExprCtx(C,with_commas){
  2119. this.type='abstract_expr'
  2120. this.with_commas=with_commas
  2121. this.name=name
  2122. this.parent=C
  2123. this.tree=[]
  2124. C.tree.push(this)
  2125. this.toString=function(){return '(abstract_expr '+with_commas+') '+this.tree}
  2126. this.to_js=function(){
  2127. if(this.type==='list'){return '['+$to_js(this.tree)+']'}
  2128. else{return $to_js(this.tree)}
  2129. }
  2130. }
  2131. function $AssertCtx(C){
  2132. this.type='assert'
  2133. this.toString=function(){return '(assert) '+this.tree}
  2134. this.parent=C
  2135. this.tree=[]
  2136. C.tree.push(this)
  2137. this.transform=function(node,rank){
  2138. var new_ctx=new $ConditionCtx(node.C,'if')
  2139. var not_ctx=new $NotCtx(new_ctx)
  2140. not_ctx.tree=[this.tree[0]]
  2141. node.C=new_ctx
  2142. var new_node=new $Node('expression')
  2143. var js='throw AssertionError("")'
  2144. if(this.tree.length==2){
  2145. js='throw AssertionError(str('+this.tree[1].to_js()+'))'
  2146. }
  2147. new $NodeJSCtx(new_node,js)
  2148. node.add(new_node)
  2149. }
  2150. }
  2151. function $AssignCtx(C){
  2152. this.type='assign'
  2153. C.parent.tree.pop()
  2154. C.parent.tree.push(this)
  2155. this.parent=C.parent
  2156. this.tree=[C]
  2157. this.toString=function(){return '(assign) '+this.tree[0]+'='+this.tree[1]}
  2158. this.transform=function(node,rank){
  2159. var left=this.tree[0]
  2160. while(left.type==='assign'){
  2161. var new_node=new $Node('expression')
  2162. var node_ctx=new $NodeCtx(new_node)
  2163. node_ctx.tree=[left]
  2164. node.parent.insert(rank+1,new_node)
  2165. this.tree[0]=left.tree[1]
  2166. left=this.tree[0]
  2167. }
  2168. var left_items=null
  2169. if(left.type==='expr' && left.tree.length>1){
  2170. var left_items=left.tree
  2171. }else if(left.type==='expr' && left.tree[0].type==='list_or_tuple'){
  2172. var left_items=left.tree[0].tree
  2173. }else if(left.type==='target_list'){
  2174. var left_items=left.tree
  2175. }else if(left.type==='list_or_tuple'){
  2176. var left_items=left.tree
  2177. }
  2178. if(left_items===null){return}
  2179. var right=this.tree[1]
  2180. var right_items=null
  2181. if(right.type==='list'||right.type==='tuple'||
  2182. (right.type==='expr' && right.tree.length>1)){
  2183. var right_items=right.tree
  2184. }
  2185. if(right_items!==null){
  2186. if(right_items.length>left_items.length){
  2187. throw Error('ValueError : too many values to unpack (expected '+left_items.length+')')
  2188. }else if(right_items.length<left_items.length){
  2189. throw Error('ValueError : need more than '+right_items.length+' to unpack')
  2190. }
  2191. var new_nodes=[]
  2192. var new_node=new $Node('expression')
  2193. new $NodeJSCtx(new_node,'void(0)')
  2194. new_nodes.push(new_node)
  2195. var new_node=new $Node('expression')
  2196. new $NodeJSCtx(new_node,'var $temp'+$loop_num+'=[]')
  2197. new_nodes.push(new_node)
  2198. for(var i=0;i<right_items.length;i++){
  2199. var js='$temp'+$loop_num+'.push('+right_items[i].to_js()+')'
  2200. var new_node=new $Node('expression')
  2201. new $NodeJSCtx(new_node,js)
  2202. new_nodes.push(new_node)
  2203. }
  2204. for(var i=0;i<left_items.length;i++){
  2205. var new_node=new $Node('expression')
  2206. var C=new $NodeCtx(new_node)
  2207. left_items[i].parent=C
  2208. var assign=new $AssignCtx(left_items[i])
  2209. assign.tree[1]=new $JSCode('$temp'+$loop_num+'['+i+']')
  2210. new_nodes.push(new_node)
  2211. }
  2212. node.parent.children.splice(rank,1)
  2213. for(var i=new_nodes.length-1;i>=0;i--){
  2214. node.parent.insert(rank,new_nodes[i])
  2215. }
  2216. $loop_num++
  2217. }else{
  2218. var new_node=new $Node('expression')
  2219. new $NodeJSCtx(new_node,'$right='+right.to_js())
  2220. var new_nodes=[new_node]
  2221. for(var i=0;i<left_items.length;i++){
  2222. var new_node=new $Node('expression')
  2223. var C=new $NodeCtx(new_node)
  2224. left_items[i].parent=C
  2225. var assign=new $AssignCtx(left_items[i])
  2226. assign.tree[1]=new $JSCode('$right.__item__('+i+')')
  2227. new_nodes.push(new_node)
  2228. }
  2229. node.parent.children.splice(rank,1)
  2230. for(var i=new_nodes.length-1;i>=0;i--){
  2231. node.parent.insert(rank,new_nodes[i])
  2232. }
  2233. }
  2234. }
  2235. this.to_js=function(){
  2236. if(this.parent.type==='call'){
  2237. return '$Kw('+this.tree[0].to_js()+','+this.tree[1].to_js()+')'
  2238. }else{
  2239. var left=this.tree[0]
  2240. if(left.type==='expr'){
  2241. left=left.tree[0]
  2242. }
  2243. var right=this.tree[1]
  2244. if(left.type==='attribute'){
  2245. left.func='setattr'
  2246. var res=left.to_js()
  2247. left.func='getattr'
  2248. res=res.substr(0,res.length-1)
  2249. res +=','+right.to_js()+')'
  2250. return res
  2251. }else if(left.type==='sub'){
  2252. left.func='setitem'
  2253. var res=left.to_js()
  2254. res=res.substr(0,res.length-1)
  2255. left.func='getitem'
  2256. res +=','+right.to_js()+')'
  2257. return res
  2258. }
  2259. var scope=$get_scope(this)
  2260. if(scope===null){
  2261. return left.to_js()+'='+right.to_js()
  2262. }else if(scope.ntype==='def'){
  2263. if(scope.globals && scope.globals.indexOf(left.value)>-1){
  2264. return left.to_js()+'='+right.to_js()
  2265. }else{
  2266. return 'var '+left.to_js()+'='+right.to_js()
  2267. }
  2268. }else if(scope.ntype==='class'){
  2269. var attr=left.to_js()
  2270. return 'var '+attr+' = $class.'+attr+'='+right.to_js()
  2271. }
  2272. }
  2273. }
  2274. }
  2275. function $AttrCtx(C){
  2276. this.type='attribute'
  2277. this.value=C.tree[0]
  2278. this.parent=C
  2279. C.tree.pop()
  2280. C.tree.push(this)
  2281. this.tree=[]
  2282. this.func='getattr'
  2283. this.toString=function(){return '(attr) '+this.value+'.'+this.name}
  2284. this.to_js=function(){
  2285. var name=this.name
  2286. if(name.substr(0,2)==='$$'){name=name.substr(2)}
  2287. if(name!=='__getattr__'){name='__'+this.func+'__("'+name+'")'}
  2288. return this.value.to_js()+'.'+name
  2289. }
  2290. }
  2291. function $CallArgCtx(C){
  2292. this.type='call_arg'
  2293. this.toString=function(){return 'call_arg '+this.tree}
  2294. this.parent=C
  2295. this.tree=[]
  2296. C.tree.push(this)
  2297. this.expect='id'
  2298. this.to_js=function(){return $to_js(this.tree)}
  2299. }
  2300. function $CallCtx(C){
  2301. this.type='call'
  2302. this.func=C.tree[0]
  2303. this.parent=C
  2304. C.tree.pop()
  2305. C.tree.push(this)
  2306. this.tree=[]
  2307. this.toString=function(){return '(call) '+this.func+'('+this.tree+')'}
  2308. this.to_js=function(){return this.func.to_js()+'('+$to_js(this.tree)+')'}
  2309. }
  2310. function $ClassCtx(C){
  2311. this.type='class'
  2312. this.parent=C
  2313. this.tree=[]
  2314. C.tree.push(this)
  2315. this.expect='id'
  2316. this.toString=function(){return 'class '+this.tree}
  2317. this.transform=function(node,rank){
  2318. var instance_decl=new $Node('expression')
  2319. new $NodeJSCtx(instance_decl,'var $class = new Object()')
  2320. node.insert(0,instance_decl)
  2321. var ret_obj=new $Node('expression')
  2322. new $NodeJSCtx(ret_obj,'return $class')
  2323. node.insert(node.children.length,ret_obj)
  2324. var run_func=new $Node('expression')
  2325. new $NodeJSCtx(run_func,')()')
  2326. node.parent.insert(rank+1,run_func)
  2327. var scope=$get_scope(this)
  2328. if(scope===null||scope.ntype!=='class'){
  2329. js='var '+this.name
  2330. }else{
  2331. js='var '+this.name+' = $class.'+this.name
  2332. }
  2333. js +='=$class_constructor("'+this.name+'",$'+this.name
  2334. if(this.tree.length>0 && this.tree[0].tree.length>0){
  2335. js +=','+$to_js(this.tree[0].tree)
  2336. }
  2337. js +=')'
  2338. var cl_cons=new $Node('expression')
  2339. new $NodeJSCtx(cl_cons,js)
  2340. node.parent.insert(rank+2,cl_cons)
  2341. if(scope===null && this.parent.node.module==='__main__'){
  2342. js='window.'+this.name+'='+this.name
  2343. var w_decl=new $Node('expression')
  2344. new $NodeJSCtx(w_decl,js)
  2345. node.parent.insert(rank+3,w_decl)
  2346. }
  2347. }
  2348. this.to_js=function(){
  2349. return 'var $'+this.name+'=(function()'
  2350. }
  2351. }
  2352. function $CompIfCtx(C){
  2353. this.type='comp_if'
  2354. C.parent.intervals.push($pos)
  2355. this.parent=C
  2356. this.tree=[]
  2357. C.tree.push(this)
  2358. this.toString=function(){return '(comp if) '+this.tree}
  2359. this.to_js=function(){return 'comp if to js'}
  2360. }
  2361. function $ComprehensionCtx(C){
  2362. this.type='comprehension'
  2363. this.parent=C
  2364. this.tree=[]
  2365. C.tree.push(this)
  2366. this.toString=function(){return '(comprehension) '+this.tree}
  2367. this.to_js=function(){
  2368. var intervals=[]
  2369. for(var i=0;i<this.tree.length;i++){
  2370. intervals.push(this.tree[i].start)
  2371. }
  2372. return intervals
  2373. }
  2374. }
  2375. function $CompForCtx(C){
  2376. this.type='comp_for'
  2377. C.parent.intervals.push($pos)
  2378. this.parent=C
  2379. this.tree=[]
  2380. this.expect='in'
  2381. C.tree.push(this)
  2382. this.toString=function(){return '(comp for) '+this.tree}
  2383. this.to_js=function(){return 'comp for to js'}
  2384. }
  2385. function $CompIterableCtx(C){
  2386. this.type='comp_iterable'
  2387. this.parent=C
  2388. this.tree=[]
  2389. C.tree.push(this)
  2390. this.toString=function(){return '(comp iter) '+this.tree}
  2391. this.to_js=function(){return 'comp iter to js'}
  2392. }
  2393. function $ConditionCtx(C,token){
  2394. this.type='condition'
  2395. this.token=token
  2396. this.parent=C
  2397. this.tree=[]
  2398. C.tree.push(this)
  2399. this.toString=function(){return this.token+' '+this.tree}
  2400. this.to_js=function(){
  2401. var tok=this.token
  2402. if(tok==='elif'){tok='else if'}
  2403. if(this.tree.length==1){
  2404. var res=tok+'(bool('+$to_js(this.tree)+'))'
  2405. }else{
  2406. var res=tok+'(bool('+this.tree[0].to_js()+'))'
  2407. if(this.tree[1].tree.length>0){
  2408. res +='{'+this.tree[1].to_js()+'}'
  2409. }
  2410. }
  2411. return res
  2412. }
  2413. }
  2414. function $DecoratorCtx(C){
  2415. this.type='decorator'
  2416. this.parent=C
  2417. C.tree.push(this)
  2418. this.tree=[]
  2419. this.toString=function(){return '(decorator) '+this.tree}
  2420. this.to_js=function(){return $to_js(this.tree)}
  2421. }
  2422. function $DefCtx(C){
  2423. this.type='def'
  2424. this.name=null
  2425. this.parent=C
  2426. this.tree=[]
  2427. C.tree.push(this)
  2428. this.toString=function(){return 'def '+this.name+'('+this.tree+')'}
  2429. this.transform=function(node,rank){
  2430. if(this.transformed!==undefined){return}
  2431. this.rank=rank
  2432. if(this.in_line!==undefined){
  2433. var new_node=new $Node('expression')
  2434. var ctx=new $NodeCtx(new_node)
  2435. ctx.tree=[this.tree[this.tree.length-1]]
  2436. node.add(new_node)
  2437. }
  2438. var scope=$get_scope(this)
  2439. var required=''
  2440. var defaults=''
  2441. var other_args=null
  2442. var other_kw=null
  2443. var env=[]
  2444. for(var i=0;i<this.tree[0].tree.length;i++){
  2445. var arg=this.tree[0].tree[i]
  2446. if(arg.type==='func_arg_id'){
  2447. if(arg.tree.length===0){required+='"'+arg.name+'",'}
  2448. else{
  2449. defaults+='"'+arg.name+'":'+$to_js(arg.tree)+','
  2450. if(arg.tree[0].type==='expr'
  2451. && arg.tree[0].tree[0].type==='id'){
  2452. env.push(arg.tree[0].tree[0].value)
  2453. }
  2454. }
  2455. }else if(arg.type==='func_star_arg'&&arg.op==='*'){other_args='"'+arg.name+'"'}
  2456. else if(arg.type==='func_star_arg'&&arg.op==='**'){other_kw='"'+arg.name+'"'}
  2457. }
  2458. this.env=env
  2459. if(required.length>0){required=required.substr(0,required.length-1)}
  2460. if(defaults.length>0){defaults=defaults.substr(0,defaults.length-1)}
  2461. var js='var $ns=$MakeArgs("'+this.name+'",arguments,['+required+'],'
  2462. js +='{'+defaults+'},'+other_args+','+other_kw+')'
  2463. var new_node1=new $Node('expression')
  2464. new $NodeJSCtx(new_node1,js)
  2465. var js='for($var in $ns){eval("var "+$var+"=$ns[$var]")}'
  2466. var new_node2=new $Node('expression')
  2467. new $NodeJSCtx(new_node2,js)
  2468. node.children.splice(0,0,new_node1,new_node2)
  2469. var def_func_node=new $Node('expression')
  2470. new $NodeJSCtx(def_func_node,'return function()')
  2471. var try_node=new $Node('expression')
  2472. new $NodeJSCtx(try_node,'try')
  2473. for(var i=0;i<node.children.length;i++){
  2474. try_node.add(node.children[i])
  2475. }
  2476. def_func_node.add(try_node)
  2477. var ret_node=new $Node('expression')
  2478. var catch_node=new $Node('expression')
  2479. var js='catch(err'+$loop_num+')'
  2480. js +='{throw RuntimeError(err'+$loop_num+'.message)}'
  2481. new $NodeJSCtx(catch_node,js)
  2482. node.children=[]
  2483. def_func_node.add(catch_node)
  2484. node.add(def_func_node)
  2485. var txt=')('
  2486. for(var i=0;i<this.env.length;i++){
  2487. txt +=this.env[i]
  2488. if(i<this.env.length-1){txt +=','}
  2489. }
  2490. new $NodeJSCtx(ret_node,txt+')')
  2491. node.parent.insert(rank+1,ret_node)
  2492. js=this.name+'.__name__'
  2493. if(scope !==null && scope.ntype==='class'){
  2494. js +='=$class.'+this.name+'.__name__'
  2495. }
  2496. js +='="'+this.name+'"'
  2497. var name_decl=new $Node('expression')
  2498. new $NodeJSCtx(name_decl,js)
  2499. node.parent.children.splice(rank+2,0,name_decl)
  2500. if(scope===null && node.module==='__main__'){
  2501. js='window.'+this.name+'='+this.name
  2502. new_node1=new $Node('expression')
  2503. new $NodeJSCtx(new_node1,js)
  2504. node.parent.children.splice(rank+3,0,new_node1)
  2505. }
  2506. this.transformed=true
  2507. }
  2508. this.add_generator_declaration=function(){
  2509. var scope=$get_scope(this)
  2510. var node=this.parent.node
  2511. if(this.type==='generator'){
  2512. js=this.name
  2513. if(scope.ntype==='class'){js +="=$class."+this.name}
  2514. js +='=$generator($'+this.name+')'
  2515. var gen_node=new $Node('expression')
  2516. new $NodeJSCtx(gen_node,js)
  2517. node.parent.children.splice(this.rank+2,0,gen_node)
  2518. }
  2519. }
  2520. this.to_js=function(){
  2521. var scope=$get_scope(this)
  2522. var name=this.name
  2523. if(this.type==='generator'){name='$'+name}
  2524. if(scope===null || scope.ntype!=='class'){
  2525. res=name+'= (function ('
  2526. }else{
  2527. res='var '+name+' = $class.'+name+'= (function ('
  2528. }
  2529. for(var i=0;i<this.env.length;i++){
  2530. res+=this.env[i]
  2531. if(i<this.env.length-1){res+=','}
  2532. }
  2533. res +=')'
  2534. return res
  2535. }
  2536. }
  2537. function $DelCtx(C){
  2538. this.type='del'
  2539. this.parent=C
  2540. C.tree.push(this)
  2541. this.tree=[]
  2542. this.toString=function(){return 'del '+this.tree}
  2543. this.to_js=function(){
  2544. res=[]
  2545. var tree=this.tree[0].tree
  2546. for(var i=0;i<tree.length;i++){
  2547. var expr=tree[i]
  2548. if(expr.type==='expr'||expr.type==='id'){
  2549. res.push('delete '+expr.to_js())
  2550. }else if(expr.type==='sub'){
  2551. expr.func='delitem'
  2552. res.push(expr.to_js())
  2553. expr.func='getitem'
  2554. }else{
  2555. throw SyntaxError("wrong argument for del "+expr.type)
  2556. }
  2557. }
  2558. return res.join(';')
  2559. }
  2560. }
  2561. function $DictCtx(C){
  2562. this.type='dict'
  2563. this.parent=C.parent
  2564. C.parent.tree.pop()
  2565. C.parent.tree.push(this)
  2566. C.name='dict_key'
  2567. this.tree=[C]
  2568. this.expect=','
  2569. this.toString=function(){return 'dict '+this.tree}
  2570. }
  2571. function $DictOrSetCtx(C){
  2572. this.type='dict_or_set'
  2573. this.real='dict_or_set'
  2574. this.expect='id'
  2575. this.closed=false
  2576. this.start=$pos
  2577. this.toString=function(){
  2578. if(this.real==='dict'){return '(dict) {'+this.tree+'}'}
  2579. else if(this.real==='set'){return '(set) {'+this.tree+'}'}
  2580. else{return '(dict_or_set) {'+this.tree+'}'}
  2581. }
  2582. this.parent=C
  2583. this.tree=[]
  2584. C.tree.push(this)
  2585. this.to_js=function(){
  2586. if(this.real==='dict'){
  2587. var res='dict(['
  2588. for(var i=0;i<this.items.length;i+=2){
  2589. res+='['+this.items[i].to_js()+','+this.items[i+1].to_js()+']'
  2590. if(i<this.items.length-2){res+=','}
  2591. }
  2592. return res+'])'+$to_js(this.tree)
  2593. }else if(this.real==='set_comp'){return 'set('+$to_js(this.items)+')'+$to_js(this.tree)}
  2594. else if(this.real==='dict_comp'){
  2595. console.log('expression '+this.items[0].expression)
  2596. console.log('items '+this.items[0].type)
  2597. var key_items=this.items[0].expression[0].to_js()
  2598. var value_items=this.items[0].expression[1].to_js()
  2599. return 'dict('+$to_js(this.items)+')'+$to_js(this.tree)
  2600. }else{return 'set(['+$to_js(this.items)+'])'+$to_js(this.tree)}
  2601. }
  2602. }
  2603. function $DoubleStarArgCtx(C){
  2604. this.type='double_star_arg'
  2605. this.parent=C
  2606. this.tree=[]
  2607. C.tree.push(this)
  2608. this.toString=function(){return '**'+this.tree}
  2609. this.to_js=function(){return '$pdict('+$to_js(this.tree)+')'}
  2610. }
  2611. function $ExceptCtx(C){
  2612. this.type='except'
  2613. this.parent=C
  2614. C.tree.push(this)
  2615. this.tree=[]
  2616. this.expect='id'
  2617. this.toString=function(){return '(except) '}
  2618. this.to_js=function(){
  2619. if(this.tree.length===0){return 'else'}
  2620. else{
  2621. var res='else if(['
  2622. for(var i=0;i<this.tree.length;i++){
  2623. res+='"'+this.tree[i].name+'"'
  2624. if(i<this.tree.length-1){res+=','}
  2625. }
  2626. res +='].indexOf('+this.error_name+'.__name__)>-1)'
  2627. return res
  2628. }
  2629. }
  2630. }
  2631. function $ExprCtx(C,name,with_commas){
  2632. this.type='expr'
  2633. this.name=name
  2634. this.with_commas=with_commas
  2635. this.expect=','
  2636. this.parent=C
  2637. this.tree=[]
  2638. C.tree.push(this)
  2639. this.toString=function(){return '(expr '+with_commas+') '+this.tree}
  2640. this.to_js=function(){
  2641. if(this.type==='list'){return '['+$to_js(this.tree)+']'}
  2642. else if(this.tree.length===1){return this.tree[0].to_js()}
  2643. else{return 'tuple('+$to_js(this.tree)+')'}
  2644. }
  2645. }
  2646. function $ExprNot(C){
  2647. this.type='expr_not'
  2648. this.toString=function(){return '(expr_not)'}
  2649. this.parent=C
  2650. this.tree=[]
  2651. C.tree.push(this)
  2652. }
  2653. function $FloatCtx(C,value){
  2654. this.type='float'
  2655. this.value=value
  2656. this.toString=function(){return 'float '+this.value}
  2657. this.parent=C
  2658. this.tree=[]
  2659. C.tree.push(this)
  2660. this.to_js=function(){return 'float('+this.value+')'}
  2661. }
  2662. function $ForTarget(C){
  2663. this.type='for_target'
  2664. this.parent=C
  2665. this.tree=[]
  2666. C.tree.push(this)
  2667. this.toString=function(){return 'for_target'+' '+this.tree}
  2668. this.to_js=function(){return $to_js(this.tree)}
  2669. }
  2670. function $ForExpr(C){
  2671. this.type='for'
  2672. this.parent=C
  2673. this.tree=[]
  2674. C.tree.push(this)
  2675. this.toString=function(){return '(for) '+this.tree}
  2676. this.transform=function(node,rank){
  2677. var new_nodes=[]
  2678. var new_node=new $Node('expression')
  2679. var target=this.tree[0]
  2680. var iterable=this.tree[1]
  2681. new $NodeJSCtx(new_node,'var $iter'+$loop_num+'='+iterable.to_js())
  2682. new_nodes.push(new_node)
  2683. new_node=new $Node('expression')
  2684. var js='for(var $i'+$loop_num+'=0;$i'+$loop_num
  2685. js +='<$iter'+$loop_num+'.__len__();$i'+$loop_num+'++)'
  2686. new $NodeJSCtx(new_node,js)
  2687. new_nodes.push(new_node)
  2688. var children=node.children
  2689. node.parent.children.splice(rank,1)
  2690. for(var i=new_nodes.length-1;i>=0;i--){
  2691. node.parent.insert(rank,new_nodes[i])
  2692. }
  2693. var new_node=new $Node('expression')
  2694. node.insert(0,new_node)
  2695. var C=new $NodeCtx(new_node)
  2696. var target_expr=new $ExprCtx(C,'left',true)
  2697. target_expr.tree=target.tree
  2698. var assign=new $AssignCtx(target_expr)
  2699. assign.tree[1]=new $JSCode('$iter'+$loop_num+'.__item__($i'+$loop_num+')')
  2700. node.parent.children[rank+1].children=children
  2701. $loop_num++
  2702. }
  2703. this.to_js=function(){
  2704. var iterable=this.tree.pop()
  2705. return 'for '+$to_js(this.tree)+' in '+iterable.to_js()
  2706. }
  2707. }
  2708. function $FromCtx(C){
  2709. this.type='from'
  2710. this.parent=C
  2711. this.names=[]
  2712. this.aliases={}
  2713. C.tree.push(this)
  2714. this.expect='module'
  2715. this.toString=function(){return '(from) '+this.module+' (import) '+this.names + '(parent module)' + this.parent_module + '(as)' + this.aliases}
  2716. this.to_js=function(){
  2717. var res='$import_from("'+this.module+'",'+this.names
  2718. if(this.parent_module!==undefined){res+=',"' + this.parent_module +'"'
  2719. }else{res+=',undefined'}
  2720. if(this.aliases !=undefined){
  2721. var a=[]
  2722. for(var i=0;i < this.names.length;i++){
  2723. if(this.names[i]in this.aliases){
  2724. a.push(this.aliases[this.names[i]])
  2725. }else{
  2726. a.push(this.names[i])
  2727. }
  2728. }
  2729. res+=',' + a
  2730. }else{res+=',undefined'}
  2731. res +=')\n'
  2732. return res
  2733. }
  2734. }
  2735. function $FuncArgs(C){
  2736. this.type='func_args'
  2737. this.parent=C
  2738. this.tree=[]
  2739. C.tree.push(this)
  2740. this.toString=function(){return 'func args '+this.tree}
  2741. this.expect='id'
  2742. this.has_default=false
  2743. this.has_star_arg=false
  2744. this.has_kw_arg=false
  2745. this.to_js=function(){return $to_js(this.tree)}
  2746. }
  2747. function $FuncArgIdCtx(C,name){
  2748. this.type='func_arg_id'
  2749. this.name=name
  2750. this.parent=C
  2751. this.tree=[]
  2752. C.tree.push(this)
  2753. this.toString=function(){return 'func arg id '+this.name +'='+this.tree}
  2754. this.expect='='
  2755. this.to_js=function(){return this.name+$to_js(this.tree)}
  2756. }
  2757. function $FuncStarArgCtx(C,op){
  2758. this.type='func_star_arg'
  2759. this.op=op
  2760. this.parent=C
  2761. C.tree.push(this)
  2762. this.toString=function(){return '(func star arg '+this.op+') '+this.name}
  2763. }
  2764. function $GlobalCtx(C){
  2765. this.type='global'
  2766. this.parent=C
  2767. this.tree=[]
  2768. C.tree.push(this)
  2769. this.expect='id'
  2770. this.toString=function(){return 'global '+this.tree}
  2771. this.transform=function(node,rank){
  2772. var scope=$get_scope(this)
  2773. if(scope.globals===undefined){scope.globals=[]}
  2774. for(var i=0;i<this.tree.length;i++){
  2775. scope.globals.push(this.tree[i].value)
  2776. }
  2777. }
  2778. this.to_js=function(){return ''}
  2779. }
  2780. function $IdCtx(C,value,minus){
  2781. this.type='id'
  2782. this.toString=function(){return '(id) '+this.value+':'+(this.tree||'')}
  2783. this.value=value
  2784. this.minus=minus
  2785. this.parent=C
  2786. this.tree=[]
  2787. C.tree.push(this)
  2788. this.to_js=function(){
  2789. var val=this.value
  2790. if(['print','alert','eval','open'].indexOf(this.value)>-1){val='$'+val}
  2791. return val+$to_js(this.tree,'')
  2792. }
  2793. }
  2794. function $ImportCtx(C){
  2795. this.type='import'
  2796. this.toString=function(){return 'import '+this.tree}
  2797. this.parent=C
  2798. this.tree=[]
  2799. C.tree.push(this)
  2800. this.expect='id'
  2801. this.to_js=function(){
  2802. return '$import_list(['+$to_js(this.tree)+'])'
  2803. }
  2804. }
  2805. function $ImportedModuleCtx(C,name){
  2806. this.toString=function(){return ' (imported module) '+this.name}
  2807. this.parent=C
  2808. this.name=name
  2809. this.alias=name
  2810. C.tree.push(this)
  2811. this.to_js=function(){
  2812. return '["'+this.name+'","'+this.alias+'"]'
  2813. }
  2814. }
  2815. function $IntCtx(C,value){
  2816. this.type='int'
  2817. this.value=value
  2818. this.toString=function(){return 'int '+this.value}
  2819. this.parent=C
  2820. this.tree=[]
  2821. C.tree.push(this)
  2822. this.to_js=function(){return 'Number('+this.value+')'}
  2823. }
  2824. function $JSCode(js){
  2825. this.js=js
  2826. this.toString=function(){return this.js}
  2827. this.to_js=function(){return this.js}
  2828. }
  2829. function $KwArgCtx(C){
  2830. this.type='kwarg'
  2831. this.toString=function(){return 'kwarg '+this.tree[0]+'='+this.tree[1]}
  2832. this.parent=C.parent
  2833. this.tree=[C.tree[0]]
  2834. C.parent.tree.pop()
  2835. C.parent.tree.push(this)
  2836. this.to_js=function(){
  2837. var key=this.tree[0].to_js()
  2838. if(key.substr(0,2)=='$$'){key=key.substr(2)}
  2839. var res='$Kw("'+key+'",'
  2840. res +=$to_js(this.tree.slice(1,this.tree.length))+')'
  2841. return res
  2842. }
  2843. }
  2844. function $LambdaCtx(C){
  2845. this.type='lambda'
  2846. this.toString=function(){return '(lambda) '+this.args_start+' '+this.body_start}
  2847. this.parent=C
  2848. C.tree.push(this)
  2849. this.tree=[]
  2850. this.to_js=function(){
  2851. var ctx_node=this
  2852. while(ctx_node.parent!==undefined){ctx_node=ctx_node.parent}
  2853. var module=ctx_node.node.module
  2854. var src=document.$py_src[module]
  2855. var qesc=new RegExp('"',"g")
  2856. var args=src.substring(this.args_start,this.body_start).replace(qesc,'\\"')
  2857. var body=src.substring(this.body_start+1,this.body_end).replace(qesc,'\\"')
  2858. return '$lambda("'+args+'","'+body+'")'
  2859. }
  2860. }
  2861. function $ListOrTupleCtx(C,real){
  2862. this.type='list_or_tuple'
  2863. this.start=$pos
  2864. this.real=real
  2865. this.expect='id'
  2866. this.closed=false
  2867. this.toString=function(){
  2868. if(this.real==='list'){return '(list) ['+this.tree+']'}
  2869. else if(this.real==='list_comp'){return '(list comp) ['+this.intervals+'-'+this.tree+']'}
  2870. else{return '(tuple) ('+this.tree+')'}
  2871. }
  2872. this.parent=C
  2873. this.tree=[]
  2874. C.tree.push(this)
  2875. this.to_js=function(){
  2876. if(this.real==='list'){return '['+$to_js(this.tree)+']'}
  2877. else if(['list_comp','gen_expr','dict_or_set_comp'].indexOf(this.real)>-1){
  2878. var res_env=[],local_env=[],env=[]
  2879. var ctx_node=this
  2880. while(ctx_node.parent!==undefined){ctx_node=ctx_node.parent}
  2881. var module=ctx_node.node.module
  2882. var src=document.$py_src[module]
  2883. for(var i=0;i<this.expression.length;i++){
  2884. var ids=$get_ids(this.expression[i])
  2885. for(var i=0;i<ids.length;i++){
  2886. if(res_env.indexOf(ids[i])===-1){res_env.push(ids[i])}
  2887. }
  2888. }
  2889. var comp=this.tree[0]
  2890. for(var i=0;i<comp.tree.length;i++){
  2891. var elt=comp.tree[i]
  2892. if(elt.type==='comp_for'){
  2893. var target_list=elt.tree[0]
  2894. for(var j=0;j<target_list.tree.length;j++){
  2895. var name=target_list.tree[j].value
  2896. if(local_env.indexOf(name)===-1){
  2897. local_env.push(name)
  2898. }
  2899. }
  2900. var comp_iter=elt.tree[1].tree[0]
  2901. var ids=$get_ids(comp_iter)
  2902. for(var i=0;i<ids.length;i++){
  2903. if(env.indexOf(ids[i])===-1){env.push(ids[i])}
  2904. }
  2905. }else if(elt.type==="comp_if"){
  2906. var if_expr=elt.tree[0]
  2907. var ids=$get_ids(if_expr)
  2908. for(var i=0;i<ids.length;i++){
  2909. if(env.indexOf(ids[i])===-1){env.push(ids[i])}
  2910. }
  2911. }
  2912. }
  2913. for(var i=0;i<res_env.length;i++){
  2914. if(local_env.indexOf(res_env[i])===-1){
  2915. env.push(res_env[i])
  2916. }
  2917. }
  2918. var res='{'
  2919. for(var i=0;i<env.length;i++){
  2920. res +="'"+env[i]+"':"+env[i]
  2921. if(i<env.length-1){res+=','}
  2922. }
  2923. res +='},'
  2924. var qesc=new RegExp('"',"g")
  2925. for(var i=1;i<this.intervals.length;i++){
  2926. var txt=src.substring(this.intervals[i-1],this.intervals[i]).replace(qesc,'\\"')
  2927. txt=txt.replace(/\n/g,' ')
  2928. res +='"'+txt+'"'
  2929. if(i<this.intervals.length-1){res+=','}
  2930. }
  2931. if(this.real==='dict_or_set_comp'){console.log('exprss '+this.expression)}
  2932. if(this.real==='list_comp'){return '$list_comp('+res+')'}
  2933. else if(this.real==='dict_or_set_comp'){
  2934. if(this.expression.length===1){return '$gen_expr('+res+')'}
  2935. else{return '$dict_comp('+res+')'}
  2936. }else{return '$gen_expr('+res+')'}
  2937. }else if(this.real==='tuple'){
  2938. if(this.tree.length===1 && this.has_comma===undefined){return this.tree[0].to_js()}
  2939. else{return 'tuple('+$to_js(this.tree)+')'}
  2940. }
  2941. }
  2942. }
  2943. function $NodeCtx(node){
  2944. this.node=node
  2945. node.C=this
  2946. this.tree=[]
  2947. this.type='node'
  2948. this.toString=function(){return 'node '+this.tree}
  2949. this.to_js=function(){
  2950. if(this.tree.length>1){
  2951. var new_node=new $Node('expression')
  2952. var ctx=new $NodeCtx(new_node)
  2953. ctx.tree=[this.tree[1]]
  2954. new_node.indent=node.indent+4
  2955. this.tree.pop()
  2956. node.add(new_node)
  2957. }
  2958. return $to_js(this.tree)
  2959. }
  2960. }
  2961. function $NodeJSCtx(node,js){
  2962. this.node=node
  2963. node.C=this
  2964. this.type='node_js'
  2965. this.tree=[js]
  2966. this.toString=function(){return 'js '+js}
  2967. this.to_js=function(){return js}
  2968. }
  2969. function $NotCtx(C){
  2970. this.type='not'
  2971. this.parent=C
  2972. this.tree=[]
  2973. C.tree.push(this)
  2974. this.toString=function(){return 'not ('+this.tree+')'}
  2975. this.to_js=function(){return '!bool('+$to_js(this.tree)+')'}
  2976. }
  2977. function $OpCtx(C,op){
  2978. this.type='op'
  2979. this.op=op
  2980. this.toString=function(){return '(op '+this.op+')'+this.tree}
  2981. this.parent=C.parent
  2982. this.tree=[C]
  2983. C.parent.tree.pop()
  2984. C.parent.tree.push(this)
  2985. this.to_js=function(){
  2986. if(this.op==='and'){
  2987. var res='$test_expr($test_item('+this.tree[0].to_js()+')&&'
  2988. res +='$test_item('+this.tree[1].to_js()+'))'
  2989. return res
  2990. }else if(this.op==='or'){
  2991. var res='$test_expr($test_item('+this.tree[0].to_js()+')||'
  2992. res +='$test_item('+this.tree[1].to_js()+'))'
  2993. return res
  2994. }else{
  2995. var res=this.tree[0].to_js()
  2996. if(this.op==="is"){
  2997. res +='==='+this.tree[1].to_js()
  2998. }else{
  2999. res +='.__'+$operators[this.op]+'__('+this.tree[1].to_js()+')'
  3000. }
  3001. return res
  3002. }
  3003. }
  3004. }
  3005. function $PassCtx(C){
  3006. this.type='pass'
  3007. this.toString=function(){return '(pass)'}
  3008. this.parent=C
  3009. this.tree=[]
  3010. C.tree.push(this)
  3011. this.to_js=function(){return 'void(0)'}
  3012. }
  3013. function $RaiseCtx(C){
  3014. this.type='raise'
  3015. this.toString=function(){return ' (raise) '+this.tree}
  3016. this.parent=C
  3017. this.tree=[]
  3018. C.tree.push(this)
  3019. this.to_js=function(){
  3020. if(this.tree.length===0){return '$raise()'}
  3021. var exc=this.tree[0]
  3022. if(exc.type==='id'){return 'throw '+exc.value+'("")'}
  3023. else{return 'throw '+$to_js(this.tree)}
  3024. }
  3025. }
  3026. function $ReturnCtx(C){
  3027. this.type='return'
  3028. this.toString=function(){return 'return '+this.tree}
  3029. this.parent=C
  3030. this.tree=[]
  3031. C.tree.push(this)
  3032. this.to_js=function(){return 'return '+$to_js(this.tree)}
  3033. }
  3034. function $SingleKwCtx(C,token){
  3035. this.type='single_kw'
  3036. this.token=token
  3037. this.parent=C
  3038. this.tree=[]
  3039. C.tree.push(this)
  3040. this.toString=function(){return this.token}
  3041. this.to_js=function(){return this.token}
  3042. }
  3043. function $StarArgCtx(C){
  3044. this.type='star_arg'
  3045. this.parent=C
  3046. this.tree=[]
  3047. C.tree.push(this)
  3048. this.toString=function(){return '(star arg) '+this.tree}
  3049. this.to_js=function(){
  3050. return '$ptuple('+$to_js(this.tree)+')'
  3051. }
  3052. }
  3053. function $StringCtx(C,value){
  3054. this.type='str'
  3055. this.value=value
  3056. this.toString=function(){return 'string '+this.value+' '+(this.tree||'')}
  3057. this.parent=C
  3058. this.tree=[]
  3059. C.tree.push(this)
  3060. this.to_js=function(){
  3061. return this.value.replace(/\n/g,' \\\n')+$to_js(this.tree,'')
  3062. }
  3063. }
  3064. function $SubCtx(C){
  3065. this.type='sub'
  3066. this.func='getitem'
  3067. this.toString=function(){return '(sub) '+this.tree}
  3068. this.value=C.tree[0]
  3069. C.tree.pop()
  3070. C.tree.push(this)
  3071. this.parent=C
  3072. this.tree=[]
  3073. this.to_js=function(){
  3074. var res=this.value.to_js()+'.__getattr__("__'+this.func+'__")('
  3075. if(this.tree.length===1){
  3076. return res+this.tree[0].to_js()+')'
  3077. }else{
  3078. res +='slice('
  3079. for(var i=0;i<this.tree.length;i++){
  3080. if(this.tree[i].type==='abstract_expr'){res+='null'}
  3081. else{res+=this.tree[i].to_js()}
  3082. if(i<this.tree.length-1){res+=','}
  3083. }
  3084. return res+'))'
  3085. }
  3086. }
  3087. }
  3088. function $TargetCtx(C,name){
  3089. this.toString=function(){return ' (target) '+this.name}
  3090. this.parent=C
  3091. this.name=name
  3092. this.alias=null
  3093. C.tree.push(this)
  3094. this.to_js=function(){
  3095. return '["'+this.name+'","'+this.alias+'"]'
  3096. }
  3097. }
  3098. function $TargetListCtx(C){
  3099. this.type='target_list'
  3100. this.parent=C
  3101. this.tree=[]
  3102. this.expect='id'
  3103. C.tree.push(this)
  3104. this.toString=function(){return '(target list) '+this.tree}
  3105. }
  3106. function $TernaryCtx(C){
  3107. this.type='ternary'
  3108. this.parent=C.parent
  3109. C.parent.tree.pop()
  3110. C.parent.tree.push(this)
  3111. C.parent=this
  3112. this.tree=[C]
  3113. this.toString=function(){return '(ternary) '+this.tree}
  3114. this.to_js=function(){
  3115. var env='{'
  3116. var ids=$get_ids(this)
  3117. for(var i=0;i<ids.length;i++){
  3118. env +='"'+ids[i]+'":'+ids[i]
  3119. if(i<ids.length-1){env+=','}
  3120. }
  3121. env+='}'
  3122. var qesc=new RegExp('"',"g")
  3123. var args='"'+this.tree[1].to_js().replace(qesc,'\\"')+'","'
  3124. args +=this.tree[0].to_js().replace(qesc,'\\"')+'","'
  3125. args +=this.tree[2].to_js().replace(qesc,'\\"')
  3126. return '$ternary('+env+','+args+'")'
  3127. }
  3128. }
  3129. function $TryCtx(C){
  3130. this.type='try'
  3131. this.parent=C
  3132. C.tree.push(this)
  3133. this.toString=function(){return '(try) '}
  3134. this.transform=function(node,rank){
  3135. if(node.parent.children.length===rank+1){
  3136. $_SyntaxError(C,"missing clause after 'try' 1")
  3137. }else{
  3138. var next_ctx=node.parent.children[rank+1].C.tree[0]
  3139. if(['except','finally'].indexOf(next_ctx.type)===-1){
  3140. $_SyntaxError(C,"missing clause after 'try' 2")
  3141. }
  3142. }
  3143. new $NodeJSCtx(node,'try')
  3144. var catch_node=new $Node('expression')
  3145. new $NodeJSCtx(catch_node,'catch($err'+$loop_num+')')
  3146. node.parent.insert(rank+1,catch_node)
  3147. var new_node=new $Node('expression')
  3148. new $NodeJSCtx(new_node,'if(false){void(0)}')
  3149. catch_node.insert(0,new_node)
  3150. var pos=rank+2
  3151. var has_default=false
  3152. var has_else=false
  3153. while(true){
  3154. if(pos===node.parent.children.length){break}
  3155. var ctx=node.parent.children[pos].C.tree[0]
  3156. if(ctx.type==='except'||
  3157. (ctx.type==='single_kw' && ctx.token==='finally')){
  3158. if(has_else){$_SyntaxError(C,"'except' or 'finally' after 'else'")}
  3159. ctx.error_name='$err'+$loop_num
  3160. if(ctx.tree.length>0 && ctx.tree[0].alias!==null){
  3161. var new_node=new $Node('expression')
  3162. var js='var '+ctx.tree[0].alias+'=$err'+$loop_num
  3163. new $NodeJSCtx(new_node,js)
  3164. node.parent.children[pos].insert(0,new_node)
  3165. }
  3166. catch_node.insert(catch_node.children.length,
  3167. node.parent.children[pos])
  3168. if(ctx.type==='except' && ctx.tree.length===0){
  3169. if(has_default){$_SyntaxError(C,'more than one except: line')}
  3170. has_default=true
  3171. }
  3172. node.parent.children.splice(pos,1)
  3173. }else if(ctx.type==='single_kw' && ctx.token==='else'){
  3174. if(has_else){$_SyntaxError(C,"more than one 'else'")}
  3175. has_else=true
  3176. var else_children=node.parent.children[pos].children
  3177. for(var i=0;i<else_children.length;i++){
  3178. node.add(else_children[i])
  3179. }
  3180. node.parent.children.splice(pos,1)
  3181. }else{break}
  3182. }
  3183. if(!has_default){
  3184. var new_node=new $Node('expression')
  3185. new $NodeJSCtx(new_node,'else{throw $err'+$loop_num+'}')
  3186. catch_node.insert(catch_node.children.length,new_node)
  3187. }
  3188. $loop_num++
  3189. }
  3190. this.to_js=function(){return 'try'}
  3191. }
  3192. function $UnaryCtx(C,op){
  3193. this.type='unary'
  3194. this.op=op
  3195. this.toString=function(){return '(unary) '+this.op+' ['+this.tree+']'}
  3196. this.parent=C
  3197. this.tree=[]
  3198. C.tree.push(this)
  3199. this.to_js=function(){return this.op+$to_js(this.tree)}
  3200. }
  3201. function $YieldCtx(C){
  3202. this.type='yield'
  3203. this.toString=function(){return '(yield) '+this.tree}
  3204. this.parent=C
  3205. this.tree=[]
  3206. C.tree.push(this)
  3207. this.transform=function(node,rank){
  3208. if(this.transformed!==undefined){return}
  3209. var scope=$get_scope(node.C.tree[0])
  3210. scope.C.tree[0].type='generator'
  3211. this.transformed=true
  3212. this.func_name=scope.C.tree[0].name
  3213. scope.C.tree[0].add_generator_declaration()
  3214. }
  3215. this.to_js=function(){
  3216. return '$'+this.func_name+'.$iter.push('+$to_js(this.tree)+')'
  3217. }
  3218. }
  3219. var $loop_num=0
  3220. var $iter_num=0
  3221. function $add_line_num(node,rank){
  3222. if(node.type==='module'){
  3223. var i=0
  3224. while(i<node.children.length){
  3225. i +=$add_line_num(node.children[i],i)
  3226. }
  3227. }else{
  3228. var elt=node.C.tree[0],offset=1
  3229. var flag=true
  3230. if(node.line_num===undefined){flag=false}
  3231. if(elt.type==='condition' && elt.token==='elif'){flag=false}
  3232. else if(elt.type==='except'){flag=false}
  3233. else if(elt.type==='single_kw'){flag=false}
  3234. if(flag){
  3235. js='document.$line_info=['+node.line_num+',"'+node.module+'"]'
  3236. var new_node=new $Node('expression')
  3237. new $NodeJSCtx(new_node,js)
  3238. node.parent.insert(rank,new_node)
  3239. offset=2
  3240. }
  3241. var i=0
  3242. while(i<node.children.length){
  3243. i +=$add_line_num(node.children[i],i)
  3244. }
  3245. return offset
  3246. }
  3247. }
  3248. function $augmented_assign(C,op){
  3249. var assign=new $AssignCtx(C)
  3250. var new_op=new $OpCtx(C,op.substr(0,op.length-1))
  3251. assign.tree.push(new_op)
  3252. C.parent.tree.pop()
  3253. C.parent.tree.push(assign)
  3254. return new_op
  3255. }
  3256. function $get_scope(C){
  3257. var ctx_node=C.parent
  3258. while(ctx_node.type!=='node'){ctx_node=ctx_node.parent}
  3259. var tree_node=ctx_node.node
  3260. var scope=null
  3261. while(tree_node.parent.type!=='module'){
  3262. var ntype=tree_node.parent.C.tree[0].type
  3263. if(['def','class'].indexOf(ntype)>-1){
  3264. scope=tree_node.parent
  3265. scope.ntype=ntype
  3266. break
  3267. }
  3268. tree_node=tree_node.parent
  3269. }
  3270. return scope
  3271. }
  3272. function $get_ids(ctx){
  3273. var res=[]
  3274. if(ctx.type==='expr' &&
  3275. ctx.tree[0].type==='list_or_tuple' &&
  3276. ctx.tree[0].real==='list_comp'){return[]}
  3277. if(ctx.type==='id'){res.push(ctx.value)}
  3278. else if(ctx.type==='attribute'||ctx.type==='sub'){
  3279. var res1=$get_ids(ctx.value)
  3280. for(var i=0;i<res1.length;i++){
  3281. if(res.indexOf(res1[i])===-1){res.push(res1[i])}
  3282. }
  3283. }else if(ctx.type==='call'){
  3284. var res1=$get_ids(ctx.func)
  3285. for(var i=0;i<res1.length;i++){
  3286. if(res.indexOf(res1[i])===-1){res.push(res1[i])}
  3287. }
  3288. }
  3289. if(ctx.tree!==undefined){
  3290. for(var i=0;i<ctx.tree.length;i++){
  3291. var res1=$get_ids(ctx.tree[i])
  3292. for(var j=0;j<res1.length;j++){
  3293. if(res.indexOf(res1[j])===-1){
  3294. res.push(res1[j])
  3295. }
  3296. }
  3297. }
  3298. }
  3299. return res
  3300. }
  3301. function $to_js(tree,sep){
  3302. if(sep===undefined){sep=','}
  3303. var res=''
  3304. for(var i=0;i<tree.length;i++){
  3305. if(tree[i].to_js!==undefined){
  3306. res +=tree[i].to_js()
  3307. }else{
  3308. throw Error('no to_js() for '+tree[i])
  3309. }
  3310. if(i<tree.length-1){res+=sep}
  3311. }
  3312. return res
  3313. }
  3314. var $expr_starters=['id','int','float','str','[','(','{','not','lambda']
  3315. function $arbo(ctx){
  3316. while(ctx.parent!=undefined){ctx=ctx.parent}
  3317. return ctx
  3318. }
  3319. function $transition(C,token){
  3320. if(C.type==='abstract_expr'){
  3321. if($expr_starters.indexOf(token)>-1){
  3322. C.parent.tree.pop()
  3323. var commas=C.with_commas
  3324. C=C.parent
  3325. }
  3326. if(token==='id'){return new $IdCtx(new $ExprCtx(C,'id',commas),arguments[2])}
  3327. else if(token==='str'){return new $StringCtx(new $ExprCtx(C,'str',commas),arguments[2])}
  3328. else if(token==='int'){return new $IntCtx(new $ExprCtx(C,'int',commas),arguments[2])}
  3329. else if(token==='float'){return new $FloatCtx(new $ExprCtx(C,'float',commas),arguments[2])}
  3330. else if(token==='('){return new $ListOrTupleCtx(new $ExprCtx(C,'tuple',commas),'tuple')}
  3331. else if(token==='['){return new $ListOrTupleCtx(new $ExprCtx(C,'list',commas),'list')}
  3332. else if(token==='{'){return new $DictOrSetCtx(new $ExprCtx(C,'dict_or_set',commas))}
  3333. else if(token==='not'){return new $NotCtx(new $ExprCtx(C,'not',commas))}
  3334. else if(token==='lambda'){return new $LambdaCtx(new $ExprCtx(C,'lambda',commas))}
  3335. else if(token==='op'){
  3336. if('+-'.search(arguments[2])>-1){
  3337. return new $UnaryCtx(C,arguments[2])
  3338. }else{$_SyntaxError(C,'token '+token+' after '+C)}
  3339. }else if(token==='='){$_SyntaxError(C,token)}
  3340. else{return $transition(C.parent,token,arguments[2])}
  3341. }else if(C.type==='assert'){
  3342. if($expr_starters.indexOf(token)>-1&&C.expect===undefined){
  3343. C.expect='cond'
  3344. return $transition(new $AbstractExprCtx(C,false),token,arguments[2])
  3345. }else if(token===',' && C.expect==='cond'){
  3346. C.expect='arg'
  3347. return C
  3348. }else if($expr_starters.indexOf(token)>-1 && C.expect==='arg'){
  3349. return $transition(new $AbstractExprCtx(C,false),token,arguments[2])
  3350. }else if(token==='eol' && C.expect){
  3351. return $transition(C.parent,token)
  3352. }else{$_SyntaxError(C,token)}
  3353. }else if(C.type==='assign'){
  3354. if(token==='eol'){return $transition(C.parent,'eol')}
  3355. else{$_SyntaxError(C,'token '+token+' after '+C)}
  3356. }else if(C.type==='attribute'){
  3357. if(token==='id'){
  3358. var name=arguments[2]
  3359. if(name.substr(0,2)=='$$'){name=name.substr(2)}
  3360. C.name=name
  3361. return C.parent
  3362. }else{$_SyntaxError(C,token)}
  3363. }else if(C.type==='call'){
  3364. if(token===','){return C}
  3365. else if($expr_starters.indexOf(token)>-1){
  3366. var expr=new $CallArgCtx(C)
  3367. return $transition(expr,token,arguments[2])
  3368. }else if(token===')'){return C.parent}
  3369. else if(token==='op'){
  3370. var op=arguments[2]
  3371. if(op==='-'){return new $UnaryCtx(C,'-')}
  3372. else if(op==='+'){return C}
  3373. else if(op==='*'){return new $StarArgCtx(C)}
  3374. else if(op==='**'){return new $DoubleStarArgCtx(C)}
  3375. else{throw Error('SyntaxError')}
  3376. }else{return $transition(C.parent,token,arguments[2])}
  3377. }else if(C.type==='call_arg'){
  3378. if($expr_starters.indexOf(token)>-1 && C.expect==='id'){
  3379. C.expect=','
  3380. var expr=new $AbstractExprCtx(C,false)
  3381. return $transition(expr,token,arguments[2])
  3382. }else if(token==='=' && C.expect===','){
  3383. return new $ExprCtx(new $KwArgCtx(C),'kw_value',false)
  3384. }else if(token==='op' && C.expect==='id'){
  3385. var op=arguments[2]
  3386. C.expect=','
  3387. if(op==='+'||op==='-'){
  3388. return $transition(new $AbstractExprCtx(C,false),token,op)
  3389. }else if(op==='*'){C.expect=',';return new $StarArgCtx(C)}
  3390. else if(op==='**'){C.expect=',';return new $DoubleStarArgCtx(C)}
  3391. else{$_SyntaxError(C,'token '+token+' after '+C)}
  3392. }else if(token===')' && C.expect===','){
  3393. return $transition(C.parent,token)
  3394. }else if(token===','&& C.expect===','){
  3395. return new $CallArgCtx(C.parent)
  3396. }else{$_SyntaxError(C,'token '+token+' after '+C)}
  3397. }else if(C.type==='class'){
  3398. if(token==='id' && C.expect==='id'){
  3399. C.name=arguments[2]
  3400. C.expect='(:'
  3401. return C
  3402. }
  3403. else if(token==='(' && C.expect==='(:'){
  3404. return $transition(new $AbstractExprCtx(C,true),'(')
  3405. }else if(token===':' && C.expect==='(:'){return C.parent}
  3406. else{$_SyntaxError(C,'token '+token+' after '+C)}
  3407. }else if(C.type==='comp_if'){
  3408. return $transition(C.parent,token,arguments[2])
  3409. }else if(C.type==='comp_for'){
  3410. if(token==='in' && C.expect==='in'){
  3411. C.expect=null
  3412. return new $AbstractExprCtx(new $CompIterableCtx(C),true)
  3413. }else if(C.expect===null){
  3414. return $transition(C.parent,token,arguments[2])
  3415. }else{$_SyntaxError(C,'token '+token+' after '+C)}
  3416. }else if(C.type==='comp_iterable'){
  3417. return $transition(C.parent,token,arguments[2])
  3418. }else if(C.type==='comprehension'){
  3419. if(token==='if'){return new $AbstractExprCtx(new $CompIfCtx(C),false)}
  3420. else if(token==='for'){return new $TargetListCtx(new $CompForCtx(C))}
  3421. else{return $transition(C.parent,token,arguments[2])}
  3422. }else if(C.type==='condition'){
  3423. if(token===':'){
  3424. var new_node=new $Node('expression')
  3425. C.parent.node.add(new_node)
  3426. return new $NodeCtx(new_node)
  3427. }
  3428. else{$_SyntaxError(C,'token '+token+' after '+C)}
  3429. }else if(C.type==='decorator'){
  3430. if(token==='id' && C.tree.length===0){
  3431. return $transition(new $AbstractExprCtx(C,false),token,arguments[2])
  3432. }else if(token==='eol'){return $transition(C.parent,token)}
  3433. else{$_SyntaxError(C,'token '+token+' after '+C)}
  3434. }else if(C.type==='def'){
  3435. if(token==='id'){
  3436. if(C.name){
  3437. $_SyntaxError(C,'token '+token+' after '+C)
  3438. }else{
  3439. C.name=arguments[2]
  3440. return C
  3441. }
  3442. }else if(token==='('){return new $FuncArgs(C)}
  3443. else if(token===':'){return C.parent}
  3444. else{$_SyntaxError(C,'token '+token+' after '+C)}
  3445. }else if(C.type==='del'){
  3446. if(token==='eol'){return $transition(C.parent,token)}
  3447. else{$_SyntaxError(C,'token '+token+' after '+C)}
  3448. }else if(C.type==='dict_or_set'){
  3449. if(C.closed){
  3450. if(token==='['){return new $SubCtx(C)}
  3451. else if(token==='('){return new $CallArgCtx(new $CallCtx(C))}
  3452. else if(token==='op'){
  3453. return new $AbstractExprCtx(new $OpCtx(C,arguments[2]),false)
  3454. }else{return $transition(C.parent,token,arguments[2])}
  3455. }else{
  3456. if(C.expect===','){
  3457. if(token==='}'){
  3458. if(['set','set_comp','dict_comp'].indexOf(C.real)>-1||
  3459. (C.real==='dict'&&C.tree.length%2===0)){
  3460. C.items=C.tree
  3461. C.tree=[]
  3462. C.closed=true
  3463. return C
  3464. }else{$_SyntaxError(C,'token '+token+' after '+C)}
  3465. }else if(token===','){
  3466. if(C.real==='dict_or_set'){C.real='set'}
  3467. if(C.real==='dict' && C.tree.length%2){
  3468. $_SyntaxError(C,'token '+token+' after '+C)
  3469. }
  3470. C.expect='id'
  3471. return C
  3472. }else if(token===':'){
  3473. if(C.real==='dict_or_set'){C.real='dict'}
  3474. if(C.real==='dict'){
  3475. C.expect='id'
  3476. return C
  3477. }else{$_SyntaxError(C,'token '+token+' after '+C)}
  3478. }else if(token==='for'){
  3479. if(C.real==='dict_or_set'){C.real='set_comp'}
  3480. else{C.real='dict_comp'}
  3481. var lst=new $ListOrTupleCtx(C,'dict_or_set_comp')
  3482. lst.intervals=[C.start+1]
  3483. C.tree.pop()
  3484. lst.expression=C.tree
  3485. C.tree=[lst]
  3486. lst.tree=[]
  3487. var comp=new $ComprehensionCtx(lst)
  3488. return new $TargetListCtx(new $CompForCtx(comp))
  3489. }else{$_SyntaxError(C,'token '+token+' after '+C)}
  3490. }else if(C.expect==='id'){
  3491. if(token==='}'&&C.tree.length===0){
  3492. C.items=[]
  3493. C.tree=[]
  3494. C.closed=true
  3495. C.real='dict'
  3496. return C
  3497. }else if($expr_starters.indexOf(token)>-1){
  3498. C.expect=','
  3499. var expr=new $AbstractExprCtx(C,false)
  3500. return $transition(expr,token,arguments[2])
  3501. }else{$_SyntaxError(C,'token '+token+' after '+C)}
  3502. }else{return $transition(C.parent,token,arguments[2])}
  3503. }
  3504. }else if(C.type==='double_star_arg'){
  3505. if($expr_starters.indexOf(token)>-1){
  3506. return $transition(new $AbstractExprCtx(C,false),token,arguments[2])
  3507. }else if(token===','){return C.parent}
  3508. else if(token===')'){return $transition(C.parent,token)}
  3509. else{$_SyntaxError(C,'token '+token+' after '+C)}
  3510. }else if(C.type==='except'){
  3511. if(token==='id' && C.expect==='id'){
  3512. new $TargetCtx(C,arguments[2])
  3513. C.expect='as'
  3514. return C
  3515. }else if(token==='as' && C.expect==='as'
  3516. && C.has_alias===undefined
  3517. && C.tree.length===1){
  3518. C.expect='alias'
  3519. C.has_alias=true
  3520. return C
  3521. }else if(token==='id' && C.expect==='alias'){
  3522. if(C.parenth!==undefined){C.expect=','}
  3523. else{C.expect=':'}
  3524. C.tree[C.tree.length-1].alias=arguments[2]
  3525. return C
  3526. }else if(token===':' &&['id','as',':'].indexOf(C.expect)>-1){
  3527. return C.parent
  3528. }else if(token==='(' && C.expect==='id' && C.tree.length===0){
  3529. C.parenth=true
  3530. return C
  3531. }else if(token===')' &&[',','as'].indexOf(C.expect)>-1){
  3532. C.expect=':'
  3533. return C
  3534. }else if(token===',' && C.parenth!==undefined &&
  3535. C.has_alias===undefined &&
  3536. ['as',','].indexOf(C.expect)>-1){
  3537. C.expect='id'
  3538. return C
  3539. }else{$_SyntaxError(C,'token '+token+' after '+C.expect)}
  3540. }else if(C.type==='expr'){
  3541. if($expr_starters.indexOf(token)>-1 && C.expect==='expr'){
  3542. C.expect=','
  3543. return $transition(new $AbstractExprCtx(C,false),token,arguments[2])
  3544. }else if(token==='not'&&C.expect===','){
  3545. return new $ExprNot(C)
  3546. }else if(token==='in'&&C.expect===','){
  3547. return new $AbstractExprCtx(new $OpCtx(C,'in'),false)
  3548. }else if(token===',' && C.expect===','){
  3549. if(C.with_commas){
  3550. C.expect='expr'
  3551. return C
  3552. }else{return $transition(C.parent,token)}
  3553. }else if(token==='.'){return new $AttrCtx(C)}
  3554. else if(token==='['){return new $AbstractExprCtx(new $SubCtx(C),false)}
  3555. else if(token==='('){return new $CallCtx(C)}
  3556. else if(token==='op'){
  3557. var op_parent=C.parent,op=arguments[2]
  3558. var op1=C.parent,repl=null
  3559. while(true){
  3560. if(op1.type==='expr'){op1=op1.parent}
  3561. else if(op1.type==='op'&&$op_weight[op1.op]>$op_weight[op]){repl=op1;op1=op1.parent}
  3562. else{break}
  3563. }
  3564. if(repl===null){
  3565. C.parent.tree.pop()
  3566. var expr=new $ExprCtx(op_parent,'operand',C.with_commas)
  3567. expr.expect=','
  3568. C.parent=expr
  3569. var new_op=new $OpCtx(C,op)
  3570. return new $AbstractExprCtx(new_op,false)
  3571. }
  3572. repl.parent.tree.pop()
  3573. var expr=new $ExprCtx(repl.parent,'operand',false)
  3574. expr.tree=[op1]
  3575. repl.parent=expr
  3576. var new_op=new $OpCtx(repl,op)
  3577. return new $AbstractExprCtx(new_op,false)
  3578. }else if(token==='augm_assign' && C.expect===','){
  3579. return $augmented_assign(C,arguments[2])
  3580. }else if(token==='=' && C.expect===','){
  3581. if(C.parent.type==="call_arg"){
  3582. return new $AbstractExprCtx(new $KwArgCtx(C),true)
  3583. }else{
  3584. while(C.parent!==undefined){C=C.parent}
  3585. C=C.tree[0]
  3586. return new $AbstractExprCtx(new $AssignCtx(C),true)
  3587. }
  3588. }else if(token==='if' && C.parent.type!=='comp_iterable'){
  3589. return new $AbstractExprCtx(new $TernaryCtx(C),false)
  3590. }else{return $transition(C.parent,token)}
  3591. }else if(C.type==='expr_not'){
  3592. if(token==='in'){
  3593. C.parent.tree.pop()
  3594. return new $AbstractExprCtx(new $OpCtx(C.parent,'not_in'),false)
  3595. }else{$_SyntaxError(C,'token '+token+' after '+C)}
  3596. }else if(C.type==='for'){
  3597. if(token==='in'){return new $AbstractExprCtx(C,true)}
  3598. else if(token===':'){return C.parent}
  3599. else{$_SyntaxError(C,'token '+token+' after '+C)}
  3600. }else if(C.type==='from'){
  3601. if(token==='id' && C.expect==='module'){
  3602. C.module=arguments[2]
  3603. C.expect='import'
  3604. return C
  3605. }else if(token==='import' && C.expect==='import'){
  3606. C.expect='id'
  3607. return C
  3608. }else if(token==='import' && C.expect==='module'
  3609. && C.relpath !==undefined){
  3610. C.expect='id'
  3611. return C
  3612. }else if(token==='id' && C.expect==='id'){
  3613. C.names.push(arguments[2])
  3614. C.expect=','
  3615. return C
  3616. }else if(token==='op' && arguments[2]==='*'
  3617. && C.expect==='id'
  3618. && C.names.length===0){
  3619. C.names.push('*')
  3620. C.expect='eol'
  3621. return C
  3622. }else if(token===',' && C.expect===','){
  3623. C.expect='id'
  3624. return C
  3625. }else if(token==='eol' &&
  3626. (C.expect===',' || C.expect==='eol')){
  3627. return $transition(C.parent,token)
  3628. }else if(token==='.' && C.expect==='module'){
  3629. C.expect='module'
  3630. C.parent_module=C.parent.node.module
  3631. return C
  3632. }else if(token==='as' &&
  3633. (C.expect===',' || C.expect==='eol')){
  3634. C.expect='alias'
  3635. return C
  3636. }else if(token==='id' && C.expect==='alias'){
  3637. C.aliases[C.names[C.names.length-1]]=arguments[2]
  3638. C.expect=','
  3639. return C
  3640. }else if(token==='(' && C.expect==='id'){
  3641. C.expect='id'
  3642. return C
  3643. }else if(token===')' && C.expect===','){
  3644. C.expect='eol'
  3645. return C
  3646. }else{$_SyntaxError(C,'token '+token+' after '+C)}
  3647. }else if(C.type==='func_arg_id'){
  3648. if(token==='=' && C.expect==='='){
  3649. C.parent.has_default=true
  3650. return new $AbstractExprCtx(C,false)
  3651. }else if(token===',' || token===')'){
  3652. if(C.parent.has_default && C.tree.length==0){
  3653. throw Error('SyntaxError: non-default argument follows default argument')
  3654. }else{
  3655. return $transition(C.parent,token)
  3656. }
  3657. }else{$_SyntaxError(C,'token '+token+' after '+C)}
  3658. }else if(C.type==='func_args'){
  3659. if(token==='id' && C.expect==='id'){
  3660. C.expect=','
  3661. return new $FuncArgIdCtx(C,arguments[2])
  3662. }else if(token===','){
  3663. if(C.has_kw_arg){throw Error('SyntaxError')}
  3664. else if(C.expect===','){
  3665. C.expect='id'
  3666. return C
  3667. }else{$_SyntaxError(C,'token '+token+' after '+C)}
  3668. }else if(token===')'){
  3669. if(C.expect===','){return C.parent}
  3670. else if(C.tree.length==0){return C.parent}
  3671. else{$_SyntaxError(C,'token '+token+' after '+C)}
  3672. }else if(token==='op'){
  3673. var op=arguments[2]
  3674. C.expect=','
  3675. if(op=='*'){return new $FuncStarArgCtx(C,'*')}
  3676. else if(op=='**'){return new $FuncStarArgCtx(C,'**')}
  3677. else{$_SyntaxError(C,'token '+op+' after '+C)}
  3678. }else{$_SyntaxError(C,'token '+token+' after '+C)}
  3679. }else if(C.type==='func_star_arg'){
  3680. if(token==='id' && C.name===undefined){
  3681. C.name=arguments[2]
  3682. return C.parent
  3683. }else{$_SyntaxError(C,'token '+token+' after '+C)}
  3684. }else if(C.type==='global'){
  3685. if(token==='id' && C.expect==='id'){
  3686. new $IdCtx(C,arguments[2])
  3687. C.expect=','
  3688. return C
  3689. }else if(token===',' && C.expect===','){
  3690. C.expect='id'
  3691. return C
  3692. }else if(token==='eol' && C.expect===','){
  3693. return $transition(C.parent,token)
  3694. }else{$_SyntaxError(C,'token '+token+' after '+C)}
  3695. }else if(C.type==='id'){
  3696. if(token==='='){
  3697. if(C.parent.type==='expr' &&
  3698. C.parent.parent !==undefined &&
  3699. C.parent.parent.type==='call_arg'){
  3700. return new $AbstractExprCtx(new $KwArgCtx(C.parent),false)
  3701. }else{return $transition(C.parent,token,arguments[2])}
  3702. }else if(token==='op'){return $transition(C.parent,token,arguments[2])}
  3703. else if(token=='id'){$_SyntaxError(C,'token '+token+' after '+C)}
  3704. else{return $transition(C.parent,token,arguments[2])}
  3705. }else if(C.type==='import'){
  3706. if(token==='id' && C.expect==='id'){
  3707. new $ImportedModuleCtx(C,arguments[2])
  3708. C.expect=','
  3709. return C
  3710. }else if(token===',' && C.expect===','){
  3711. C.expect='id'
  3712. return C
  3713. }else if(token==='as' && C.expect===','){
  3714. C.expect='alias'
  3715. return C
  3716. }else if(token==='id' && C.expect==='alias'){
  3717. C.expect=','
  3718. C.tree[C.tree.length-1].alias=arguments[2]
  3719. var mod_name=C.tree[C.tree.length-1].name
  3720. document.$py_module_alias[mod_name]=arguments[2]
  3721. return C
  3722. }else if(token==='eol' && C.expect===','){
  3723. return $transition(C.parent,token)
  3724. }else{$_SyntaxError(C,'token '+token+' after '+C)}
  3725. }else if(C.type==='int'||C.type==='float'){
  3726. if($expr_starters.indexOf(token)>-1){
  3727. $_SyntaxError(C,'token '+token+' after '+C)
  3728. }else{return $transition(C.parent,token,arguments[2])}
  3729. }else if(C.type==='kwarg'){
  3730. if(token===')'){return $transition(C.parent,token)}
  3731. else if(token===','){return new $CallArgCtx(C.parent)}
  3732. else{$_SyntaxError(C,'token '+token+' after '+C)}
  3733. }else if(C.type==="lambda"){
  3734. if(C.args_start===undefined){
  3735. C.args_start=$pos
  3736. return C
  3737. }else if(token===':' && C.tree.length===0){
  3738. C.body_start=$pos
  3739. return new $AbstractExprCtx(C,false)
  3740. }else if(C.tree.length>0){
  3741. C.body_end=$pos
  3742. return $transition(C.parent,token)
  3743. }else if(C.tree.length===0){return C}
  3744. else{$_SyntaxError(C,'token '+token+' after '+C)}
  3745. }else if(C.type==='list_or_tuple'){
  3746. if(C.closed){
  3747. if(token==='['){return new $SubCtx(C.parent)}
  3748. else if(token==='('){return new $CallCtx(C)}
  3749. else if(token==='.'){return new $AttrCtx(C)}
  3750. else if(token==='op'){
  3751. return new $AbstractExprCtx(new $OpCtx(C,arguments[2]),false)
  3752. }else{return $transition(C.parent,token,arguments[2])}
  3753. }else{
  3754. if(C.expect===','){
  3755. if((C.real==='tuple'||C.real==='gen_expr')
  3756. && token===')'){
  3757. C.closed=true
  3758. if(C.real==='gen_expr'){C.intervals.push($pos)}
  3759. return C
  3760. }else if((C.real==='list'||C.real==='list_comp')
  3761. && token===']'){
  3762. C.closed=true
  3763. if(C.real==='list_comp'){C.intervals.push($pos)}
  3764. return C
  3765. }else if(C.real==='dict_or_set_comp' && token==='}'){
  3766. C.intervals.push($pos)
  3767. return $transition(C.parent,token)
  3768. }else if(token===','){
  3769. if(C.real==='tuple'){C.has_comma=true}
  3770. C.expect='id'
  3771. return C
  3772. }else if(token==='for'){
  3773. if(C.real==='list'){C.real='list_comp'}
  3774. else{C.real='gen_expr'}
  3775. C.intervals=[C.start+1]
  3776. C.expression=C.tree
  3777. C.tree=[]
  3778. var comp=new $ComprehensionCtx(C)
  3779. return new $TargetListCtx(new $CompForCtx(comp))
  3780. }else{return $transition(C.parent,token,arguments[2])}
  3781. }else if(C.expect==='id'){
  3782. if(C.real==='tuple' && token===')'){
  3783. C.closed=true
  3784. return C
  3785. }else if(C.real==='list'&& token===']'){
  3786. C.closed=true
  3787. return C
  3788. }else if(token !==')'&&token!==']'&&token!==','){
  3789. C.expect=','
  3790. var expr=new $AbstractExprCtx(C,false)
  3791. return $transition(expr,token,arguments[2])
  3792. }
  3793. }else{return $transition(C.parent,token,arguments[2])}
  3794. }
  3795. }else if(C.type==='list_comp'){
  3796. if(token===']'){return C.parent}
  3797. else if(token==='in'){return new $ExprCtx(C,'iterable',true)}
  3798. else if(token==='if'){return new $ExprCtx(C,'condition',true)}
  3799. else{$_SyntaxError(C,'token '+token+' after '+C)}
  3800. }else if(C.type==='node'){
  3801. if($expr_starters.indexOf(token)>-1){
  3802. var expr=new $AbstractExprCtx(C,true)
  3803. return $transition(expr,token,arguments[2])
  3804. }else if(token==='class'){return new $ClassCtx(C)}
  3805. else if(token==='def'){return new $DefCtx(C)}
  3806. else if(token==='for'){return new $TargetListCtx(new $ForExpr(C))}
  3807. else if(['if','elif','while'].indexOf(token)>-1){
  3808. return new $AbstractExprCtx(new $ConditionCtx(C,token),false)
  3809. }else if(['else','finally'].indexOf(token)>-1){
  3810. return new $SingleKwCtx(C,token)
  3811. }else if(token==='try'){return new $TryCtx(C)}
  3812. else if(token==='except'){return new $ExceptCtx(C)}
  3813. else if(token==='assert'){return new $AssertCtx(C)}
  3814. else if(token==='from'){return new $FromCtx(C)}
  3815. else if(token==='import'){return new $ImportCtx(C)}
  3816. else if(token==='global'){return new $GlobalCtx(C)}
  3817. else if(token==='lambda'){return new $LambdaCtx(C)}
  3818. else if(token==='pass'){return new $PassCtx(C)}
  3819. else if(token==='raise'){return new $RaiseCtx(C)}
  3820. else if(token==='return'){
  3821. var ret=new $ReturnCtx(C)
  3822. return new $AbstractExprCtx(ret,true)
  3823. }else if(token==='yield'){
  3824. var yield=new $YieldCtx(C)
  3825. return new $AbstractExprCtx(yield,true)
  3826. }else if(token==='del'){return new $AbstractExprCtx(new $DelCtx(C),true)}
  3827. else if(token==='@'){return new $DecoratorCtx(C)}
  3828. else if(token===':'){
  3829. var tree_node=C.node
  3830. var new_node=new $Node('expression')
  3831. tree_node.add(new_node)
  3832. return new $NodeCtx(new_node)
  3833. }else if(token==='eol'){
  3834. if(C.tree.length===0){
  3835. C.node.parent.children.pop()
  3836. return C.node.parent.C
  3837. }
  3838. return C
  3839. }else{$_SyntaxError(C,'token '+token+' after '+C)}
  3840. }else if(C.type==='not'){
  3841. if(token==='in'){
  3842. C.parent.parent.tree.pop()
  3843. return new $ExprCtx(new $OpCtx(C.parent,'not_in'),'op',false)
  3844. }else if($expr_starters.indexOf(token)>-1){
  3845. var expr=new $AbstractExprCtx(C,false)
  3846. return $transition(expr,token,arguments[2])
  3847. }else{return $transition(C.parent,token)}
  3848. }else if(C.type==='op'){
  3849. if($expr_starters.indexOf(token)>-1){
  3850. return $transition(new $AbstractExprCtx(C,false),token,arguments[2])
  3851. }else if(token==='op' && '+-'.search(arguments[2])>-1){
  3852. return new $UnaryCtx(C,arguments[2])
  3853. }else{return $transition(C.parent,token)}
  3854. }else if(C.type==='pass'){
  3855. if(token==='eol'){return C.parent}
  3856. else{$_SyntaxError(C,'token '+token+' after '+C)}
  3857. }else if(C.type==='raise'){
  3858. if(token==='id' && C.tree.length===0){
  3859. return new $IdCtx(new $ExprCtx(C,'exc',false),arguments[2])
  3860. }else if(token==='eol'){
  3861. return $transition(C.parent,token)
  3862. }else{$_SyntaxError(C,'token '+token+' after '+C)}
  3863. }else if(C.type==='return'){
  3864. return $transition(C.parent,token)
  3865. }else if(C.type==='single_kw'){
  3866. if(token===':'){return C.parent}
  3867. else{$_SyntaxError(C,'token '+token+' after '+C)}
  3868. }else if(C.type==='star_arg'){
  3869. if($expr_starters.indexOf(token)>-1){
  3870. return $transition(new $AbstractExprCtx(C,false),token,arguments[2])
  3871. }else if(token===','){return C.parent}
  3872. else if(token===')'){return $transition(C.parent,token)}
  3873. else{$_SyntaxError(C,'token '+token+' after '+C)}
  3874. }else if(C.type==='str'){
  3875. if(token==='['){return new $AbstractExprCtx(new $SubCtx(C),false)}
  3876. else if(token==='('){return new $CallCtx(C)}
  3877. else if(token=='str'){C.value +='+'+arguments[2];return C}
  3878. else{return $transition(C.parent,token,arguments[2])}
  3879. }else if(C.type==='sub'){
  3880. if($expr_starters.indexOf(token)>-1){
  3881. var expr=new $AbstractExprCtx(C,false)
  3882. return $transition(expr,token,arguments[2])
  3883. }else if(token===']'){return C.parent}
  3884. else if(token===':'){
  3885. return new $AbstractExprCtx(C,false)
  3886. }else{$_SyntaxError(C,'token '+token+' after '+C)}
  3887. }else if(C.type==='target_list'){
  3888. if(token==='id' && C.expect==='id'){
  3889. C.expect=','
  3890. new $IdCtx(C,arguments[2])
  3891. return C
  3892. }else if((token==='('||token==='[')&&C.expect==='id'){
  3893. C.expect=','
  3894. return new $TargetListCtx(C)
  3895. }else if((token===')'||token===']')&&C.expect===','){
  3896. return C.parent
  3897. }else if(token===',' && C.expect==','){
  3898. C.expect='id'
  3899. return C
  3900. }else if(C.expect===','){return $transition(C.parent,token,arguments[2])}
  3901. else{$_SyntaxError(C,'token '+token+' after '+C)}
  3902. }else if(C.type==='ternary'){
  3903. if(token==='else'){return new $AbstractExprCtx(C,false)}
  3904. else{return $transition(C.parent,token,arguments[2])}
  3905. }else if(C.type==='try'){
  3906. if(token===':'){return C.parent}
  3907. else{$_SyntaxError(C,'token '+token+' after '+C)}
  3908. }else if(C.type==='unary'){
  3909. if(['int','float'].indexOf(token)>-1){
  3910. C.parent.tree.pop()
  3911. var value=arguments[2]
  3912. if(C.op==='-'){value=-value}
  3913. return $transition(C.parent,token,value)
  3914. }else if(token==='id'){
  3915. C.parent.tree.pop()
  3916. if(C.op==='-'){
  3917. var int_expr=new $IntCtx(C.parent,-1)
  3918. return $transition(new $OpCtx(int_expr,'*'),token,arguments[2])
  3919. }else{
  3920. return $transition(C.parent,token,arguments[2])
  3921. }
  3922. }else if(token==="op" && '+-'.search(arguments[2])>-1){
  3923. var op=arguments[2]
  3924. if(C.op===op){C.op='+'}else{C.op='-'}
  3925. return C
  3926. }else{return $transition(C.parent,token,arguments[2])}
  3927. }else if(C.type==='yield'){
  3928. return $transition(C.parent,token)
  3929. }
  3930. }
  3931. __BRYTHON__.py2js=function(src,module){
  3932. src=src.replace(/\r\n/gm,'\n')
  3933. while(src.length>0 &&(src.charAt(0)=="\n" || src.charAt(0)=="\r")){
  3934. src=src.substr(1)
  3935. }
  3936. if(src.charAt(src.length-1)!="\n"){src+='\n'}
  3937. if(module===undefined){module='__main__'}
  3938. document.$py_src[module]=src
  3939. var root=$tokenize(src,module)
  3940. root.transform()
  3941. if(document.$debug>0){$add_line_num(root,null,module)}
  3942. return root
  3943. }
  3944. function $tokenize(src,module){
  3945. var delimiters=[["#","\n","comment"],['"""','"""',"triple_string"],
  3946. ["'","'","string"],['"','"',"string"],
  3947. ["r'","'","raw_string"],['r"','"',"raw_string"]]
  3948. var br_open={"(":0,"[":0,"{":0}
  3949. var br_close={")":"(","]":"[","}":"{"}
  3950. var br_stack=""
  3951. var br_pos=new Array()
  3952. var kwdict=["class","return",
  3953. "for","lambda","try","finally","raise","def","from",
  3954. "nonlocal","while","del","global","with",
  3955. "as","elif","else","if","yield","assert","import",
  3956. "except","raise","in","not","pass",
  3957. ]
  3958. var unsupported=["nonlocal","with"]
  3959. var $indented=['class','def','for','condition','single_kw','try','except']
  3960. var forbidden=['case','catch','debugger','default','delete',
  3961. 'do','function','instanceof','new','switch','this','throw',
  3962. 'typeof','var','void','with','enum','export','extends','super',
  3963. 'Anchor','Area','arguments','Array','assign','blur','Boolean','Button',
  3964. 'callee','caller','captureEvents','Checkbox','clearInterval','clearTimeout',
  3965. 'close','closed','constructor','Date','defaultStatus','document','Document',
  3966. 'Element','escape','FileUpload','find','focus','Form','Frame','Frames','Function',
  3967. 'getClass','Hidden','history','History','home','Image','Infinity','InnerHeight',
  3968. 'InnerWidth','isFinite','isNan','java','JavaArray','JavaClass','JavaObject',
  3969. 'JavaPackage','length','Link','location','Location','locationbar','Math','menubar',
  3970. 'MimeType','moveBy','moveTo','name','NaN','navigate','navigator','Navigator','netscape',
  3971. 'Number','Object','onBlur','onError','onFocus','onLoad','onUnload','opener',
  3972. 'Option','outerHeight','OuterWidth','Packages','pageXoffset','pageYoffset',
  3973. 'parent','parseFloat','parseInt','Password','personalbar','Plugin','prototype',
  3974. 'Radio','ref','RegExp','releaseEvents','Reset','resizeBy','resizeTo','routeEvent',
  3975. 'scroll','scrollbars','scrollBy','scrollTo','Select','self','setInterval','setTimeout',
  3976. 'status','statusbar','stop','String','Submit','sun','taint','Text','Textarea','toolbar',
  3977. 'top','toString','unescape','untaint','unwatch','valueOf','watch','window','Window'
  3978. ]
  3979. var punctuation={',':0,':':0}
  3980. var int_pattern=new RegExp("^\\d+")
  3981. var float_pattern1=new RegExp("^\\d+\\.\\d*(e-?\\d+)?")
  3982. var float_pattern2=new RegExp("^\\d+(e-?\\d+)")
  3983. var id_pattern=new RegExp("[\\$_a-zA-Z]\\w*")
  3984. var qesc=new RegExp('"',"g")
  3985. var C=null
  3986. var root=new $Node('module')
  3987. root.indent=-1
  3988. var new_node=new $Node('expression')
  3989. current=root
  3990. var name=""
  3991. var _type=null
  3992. var pos=0
  3993. indent=null
  3994. var lnum=1
  3995. while(pos<src.length){
  3996. var flag=false
  3997. var car=src.charAt(pos)
  3998. if(indent===null){
  3999. var indent=0
  4000. while(pos<src.length){
  4001. if(src.charAt(pos)==" "){indent++;pos++}
  4002. else if(src.charAt(pos)=="\t"){
  4003. indent++;pos++
  4004. while(indent%8>0){indent++}
  4005. }else{break}
  4006. }
  4007. if(src.charAt(pos)=='\n'){pos++;lnum++;indent=null;continue}
  4008. else if(src.charAt(pos)==='#'){
  4009. var offset=src.substr(pos).search(/\n/)
  4010. if(offset===-1){break}
  4011. pos+=offset+1;lnum++;indent=null;continue
  4012. }
  4013. new_node.indent=indent
  4014. new_node.line_num=lnum
  4015. new_node.module=module
  4016. if(indent>current.indent){
  4017. if(C!==null){
  4018. if($indented.indexOf(C.tree[0].type)==-1){
  4019. $pos=pos
  4020. $_SyntaxError(C,'unexpected indent',pos)
  4021. }
  4022. }
  4023. current.add(new_node)
  4024. }else if(indent<=current.indent &&
  4025. $indented.indexOf(C.tree[0].type)>-1){
  4026. $pos=pos
  4027. $_SyntaxError(C,'expected an indented block',pos)
  4028. }else{
  4029. while(indent!==current.indent){
  4030. current=current.parent
  4031. if(current===undefined || indent>current.indent){
  4032. $pos=pos
  4033. $_SyntaxError(C,'unexpected indent',pos)
  4034. }
  4035. }
  4036. current.parent.add(new_node)
  4037. }
  4038. current=new_node
  4039. C=new $NodeCtx(new_node)
  4040. continue
  4041. }
  4042. if(car=="#"){
  4043. var end=src.substr(pos+1).search('\n')
  4044. if(end==-1){end=src.length-1}
  4045. pos +=end+1;continue
  4046. }
  4047. if(car=='"' || car=="'"){
  4048. var raw=false
  4049. var end=null
  4050. if(name.length>0 && name.toLowerCase()=="r"){
  4051. raw=true;name=""
  4052. }
  4053. if(src.substr(pos,3)==car+car+car){_type="triple_string";end=pos+3}
  4054. else{_type="string";end=pos+1}
  4055. var escaped=false
  4056. var zone=car
  4057. var found=false
  4058. while(end<src.length){
  4059. if(escaped){zone+=src.charAt(end);escaped=false;end+=1}
  4060. else if(src.charAt(end)=="\\"){
  4061. if(raw){
  4062. zone +='\\\\'
  4063. end++
  4064. }else{
  4065. if(src.charAt(end+1)=='\n'){
  4066. end +=2
  4067. lnum++
  4068. }else{
  4069. zone+=src.charAt(end);escaped=true;end+=1
  4070. }
  4071. }
  4072. }else if(src.charAt(end)==car){
  4073. if(_type=="triple_string" && src.substr(end,3)!=car+car+car){
  4074. end++
  4075. }else{
  4076. found=true
  4077. $pos=pos-zone.length-1
  4078. var string=zone.substr(1).replace(qesc,'\\"')
  4079. C=$transition(C,'str',zone+car)
  4080. pos=end+1
  4081. if(_type=="triple_string"){pos=end+3}
  4082. break
  4083. }
  4084. }else{
  4085. zone +=src.charAt(end)
  4086. if(src.charAt(end)=='\n'){lnum++}
  4087. end++
  4088. }
  4089. }
  4090. if(!found){$_SyntaxError(C,"String end not found")}
  4091. continue
  4092. }
  4093. if(name==""){
  4094. if(car.search(/[a-zA-Z_]/)!=-1){
  4095. name=car
  4096. pos++;continue
  4097. }
  4098. }else{
  4099. if(car.search(/\w/)!=-1){
  4100. name+=car
  4101. pos++;continue
  4102. }else{
  4103. if(kwdict.indexOf(name)>-1){
  4104. if(unsupported.indexOf(name)>-1){
  4105. $_SyntaxError(C,"Unsupported Python keyword '"+name+"'")
  4106. }
  4107. $pos=pos-name.length
  4108. C=$transition(C,name)
  4109. }else if(name in $operators){
  4110. $pos=pos-name.length
  4111. C=$transition(C,'op',name)
  4112. }else{
  4113. if(forbidden.indexOf(name)>-1){name='$$'+name}
  4114. $pos=pos-name.length
  4115. C=$transition(C,'id',name)
  4116. }
  4117. name=""
  4118. continue
  4119. }
  4120. }
  4121. if(car=="."){
  4122. $pos=pos
  4123. C=$transition(C,'.')
  4124. pos++;continue
  4125. }
  4126. if(car.search(/\d/)>-1){
  4127. var res=float_pattern1.exec(src.substr(pos))
  4128. if(res){
  4129. if(res[0].search('e')>-1){
  4130. $pos=pos
  4131. C=$transition(C,'float',res[0])
  4132. }else{
  4133. $pos=pos
  4134. C=$transition(C,'float',eval(res[0]))
  4135. }
  4136. }else{
  4137. res=float_pattern2.exec(src.substr(pos))
  4138. if(res){
  4139. $pos=pos
  4140. C=$transition(C,'float',res[0])
  4141. }else{
  4142. res=int_pattern.exec(src.substr(pos))
  4143. $pos=pos
  4144. C=$transition(C,'int',eval(res[0]))
  4145. }
  4146. }
  4147. pos +=res[0].length
  4148. continue
  4149. }
  4150. if(car=="\n"){
  4151. lnum++
  4152. if(br_stack.length>0){
  4153. pos++;continue
  4154. }else{
  4155. if(current.C.tree.length>0){
  4156. $pos=pos
  4157. C=$transition(C,'eol')
  4158. indent=null
  4159. new_node=new $Node()
  4160. }else{
  4161. new_node.line_num=lnum
  4162. }
  4163. pos++;continue
  4164. }
  4165. }
  4166. if(car in br_open){
  4167. br_stack +=car
  4168. br_pos[br_stack.length-1]=[C,pos]
  4169. $pos=pos
  4170. C=$transition(C,car)
  4171. pos++;continue
  4172. }
  4173. if(car in br_close){
  4174. if(br_stack==""){
  4175. $_SyntaxError(C,"Unexpected closing bracket")
  4176. }else if(br_close[car]!=$last(br_stack)){
  4177. $_SyntaxError(C,"Unbalanced bracket")
  4178. }else{
  4179. br_stack=br_stack.substr(0,br_stack.length-1)
  4180. $pos=pos
  4181. C=$transition(C,car)
  4182. pos++;continue
  4183. }
  4184. }
  4185. if(car=="="){
  4186. if(src.charAt(pos+1)!="="){
  4187. $pos=pos
  4188. C=$transition(C,'=')
  4189. pos++;continue
  4190. }else{
  4191. $pos=pos
  4192. C=$transition(C,'op','==')
  4193. pos+=2;continue
  4194. }
  4195. }
  4196. if(car in punctuation){
  4197. $pos=pos
  4198. C=$transition(C,car)
  4199. pos++;continue
  4200. }
  4201. if(car in $first_op_letter){
  4202. var op_match=""
  4203. for(op_sign in $operators){
  4204. if(op_sign==src.substr(pos,op_sign.length)
  4205. && op_sign.length>op_match.length){
  4206. op_match=op_sign
  4207. }
  4208. }
  4209. $pos=pos
  4210. if(op_match.length>0){
  4211. if(op_match in $augmented_assigns){
  4212. C=$transition(C,'augm_assign',op_match)
  4213. }else{
  4214. C=$transition(C,'op',op_match)
  4215. }
  4216. pos +=op_match.length
  4217. continue
  4218. }
  4219. }
  4220. if(car=='\\' && src.charAt(pos+1)=='\n'){
  4221. lnum++;pos+=2;continue
  4222. }
  4223. if(car=='@'){
  4224. $pos=pos
  4225. C=$transition(C,car)
  4226. pos++;continue
  4227. }
  4228. if(car!=' '&&car!=='\t'){$pos=pos;$_SyntaxError(C,'unknown token ['+car+']')}
  4229. pos +=1
  4230. }
  4231. if(br_stack.length!=0){
  4232. var br_err=br_pos[0]
  4233. $pos=br_err[1]
  4234. $_SyntaxError(br_err[0],"Unbalanced bracket "+br_stack.charAt(br_stack.length-1))
  4235. }
  4236. return root
  4237. }
  4238. function brython(debug){
  4239. document.$py_src={}
  4240. document.$py_module_path={}
  4241. document.$py_module_alias={}
  4242. document.$py_next_hash=-Math.pow(2,53)
  4243. document.$debug=debug
  4244. __BRYTHON__.exception_stack=[]
  4245. var elts=document.getElementsByTagName("script")
  4246. var href=window.location.href
  4247. var href_elts=href.split('/')
  4248. href_elts.pop()
  4249. var script_path=href_elts.join('/')
  4250. __BRYTHON__.path=[script_path]
  4251. for(var $i=0;$i<elts.length;$i++){
  4252. var elt=elts[$i]
  4253. if(elt.type=="text/python"){
  4254. if(elt.src!==''){
  4255. if(window.XMLHttpRequest){
  4256. var $xmlhttp=new XMLHttpRequest()
  4257. }else{
  4258. var $xmlhttp=new ActiveXObject("Microsoft.XMLHTTP")
  4259. }
  4260. $xmlhttp.onreadystatechange=function(){
  4261. var state=this.readyState
  4262. if(state===4){
  4263. src=$xmlhttp.responseText
  4264. }
  4265. }
  4266. $xmlhttp.open('GET',elt.src,false)
  4267. $xmlhttp.send()
  4268. document.$py_module_path['__main__']=elt.src
  4269. __BRYTHON__.path=[elt.src]
  4270. }else{
  4271. var src=(elt.innerHTML || elt.textContent)
  4272. document.$py_module_path['__main__']='.'
  4273. }
  4274. var root=__BRYTHON__.py2js(src,'__main__')
  4275. var js=root.to_js()
  4276. if(debug===2){console.log(js)}
  4277. eval(js)
  4278. }else{
  4279. var br_scripts=['brython.js','py_list.js']
  4280. for(var j=0;j<br_scripts.length;j++){
  4281. var bs=br_scripts[j]
  4282. if(elt.src.substr(elt.src.length-bs.length)==bs){
  4283. if(elt.src.length===bs.length ||
  4284. elt.src.charAt(elt.src.length-bs.length-1)=='/'){
  4285. var path=elt.src.substr(0,elt.src.length-bs.length)
  4286. __BRYTHON__.brython_path=path
  4287. __BRYTHON__.path.push(path+'Lib')
  4288. break
  4289. }
  4290. }
  4291. }
  4292. }
  4293. }
  4294. }
  4295. function $MakeArgs($fname,$args,$required,$defaults,$other_args,$other_kw){
  4296. var i=null,$PyVars={},$def_names=[],$ns={}
  4297. for(var k in $defaults){$def_names.push(k);$ns[k]=$defaults[k]}
  4298. if($other_args !=null){$ns[$other_args]=[]}
  4299. if($other_kw !=null){$dict_keys=[];$dict_values=[]}
  4300. var upargs=[]
  4301. for(var i=0;i<$args.length;i++){
  4302. if($args[i]===null){upargs.push(null)}
  4303. else if(isinstance($args[i],$ptuple)){
  4304. for(var j=0;j<$args[i].arg.length;j++){
  4305. upargs.push($args[i].arg[j])
  4306. }
  4307. }else if(isinstance($args[i],$pdict)){
  4308. for(var j=0;j<$args[i].arg.$keys.length;j++){
  4309. upargs.push($Kw($args[i].arg.$keys[j],$args[i].arg.$values[j]))
  4310. }
  4311. }else{
  4312. upargs.push($args[i])
  4313. }
  4314. }
  4315. for(var $i=0;$i<upargs.length;$i++){
  4316. $arg=upargs[$i]
  4317. $PyVar=$JS2Py($arg)
  4318. if(isinstance($arg,$Kw)){
  4319. $PyVar=$arg.value
  4320. if($arg.name in $PyVars){
  4321. throw new TypeError($fname+"() got multiple values for argument '"+$arg.name+"'")
  4322. }else if($required.indexOf($arg.name)>-1){
  4323. var ix=$required.indexOf($arg.name)
  4324. eval('var '+$required[ix]+"=$PyVar")
  4325. $ns[$required[ix]]=$PyVar
  4326. }else if($arg.name in $defaults){
  4327. $ns[$arg.name]=$PyVar
  4328. }else if($other_kw!=null){
  4329. $dict_keys.push($arg.name)
  4330. $dict_values.push($PyVar)
  4331. }else{
  4332. throw new TypeError($fname+"() got an unexpected keyword argument '"+$arg.name+"'")
  4333. }
  4334. if($arg.name in $defaults){delete $defaults[$arg.name]}
  4335. }else{
  4336. if($i<$required.length){
  4337. eval('var '+$required[$i]+"=$PyVar")
  4338. $ns[$required[$i]]=$PyVar
  4339. }else if($i<$required.length+$def_names.length){
  4340. $ns[$def_names[$i-$required.length]]=$PyVar
  4341. }else if($other_args!=null){
  4342. eval('$ns["'+$other_args+'"].push($PyVar)')
  4343. }else{
  4344. msg=$fname+"() takes "+$required.length+' positional arguments '
  4345. msg +='but more were given'
  4346. throw TypeError(msg)
  4347. }
  4348. }
  4349. }
  4350. if($other_kw!=null){$ns[$other_kw]=new $DictClass($dict_keys,$dict_values)}
  4351. return $ns
  4352. }
  4353. function $list_comp(){
  4354. var $env=arguments[0]
  4355. for(var $arg in $env){
  4356. eval("var "+$arg+'=$env["'+$arg+'"]')
  4357. }
  4358. var $res='res'+Math.random().toString(36).substr(2,8)
  4359. var $py=$res+"=[]\n"
  4360. var indent=0
  4361. for(var i=2;i<arguments.length;i++){
  4362. for(var j=0;j<indent;j++){$py +=' '}
  4363. $py +=arguments[i]+':\n'
  4364. indent +=4
  4365. }
  4366. for(var j=0;j<indent;j++){$py +=' '}
  4367. $py +=$res+'.append('+arguments[1]+')'
  4368. var $js=__BRYTHON__.py2js($py,'list comprehension').to_js()
  4369. eval($js)
  4370. return eval($res)
  4371. }
  4372. function $gen_expr(){
  4373. var $env=arguments[0]
  4374. for(var $arg in $env){
  4375. eval("var "+$arg+'=$env["'+$arg+'"]')
  4376. }
  4377. var $res='res'+Math.random().toString(36).substr(2,8)
  4378. var $py=$res+"=[]\n"
  4379. var indent=0
  4380. for(var i=2;i<arguments.length;i++){
  4381. for(var j=0;j<indent;j++){$py +=' '}
  4382. $py +=arguments[i]+':\n'
  4383. indent +=4
  4384. }
  4385. for(var j=0;j<indent;j++){$py +=' '}
  4386. $py +=$res+'.append('+arguments[1]+')'
  4387. var $js=__BRYTHON__.py2js($py,'generator expression').to_js()
  4388. eval($js)
  4389. return eval($res)
  4390. }
  4391. function $dict_comp(){
  4392. var $env=arguments[0]
  4393. for(var $arg in $env){
  4394. eval("var "+$arg+'=$env["'+$arg+'"]')
  4395. }
  4396. var $res='res'+Math.random().toString(36).substr(2,8)
  4397. var $py=$res+"={}\n"
  4398. var indent=0
  4399. for(var i=2;i<arguments.length;i++){
  4400. for(var j=0;j<indent;j++){$py +=' '}
  4401. $py +=arguments[i]+':\n'
  4402. indent +=4
  4403. }
  4404. for(var j=0;j<indent;j++){$py +=' '}
  4405. $py +=$res+'.update({'+arguments[1]+'})'
  4406. alert($py)
  4407. var $js=__BRYTHON__.py2js($py,'dict comprehension').to_js()
  4408. eval($js)
  4409. return eval($res)
  4410. }
  4411. function $generator(func){
  4412. var res=function(){
  4413. func.$iter=[]
  4414. func.apply(this,arguments)
  4415. var obj=new Object()
  4416. obj.__class__=$generator
  4417. obj.__len__=function(){return func.$iter.__len__()}
  4418. obj.__item__=function(rank){return func.$iter.__item__(rank)}
  4419. return obj
  4420. }
  4421. res.__str__=function(){return "<function "+res.__name__+">"}
  4422. return res
  4423. }
  4424. function $ternary(env,cond,expr1,expr2){
  4425. for(var attr in env){eval('var '+attr+'=env["'+attr+'"]')}
  4426. var res='if ('+cond+'){\n'
  4427. res +=' var $res = '+expr1+'\n}else{\n'
  4428. res +=' var $res = '+expr2+'\n}'
  4429. eval(res)
  4430. return $res
  4431. }
  4432. function $lambda(args,body){
  4433. var $res='res'+Math.random().toString(36).substr(2,8)
  4434. var $py='def '+$res+'('+args+'):\n'
  4435. $py +=' return '+body
  4436. var $js=__BRYTHON__.py2js($py,'lambda').to_js()
  4437. eval($js)
  4438. return eval($res)
  4439. }
  4440. function $JS2Py(src){
  4441. if(src===null){return None}
  4442. if(typeof src==='number'){
  4443. if(src%1===0){return src}
  4444. else{return float(src)}
  4445. }
  4446. if(src.__class__!==undefined){return src}
  4447. if(typeof src=="object"){
  4448. if(src.constructor===Array){return src}
  4449. else if($isNode(src)){return $DOMNode(src)}
  4450. else if($isEvent(src)){return $DOMEvent(src)}
  4451. }
  4452. return JSObject(src)
  4453. }
  4454. function $module(){}
  4455. $module.__class__=$type
  4456. $module.__str__=function(){return "<class 'module'>"}
  4457. function $getattr(obj,attr){
  4458. if(obj[attr]!==undefined){
  4459. var res=obj[attr]
  4460. if(typeof res==="function"){
  4461. res=$bind(res, obj)
  4462. }
  4463. return $JS2Py(res)
  4464. }
  4465. }
  4466. function $bind(func, thisValue){
  4467. return function(){return func.apply(thisValue, arguments)}
  4468. }
  4469. function $raise(){
  4470. if(__BRYTHON__.exception_stack.length>0){throw $last(__BRYTHON__.exception_stack)}
  4471. else{throw Error('Exception')}
  4472. }
  4473. function $src_error(name,module,msg,pos){
  4474. var pos2line={}
  4475. var lnum=1
  4476. var src=document.$py_src[module]
  4477. var line_pos={1:0}
  4478. for(i=0;i<src.length;i++){
  4479. pos2line[i]=lnum
  4480. if(src.charAt(i)=='\n'){lnum+=1;line_pos[lnum]=i}
  4481. }
  4482. var line_num=pos2line[pos]
  4483. var lines=src.split('\n')
  4484. info="\nmodule '"+module+"' line "+line_num
  4485. info +='\n'+lines[line_num-1]+'\n'
  4486. var lpos=pos-line_pos[line_num]
  4487. for(var i=0;i<lpos;i++){info+=' '}
  4488. info +='^\n'
  4489. err=new Error()
  4490. err.name=name
  4491. err.__name__=name
  4492. err.message=msg
  4493. err.info=info
  4494. err.py_error=true
  4495. throw err
  4496. }
  4497. function $SyntaxError(module,msg,pos){
  4498. $src_error('SyntaxError',module,msg,pos)
  4499. }
  4500. function $IndentationError(module,msg,pos){
  4501. $src_error('IndentationError',module,msg,pos)
  4502. }
  4503. function $resolve_attr(obj,factory,attr){
  4504. if(attr==='__class__'){return obj.__class__}
  4505. if(obj[attr]!==undefined){
  4506. if(typeof obj[attr]==='function'){
  4507. var res=function(){return obj[attr].apply(obj,arguments)}
  4508. res.__str__=function(){
  4509. return "<bound method '"+attr+"' of "+obj.__class__.__name__+" object>"
  4510. }
  4511. return res
  4512. }else{return obj[attr]}
  4513. }
  4514. if(factory[attr]!==undefined){
  4515. var res=factory[attr]
  4516. if(typeof res==='function'){
  4517. res=(function(func){
  4518. return function(){
  4519. var args=[obj]
  4520. for(var i=0;i<arguments.length;i++){args.push(arguments[i])}
  4521. return func.apply(obj,args)
  4522. }
  4523. })(res)
  4524. res.__str__=(function(x){
  4525. return function(){
  4526. var res="<bound method "+factory.__name__+'.'+x
  4527. res +=' of '+obj.__str__()+'>'
  4528. return res
  4529. }
  4530. })(attr)
  4531. }
  4532. return res
  4533. }else{
  4534. for(var i=0;i<factory.parents.length;i++){
  4535. try{
  4536. return $resolve_attr(obj,factory.parents[i],attr)
  4537. }catch(err){
  4538. void(0)
  4539. }
  4540. }
  4541. throw AttributeError("'"+factory.__name__+"' object has no attribute '"+attr+"'")
  4542. }
  4543. }
  4544. function $class_constructor(class_name,factory,parents){
  4545. var parent_classes=[]
  4546. if(parents!==undefined){
  4547. if(isinstance(parents,tuple)){
  4548. for(var i=0;i<parents.length;i++){
  4549. if(parents[i]!==object){
  4550. parent_classes.push(parents[i])
  4551. }
  4552. }
  4553. }else if(parents!==object){parent_classes=[parents]}
  4554. }
  4555. factory.parents=parent_classes
  4556. factory.__name__=class_name
  4557. var f=function(){
  4558. var obj=new Object()
  4559. var initialized=false
  4560. if(factory.parents.length){
  4561. eval('var obj = '+factory.parents[0].__name__+'.apply(null,arguments)')
  4562. initialized=true
  4563. }
  4564. obj.__class__=f
  4565. for(var attr in factory){
  4566. if(attr=='__getattr__'){continue}
  4567. if(attr=='__class__'){return f}
  4568. else if(typeof factory[attr]==="function"){
  4569. var func=factory[attr]
  4570. obj[attr]=(function(func){
  4571. return function(){
  4572. var args=[obj]
  4573. for(var i=0;i<arguments.length;i++){args.push(arguments[i])}
  4574. return func.apply(obj,args)
  4575. }
  4576. })(func)
  4577. obj[attr].__str__=(function(x){
  4578. return function(){
  4579. var res="<bound method "+class_name+'.'+x
  4580. res +=' of '+obj.__str__()+'>'
  4581. return res
  4582. }
  4583. })(attr)
  4584. }else{obj[attr]=factory[attr]}
  4585. }
  4586. obj.__getattr__=function(attr){
  4587. return $resolve_attr(obj,factory,attr)
  4588. }
  4589. obj.__setattr__=function(attr,value){
  4590. obj[attr]=value
  4591. }
  4592. try{$resolve_attr(obj,factory,'__str__')}
  4593. catch(err){
  4594. obj.__str__=function(){return "<"+class_name+" object>"}
  4595. obj.__str__.__name__="<bound method __str__ of "+class_name+" object>"
  4596. }
  4597. obj.toString=obj.__str__
  4598. if(!initialized){
  4599. try{
  4600. var init_func=$resolve_attr(obj,factory,'__init__')
  4601. var args=[obj]
  4602. for(var i=0;i<arguments.length;i++){args.push(arguments[i])}
  4603. init_func.apply(null,arguments)
  4604. }catch(err){void(0)}
  4605. }
  4606. return obj
  4607. }
  4608. f.__str__=function(){return "<class '"+class_name+"'>"}
  4609. for(var attr in factory){
  4610. f[attr]=factory[attr]
  4611. f[attr].__str__=(function(x){
  4612. return function(){return "<function "+class_name+'.'+x+'>'}
  4613. })(attr)
  4614. }
  4615. f.__getattr__=function(attr){
  4616. if(f[attr]!==undefined){return f[attr]}
  4617. return factory[attr]
  4618. }
  4619. f.__setattr__=function(attr,value){factory[attr]=value}
  4620. return f
  4621. }
  4622. var $dq_regexp=new RegExp('"',"g")
  4623. function $escape_dq(arg){return arg.replace($dq_regexp,'\\"')}
  4624. document.$stderr={'write':function(data){void(0)}}
  4625. document.$stderr_buff=''
  4626. document.$stdout={
  4627. __getattr__:function(attr){return this[attr]},
  4628. write: function(data){console.log(data)}
  4629. }
  4630. function $type(){}
  4631. $type.__class__=$type
  4632. $type.__name__='type'
  4633. $type.__str__=function(){return "<class 'type'>"}
  4634. $type.toString=$type.__str__
  4635. function $UnsupportedOpType(op,class1,class2){
  4636. $raise('TypeError',
  4637. "unsupported operand type(s) for "+op+": '"+class1+"' and '"+class2+"'")
  4638. }
  4639. function $KwClass(name,value){
  4640. this.__class__=$Kw
  4641. this.name=name
  4642. this.value=value
  4643. }
  4644. $KwClass.prototype.toString=function(){
  4645. return '<kw '+this.name+' : '+this.value.toString()+'>'
  4646. }
  4647. function $Kw(name,value){
  4648. return new $KwClass(name,value)
  4649. }
  4650. function $ptuple_class(arg){
  4651. this.__class__=$ptuple
  4652. this.arg=arg
  4653. }
  4654. function $ptuple(arg){return new $ptuple_class(arg)}
  4655. function $pdict_class(arg){
  4656. this.__class__=$pdict
  4657. this.arg=arg
  4658. }
  4659. function $pdict(arg){return new $pdict_class(arg)}
  4660. function $test_item(expr){
  4661. document.$test_result=expr
  4662. return bool(expr)
  4663. }
  4664. function $test_expr(){
  4665. return document.$test_result
  4666. }
  4667. Function.prototype.__eq__=function(other){
  4668. if(typeof other !=='function'){return False}
  4669. return other+''===this+''
  4670. }
  4671. Function.prototype.__class__=Function
  4672. Function.prototype.__str__=function(){return "<function "+this.__name__+">"}
  4673. Array.prototype.match=function(other){
  4674. var $i=0
  4675. while($i<this.length && $i<other.length){
  4676. if(this[$i]!==other[$i]){return false}
  4677. $i++
  4678. }
  4679. return true
  4680. }
  4681. if(!Array.indexOf){
  4682. Array.prototype.indexOf=function(obj){
  4683. for(var i=0;i<this.length;i++){
  4684. if(this[i]==obj){
  4685. return i;
  4686. }
  4687. }
  4688. return -1;
  4689. }
  4690. }
  4691. try{console}
  4692. catch(err){
  4693. console={'log':function(data){void(0)}}
  4694. }
  4695. function $List2Dict(){
  4696. var res={}
  4697. var i=0
  4698. if(arguments.length==1 && arguments[0].constructor==Array){
  4699. for(i=0;i<arguments[0].length;i++){
  4700. res[arguments[0][i]]=0
  4701. }
  4702. }else{
  4703. for(i=0;i<arguments.length;i++){
  4704. res[arguments[i]]=0
  4705. }
  4706. }
  4707. return res
  4708. }
  4709. function $last(item){
  4710. if(typeof item=="string"){return item.charAt(item.length-1)}
  4711. else if(typeof item=="object"){return item[item.length-1]}
  4712. }
  4713. function $XmlHttpClass(obj){
  4714. this.__class__='XMLHttpRequest'
  4715. this.__getattr__=function(attr){
  4716. if('get_'+attr in this){return this['get_'+attr]()}
  4717. else{return obj[attr]}
  4718. }
  4719. this.get_text=function(){return obj.responseText}
  4720. this.get_xml=function(){return $DomObject(obj.responseXML)}
  4721. this.get_headers=function(){return list(obj.getAllResponseHeaders().split('\n'))}
  4722. this.get_get_header=function(){
  4723. var reqobj=obj
  4724. return function(header){return reqobj.getResponseHeader(header)}
  4725. }
  4726. }
  4727. function Ajax(){}
  4728. Ajax.__class__=$type
  4729. Ajax.__str__=function(){return "<class 'Ajax'>"}
  4730. function $AjaxClass(){
  4731. if(window.XMLHttpRequest){
  4732. var $xmlhttp=new XMLHttpRequest()
  4733. }else{
  4734. var $xmlhttp=new ActiveXObject("Microsoft.XMLHTTP")
  4735. }
  4736. $xmlhttp.$ajax=this
  4737. $xmlhttp.$requestTimer=null
  4738. $xmlhttp.onreadystatechange=function(){
  4739. var state=this.readyState
  4740. var req=this.$ajax
  4741. var timer=this.$requestTimer
  4742. var obj=new $XmlHttpClass($xmlhttp)
  4743. if(state===0 && 'on_uninitialized' in req){req.on_uninitialized(obj)}
  4744. else if(state===1 && 'on_loading' in req){req.on_loading(obj)}
  4745. else if(state===2 && 'on_loaded' in req){req.on_loaded(obj)}
  4746. else if(state===3 && 'on_interactive' in req){req.on_interactive(obj)}
  4747. else if(state===4 && 'on_complete' in req){
  4748. if(timer !==null){window.clearTimeout(timer)}
  4749. req.on_complete(obj)
  4750. }
  4751. }
  4752. this.__class__=Ajax
  4753. this.__getattr__=function(attr){return $getattr(this,attr)}
  4754. this.__setattr__=function(attr,value){setattr(this,attr,value)}
  4755. this.__str__=function(){return "<object 'Ajax'>"}
  4756. this.open=function(method,url,async){
  4757. $xmlhttp.open(method,url,async)
  4758. }
  4759. this.set_header=function(key,value){
  4760. $xmlhttp.setRequestHeader(key,value)
  4761. }
  4762. this.send=function(params){
  4763. if(!params || params.$keys.length==0){$xmlhttp.send();return}
  4764. if(!isinstance(params,dict)){$raise('TypeError',
  4765. "send() argument must be dictonary, not '"+str(params.__class__)+"'")}
  4766. var res=''
  4767. for(i=0;i<params.$keys.length;i++){
  4768. res +=encodeURIComponent(str(params.$keys[i]))+'='+encodeURIComponent(str(params.$values[i]))+'&'
  4769. }
  4770. res=res.substr(0,res.length-1)
  4771. $xmlhttp.send(res)
  4772. }
  4773. this.set_timeout=function(seconds,func){
  4774. $xmlhttp.$requestTimer=setTimeout(
  4775. function(){$xmlhttp.abort();func()},
  4776. seconds*1000);
  4777. }
  4778. }
  4779. function ajax(){
  4780. return new $AjaxClass()
  4781. }
  4782. function $getMouseOffset(target, ev){
  4783. ev=ev || window.event
  4784. var docPos=$getPosition(target)
  4785. var mousePos=$mouseCoords(ev)
  4786. return{x:mousePos.x - docPos.x, y:mousePos.y - docPos.y}
  4787. }
  4788. function $getPosition(e){
  4789. var left=0
  4790. var top=0
  4791. var width=e.offsetWidth
  4792. var height=e.offsetHeight
  4793. while(e.offsetParent){
  4794. left +=e.offsetLeft
  4795. top +=e.offsetTop
  4796. e=e.offsetParent
  4797. }
  4798. left +=e.offsetLeft
  4799. top +=e.offsetTop
  4800. return{left:left, top:top, width:width, height:height}
  4801. }
  4802. function $mouseCoords(ev){
  4803. var posx=0
  4804. var posy=0
  4805. if(!ev)var ev=window.event
  4806. if(ev.pageX || ev.pageY){
  4807. posx=ev.pageX
  4808. posy=ev.pageY
  4809. }else if(ev.clientX || ev.clientY){
  4810. posx=ev.clientX + document.body.scrollLeft
  4811. + document.documentElement.scrollLeft
  4812. posy=ev.clientY + document.body.scrollTop
  4813. + document.documentElement.scrollTop
  4814. }
  4815. var res=object()
  4816. res.x=int(posx)
  4817. res.y=int(posy)
  4818. res.__getattr__=function(attr){return this[attr]}
  4819. res.__class__="MouseCoords"
  4820. return res
  4821. }
  4822. var $DOMNodeAttrs=['nodeName','nodeValue','nodeType','parentNode',
  4823. 'childNodes','firstChild','lastChild','previousSibling','nextSibling',
  4824. 'attributes','ownerDocument']
  4825. function $isNode(obj){
  4826. for(var i=0;i<$DOMNodeAttrs.length;i++){
  4827. if(obj[$DOMNodeAttrs[i]]===undefined){return false}
  4828. }
  4829. return true
  4830. }
  4831. var $DOMEventAttrs_W3C=['NONE','CAPTURING_PHASE','AT_TARGET','BUBBLING_PHASE',
  4832. 'type','target','currentTarget','eventPhase','bubbles','cancelable','timeStamp',
  4833. 'stopPropagation','preventDefault','initEvent']
  4834. var $DOMEventAttrs_IE=['altKey','altLeft','button','cancelBubble',
  4835. 'clientX','clientY','contentOverflow','ctrlKey','ctrlLeft','data',
  4836. 'dataFld','dataTransfer','fromElement','keyCode','nextPage',
  4837. 'offsetX','offsetY','origin','propertyName','reason','recordset',
  4838. 'repeat','screenX','screenY','shiftKey','shiftLeft',
  4839. 'source','srcElement','srcFilter','srcUrn','toElement','type',
  4840. 'url','wheelDelta','x','y']
  4841. function $isEvent(obj){
  4842. flag=true
  4843. for(var i=0;i<$DOMEventAttrs_W3C.length;i++){
  4844. if(obj[$DOMEventAttrs_W3C[i]]===undefined){flag=false;break}
  4845. }
  4846. if(flag){return true}
  4847. for(var i=0;i<$DOMEventAttrs_IE.length;i++){
  4848. if(obj[$DOMEventAttrs_IE[i]]===undefined){return false}
  4849. }
  4850. return true
  4851. }
  4852. function DOMObject(){}
  4853. DOMObject.__class__=$type
  4854. DOMObject.__str__=function(){return "<class 'DOMObject'>"}
  4855. DOMObject.toString=function(){return "<class 'DOMObject'>"}
  4856. $DOMtoString=function(){
  4857. var res="<DOMObject object type '"
  4858. return res+$NodeTypes[this.nodeType]+"' name '"+this.nodeName+"'>"
  4859. }
  4860. $NodeTypes={1:"ELEMENT",
  4861. 2:"ATTRIBUTE",
  4862. 3:"TEXT",
  4863. 4:"CDATA_SECTION",
  4864. 5:"ENTITY_REFERENCE",
  4865. 6:"ENTITY",
  4866. 7:"PROCESSING_INSTRUCTION",
  4867. 8:"COMMENT",
  4868. 9:"DOCUMENT",
  4869. 10:"DOCUMENT_TYPE",
  4870. 11:"DOCUMENT_FRAGMENT",
  4871. 12:"NOTATION"
  4872. }
  4873. function DOMEvent(){}
  4874. DOMEvent.__class__=$type
  4875. DOMEvent.toString=function(){return "<class 'DOMEvent'>"}
  4876. function $DOMEvent(ev){
  4877. ev.__class__=DOMEvent
  4878. ev.__getattr__=function(attr){
  4879. if(attr=="x"){return $mouseCoords(ev).x}
  4880. if(attr=="y"){return $mouseCoords(ev).y}
  4881. if(attr=="data"){return new $Clipboard(ev.dataTransfer)}
  4882. return $getattr(ev,attr)
  4883. }
  4884. if(ev.preventDefault===undefined){ev.preventDefault=function(){ev.returnValue=false}}
  4885. if(ev.stopPropagation===undefined){ev.stopPropagation=function(){ev.cancelBubble=true}}
  4886. ev.__str__=function(){return '<DOMEvent object>'}
  4887. ev.toString=ev.__str__
  4888. return ev
  4889. }
  4890. function $Clipboard(data){
  4891. return{
  4892. data : data,
  4893. __class__ : "Clipboard",
  4894. __getattr__ : function(attr){return this[attr]},
  4895. __getitem__ : function(name){return data.getData(name)},
  4896. __setitem__ : function(name,value){data.setData(name,value)},
  4897. __setattr__ : function(attr,value){data[attr]=value}
  4898. }
  4899. }
  4900. function $OpenFile(file,mode,encoding){
  4901. this.reader=new FileReader()
  4902. if(mode==='r'){this.reader.readAsText(file,encoding)}
  4903. else if(mode==='rb'){this.reader.readAsBinaryString(file)}
  4904. this.file=file
  4905. this.__class__=dom.FileReader
  4906. this.__getattr__=function(attr){
  4907. if(this['get_'+attr]!==undefined){return this['get_'+attr]}
  4908. return this.reader[attr]
  4909. }
  4910. this.__setattr__=(function(obj){
  4911. return function(attr,value){
  4912. if(attr.substr(0,2)=='on'){
  4913. if(window.addEventListener){
  4914. var callback=function(ev){return value($DOMEvent(ev))}
  4915. obj.addEventListener(attr.substr(2),callback)
  4916. }else if(window.attachEvent){
  4917. var callback=function(ev){return value($DOMEvent(window.event))}
  4918. obj.attachEvent(attr,callback)
  4919. }
  4920. }else if('set_'+attr in obj){return obj['set_'+attr](value)}
  4921. else if(attr in obj){obj[attr]=value}
  4922. else{setattr(obj,attr,value)}
  4923. }
  4924. })(this.reader)
  4925. }
  4926. dom={File : function(){},
  4927. FileReader : function(){}
  4928. }
  4929. dom.File.__class__=$type
  4930. dom.File.__str__=function(){return "<class 'File'>"}
  4931. dom.FileReader.__class__=$type
  4932. dom.FileReader.__str__=function(){return "<class 'FileReader'>"}
  4933. function $OptionsClass(parent){
  4934. this.parent=parent
  4935. this.__class__='options'
  4936. this.__delitem__=function(arg){parent.options.remove(arg)}
  4937. this.__getattr__=function(attr){
  4938. if(this['get_'+attr]!==undefined){return this['get_'+attr]}
  4939. else if(this[attr]!==undefined){
  4940. var res=$JS2Py(this[attr])
  4941. return res
  4942. }
  4943. else{throw AttributeError("'DOM.Options' object has no attribute '"+attr+"'")}
  4944. }
  4945. this.__getitem__=function(key){
  4946. return $DOMNode(parent.options[key])
  4947. }
  4948. this.__len__=function(){return parent.options.length}
  4949. this.__setattr__=function(attr,value){
  4950. parent.options[attr]=value
  4951. }
  4952. this.__setitem__=function(attr,value){
  4953. parent.options[attr]=$JS2Py(value)
  4954. }
  4955. this.__str__=function(){return "<object Options wraps "+parent.options+">"}
  4956. this.get_append=function(element){
  4957. parent.options.add(element)
  4958. }
  4959. this.get_insert=function(index,element){
  4960. if(index===undefined){parent.options.add(element)}
  4961. else{parent.options.add(element,index)}
  4962. }
  4963. this.get_item=function(index){
  4964. return parent.options.item(index)
  4965. }
  4966. this.get_namedItem=function(name){
  4967. return parent.options.namedItem(name)
  4968. }
  4969. this.get_remove=function(arg){parent.options.remove(arg)}
  4970. this.toString=this.__str__
  4971. }
  4972. function JSObject(obj){
  4973. return new $JSObject(obj)
  4974. }
  4975. JSObject.__class__=$type
  4976. JSObject.__str__=function(){return "<class 'JSObject'>"}
  4977. JSObject.toString=JSObject.__str__
  4978. function $JSObject(js){
  4979. this.js=js
  4980. this.__class__=JSObject
  4981. this.__str__=function(){return "<object 'JSObject' wraps "+this.js+">"}
  4982. this.toString=this.__str__
  4983. }
  4984. $JSObject.prototype.__bool__=function(){return(new Boolean(this.js)).valueOf()}
  4985. $JSObject.prototype.__getitem__=function(rank){
  4986. if(this.js.item!==undefined){return this.js.item(rank)}
  4987. else{throw AttributeError,this+' has no attribute __getitem__'}
  4988. }
  4989. $JSObject.prototype.__item__=function(rank){
  4990. if(this.js.item!==undefined){return this.js.item(rank)}
  4991. else{throw AttributeError,this+' has no attribute __item__'}
  4992. }
  4993. $JSObject.prototype.__len__=function(){
  4994. if(this.js.length!==undefined){return this.js.length}
  4995. else{throw AttributeError,this+' has no attribute __len__'}
  4996. }
  4997. $JSObject.prototype.__getattr__=function(attr){
  4998. var obj=this
  4999. if(obj.js[attr]!==undefined){
  5000. var obj=this.js,obj_attr=this.js[attr]
  5001. if(typeof this.js[attr]=='function'){
  5002. return function(){
  5003. var args=[]
  5004. for(var i=0;i<arguments.length;i++){args.push(arguments[i])}
  5005. var res=obj_attr.apply(obj,args)
  5006. if(typeof res=='object'){return new $JSObject(res)}
  5007. else if(res===undefined){return None}
  5008. else{return $JS2Py(res)}
  5009. }
  5010. }else if(obj===window && attr==='location'){
  5011. return $Location()
  5012. }else{
  5013. return $JS2Py(this.js[attr])
  5014. }
  5015. }else{
  5016. throw AttributeError("no attribute "+attr)
  5017. }
  5018. }
  5019. $JSObject.prototype.__setattr__=function(attr,value){
  5020. if(isinstance(value,JSObject)){
  5021. this.js[attr]=value.js
  5022. }else{
  5023. this.js[attr]=value
  5024. }
  5025. }
  5026. function $Location(){
  5027. var obj=new object()
  5028. for(var x in window.location){obj[x]=window.location[x]}
  5029. obj.__class__=new $class(this,'Location')
  5030. obj.toString=function(){return window.location.toString()}
  5031. return obj
  5032. }
  5033. win=new $JSObject(window)
  5034. function DOMNode(){}
  5035. function $DOMNode(elt){
  5036. if(elt['$brython_id']===undefined){
  5037. elt.$brython_id=Math.random().toString(36).substr(2, 8)
  5038. for(var attr in DOMNode.prototype){elt[attr]=DOMNode.prototype[attr]}
  5039. elt.__str__=$DOMtoString
  5040. elt.toString=elt.__str__
  5041. }
  5042. return elt
  5043. }
  5044. DOMNode.prototype.__add__=function(other){
  5045. var res=$TagSum()
  5046. res.children=[this]
  5047. if(isinstance(other,$TagSum)){
  5048. for(var $i=0;$i<other.children.length;$i++){res.children.push(other.children[$i])}
  5049. }else if(isinstance(other,[str,int,float,list,dict,set,tuple])){
  5050. res.children.push(document.createTextNode(str(other)))
  5051. }else{res.children.push(other)}
  5052. return res
  5053. }
  5054. DOMNode.prototype.__class__=DOMObject
  5055. DOMNode.prototype.__delitem__=function(key){
  5056. if(this.nodeType===9){
  5057. var res=document.getElementById(key)
  5058. if(res){res.parentNode.removeChild(res)}
  5059. else{throw KeyError(key)}
  5060. }else{
  5061. this.removeChild(this.childNodes[key])
  5062. }
  5063. }
  5064. DOMNode.prototype.__eq__=function(other){
  5065. if(this.isEqualNode!==undefined){return this.isEqualNode(other)}
  5066. else if(this.$brython_id!==undefined){return this.$brython_id===other.$brython_id}
  5067. else{throw NotImplementedError('__eq__ is not implemented')}
  5068. }
  5069. DOMNode.prototype.__getattr__=function(attr){
  5070. if(attr==='__class__'){return DOMObject}
  5071. if(this['get_'+attr]!==undefined){return this['get_'+attr]()}
  5072. if(this.getAttribute!==undefined){
  5073. var res=this.getAttribute(attr)
  5074. if(res){return res}
  5075. }
  5076. return $getattr(this,attr)
  5077. }
  5078. DOMNode.prototype.__getitem__=function(key){
  5079. if(this.nodeType===9){
  5080. if(typeof key==="string"){
  5081. var res=document.getElementById(key)
  5082. if(res){return $DOMNode(res)}
  5083. else{throw KeyError(key)}
  5084. }else{
  5085. try{
  5086. var elts=document.getElementsByTagName(key.name),res=[]
  5087. for(var $i=0;$i<elts.length;$i++){res.push($DOMNode(elts[$i]))}
  5088. return res
  5089. }catch(err){
  5090. throw KeyError(str(key))
  5091. }
  5092. }
  5093. }else{
  5094. return $DOMNode(this.childNodes[key])
  5095. }
  5096. }
  5097. DOMNode.prototype.__in__=function(other){return other.__contains__(this)}
  5098. DOMNode.prototype.__item__=function(key){
  5099. return $DOMNode(this.childNodes[key])
  5100. }
  5101. DOMNode.prototype.__le__=function(other){
  5102. var obj=this
  5103. if(this.nodeType===9){obj=this.body}
  5104. if(isinstance(other,$TagSum)){
  5105. var $i=0
  5106. for($i=0;$i<other.children.length;$i++){
  5107. obj.appendChild(other.children[$i])
  5108. }
  5109. }else if(typeof other==="string" || typeof other==="number"){
  5110. var $txt=document.createTextNode(other.toString())
  5111. obj.appendChild($txt)
  5112. }else{
  5113. obj.appendChild(other)
  5114. }
  5115. }
  5116. DOMNode.prototype.__len__=function(){return this.childNodes.length}
  5117. DOMNode.prototype.__mul__=function(other){
  5118. if(isinstance(other,int)&& other.valueOf()>0){
  5119. var res=$TagSum()
  5120. for(var i=0;i<other.valueOf();i++){
  5121. var clone=this.get_clone()()
  5122. res.children.push(clone)
  5123. }
  5124. return res
  5125. }else{
  5126. throw ValueError("can't multiply "+this.__class__+"by "+other)
  5127. }
  5128. }
  5129. DOMNode.prototype.__ne__=function(other){return !this.__eq__(other)}
  5130. DOMNode.prototype.__radd__=function(other){
  5131. var res=$TagSum()
  5132. var txt=document.createTextNode(other)
  5133. res.children=[txt,this]
  5134. return res
  5135. }
  5136. DOMNode.prototype.__setattr__=function(attr,value){
  5137. if(attr.substr(0,2)=='on'){
  5138. if(window.addEventListener){
  5139. var callback=function(ev){return value($DOMEvent(ev))}
  5140. this.addEventListener(attr.substr(2),callback)
  5141. }else if(window.attachEvent){
  5142. var callback=function(ev){return value($DOMEvent(window.event))}
  5143. this.attachEvent(attr,callback)
  5144. }
  5145. }else{
  5146. attr=attr.replace('_','-')
  5147. if(this['set_'+attr]!==undefined){return this['set_'+attr](value)}
  5148. var res=this.getAttribute(attr)
  5149. if(res!==undefined){this.setAttribute(attr,value)}
  5150. else if(this[attr]!==undefined){this[attr]=value}
  5151. else{setattr(this,attr,value)}
  5152. }
  5153. }
  5154. DOMNode.prototype.__setitem__=function(key,value){
  5155. this.childNodes[key]=value
  5156. }
  5157. DOMNode.prototype.get_get=function(){
  5158. if(this.getElementsByName!==undefined){
  5159. return function(){
  5160. var $ns=$MakeArgs('get',arguments,[],{},null,'kw')
  5161. if('$$name'.__in__($ns['kw'])){
  5162. var res=[]
  5163. var node_list=document.getElementsByName($ns['kw'].__getitem__('$$name'))
  5164. if(node_list.length===0){return[]}
  5165. for(var i=0;i<node_list.length;i++){
  5166. res.push($DOMNode(node_list[i]))
  5167. }
  5168. }
  5169. if('id'.__in__($ns['kw'])){
  5170. var id_res=document.getElementById($ns['kw'].__getitem__('id'))
  5171. if(!id_res){return[]}
  5172. else{
  5173. var elt=$DOMNode(id_res)
  5174. if(res===undefined){res=[elt]}
  5175. else{
  5176. flag=false
  5177. for(var i=0;i<res.length;i++){
  5178. if(elt.__eq__(res[i])){flag=true;break}
  5179. }
  5180. if(!flag){return[]}
  5181. }
  5182. }
  5183. }
  5184. if('selector'.__in__($ns['kw'])){
  5185. var node_list=document.querySelectorAll($ns['kw'].__getitem__('selector'))
  5186. var sel_res=[]
  5187. if(node_list.length===0){return[]}
  5188. for(var i=0;i<node_list.length;i++){
  5189. sel_res.push($DOMNode(node_list[i]))
  5190. }
  5191. if(res===undefined){return sel_res}
  5192. var to_delete=[]
  5193. for(var i=0;i<res.length;i++){
  5194. var elt=res[i]
  5195. flag=false
  5196. for(var j=0;j<sel_res.length;j++){
  5197. if(elt.__eq__(sel_res[j])){flag=true;break}
  5198. }
  5199. if(!flag){to_delete.push(i)}
  5200. }
  5201. for(var i=to_delete.length-1;i>=0;i--){
  5202. res.splice(to_delete[i],1)
  5203. }
  5204. return res
  5205. }
  5206. return res
  5207. }
  5208. }
  5209. }
  5210. DOMNode.prototype.get_clone=function(){
  5211. res=$DOMNode(this.cloneNode(true))
  5212. for(var attr in this){
  5213. if(attr.substr(0,2)=='on' && this[attr]!==undefined){
  5214. res[attr]=this[attr]
  5215. }
  5216. }
  5217. var func=function(){return res}
  5218. return func
  5219. }
  5220. DOMNode.prototype.get_remove=function(){
  5221. var obj=this
  5222. return function(child){obj.removeChild(child)}
  5223. }
  5224. DOMNode.prototype.get_getContext=function(){
  5225. if(!('getContext' in this)){throw AttributeError(
  5226. "object has no attribute 'getContext'")}
  5227. var obj=this
  5228. return function(ctx){return new $JSObject(obj.getContext(ctx))}
  5229. }
  5230. DOMNode.prototype.get_parent=function(){
  5231. if(this.parentElement){return $DOMNode(this.parentElement)}
  5232. else{return None}
  5233. }
  5234. DOMNode.prototype.get_options=function(){
  5235. return new $OptionsClass(this)
  5236. }
  5237. DOMNode.prototype.get_left=function(){
  5238. return int($getPosition(this)["left"])
  5239. }
  5240. DOMNode.prototype.get_top=function(){
  5241. return int($getPosition(this)["top"])
  5242. }
  5243. DOMNode.prototype.get_children=function(){
  5244. var res=[]
  5245. for(var i=0;i<this.childNodes.length;i++){
  5246. res.push($DOMNode(this.childNodes[i]))
  5247. }
  5248. return res
  5249. }
  5250. DOMNode.prototype.get_reset=function(){
  5251. var $obj=this
  5252. return function(){$obj.reset()}
  5253. }
  5254. DOMNode.prototype.get_style=function(){
  5255. return new $JSObject(this.style)
  5256. }
  5257. DOMNode.prototype.set_style=function(style){
  5258. for(var i=0;i<style.$keys.length;i++){
  5259. this.style[style.$keys[i]]=style.$values[i]
  5260. }
  5261. }
  5262. DOMNode.prototype.get_submit=function(){
  5263. var $obj=this
  5264. return function(){$obj.submit()}
  5265. }
  5266. DOMNode.prototype.get_text=function(){
  5267. return this.innerText || this.textContent
  5268. }
  5269. DOMNode.prototype.get_html=function(){return this.innerHTML}
  5270. DOMNode.prototype.get_value=function(value){return this.value}
  5271. DOMNode.prototype.set_html=function(value){this.innerHTML=str(value)}
  5272. DOMNode.prototype.set_text=function(value){
  5273. this.innerText=str(value)
  5274. this.textContent=str(value)
  5275. }
  5276. DOMNode.prototype.set_value=function(value){this.value=value.toString()}
  5277. doc=$DOMNode(document)
  5278. function $Tag(tagName,args){
  5279. var $i=null
  5280. var elt=null
  5281. var elt=$DOMNode(document.createElement(tagName))
  5282. elt.parent=this
  5283. if(args!=undefined && args.length>0){
  5284. $start=0
  5285. $first=args[0]
  5286. if(!isinstance($first,$Kw)){
  5287. $start=1
  5288. if(isinstance($first,[str,int,float])){
  5289. txt=document.createTextNode($first.toString())
  5290. elt.appendChild(txt)
  5291. }else if(isinstance($first,$TagSum)){
  5292. for($i=0;$i<$first.children.length;$i++){
  5293. elt.appendChild($first.children[$i])
  5294. }
  5295. }else{
  5296. try{elt.appendChild($first)}
  5297. catch(err){throw ValueError('wrong element '+$first)}
  5298. }
  5299. }
  5300. for($i=$start;$i<args.length;$i++){
  5301. $arg=args[$i]
  5302. if(isinstance($arg,$Kw)){
  5303. if($arg.name.toLowerCase().substr(0,2)==="on"){
  5304. eval('elt.'+$arg.name.toLowerCase()+'=function(){'+$arg.value+'}')
  5305. }else if($arg.name.toLowerCase()=="style"){
  5306. elt.set_style($arg.value)
  5307. }else{
  5308. if($arg.value!==false){
  5309. try{
  5310. elt.setAttribute($arg.name.toLowerCase(),$arg.value)
  5311. }catch(err){
  5312. throw ValueError("can't set attribute "+$arg.name)
  5313. }
  5314. }
  5315. }
  5316. }
  5317. }
  5318. }
  5319. return elt
  5320. }
  5321. function $TagSumClass(){
  5322. this.__class__=$TagSum
  5323. this.children=[]
  5324. }
  5325. $TagSumClass.prototype.appendChild=function(child){
  5326. this.children.push(child)
  5327. }
  5328. $TagSumClass.prototype.__add__=function(other){
  5329. if(isinstance(other,$TagSum)){
  5330. this.children=this.children.concat(other.children)
  5331. }else if(isinstance(other,str)){
  5332. this.children=this.children.concat(document.createTextNode(other))
  5333. }else{this.children.push(other)}
  5334. return this
  5335. }
  5336. $TagSumClass.prototype.__radd__=function(other){
  5337. var res=$TagSum()
  5338. res.children=this.children.concat(document.createTextNode(other))
  5339. return res
  5340. }
  5341. $TagSumClass.prototype.clone=function(){
  5342. var res=$TagSum(), $i=0
  5343. for($i=0;$i<this.children.length;$i++){
  5344. res.children.push(this.children[$i].cloneNode(true))
  5345. }
  5346. return res
  5347. }
  5348. function $TagSum(){
  5349. return new $TagSumClass()
  5350. }
  5351. function A(){return $Tag('A',arguments)}
  5352. var $src=A+''
  5353. $tags=['A', 'ABBR', 'ACRONYM', 'ADDRESS', 'APPLET',
  5354. 'B', 'BDO', 'BIG', 'BLOCKQUOTE', 'BUTTON',
  5355. 'CAPTION', 'CENTER', 'CITE', 'CODE',
  5356. 'DEL', 'DFN', 'DIR', 'DIV', 'DL',
  5357. 'EM', 'FIELDSET', 'FONT', 'FORM', 'FRAMESET',
  5358. 'H1', 'H2', 'H3', 'H4', 'H5', 'H6',
  5359. 'I', 'IFRAME', 'INS', 'KBD', 'LABEL', 'LEGEND',
  5360. 'MAP', 'MENU', 'NOFRAMES', 'NOSCRIPT', 'OBJECT',
  5361. 'OL', 'OPTGROUP', 'PRE', 'Q', 'S', 'SAMP',
  5362. 'SCRIPT', 'SELECT', 'SMALL', 'SPAN', 'STRIKE',
  5363. 'STRONG', 'STYLE', 'SUB', 'SUP', 'TABLE',
  5364. 'TEXTAREA', 'TITLE', 'TT', 'U', 'UL',
  5365. 'VAR', 'BODY', 'COLGROUP', 'DD', 'DT', 'HEAD',
  5366. 'HTML', 'LI', 'P', 'TBODY','OPTION',
  5367. 'TD', 'TFOOT', 'TH', 'THEAD', 'TR',
  5368. 'AREA', 'BASE', 'BASEFONT', 'BR', 'COL', 'FRAME',
  5369. 'HR', 'IMG', 'INPUT', 'ISINDEX', 'LINK',
  5370. 'META', 'PARAM']
  5371. $tags=$tags.concat(['ARTICLE','ASIDE','FIGURE','FOOTER','HEADER','NAV',
  5372. 'SECTION','AUDIO','VIDEO','CANVAS','COMMAND','DATALIST',
  5373. 'DETAILS','OUTPUT','PROGRESS','HGROUP','MARK','METER','TIME',
  5374. 'RP','RT','RUBY'])
  5375. for($i=0;$i<$tags.length;$i++){
  5376. $code=$src.replace(/A/gm,$tags[$i])
  5377. eval($code)
  5378. eval($tags[$i]+'.name="'+$tags[$i]+'"')
  5379. }
  5380. function $LocalStorageClass(){
  5381. this.__class__='localStorage'
  5382. this.supported=typeof(Storage)!=="undefined"
  5383. this.__delitem__=function(key){
  5384. if(this.supported){localStorage.removeItem(key)}
  5385. else{$raise('NameError',"local storage is not supported by this browser")}
  5386. }
  5387. this.__getitem__=function(key){
  5388. if(this.supported){
  5389. res=localStorage[key]
  5390. if(res===undefined){return None}
  5391. else{return res}
  5392. }
  5393. else{$raise('NameError',"local storage is not supported by this browser")}
  5394. }
  5395. this.__setitem__=function(key,value){
  5396. if(this.supported){localStorage[key]=value}
  5397. else{$raise('NameError',"local storage is not supported by this browser")}
  5398. }
  5399. }
  5400. local_storage=new $LocalStorageClass()