forked from hedyorg/hedy
-
Notifications
You must be signed in to change notification settings - Fork 0
/
hedy.py
3383 lines (2766 loc) · 134 KB
/
hedy.py
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
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
import textwrap
from functools import lru_cache, cache
import lark
from flask_babel import gettext
from lark import Lark
from lark.exceptions import UnexpectedEOF, UnexpectedCharacters, VisitError
from lark import Tree, Transformer, visitors, v_args
from os import path, getenv
import warnings
import hedy
import hedy_translation
from utils import atomic_write_file
from hedy_content import ALL_KEYWORD_LANGUAGES
from collections import namedtuple
import re
import regex
from dataclasses import dataclass, field
import exceptions
import program_repair
import yaml
import hashlib
import os
import pickle
import sys
import tempfile
import utils
# Some useful constants
from hedy_content import KEYWORDS
from hedy_sourcemap import SourceMap, source_map_transformer
HEDY_MAX_LEVEL = 18
HEDY_MAX_LEVEL_SKIPPING_FAULTY = 5
MAX_LINES = 100
LEVEL_STARTING_INDENTATION = 8
# Boolean variables to allow code which is under construction to not be executed
local_keywords_enabled = True
# dictionary to store transpilers
TRANSPILER_LOOKUP = {}
# define source-map
source_map = SourceMap()
# builtins taken from 3.11.0 docs: https://docs.python.org/3/library/functions.html
PYTHON_BUILTIN_FUNCTIONS = [
'abs',
'aiter',
'all',
'any',
'anext',
'ascii',
'bin',
'bool',
'breakpoint',
'bytearray',
'bytes',
'callable',
'chr',
'classmethod',
'compile',
'complex',
'delattr',
'dict',
'dir',
'divmod',
'enumerate',
'eval',
'exec',
'filter',
'float',
'format',
'frozenset',
'getattr',
'globals',
'hasattr',
'hash',
'help',
'hex',
'id',
'input',
'int',
'isinstance',
'issubclass',
'iter',
'len',
'list',
'locals',
'map',
'max',
'memoryview',
'min',
'next',
'object',
'oct',
'open',
'ord',
'pow',
'print',
'property',
'range',
'repr',
'reversed',
'round',
'set',
'setattr',
'slice',
'sorted',
'staticmethod',
'str',
'sum',
'super',
'tuple',
'type',
'vars',
'zip']
PYTHON_KEYWORDS = [
'and',
'except',
'lambda',
'with',
'as',
'finally',
'nonlocal',
'while',
'assert',
'False',
'None',
'yield',
'break',
'for',
'not',
'class',
'from',
'or',
'continue',
'global',
'pass',
'def',
'if',
'raise',
'del',
'import',
'return',
'elif',
'in',
'True',
'else',
'is',
'try',
'int']
# Python keywords and function names need hashing when used as var names
reserved_words = set(PYTHON_BUILTIN_FUNCTIONS + PYTHON_KEYWORDS)
# Let's retrieve all keywords dynamically from the cached KEYWORDS dictionary
indent_keywords = {}
for lang, keywords in KEYWORDS.items():
indent_keywords[lang] = []
for keyword in ['if', 'elif', 'for', 'repeat', 'while', 'else', 'define', 'def']:
indent_keywords[lang].append(keyword) # always also check for En
indent_keywords[lang].append(keywords.get(keyword))
# These are the preprocessor rules that we use to specify changes in the rules that
# are expected to work across several rules
# Example
# for<needs_colon> instead of defining the whole rule again.
def needs_colon(rule):
pos = rule.find('_EOL (_SPACE command)')
return f'{rule[0:pos]} _COLON {rule[pos:]}'
def _translate_index_error(code, list_name):
exception_text = gettext('catch_index_exception').replace('{list_name}', style_command(list_name))
return textwrap.dedent(f"""\
try:
{code}
except IndexError:
raise Exception({repr(exception_text)})
""")
PREPROCESS_RULES = {
'needs_colon': needs_colon
}
class Command:
print = 'print'
ask = 'ask'
echo = 'echo'
turn = 'turn'
forward = 'forward'
sleep = 'sleep'
color = 'color'
add_to_list = 'add to list'
remove_from_list = 'remove from list'
list_access = 'at random'
in_list = 'in list'
equality = 'is (equality)'
repeat = 'repeat'
for_list = 'for in'
for_loop = 'for in range'
addition = '+'
subtraction = '-'
multiplication = '*'
division = '/'
smaller = '<'
smaller_equal = '<='
bigger = '>'
bigger_equal = '>='
not_equal = '!='
pressed = 'pressed'
clear = 'clear'
define = 'define'
call = 'call'
returns = 'return'
translatable_commands = {Command.print: ['print'],
Command.ask: ['ask'],
Command.echo: ['echo'],
Command.turn: ['turn'],
Command.sleep: ['sleep'],
Command.color: ['color'],
Command.forward: ['forward'],
Command.add_to_list: ['add', 'to_list'],
Command.remove_from_list: ['remove', 'from'],
Command.list_access: ['at', 'random'],
Command.in_list: ['in'],
Command.equality: ['is', '=', '=='],
Command.repeat: ['repeat', 'times'],
Command.for_list: ['for', 'in'],
Command.for_loop: ['in', 'range', 'to'],
Command.define: ['define'],
Command.call: ['call'],
Command.returns: ['return'], }
class HedyType:
any = 'any'
none = 'none'
string = 'string'
integer = 'integer'
list = 'list'
float = 'float'
boolean = 'boolean'
input = 'input'
# Type promotion rules are used to implicitly convert one type to another, e.g. integer should be auto converted
# to float in 1 + 1.5. Additionally, before level 12, we want to convert numbers to strings, e.g. in equality checks.
int_to_float = (HedyType.integer, HedyType.float)
int_to_string = (HedyType.integer, HedyType.string)
float_to_string = (HedyType.float, HedyType.string)
input_to_int = (HedyType.input, HedyType.integer)
input_to_float = (HedyType.input, HedyType.float)
input_to_string = (HedyType.input, HedyType.string)
def promote_types(types, rules):
for (from_type, to_type) in rules:
if to_type in types:
types = [to_type if t == from_type else t for t in types]
return types
# Commands per Hedy level which are used to suggest the closest command when kids make a mistake
commands_per_level = {
1: ['print', 'ask', 'echo', 'turn', 'forward', 'color'],
2: ['print', 'ask', 'is', 'turn', 'forward', 'color', 'sleep'],
3: ['ask', 'is', 'print', 'forward', 'turn', 'color', 'sleep', 'at', 'random', 'add', 'to', 'remove', 'from'],
4: ['ask', 'is', 'print', 'forward', 'turn', 'color', 'sleep', 'at', 'random', 'add', 'to', 'remove', 'from', 'clear'],
5: ['ask', 'is', 'print', 'forward', 'turn', 'color', 'sleep', 'at', 'random', 'add', 'to', 'remove', 'from', 'in', 'not in', 'if', 'else', 'ifpressed', 'assign_button', 'clear'],
6: ['ask', 'is', 'print', 'forward', 'turn', 'color', 'sleep', 'at', 'random', 'add', 'to', 'remove', 'from', 'in', 'not in', 'if', 'else', 'ifpressed', 'assign_button', 'clear'],
7: ['ask', 'is', 'print', 'forward', 'turn', 'color', 'sleep', 'at', 'random', 'add', 'to', 'remove', 'from', 'in', 'not in', 'if', 'else', 'ifpressed', 'assign_button', 'repeat', 'times', 'clear'],
8: ['ask', 'is', 'print', 'forward', 'turn', 'color', 'sleep', 'at', 'random', 'add', 'to', 'remove', 'from', 'in', 'not in', 'if', 'else', 'ifpressed', 'assign_button', 'repeat', 'times', 'clear'],
9: ['ask', 'is', 'print', 'forward', 'turn', 'color', 'sleep', 'at', 'random', 'add', 'to', 'remove', 'from', 'in', 'not in', 'if', 'else', 'ifpressed', 'assign_button', 'repeat', 'times', 'clear'],
10: ['ask', 'is', 'print', 'forward', 'turn', 'color', 'sleep', 'at', 'random', 'add', 'to', 'remove', 'from', 'in', 'not in', 'if', 'else', 'ifpressed', 'assign_button', 'repeat', 'times', 'for', 'clear'],
11: ['ask', 'is', 'print', 'forward', 'turn', 'color', 'sleep', 'at', 'random', 'add', 'to', 'remove', 'from', 'in', 'not in', 'if', 'else', 'ifpressed', 'assign_button', 'for', 'range', 'repeat', 'clear'],
12: ['ask', 'is', 'print', 'forward', 'turn', 'color', 'sleep', 'at', 'random', 'add', 'to', 'remove', 'from', 'in', 'not in', 'if', 'else', 'ifpressed', 'assign_button', 'for', 'range', 'repeat', 'clear', 'define', 'call'],
13: ['ask', 'is', 'print', 'forward', 'turn', 'color', 'sleep', 'at', 'random', 'add', 'to', 'remove', 'from', 'in', 'not in', 'if', 'else', 'ifpressed', 'assign_button', 'for', 'range', 'repeat', 'and', 'or', 'clear', 'define', 'call'],
14: ['ask', 'is', 'print', 'forward', 'turn', 'color', 'sleep', 'at', 'random', 'add', 'to', 'remove', 'from', 'in', 'not in', 'if', 'else', 'ifpressed', 'assign_button', 'for', 'range', 'repeat', 'and', 'or', 'clear', 'define', 'call'],
15: ['ask', 'is', 'print', 'forward', 'turn', 'color', 'sleep', 'at', 'random', 'add', 'to', 'remove', 'from', 'in', 'not in', 'if', 'else', 'ifpressed', 'assign_button', 'for', 'range', 'repeat', 'and', 'or', 'while', 'clear', 'define', 'call'],
16: ['ask', 'is', 'print', 'forward', 'turn', 'color', 'sleep', 'at', 'random', 'add', 'to', 'remove', 'from', 'in', 'not in', 'if', 'else', 'ifpressed', 'assign_button', 'for', 'range', 'repeat', 'and', 'or', 'while', 'clear', 'define', 'call'],
17: ['ask', 'is', 'print', 'forward', 'turn', 'color', 'sleep', 'at', 'random', 'add', 'to', 'remove', 'from', 'in', 'not in', 'if', 'else', 'ifpressed', 'assign_button', 'for', 'range', 'repeat', 'and', 'or', 'while', 'elif', 'clear', 'define', 'call'],
18: ['is', 'print', 'forward', 'turn', 'color', 'sleep', 'at', 'random', 'add', 'to', 'remove', 'from', 'in', 'if', 'not in', 'else', 'for', 'ifpressed', 'assign_button', 'range', 'repeat', 'and', 'or', 'while', 'elif', 'input', 'clear', 'define', 'call'],
}
command_turn_literals = ['right', 'left']
command_make_color = ['black', 'blue', 'brown', 'gray', 'green', 'orange', 'pink', 'purple', 'red', 'white', 'yellow']
def color_commands_local(language):
colors_local = [hedy_translation.translate_keyword_from_en(k, language) for k in command_make_color]
return colors_local
def command_make_color_local(language):
if language == "en":
return command_make_color
else:
return command_make_color + color_commands_local(language)
# Commands and their types per level (only partially filled!)
commands_and_types_per_level = {
Command.print: {
1: [HedyType.string, HedyType.integer, HedyType.input],
12: [HedyType.string, HedyType.integer, HedyType.input, HedyType.float],
16: [HedyType.string, HedyType.integer, HedyType.input, HedyType.float, HedyType.list]
},
Command.ask: {
1: [HedyType.string, HedyType.integer, HedyType.input],
12: [HedyType.string, HedyType.integer, HedyType.input, HedyType.float],
16: [HedyType.string, HedyType.integer, HedyType.input, HedyType.float, HedyType.list]
},
Command.turn: {1: command_turn_literals,
2: [HedyType.integer, HedyType.input],
12: [HedyType.integer, HedyType.input, HedyType.float]
},
Command.color: {1: command_make_color,
2: [command_make_color, HedyType.string, HedyType.input]},
Command.forward: {1: [HedyType.integer, HedyType.input],
12: [HedyType.integer, HedyType.input, HedyType.float]
},
Command.sleep: {1: [HedyType.integer, HedyType.input]},
Command.list_access: {1: [HedyType.list]},
Command.in_list: {1: [HedyType.list]},
Command.add_to_list: {1: [HedyType.list]},
Command.remove_from_list: {1: [HedyType.list]},
Command.equality: {1: [HedyType.string, HedyType.integer, HedyType.input, HedyType.float],
14: [HedyType.string, HedyType.integer, HedyType.input, HedyType.float, HedyType.list]},
Command.addition: {
6: [HedyType.integer, HedyType.input],
12: [HedyType.string, HedyType.integer, HedyType.input, HedyType.float]
},
Command.subtraction: {
1: [HedyType.integer, HedyType.input],
12: [HedyType.integer, HedyType.float, HedyType.input],
},
Command.multiplication: {
1: [HedyType.integer, HedyType.input],
12: [HedyType.integer, HedyType.float, HedyType.input],
},
Command.division: {
1: [HedyType.integer, HedyType.input],
12: [HedyType.integer, HedyType.float, HedyType.input],
},
Command.repeat: {7: [HedyType.integer, HedyType.input]},
Command.for_list: {10: {HedyType.list}},
Command.for_loop: {11: [HedyType.integer, HedyType.input]},
Command.smaller: {14: [HedyType.integer, HedyType.float, HedyType.input]},
Command.smaller_equal: {14: [HedyType.integer, HedyType.float, HedyType.input]},
Command.bigger: {14: [HedyType.integer, HedyType.float, HedyType.input]},
Command.bigger_equal: {14: [HedyType.integer, HedyType.float, HedyType.input]},
Command.not_equal: {14: [HedyType.integer, HedyType.float, HedyType.string, HedyType.input, HedyType.list]},
Command.pressed: {5: [HedyType.string]} # TODO: maybe use a seperate type character in the future.
}
# we generate Python strings with ' always, so ' needs to be escaped but " works fine
# \ also needs to be escaped because it eats the next character
characters_that_need_escaping = ["\\", "'"]
character_skulpt_cannot_parse = re.compile('[^a-zA-Z0-9_]')
def get_list_keywords(commands, to_lang):
""" Returns a list with the local keywords of the argument 'commands'
"""
translation_commands = []
dir = path.abspath(path.dirname(__file__))
path_keywords = dir + "/content/keywords"
to_yaml_filesname_with_path = path.join(path_keywords, to_lang + '.yaml')
en_yaml_filesname_with_path = path.join(path_keywords, 'en' + '.yaml')
with open(en_yaml_filesname_with_path, 'r', encoding='utf-8') as stream:
en_yaml_dict = yaml.safe_load(stream)
try:
with open(to_yaml_filesname_with_path, 'r', encoding='utf-8') as stream:
to_yaml_dict = yaml.safe_load(stream)
for command in commands:
if command == 'ifpressed': # TODO: this is a bit of a hack
command = 'pressed' # since in the yamls they are called pressed
if command == 'assign_button': # but in the grammar 'ifpressed'
command = 'button' # should be changed in the yaml eventually!
try:
translation_commands.append(to_yaml_dict[command])
except Exception:
translation_commands.append(en_yaml_dict[command])
except Exception:
for command in commands:
translation_commands.append(en_yaml_dict[command])
return translation_commands
def get_suggestions_for_language(lang, level):
if not local_keywords_enabled:
lang = 'en'
lang_commands = get_list_keywords(commands_per_level[level], lang)
# if we allow multiple keyword languages:
en_commands = get_list_keywords(commands_per_level[level], 'en')
en_lang_commands = list(set(en_commands + lang_commands))
return en_lang_commands
def escape_var(var):
var_name = var.name if type(var) is LookupEntry else var
return "_" + var_name if var_name in reserved_words else var_name
def closest_command(invalid_command, known_commands, threshold=2):
# closest_command() searches for a similar command (distance smaller than threshold)
# TODO: make the result value be tuple instead of a ugly None & string mix
# returns None if the invalid command does not contain any known command.
# returns 'keyword' if the invalid command is exactly a command (so shoudl not be suggested)
min_command = closest_command_with_min_distance(invalid_command, known_commands, threshold)
# Check if we are not returning the found command
# In that case we have no suggestion
# This is to prevent "print is not a command in Hedy level 3, did you mean print?" error message
if min_command == invalid_command:
return 'keyword'
return min_command
def style_command(command):
return f'<span class="command-highlighted">{command}</span>'
def closest_command_with_min_distance(invalid_command, commands, threshold):
# FH, early 2020: simple string distance, could be more sophisticated MACHINE LEARNING!
minimum_distance = 1000
closest_command = None
for command in commands:
minimum_distance_for_command = calculate_minimum_distance(command, invalid_command)
if minimum_distance_for_command < minimum_distance and minimum_distance_for_command <= threshold:
minimum_distance = minimum_distance_for_command
closest_command = command
return closest_command
def calculate_minimum_distance(s1, s2):
"""Return string distance between 2 strings."""
if len(s1) > len(s2):
s1, s2 = s2, s1
distances = range(len(s1) + 1)
for index2, char2 in enumerate(s2):
new_distances = [index2 + 1]
for index1, char1 in enumerate(s1):
if char1 == char2:
new_distances.append(distances[index1])
else:
new_distances.append(1 + min((distances[index1], distances[index1 + 1], new_distances[-1])))
distances = new_distances
return distances[-1]
@dataclass
class InvalidInfo:
error_type: str
command: str = ''
arguments: list = field(default_factory=list)
line: int = 0
column: int = 0
# used in to construct lookup table entries and infer their type
@dataclass
class LookupEntry:
name: str
tree: Tree
linenumber: int
skip_hashing: bool
type_: str = None
currently_inferring: bool = False # used to detect cyclic type inference
class TypedTree(Tree):
def __init__(self, data, children, meta, type_):
super().__init__(data, children, meta)
self.type_ = type_
@v_args(meta=True)
class ExtractAST(Transformer):
# simplifies the tree: f.e. flattens arguments of text, var and punctuation for further processing
def text(self, meta, args):
return Tree('text', [' '.join([str(c) for c in args])], meta)
def INT(self, args):
return Tree('integer', [str(args)])
def NUMBER(self, args):
return Tree('number', [str(args)])
def POSITIVE_NUMBER(self, args):
return Tree('number', [str(args)])
def NEGATIVE_NUMBER(self, args):
return Tree('number', [str(args)])
# level 2
def var(self, meta, args):
return Tree('var', [''.join([str(c) for c in args])], meta)
def list_access(self, meta, args):
# FH, may 2022 I don't fully understand why we remove INT here and just plemp
# the number in the tree. should be improved but that requires rewriting the further processing code too (TODO)
if isinstance(args[1], Tree):
if "random" in args[1].data:
return Tree('list_access', [args[0], 'random'], meta)
elif args[1].data == "var_access":
return Tree('list_access', [args[0], args[1].children[0]], meta)
else:
# convert to latin int
latin_int_index = str(int(args[1].children[0]))
return Tree('list_access', [args[0], latin_int_index], meta)
else:
return Tree('list_access', [args[0], args[1]], meta)
# level 5
def error_unsupported_number(self, meta, args):
return Tree('unsupported_number', [''.join([str(c) for c in args])], meta)
# This visitor collects all entries that should be part of the lookup table. It only stores the name of the entry
# (e.g. 'animal') and its value as a tree node (e.g. Tree['text', ['cat']]) which is later used to infer the type
# of the entry. This preliminary traversal is needed to avoid issues with loops in which an iterator variable is
# used in the inner commands which are visited before the iterator variable is added to the lookup.
class LookupEntryCollector(visitors.Visitor):
def __init__(self, level):
super().__init__()
self.level = level
self.lookup = []
def ask(self, tree):
# in level 1 there is no variable name on the left side of the ask command
if self.level > 1:
self.add_to_lookup(tree.children[0].children[0], tree, tree.meta.line)
def input_empty_brackets(self, tree):
self.input(tree)
def input(self, tree):
var_name = tree.children[0].children[0]
self.add_to_lookup(var_name, tree, tree.meta.line)
def assign(self, tree):
var_name = tree.children[0].children[0]
self.add_to_lookup(var_name, tree.children[1], tree.meta.line)
def assign_list(self, tree):
var_name = tree.children[0].children[0]
self.add_to_lookup(var_name, tree, tree.meta.line)
# list access is added to the lookup table not because it must be escaped
# for example we print(dieren[1]) not print('dieren[1]')
def list_access(self, tree):
list_name = escape_var(tree.children[0].children[0])
position_name = escape_var(tree.children[1])
if position_name == 'random':
name = f'random.choice({list_name})'
else:
# We want list access to be 1-based instead of 0-based, hence the -1
name = f'{list_name}[int({position_name})-1]'
self.add_to_lookup(name, tree, tree.meta.line, True)
def change_list_item(self, tree):
self.add_to_lookup(tree.children[0].children[0], tree, tree.meta.line, True)
def for_list(self, tree):
iterator = str(tree.children[0].children[0])
# the tree is trimmed to skip contain the inner commands of the loop since
# they are not needed to infer the type of the iterator variable
trimmed_tree = Tree(tree.data, tree.children[0:2], tree.meta)
self.add_to_lookup(iterator, trimmed_tree, tree.meta.line)
def for_loop(self, tree):
iterator = str(tree.children[0].children[0])
# the tree is trimmed to skip contain the inner commands of the loop since
# they are not needed to infer the type of the iterator variable
trimmed_tree = Tree(tree.data, tree.children[0:3], tree.meta)
self.add_to_lookup(iterator, trimmed_tree, tree.meta.line)
def define(self, tree):
# add function name to lookup
self.add_to_lookup(str(tree.children[0].children[0]) + "()", tree, tree.meta.line)
# add arguments to lookup
if tree.children[1].data == 'arguments':
for x in (c for c in tree.children[1].children if isinstance(c, Tree)):
self.add_to_lookup(x.children[0], tree.children[1], tree.meta.line)
def call(self, tree):
function_name = tree.children[0].children[0]
args_str = ""
if len(tree.children) > 1:
args_str = ", ".join(str(x.children[0]) if isinstance(x, Tree) else str(x)
for x in tree.children[1].children)
self.add_to_lookup(f"{function_name}({args_str})", tree, tree.meta.line)
def add_to_lookup(self, name, tree, linenumber, skip_hashing=False):
entry = LookupEntry(name, tree, linenumber, skip_hashing)
hashed_name = escape_var(entry)
entry.name = hashed_name
self.lookup.append(entry)
# The transformer traverses the whole AST and infers the type of each node. It alters the lookup table entries with
# their inferred type. It also performs type validation for commands, e.g. 'text' + 1 results in error.
@v_args(tree=True)
class TypeValidator(Transformer):
def __init__(self, lookup, level, lang, input_string):
super().__init__()
self.lookup = lookup
self.level = level
self.lang = lang
self.input_string = input_string
def print(self, tree):
self.validate_args_type_allowed(Command.print, tree.children, tree.meta)
return self.to_typed_tree(tree)
def ask(self, tree):
if self.level > 1:
self.save_type_to_lookup(tree.children[0].children[0], HedyType.input)
self.validate_args_type_allowed(Command.ask, tree.children[1:], tree.meta)
return self.to_typed_tree(tree, HedyType.input)
def input(self, tree):
self.validate_args_type_allowed(Command.ask, tree.children[1:], tree.meta)
return self.to_typed_tree(tree, HedyType.input)
def forward(self, tree):
if tree.children:
self.validate_args_type_allowed(Command.forward, tree.children, tree.meta)
return self.to_typed_tree(tree)
def color(self, tree):
if tree.children:
self.validate_args_type_allowed(Command.color, tree.children, tree.meta)
return self.to_typed_tree(tree)
def turn(self, tree):
if tree.children:
name = tree.children[0].data
if self.level > 1 or name not in command_turn_literals:
self.validate_args_type_allowed(Command.turn, tree.children, tree.meta)
return self.to_typed_tree(tree)
def sleep(self, tree):
if tree.children:
self.validate_args_type_allowed(Command.sleep, tree.children, tree.meta)
return self.to_typed_tree(tree)
def assign(self, tree):
try:
type_ = self.get_type(tree.children[1])
self.save_type_to_lookup(tree.children[0].children[0], type_)
except hedy.exceptions.UndefinedVarException as ex:
if self.level >= 12:
raise hedy.exceptions.UnquotedAssignTextException(
text=ex.arguments['name'],
line_number=tree.meta.line)
else:
raise
return self.to_typed_tree(tree, HedyType.none)
def assign_list(self, tree):
self.save_type_to_lookup(tree.children[0].children[0], HedyType.list)
return self.to_typed_tree(tree, HedyType.list)
def list_access(self, tree):
self.validate_args_type_allowed(Command.list_access, tree.children[0], tree.meta)
list_name = escape_var(tree.children[0].children[0])
if tree.children[1] == 'random':
name = f'random.choice({list_name})'
else:
# We want list access to be 1-based instead of 0-based, hence the -1
name = f'{list_name}[int({tree.children[1]})-1]'
self.save_type_to_lookup(name, HedyType.any)
return self.to_typed_tree(tree, HedyType.any)
def add(self, tree):
self.validate_args_type_allowed(Command.add_to_list, tree.children[1], tree.meta)
return self.to_typed_tree(tree)
def remove(self, tree):
self.validate_args_type_allowed(Command.remove_from_list, tree.children[1], tree.meta)
return self.to_typed_tree(tree)
def in_list_check(self, tree):
self.validate_args_type_allowed(Command.in_list, tree.children[1], tree.meta)
return self.to_typed_tree(tree, HedyType.boolean)
def equality_check(self, tree):
if self.level < 12:
rules = [int_to_float, int_to_string, float_to_string, input_to_string, input_to_int, input_to_float]
else:
rules = [int_to_float, input_to_string, input_to_int, input_to_float]
self.validate_binary_command_args_type(Command.equality, tree, rules)
return self.to_typed_tree(tree, HedyType.boolean)
def repeat(self, tree):
command = Command.repeat
allowed_types = get_allowed_types(command, self.level)
self.check_type_allowed(command, allowed_types, tree.children[0], tree.meta)
return self.to_typed_tree(tree, HedyType.none)
def for_list(self, tree):
command = Command.for_list
allowed_types = get_allowed_types(command, self.level)
self.check_type_allowed(command, allowed_types, tree.children[1], tree.meta)
self.save_type_to_lookup(tree.children[0].children[0], HedyType.any)
return self.to_typed_tree(tree, HedyType.none)
def for_loop(self, tree):
command = Command.for_loop
allowed_types = get_allowed_types(command, self.level)
start_type = self.check_type_allowed(command, allowed_types, tree.children[1], tree.meta)
self.check_type_allowed(command, allowed_types, tree.children[2], tree.meta)
iterator = str(tree.children[0])
self.save_type_to_lookup(iterator, start_type)
return self.to_typed_tree(tree, HedyType.none)
def integer(self, tree):
return self.to_typed_tree(tree, HedyType.integer)
def text(self, tree):
# under level 12 integers appear as text, so we parse them
if self.level < 12:
type_ = HedyType.integer if ConvertToPython.is_int(tree.children[0]) else HedyType.string
else:
type_ = HedyType.string
return self.to_typed_tree(tree, type_)
def text_in_quotes(self, tree):
return self.to_typed_tree(tree.children[0], HedyType.string)
def var_access(self, tree):
return self.to_typed_tree(tree, HedyType.string)
def var_access_print(self, tree):
return self.var_access(tree)
def var(self, tree):
return self.to_typed_tree(tree, HedyType.none)
def number(self, tree):
number = tree.children[0]
if ConvertToPython.is_int(number):
return self.to_typed_tree(tree, HedyType.integer)
if ConvertToPython.is_float(number):
return self.to_typed_tree(tree, HedyType.float)
# We managed to parse a number that cannot be parsed by python
raise exceptions.ParseException(level=self.level, location='', found=number)
def subtraction(self, tree):
return self.to_sum_typed_tree(tree, Command.subtraction)
def addition(self, tree):
return self.to_sum_typed_tree(tree, Command.addition)
def multiplication(self, tree):
return self.to_sum_typed_tree(tree, Command.multiplication)
def division(self, tree):
return self.to_sum_typed_tree(tree, Command.division)
def to_sum_typed_tree(self, tree, command):
rules = [int_to_float, input_to_int, input_to_float]
prom_left_type, prom_right_type = self.validate_binary_command_args_type(command, tree, rules)
return TypedTree(tree.data, tree.children, tree.meta, prom_left_type)
def smaller(self, tree):
return self.to_comparison_tree(Command.smaller, tree)
def smaller_equal(self, tree):
return self.to_comparison_tree(Command.smaller_equal, tree)
def bigger(self, tree):
return self.to_comparison_tree(Command.bigger, tree)
def bigger_equal(self, tree):
return self.to_comparison_tree(Command.bigger_equal, tree)
def not_equal(self, tree):
rules = [int_to_float, input_to_int, input_to_float, input_to_string]
self.validate_binary_command_args_type(Command.not_equal, tree, rules)
return self.to_typed_tree(tree, HedyType.boolean)
def to_comparison_tree(self, command, tree):
allowed_types = get_allowed_types(command, self.level)
self.check_type_allowed(command, allowed_types, tree.children[0], tree.meta)
self.check_type_allowed(command, allowed_types, tree.children[1], tree.meta)
return self.to_typed_tree(tree, HedyType.boolean)
def validate_binary_command_args_type(self, command, tree, type_promotion_rules):
allowed_types = get_allowed_types(command, self.level)
left_type = self.check_type_allowed(command, allowed_types, tree.children[0], tree.meta)
right_type = self.check_type_allowed(command, allowed_types, tree.children[1], tree.meta)
if self.ignore_type(left_type) or self.ignore_type(right_type):
return HedyType.any, HedyType.any
prom_left_type, prom_right_type = promote_types([left_type, right_type], type_promotion_rules)
if prom_left_type != prom_right_type:
left_arg = tree.children[0].children[0]
right_arg = tree.children[1].children[0]
raise hedy.exceptions.InvalidTypeCombinationException(
command, left_arg, right_arg, left_type, right_type, tree.meta.line)
return prom_left_type, prom_right_type
def validate_args_type_allowed(self, command, children, meta):
allowed_types = get_allowed_types(command, self.level)
children = children if type(children) is list else [children]
for child in children:
self.check_type_allowed(command, allowed_types, child, meta)
def check_type_allowed(self, command, allowed_types, tree, meta=None):
arg_type = self.get_type(tree)
if arg_type not in allowed_types and not self.ignore_type(arg_type):
variable = tree.children[0]
if command in translatable_commands:
keywords = translatable_commands[command]
result = hedy_translation.find_command_keywords(
self.input_string,
self.lang,
self.level,
keywords,
meta.line,
meta.end_line,
meta.column - 1,
meta.end_column - 2)
result = {k: v for k, v in result.items()}
command = ' '.join([v.strip() for v in result.values() if v is not None])
raise exceptions.InvalidArgumentTypeException(command=command, invalid_type=arg_type,
invalid_argument=variable, allowed_types=allowed_types, line_number=meta.line)
return arg_type
def get_type(self, tree):
# The rule var_access is used in the grammars definitions only in places where a variable needs to be accessed.
# So, if it cannot be found in the lookup table, then it is an undefined variable for sure.
if tree.data == 'var_access':
var_name = tree.children[0]
in_lookup, type_in_lookup = self.try_get_type_from_lookup(var_name)
if in_lookup:
return type_in_lookup
else:
raise hedy.exceptions.UndefinedVarException(name=var_name, line_number=tree.meta.line)
if tree.data == 'var_access_print':
var_name = tree.children[0]
in_lookup, type_in_lookup = self.try_get_type_from_lookup(var_name)
if in_lookup:
return type_in_lookup
else:
# is there a variable that is mildly similar?
# if so, we probably meant that one
# we first check if the list of vars is empty since that is cheaper than stringdistancing.
# TODO: Can be removed since fall back handles that now
if len(self.lookup) == 0:
raise hedy.exceptions.UnquotedTextException(
level=self.level, unquotedtext=var_name, line_number=tree.meta.line)
else:
# TODO: decide when this runs for a while whether this distance small enough!
minimum_distance_allowed = 4
for var_in_lookup in self.lookup:
if calculate_minimum_distance(var_in_lookup.name, var_name) <= minimum_distance_allowed:
raise hedy.exceptions.UndefinedVarException(name=var_name, line_number=tree.meta.line)
# nothing found? fall back to UnquotedTextException
raise hedy.exceptions.UnquotedTextException(
level=self.level, unquotedtext=var_name, line_number=tree.meta.line)
# TypedTree with type 'None' and 'string' could be in the lookup because of the grammar definitions
# If the tree has more than 1 child, then it is not a leaf node, so do not search in the lookup
if tree.type_ in [HedyType.none, HedyType.string] and len(tree.children) == 1:
in_lookup, type_in_lookup = self.try_get_type_from_lookup(tree.children[0])
if in_lookup:
return type_in_lookup
# If the value is not in the lookup or the type is other than 'None' or 'string', return evaluated type
return tree.type_
def ignore_type(self, type_):
return type_ in [HedyType.any, HedyType.none]
def save_type_to_lookup(self, name, inferred_type):
for entry in self.lookup:
if entry.name == escape_var(name):
entry.type_ = inferred_type
# Usually, variable definitions are sequential and by the time we need the type of a lookup entry, it would already
# be inferred. However, there are valid cases in which the lookup entries will be accessed before their type
# is inferred. This is the case with for loops:
# for i in 1 to 10
# print i
# In the above case, we visit `print i`, before the definition of i in the for cycle. In this case, the tree of
# lookup entry is used to infer the type and continue the started validation. This approach might cause issues
# in case of cyclic references, e.g. b is b + 1. The flag `inferring` is used as a guard against these cases.
def try_get_type_from_lookup(self, name):
matches = [entry for entry in self.lookup if entry.name == escape_var(name)]
if matches:
match = matches[0]
if not match.type_:
if match.currently_inferring: # there is a cyclic var reference, e.g. b = b + 1
raise exceptions.CyclicVariableDefinitionException(
variable=match.name, line_number=match.tree.meta.line)
else:
match.currently_inferring = True
try:
TypeValidator(self.lookup, self.level, self.lang, self.input_string).transform(match.tree)
except VisitError as ex:
raise ex.orig_exc
match.currently_inferring = False
return True, self.lookup_type_fallback(matches[0].type_)
return False, None
def lookup_type_fallback(self, type_in_lookup):
# If the entry is in the lookup table but its type has not been evaluated yet, then most probably this is a
# variable referenced before it is defined. In this case, we rely on python to return an error. For now.
return HedyType.any if type_in_lookup is None else type_in_lookup
def to_typed_tree(self, tree, type_=HedyType.none):
return TypedTree(tree.data, tree.children, tree.meta, type_)
def __default__(self, data, children, meta):
return TypedTree(data, children, meta, HedyType.none)
def flatten_list_of_lists_to_list(args):
flat_list = []
for element in args:
if isinstance(
element,
str): # str needs a special case before list because a str is also a list and we don't want to split all letters out
flat_list.append(element)
elif isinstance(element, list):
flat_list += flatten_list_of_lists_to_list(element)
else:
flat_list.append(element)
return flat_list
def are_all_arguments_true(args):
bool_arguments = [x[0] for x in args]
arguments_of_false_nodes = flatten_list_of_lists_to_list([x[1] for x in args if not x[0]])
return all(bool_arguments), arguments_of_false_nodes
# this class contains code shared between IsValid and IsComplete, which are quite similar
# because both filter out some types of 'wrong' nodes
@v_args(meta=True)
class Filter(Transformer):
def __default__(self, data, children, meta):
result, args = are_all_arguments_true(children)
return result, args, meta
def program(self, meta, args):
bool_arguments = [x[0] for x in args]
if all(bool_arguments):
return [True] # all complete
else:
for a in args:
if not a[0]:
return False, a[1]
# leafs are treated differently, they are True + their arguments flattened
def var(self, meta, args):
return True, ''.join([str(c) for c in args]), meta