-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathindex.js
150 lines (136 loc) · 4.63 KB
/
index.js
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
import { Hecto, Result } from "hecto";
class Py extends Hecto {
get hardcode() {
const that = this;
return {
setupString: `import sys
import json
import math
import traceback
import types
import copy
from collections.abc import MutableMapping, MutableSequence, Set
def copy(d):
if isinstance(d, MutableMapping):
return {k: v for k, v in d.items() if v is not __builtins__.__dict__}
if isinstance(d, types.ModuleType):
return copy(vars(d))
elif isinstance(d, (list, set, tuple)):
return type(d)(copy(item) for item in d)
else:
return d
previous_globals = dict()
def sync_globals():
mutated_globals = {}
for key, value in globals().items():
if copy(value) != previous_globals.get(key) and key not in ['previous_globals']:
# global builtins are fetched once
if key in ['__builtins__', 'builtins'] and previous_globals.get(key) != None:
continue
previous_globals[key] = copy(value)
mutated_globals[key] = copy(value)
return mutated_globals
def convert_to_serializable(obj, memo=None):
if isinstance(obj, (int, str, bool, type(None))):
return obj
elif isinstance(obj, float):
if math.isnan(obj):
return "<NaN>"
elif math.isinf(obj):
return "<Infinity>" if obj > 0 else "<-Infinity>"
return obj
elif isinstance(obj, types.FunctionType):
return f"<def>{obj.__name__}"
if memo is None:
memo = set()
if id(obj) in memo:
return "<circular>"
memo.add(id(obj))
if isinstance(obj, MutableMapping):
return {convert_to_serializable(k, memo): convert_to_serializable(v, memo) for k, v in obj.items()}
elif isinstance(obj, MutableSequence):
return [convert_to_serializable(item, memo) for item in obj]
elif isinstance(obj, Set):
return [convert_to_serializable(item, memo) for item in obj]
elif isinstance(obj, types.MappingProxyType):
return convert_to_serializable(dict(obj), memo)
elif hasattr(obj, '__dict__'):
return convert_to_serializable(vars(obj), memo)
elif isinstance(obj, type):
return f"<cls>{obj.__name__}>"
elif isinstance(obj, types.ModuleType):
return f"<lib>{obj.__name__}"
elif isinstance(obj, property):
getter_value = obj.fget() if obj.fget else None
return convert_to_serializable(getter_value, memo)
elif isinstance(obj, object):
return f"<obj>{type(obj).__name__}"
else:
return "<unknown>"
hecto_original_print = print
def emit(event, *args):
hecto_original_print('¬-' + event + '¬&' + json.dumps(convert_to_serializable(list(args))) + '-¬')
def print(*args):
emit('print', *args)
def hecto_display(value):
if value is not None:
hecto_original_print('¬¬' + json.dumps(convert_to_serializable(value)) + '¬¬')
def hecto_except(type, value, traceback_obj):
filename, line_number, line_text, line_pos, error_code = None, None, None, None, None
tb_list = None
try:
traceback.extract_tb(traceback_obj)
except Exception:
pass
if tb_list:
filename, line_number, function_name, line_text = tb_list[-1]
line_pos = traceback_obj.tb_lineno
error_code = value.args[0] if value.args else None
hecto_original_print('¬*' + json.dumps({'fn': filename, 'line': line_number, 'msg': error_code, 'name': type.__name__, 'pos': line_pos}) + '*¬')
sys.displayhook = hecto_display
#sys.excepthook = hecto_except
def hecto_ret(additional = None):
value = sync_globals()
if additional is not None:
value = additional;
hecto_original_print('¬^' + json.dumps(convert_to_serializable(value)) + '^¬')
hecto_ret()
`,
defaultShellNames: ["python3", "python"],
setup() {
that.__raw_write(this.setupString);
},
writeExecutionCommand(command) {
return that.__raw_write(`${command.trim()}\n\nhecto_ret()\n`);
},
context: {
get(
prop,
value,
{ type } = {}
) {
switch (type) {
case "def":
return async (...args) => {
return await that.exec(
`${prop}(${args.map(JSON.stringify).join(",")})`
);
};
default:
return value;
}
},
set(prop, value, oldValue) {
switch (typeof value) {
case "function":
return oldValue; // Ignore
default:
that.exec(`${prop} = ${JSON.stringify(value)}`);
return value;
}
},
},
};
}
}
export { Py, Result };