-
Notifications
You must be signed in to change notification settings - Fork 30
/
minimal_skulpt.html
339 lines (313 loc) · 15.8 KB
/
minimal_skulpt.html
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
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
<!DOCTYPE html>
<html>
<head>
<meta charset="utf-8">
<title>Simple BlockMirror Example</title>
<script>module = {}</script>
<script src="https://code.jquery.com/jquery-3.4.1.slim.min.js"
integrity="sha256-pasqAKBDmFT4eHoN2ndd6lN370kFiGUFyTiUHWhU7k8="
crossorigin="anonymous"></script>
<!-- Blockly -->
<script src="../../blockly/blockly_compressed.js" type="text/javascript"></script>
<script src="../../blockly/blocks_compressed.js" type="text/javascript"></script>
<script src="../../blockly/msg/js/en.js" type="text/javascript"></script>
<script src="../../blockly/python_compressed.js" type="text/javascript"></script>
<!-- Skulpt -->
<script src="../src/skulpt/skulpt_shim.js" type="text/javascript"></script>
<script src="../src/skulpt/astnodes.js" type="text/javascript"></script>
<script src="../src/skulpt/token.js" type="text/javascript"></script>
<script src="../src/skulpt/parse_tables.js" type="text/javascript"></script>
<script src="../src/skulpt/tokenize.js" type="text/javascript"></script>
<script src="../src/skulpt/parser.js" type="text/javascript"></script>
<script src="../src/skulpt/ast.js" type="text/javascript"></script>
<!-- CodeMirror -->
<link rel="stylesheet" href="../lib/codemirror/codemirror.css">
<link rel="stylesheet" href="../lib/codemirror/fullscreen.css">
<link rel="stylesheet" href="../lib/codemirror/show-hint.css">
<script src="../lib/codemirror/codemirror.js" type="text/javascript"></script>
<script src="../lib/codemirror/show-hint.js" type="text/javascript"></script>
<script src="../lib/codemirror/python-hint.js" type="text/javascript"></script>
<script src="../lib/codemirror/fullscreen.js" type="text/javascript"></script>
<script src="../lib/codemirror/python.js" type="text/javascript"></script>
<!-- BlockMirror -->
<link rel="stylesheet" href="../src/block_mirror.css">
<script src="../src/blockly_shims.js" type="text/javascript"></script>
<script src="../src/block_mirror.js" type="text/javascript"></script>
<script src="../src/text_editor.js" type="text/javascript"></script>
<script src="../src/block_editor.js" type="text/javascript"></script>
<script src="../src/text_to_blocks.js" type="text/javascript"></script>
<script src="../src/ast/ast_functions.js" type="text/javascript"></script>
<script src="../src/toolbars.js" type="text/javascript"></script>
<script src="../src/ast/ast_For.js" type="text/javascript"></script>
<script src="../src/ast/ast_If.js" type="text/javascript"></script>
<script src="../src/ast/ast_While.js" type="text/javascript"></script>
<script src="../src/ast/ast_Num.js" type="text/javascript"></script>
<script src="../src/ast/ast_BinOp.js" type="text/javascript"></script>
<script src="../src/ast/ast_Name.js" type="text/javascript"></script>
<script src="../src/ast/ast_Assign.js" type="text/javascript"></script>
<script src="../src/ast/ast_AnnAssign.js" type="text/javascript"></script>
<script src="../src/ast/ast_AugAssign.js" type="text/javascript"></script>
<script src="../src/ast/ast_Str.js" type="text/javascript"></script>
<script src="../src/ast/ast_Expr.js" type="text/javascript"></script>
<script src="../src/ast/ast_UnaryOp.js" type="text/javascript"></script>
<script src="../src/ast/ast_BoolOp.js" type="text/javascript"></script>
<script src="../src/ast/ast_Compare.js" type="text/javascript"></script>
<script src="../src/ast/ast_Assert.js" type="text/javascript"></script>
<script src="../src/ast/ast_NameConstant.js" type="text/javascript"></script>
<script src="../src/ast/ast_List.js" type="text/javascript"></script>
<script src="../src/ast/ast_Tuple.js" type="text/javascript"></script>
<script src="../src/ast/ast_Set.js" type="text/javascript"></script>
<script src="../src/ast/ast_Dict.js" type="text/javascript"></script>
<script src="../src/ast/ast_Starred.js" type="text/javascript"></script>
<script src="../src/ast/ast_IfExp.js" type="text/javascript"></script>
<script src="../src/ast/ast_Attribute.js" type="text/javascript"></script>
<script src="../src/ast/ast_Call.js" type="text/javascript"></script>
<script src="../src/ast/ast_Raise.js" type="text/javascript"></script>
<script src="../src/ast/ast_Delete.js" type="text/javascript"></script>
<script src="../src/ast/ast_Subscript.js" type="text/javascript"></script>
<script src="../src/ast/ast_Comp.js" type="text/javascript"></script>
<script src="../src/ast/ast_FunctionDef.js" type="text/javascript"></script>
<script src="../src/ast/ast_Lambda.js" type="text/javascript"></script>
<script src="../src/ast/ast_Return.js" type="text/javascript"></script>
<script src="../src/ast/ast_Yield.js" type="text/javascript"></script>
<script src="../src/ast/ast_YieldFrom.js" type="text/javascript"></script>
<script src="../src/ast/ast_Global.js" type="text/javascript"></script>
<!--<script src="../src/ast/ast_Nonlocal.js" type="text/javascript"></script>-->
<script src="../src/ast/ast_Break.js" type="text/javascript"></script>
<script src="../src/ast/ast_Continue.js" type="text/javascript"></script>
<script src="../src/ast/ast_Try.js" type="text/javascript"></script>
<script src="../src/ast/ast_ClassDef.js" type="text/javascript"></script>
<script src="../src/ast/ast_Import.js" type="text/javascript"></script>
<script src="../src/ast/ast_With.js" type="text/javascript"></script>
<script src="../src/ast/ast_Comment.js" type="text/javascript"></script>
<script src="../src/ast/ast_Raw.js" type="text/javascript"></script>
</head>
<body>
<button id='go'>Run Unit Tests</button>
<button id='make-image'>Make Image</button>
<div id="image-spot"></div>
<div style="width:900px; margin:0 auto;"
id='example-frame'>
<div class="btn-group" data-toggle="buttons" style="display: inline-block; margin-right: 10em;">
<label onclick="editor.setMode('block');">
<input type="radio" name="blockpy-mode-set" autocomplete="off"> Blocks
</label>
<label onclick="editor.setMode('split');">
<input type="radio" name="blockpy-mode-set" autocomplete="off" checked> Split
</label>
<label onclick="editor.setMode('text');">
<input type="radio" name="blockpy-mode-set" autocomplete="off"> Text
</label>
</div>
<div class="btn-group" data-toggle="buttons" style="display: inline-block">
<label>
<input type="checkbox" name="blockpy-mode-set" checked
onclick="editor.setImageMode(!editor.configuration.imageMode);">
Image Mode
</label>
</div>
<div id="blockmirror-editor"></div>
</div>
<script type="text/javascript">
try {
var KEY_VALUE_STORE = localStorage.getItem('code-mirror-kv-length') || 0;
//localStorage.setItem('code-mirror-kv-length', KEY_VALUE_STORE+1);
function lookupImage(value) {
}
} catch (e) {
console.error(e);
KEY_VALUE_STORE = {};
}
var editor = new BlockMirror({
'container': document.getElementById('blockmirror-editor'),
'toolbox': 'normal',
imageMode: true,
imageDownloadHOok: (oldUrl) => {
return oldUrl;
},
imageUploadHook: (blob) => {
return Promise.resolve("Image("+JSON.stringify(URL.createObjectURL(blob))+")");
},
imageLiteralHook: (oldUrl) => {
return `Image("${oldUrl}")`;
},
/*var reader = new FileReader();
reader.onload = function(event){
// Post to a server, get back a URL
console.log(event.target.result); // data url!
};*/
//'height': '2000px'
});
editor.addChangeListener(function (event) {
console.log('Change! Better save:', event)
});
editor.setCode('class X:\n """Hello world"""\ndef add(self, a, b):\n a = 0\n return a\n\nx = X()\nx.add(5,3)');
Sk.configure({
__future__: Sk.python3,
read: function (filename) {
if (Sk.builtinFiles === undefined ||
Sk.builtinFiles["files"][filename] === undefined) {
throw "File not found: '" + filename + "'";
}
return Sk.builtinFiles["files"][filename];
}
});
$("#make-image").click(function() {
editor.blockEditor.getPngFromBlocks((u, i)=> $("#image-spot").html(i));
});
$('#go').click(function () {
/*alert('Starting!')
var filename = 'main';
var code = `import pedal`;
//console.time('Run');
Sk.importMainWithBody(filename, false, code, true).$d;
//console.timeEnd('Run');
alert('Done!')*/
runTests();
});
var TESTS = [
'for ___ in ___:\n pass',
'0',
'0\n0\n0\n0\n',
'for ___ in ___:\n 0\n 0',
'for x in y:\n pass',
'1 + 1',
'(1 * 3 + 4) + 6 & 8',
'(1 + 2) - (3 * 4) / 5 | 7 & (8 % 9 << 10) >> 11 // 12',
'not 4',
'+1\n-2\n~4\nnot 5\nnot not not 4',
'1 or 2',
'1 and 2 and 3 or 4 and 5 or 3 or 4',
'1 < 5',
'(2 < 3) < 4',
'(((4 > 3) < 2) > 2) < 2',
'5 is 4',
'___ in ___',
'3 is not 4',
'(1 is 2) is 3',
'(((((((1 == 2) != 3) <= 4) >= 5) in 3) not in 3) is 4) is not 5',
'1 < 2 and 3 < 4',
'assert (1 < 2)',
'assert (1 > 4), ___',
'"Hello \'world.\'"',
"'Hello \"there.\"'",
'alpha\nbeta\ngamma',
'alpha\nalpha\nalpha',
'True\nFalse\nNone',
'[]\n[1, 2, 3]\n[1, 2, 4, 5]\n()\n(1, 2, 3)\n(1, 2)\n(1, )\n(1, 2, 3, 4, 5)',
'{1, 2, 3}\n{1}\n{4, 5, 6, 7}',
"{1: 2, 'Hello': 'World'}\n{}",
'{*{}}',
"0 if True else False",
"dog.growl\nalpha.beta.gamma\n'Test'.save",
'alpha\nalpha(1)\nbeta(2)\nbeta',
'alpha(beta)\nalpha.beta(gamma)\nhello(1, 2, 3)\nfor a in b:\n (corgi(run))',
'sorted([1, 2, 3], reverse=True)',
'complex(1, 2, *first, *second, **big, **dog, third=3, fourth=4)',
"raise\nraise Exception()\nraise Exception() from wherever",
"del alpha\ndel alpha, beta, gamma",
"simple[0]\nranged[1:2]\nranged[:2]\nranged[1:]\nranged[:]",
"ranged[::3]\nranged[1::3]\nranged[:2:3]\nranged[1:2:3]",
// acbart: This ends up the same as [:], so can't test it.
// "r[::]"
"df[1:2, 4]\ndf[1, 2, 3, 4]\ndf[6::7, 4:6, 5, 1:]",
"[x for a in b if c]\n[x for a in b for c in d if e if g]",
"{x for a in b if c}\n{x for a in b for c in d if e if g}",
"(x for a in b if c)\n(x for a in b for c in d if e if g)",
"{x: y for a in b if c}\n{x: y for a in b for c in d if e if g}",
"a = 0\na = b = c = 0",
"(a, b) = (1, 2)\n[x, (y, z)] = something",
"i: int = 0\ns: str = 'Hello'\nf: float = 4.3\nb: bool = True\nx: Z = 4",
"i: 'int' = 0\ns: 'str' = 'Hello'\nf: 'float' = 4.3\nb: 'bool' = True",
"n: None = None\na[0]: List[int] = 0\nb: Dict[str, str]",
'a += 1\nb *= 4\nc **= 4\nd ^= 10',
`def alpha(beta, gamma, delta):\n pass`,
`def alpha(beta: str, gamma=True, delta: int=0):\n pass`,
`@route\n@open('test')\ndef alpha(beta: str, gamma=True, delta: int=0):\n pass`,
`@route\n@open('test')\ndef alpha(beta: str, gamma=True, delta: int=0, *args, k=4, num: int=3, **kwargs):\n a = 0\n b = 7`,
"def do_something(a: int) -> str:\n assert (4 == 3)",
'lambda x, y=0: x + y',
'(lambda : None)()',
"def simple(a, b, c) -> int:\n return 'Hello world!'\n return",
"def simple(a, b, c) -> int:\n (yield 'Hello world!')\n (yield)\n dog = yield b + 4",
"def simple(a, b, c) -> int:\n (yield from 'Hello world!')\n dog = yield from b + 4",
"def simple(a, b, c) -> int:\n global alpha\ndef another(e, f):\n global alpha, beta, gamma",
//"def simple(a, b, c) -> int:\n def inner():\n nonlocal alpha\n nonlocal alpha, beta, gamma",
"for x in y:\n break\n continue",
("try:\n pass\nexcept NameError:\n pass" +
"\nexcept Something() as other:\n pass\n" +
"except None as some:\n pass\nexcept:\n " +
"pass\nelse:\n pass\nfinally:\n pass"),
"try:\n a = 0\nexcept:\n return",
"@whatever\nclass a(b, *d, c=0, **e):\n a = 0\nclass Dog:\n age = 1\n name = 'Ada'",
"if x:\n pass\nif y:\n pass\nelse:\n pass",
"if a:\n if j:\n pass\n elif k:\n pass\n else:\n pass\nelif b:\n pass",
"while x == 0:\n pass\nwhile y < z:\n a = 0\nelse:\n b = a",
"import x as y, b as c, d\nimport os",
"from . import x\nfrom .os import y\nfrom ..path import z\nfrom dog.house import a\nfrom cat import b, c as d, e",
//"import matplotlib.pyplot as plt",
"with open('filename') as outfile:\n pass",
"with open('filename') as outfile, open('file2') as infile, other_context:\n pass",
"#hello world!\n# Another comment\n#: int\n\na",
"#TODO: We need to work harder on this!",
"a = 0\nprint(a)\nfor x in y:\n print(b)\n (max(a, b))",
"with x():\n pass",
"(lambda x: x)()",
"class Alpha:\n def beta():\n '''\n Hello World!\n Testing.\n '''",
"'test'.replace(1, 2, 3)",
"'\\n'",
"'''\ntest'''"
];
function runTests() {
for (let i = 0; i < TESTS.length; i += 1) {
let test = TESTS[i];
editor.textEditor.setCode(test, true);
editor.blockEditor.setCode(editor.textEditor.getCode(), true);
console.assert(test.trim() === editor.textEditor.getCode().trim(),
"\nExpected:\n" + test.trim() + "\n",
"\nActual:\n" + editor.textEditor.getCode().trim() + "\n");
if (test.trim() !== editor.textEditor.getCode().trim()) {
break;
}
editor.blockEditor.changed();
editor.blockEditor.setCode(editor.textEditor.getCode(), true);
console.assert(test.trim() === editor.textEditor.getCode().trim(),
"\nExpected:\n" + test.trim() + "\n",
"\nActual:\n" + editor.textEditor.getCode().trim() + "\n(second trip)");
if (test.trim() !== editor.textEditor.getCode().trim()) {
break;
}
}
}
//runTests();
function tryGrindleHook() {
editor.textEditor.setCode('grindlehook.py', `def calculate_rating(name):
'''
Returns the customer's credit rating, according to the bank's current
status, the customer, and the alignment of the stars. This function
is delicate, and will break after being called once.
Notes:
(ghook@1/15/2018): DO NOT TOUCH THIS, I FINALLY GOT IT WORKING.
Args:
name (str): A string representing the user's full name.
Returns:
int: An integer (0-9) representing the customer's credit rating.
'''
c=calculate_rating;setattr(c,'r',lambda:setattr(c,'o',True))
j={};y=j['CELESTIAL_NAVIGATION_CONSTANT']=10
j[True]='CELESTIAL_NAVIGATION_CONSTANT'
x=str(''[:].swapcase);y=y+11,y+9,y+-2,y+-2,y+4,y+-5,y+-1,y+11,y+9,\\
y+-6,y+-6,y+-1,y+-5,y+3,y+-7,y+7,y+-1,y+-5,y+8,y+-7,y+11,y+1
z=lambda x,t,o=0:''.join(map(lambda j:x.__getitem__(j+o), t))
if hasattr(c,'o')and not getattr(c, 'o'): return z(x,y)
c.o=False;j['CELESTIAL_NAVIGATION_CONSTANT'].bit_length
d=(lambda:(lambda:None))()();g=globals()
while d:g['X567S-lumos-17-KLAUS']=((d)if(lambda:None)else(j))
p=lambda p:sum(map(int, list(str(p))))
MGC=p(sum(map(lambda v: v[0]*8+ord(v[1]), enumerate(name))))
while MGC>10:MGC=p(MGC)
if c:return MGC`);
};
</script>
</body>
</html>