Skip to content

Commit 99d2e34

Browse files
committed
Add asyncpy decorator and transpiles await expression and async code block
1 parent e917d6d commit 99d2e34

File tree

2 files changed

+57
-60
lines changed

2 files changed

+57
-60
lines changed

index.js

Lines changed: 13 additions & 5 deletions
Original file line numberDiff line numberDiff line change
@@ -51,7 +51,11 @@ module.exports = (async () => {
5151
const methods = {}
5252
methods.init = global.mp_js_init;
5353
const do_str = global.mp_js_do_str;
54+
global._mp_js_do_str = do_str;
5455
methods.do_str = async (code, concurrent) => {
56+
code = code.replace(/async {/g, 'async_py(lambda **kwargs: """').replace(/} async/g, '""")');
57+
//code = code.replace(/async {/g, 'exec("""').replace(/} async/g, '""")');
58+
code = code.replace(/:async:/g, 'return """').replace(/return async/g, '"""');
5559
const codes = code.split('\n');
5660
let spaces = '';
5761
for (let line of codes) {
@@ -65,7 +69,7 @@ module.exports = (async () => {
6569
break;
6670
}
6771
if (spaces || concurrent) {
68-
if (concurrent) spaces = ' ';
72+
if (concurrent && !spaces) spaces = ' ';
6973
let index_split = 0;
7074
const new_code = [];
7175
for (let line of codes) {
@@ -77,14 +81,18 @@ module.exports = (async () => {
7781
let code_cache = [];
7882
for (var each of new_code) {
7983
let await_code;
80-
if (each.indexOf(' = wait(') > -1) {
84+
if (each.indexOf('await ') > -1) each = each.replace('await', 'wait(') + ')';
85+
if (each.indexOf('wait(') > -1 && each.indexOf('def wait(promise') < 0) {
8186
if (code_cache.length > 0) {
8287
result.push(await global.mp_js_do_str(code_cache.join('\n'), false));
8388
code_cache = [];
8489
}
85-
const [variable, wait] = each.split(' = ')
86-
const promise = wait.slice(5, -1);
87-
await_code = variable + ' = ' + promise + '._value';
90+
91+
if (each.indexOf(' = wait(') > -1) {
92+
const [variable, wait] = each.split(' = ')
93+
const promise = wait.slice(5, -1);
94+
await_code = variable + ' = ' + promise + '._value';
95+
}
8896
}
8997
else {
9098
code_cache.push(each);

js.py

Lines changed: 44 additions & 55 deletions
Original file line numberDiff line numberDiff line change
@@ -5,6 +5,12 @@
55
funcache = {}
66
procache = {}
77

8+
#Javascript's JSON Types for eliminating json.loads
9+
true = True
10+
false = False
11+
null = None
12+
undefined = None
13+
814
def js_exec(code, *args):
915
code = format(code, *args)
1016
return js.exec('(async () => {\n' + code + '\n})();')
@@ -24,24 +30,22 @@ def format(string, *args):
2430

2531
def wait(promise):
2632
procache[promise._name] = promise
27-
#js.exec('console.log("function")')
28-
js.exec("""
29-
//console.log('exec');
33+
js_exec("""
3034
global.promiseWaitInterval = setInterval(() => {
31-
//console.log('interval')
3235
const object = global.mpjscache['{0}'];
33-
console.log(object)
36+
//console.log(object)
3437
if (object && object.constructor !== Promise) {
3538
clearInterval(global.promiseWaitInterval);
3639
global.promiseWaitInterval = undefined;
3740
global.mp_js_do_str(`
3841
import js
3942
procache['{0}']._resolved = True
43+
procache['{0}']._value = JS('global.mpjscache["{0}"]')
4044
procache['{0}'] = procache['{0}']._value
4145
`);
4246
}
4347
}, 500);
44-
""".replace('{0}', promise._name))
48+
""", promise._name)
4549
exit
4650

4751
def resolve(cache, name, value):
@@ -51,6 +55,20 @@ def resolve(cache, name, value):
5155
else:
5256
cache[name] = value
5357

58+
async_id = 0
59+
60+
def async_py(function):
61+
def wrap(**kwargs):
62+
code_string = function(**kwargs)
63+
for key in kwargs:
64+
if key not in code_string: continue
65+
async_id += 1
66+
asycache[async_id] = kwargs[key]
67+
code_string = code_string.replace(key, 'asycache[%s]' % (async_id))
68+
exec(code_string)
69+
exit
70+
return wrap
71+
5472
class JSPromise():
5573

5674
def __init__(self, name):
@@ -69,9 +87,13 @@ def __init__(self, name):
6987
self._name = name
7088

7189
def __len__(self):
72-
return 1
90+
if self._name:
91+
return 1
92+
else:
93+
return 0
7394

7495
def __dir__(self):
96+
if not self._name: return []
7597
js_exec("""
7698
let keys = JSON.stringify(Object.keys({0}));
7799
global.mp_js_do_str(`
@@ -82,7 +104,7 @@ def __dir__(self):
82104
return dircache.get(self._name, [])
83105

84106
def __getattr__(self, key):
85-
name = self._name + '.' + key
107+
name = self._name + '.' + key if self._name else key
86108
js_exec("""
87109
let object = {0};
88110
if (object && object.constructor === Promise) {
@@ -108,7 +130,7 @@ def __getattr__(self, key):
108130
return global.mp_js_do_str(`
109131
import js
110132
import json
111-
resolve(objcache, '{0}', json.loads('''${object}'''))
133+
resolve(objcache, '{0}', ${object})
112134
`);
113135
}
114136
catch(error) {
@@ -121,6 +143,7 @@ def __getattr__(self, key):
121143
return objcache.get(name)
122144

123145
def __setattr__(self, key, value):
146+
if not self._name: return
124147
value = json.dumps(value)
125148
object_name = self._name + '.' + key
126149
js_exec("""
@@ -164,7 +187,7 @@ def function(*args):
164187
return global.mp_js_do_str(`
165188
import js
166189
import json
167-
resolve(funcache, '{0}', json.loads('''${object}'''))
190+
resolve(funcache, '{0}', ${object})
168191
`);
169192
}
170193
catch(error) {
@@ -178,56 +201,22 @@ def function(*args):
178201
return function
179202

180203
def JS(variable):
181-
js_exec("""
182-
let object = {0};
183-
if (object && object.constructor === Promise) {
184-
await global.mp_js_do_str(`
185-
import js
186-
objcache['{0}'] = JSPromise('{0}')
187-
`)
188-
object = await object;
189-
}
190-
try {
191-
if (object && [Array, Object, Number, String, Boolean, Function, AsyncFunction].indexOf(object.constructor) < 0) throw Error('Not JSON Serializable');
192-
if (object && object.constructor === Object) for (let key in Object.keys({0})) {
193-
if (object.indexOf(value) < 0) throw Error('Not a JSON');
194-
}
195-
else if (object && (object.constructor === Function || object.constructor === AsyncFunction)) {
196-
delete global.mpjscache['{0}'];
197-
return global.mp_js_do_str(`
198-
import js
199-
resolve(objcache, '{0}', JSFunction('{0}'))
200-
`);
201-
}
202-
object = object !== undefined ? JSON.stringify(object) : 'null';
203-
return global.mp_js_do_str(`
204-
import js
205-
import json
206-
resolve(objcache, '{0}', json.loads('''${object}'''))
207-
`);
208-
}
209-
catch(error) {
210-
return global.mp_js_do_str(`
211-
import js
212-
resolve(objcache, '{0}', JSObject('{0}'))
213-
`);
214-
}
215-
""", variable)
216-
return objcache.get(variable)
204+
empty = JSObject('')
205+
return getattr(empty, variable)
217206

218207
#require = JS('require')
219208
#result = require('fs').readFileSync('./test.js').toString()
220209
#print(result)
221210

222211
#This code block is adaptable to Javascript's event loop
223-
#exec("""
212+
async {
224213

225-
#require = JS('require')
226-
#response = require('node-fetch')('https://github.com/')
227-
#response = wait(response)
228-
#print(response)
229-
#result = response.text()
230-
#result = wait(result)
231-
#print(result)
214+
require = JS('require')
215+
response = require('node-fetch')('https://github.com/')
216+
response = await response
217+
print(response)
218+
result = response.text()
219+
result = await result
220+
print(result)
232221

233-
#""")
222+
} async ()

0 commit comments

Comments
 (0)