forked from hedyorg/hedy
-
Notifications
You must be signed in to change notification settings - Fork 0
/
hedy.py
1968 lines (1592 loc) · 74.7 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 lark import Lark
from lark.exceptions import LarkError, UnexpectedEOF, UnexpectedCharacters, VisitError
from lark import Tree, Transformer, visitors, v_args
from os import path
import hedy
import utils
from collections import namedtuple
import hashlib
import re
from dataclasses import dataclass, field
import exceptions
import yaml
import program_repair
# Some useful constants
HEDY_MAX_LEVEL = 18
MAX_LINES = 100
LEVEL_STARTING_INDENTATION = 8
# Boolean variables to allow code which is under construction to not be executed
local_keywords_enabled = False # If this is True, only the keywords in the specified language can be used for now
#dictionary to store transpilers
TRANSPILER_LOOKUP = {}
# Python keywords need hashing when used as var names
reserved_words = ['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']
# TODO: in error messages we need to translate the names of the commands to the used language
class Command:
print = 'print'
ask = 'ask'
echo = 'echo'
turn = 'turn'
forward = 'forward'
add_to_list = 'add to list'
remove_from_list = 'remove from list'
list_access = 'at random'
in_list = 'in list'
equality = 'is (equality)'
for_loop = 'for'
addition = 'addition'
subtraction = 'subtraction'
multiplication = 'multiplication'
division = 'division'
smaller = '<'
smaller_equal = '<='
bigger = '>'
bigger_equal = '>='
not_equal = '!='
class HedyType:
any = 'any'
none = 'none'
string = 'string'
integer = 'integer'
list = 'list'
float = 'float'
boolean = 'boolean'
# 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)
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'] ,
2: ['print', 'ask', 'is', 'turn', 'forward'],
3: ['print', 'ask', 'is', 'turn', 'forward'],
4: ['print', 'ask', 'is', 'if', 'turn', 'forward'],
5: ['print', 'ask', 'is', 'if', 'repeat', 'turn', 'forward'],
6: ['print', 'ask', 'is', 'if', 'repeat', 'turn', 'forward'],
7: ['print', 'ask', 'is', 'if', 'repeat', 'turn', 'forward'],
8: ['print', 'ask', 'is', 'if', 'for', 'turn', 'forward'],
9: ['print', 'ask', 'is', 'if', 'for', 'elif', 'turn', 'forward'],
10: ['print', 'ask', 'is', 'if', 'for', 'elif', 'turn', 'forward'],
11: ['print', 'ask', 'is', 'if', 'for', 'elif', 'turn', 'forward'],
12: ['print', 'ask', 'is', 'if', 'for', 'elif', 'turn', 'forward'],
13: ['print', 'ask', 'is', 'if', 'for', 'elif', 'turn', 'forward'],
14: ['print', 'ask', 'is', 'if', 'for', 'elif', 'turn', 'forward'],
15: ['print', 'ask', 'is', 'if', 'for', 'elif', 'turn', 'forward'],
16: ['print', 'ask', 'is', 'if', 'for', 'elif', 'turn', 'forward'],
17: ['print', 'ask', 'is', 'if', 'for', 'elif', 'while', 'turn', 'forward'],
18: ['print', 'ask', 'is', 'if', 'for', 'elif', 'while', 'turn', 'forward'],
19: ['print', 'ask', 'is', 'if', 'for', 'elif', 'while', 'turn', 'forward'],
20: ['print', 'ask', 'is', 'if', 'for', 'elif', 'while', 'turn', 'forward'],
21: ['print', 'ask', 'is', 'if', 'for', 'elif', 'while', 'turn', 'forward'],
22: ['print', 'ask', 'is', 'if', 'for', 'elif', 'while', 'turn', 'forward'],
23: ['print', 'ask', 'is', 'if', 'for', 'elif', 'while', 'turn', 'forward']
}
# TODO: these need to be taken from the translated grammar keywords based on the language
command_turn_literals = ['right', 'left']
# Commands and their types per level (only partially filled!)
commands_and_types_per_level = {
Command.print: {
1: [HedyType.string, HedyType.integer],
12: [HedyType.string, HedyType.integer, HedyType.float],
16: [HedyType.string, HedyType.integer, HedyType.float, HedyType.list]
},
Command.ask: {
1: [HedyType.string, HedyType.integer],
12: [HedyType.string, HedyType.integer, HedyType.float],
16: [HedyType.string, HedyType.integer, HedyType.float, HedyType.list]
},
Command.turn: {1: command_turn_literals + [HedyType.integer],
2: [HedyType.integer]},
Command.forward: {1: [HedyType.integer]},
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.float]},
Command.addition: {
6: [HedyType.integer],
12: [HedyType.string, HedyType.integer, HedyType.float]
},
Command.subtraction: {
1: [HedyType.integer],
12: [HedyType.integer, HedyType.float],
},
Command.multiplication: {
1: [HedyType.integer],
12: [HedyType.integer, HedyType.float],
},
Command.division: {
1: [HedyType.integer],
12: [HedyType.integer, HedyType.float],
},
Command.for_loop: {11: [HedyType.integer]},
Command.smaller: {14: [HedyType.integer, HedyType.float]},
Command.smaller_equal: {14: [HedyType.integer, HedyType.float]},
Command.bigger: {14: [HedyType.integer, HedyType.float]},
Command.bigger_equal: {14: [HedyType.integer, HedyType.float]},
Command.not_equal: {14: [HedyType.integer, HedyType.float, HedyType.string]}
}
# 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 hash_needed(name):
# this function is now applied on something str sometimes Assignment
# no pretty but it will all be removed once we no longer need hashing (see issue #959) so ok for now
if not isinstance(name, str):
name = name.name
# some elements are not names but processed names, i.e. random.choice(dieren)
# they should not be hashed
# these are either of type assignment and operation or already processed and then contain ( or [
if (type(name) is LookupEntry and name.skip_hashing) or (isinstance(name, str) and '[' in name or '(' in name):
return False
return name in reserved_words or character_skulpt_cannot_parse.search(name) != None
def hash_var(name):
name = name.name if type(name) is LookupEntry else name
if hash_needed(name):
# hash "illegal" var names
# being reservered keywords
# or non-latin vars to comply with Skulpt, which does not implement PEP3131 :(
# prepend with v for when hash starts with a number
hash_object = hashlib.md5(name.encode())
return "v" + hash_object.hexdigest()
else:
return name
def closest_command(invalid_command, known_commands):
# First search for 100% match of known commands
#
# closest_command() searches for known commands in an invalid command.
#
# It will return the known command which is closest positioned at the beginning.
# It will return '' if the invalid command does not contain any known command.
#
min_position = len(invalid_command)
min_command = ''
for known_command in known_commands:
position = invalid_command.find(known_command)
if position != -1 and position < min_position:
min_position = position
min_command = known_command
# If not found, search for partial match of know commands
if min_command == '':
min_command = closest_command_with_min_distance(invalid_command, known_commands)
# 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 None
return min_command
def style_closest_command(command):
return f'<span class="command-highlighted">{command}</span>'
def closest_command_with_min_distance(command, commands):
#simple string distance, could be more sophisticated MACHINE LEARNING!
min = 1000
min_command = ''
for c in commands:
min_c = minimum_distance(c, command)
if min_c < min:
min = min_c
min_command = c
return min_command
def 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
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_
class ExtractAST(Transformer):
# simplifies the tree: f.e. flattens arguments of text, var and punctuation for further processing
def text(self, args):
return Tree('text', [''.join([str(c) for c in args])])
def INT(self, args):
return Tree('integer', [str(args)])
#level 2
def var(self, args):
return Tree('var', [''.join([str(c) for c in args])])
def punctuation(self, args):
return Tree('punctuation', [''.join([str(c) for c in args])])
def list_access(self, args):
if type(args[1]) == Tree:
if "random" in args[1].data:
return Tree('list_access', [args[0], 'random'])
else:
return Tree('list_access', [args[0], args[1].children[0]])
else:
return Tree('list_access', [args[0], args[1]])
#level 5
def unsupported_number(self, args):
return Tree('unsupported_number', [''.join([str(c) for c in args])])
#level 11
def NUMBER(self, args):
return Tree('number', [str(args)])
# 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)
def input(self, tree):
var_name = tree.children[0].children[0]
self.add_to_lookup(var_name, tree)
def assign(self, tree):
var_name = tree.children[0].children[0]
self.add_to_lookup(var_name, tree.children[1])
def assign_list(self, tree):
var_name = tree.children[0].children[0]
self.add_to_lookup(var_name, tree)
# 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 = hash_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}[{tree.children[1]}-1]'
self.add_to_lookup(name, tree, True)
def list_access_var(self, tree):
self.add_to_lookup(tree.children[0].children[0], tree)
def change_list_item(self, tree):
self.add_to_lookup(tree.children[0].children[0], tree, True)
def repeat_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)
def for_loop(self, tree):
iterator = str(tree.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)
def add_to_lookup(self, name, tree, skip_hashing=False):
entry = LookupEntry(name, tree, skip_hashing)
hashed_name = hash_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):
super().__init__()
self.lookup = lookup
self.level = level
def print(self, tree):
self.validate_args_type_allowed(tree.children, Command.print)
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.any)
self.validate_args_type_allowed(tree.children[1:], Command.ask)
return self.to_typed_tree(tree, HedyType.any)
def input(self, tree):
self.validate_args_type_allowed(tree.children[1:], Command.ask)
return self.to_typed_tree(tree, HedyType.any)
def forward(self, tree):
if tree.children:
self.validate_args_type_allowed(tree.children, Command.forward)
return self.to_typed_tree(tree)
def turn(self, tree):
if tree.children:
name = tree.children[0].children[0]
if self.level > 1 or name not in command_turn_literals:
self.validate_args_type_allowed(tree.children, Command.turn)
return self.to_typed_tree(tree)
def assign(self, tree):
type_ = self.get_type(tree.children[1])
self.save_type_to_lookup(tree.children[0].children[0], type_)
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)
# TODO: list_access, list_access_var and repeat_list types can be inferred but for now use 'any'
def list_access(self, tree):
self.validate_args_type_allowed(tree.children[0], Command.list_access)
list_name = hash_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}[{tree.children[1]}-1]'
self.save_type_to_lookup(name, HedyType.any)
return self.to_typed_tree(tree, HedyType.any)
def list_access_var(self, tree):
self.save_type_to_lookup(tree.children[0].children[0], HedyType.any)
return self.to_typed_tree(tree)
def add(self, tree):
self.validate_args_type_allowed(tree.children[1], Command.add_to_list)
return self.to_typed_tree(tree)
def remove(self, tree):
self.validate_args_type_allowed(tree.children[1], Command.remove_from_list)
return self.to_typed_tree(tree)
def in_list_check(self, tree):
self.validate_args_type_allowed(tree.children[1], Command.in_list)
return self.to_typed_tree(tree, HedyType.boolean)
def equality_check(self, tree):
rules = [int_to_float, int_to_string, float_to_string] if self.level < 12 else [int_to_float]
self.validate_binary_command_args_type(Command.equality, tree, rules)
return self.to_typed_tree(tree, HedyType.boolean)
def repeat_list(self, tree):
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])
self.check_type_allowed(command, allowed_types, tree.children[2])
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 is_int(tree.children[0]) else HedyType.string
else:
type_ = HedyType.string
return self.to_typed_tree(tree, type_)
def punctuation(self, tree):
return self.to_typed_tree(tree, HedyType.string)
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(self, tree):
return self.to_typed_tree(tree, HedyType.none)
def number(self, tree):
number = tree.children[0]
if is_int(number):
return self.to_typed_tree(tree, HedyType.integer)
if 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):
prom_left_type, prom_right_type = self.validate_binary_command_args_type(command, tree, [int_to_float])
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):
self.validate_args_type_allowed(tree.children, Command.not_equal)
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])
self.check_type_allowed(command, allowed_types, tree.children[1])
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])
right_type = self.check_type_allowed(command, allowed_types, tree.children[1])
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)
return prom_left_type, prom_right_type
def validate_args_type_allowed(self, children, command):
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)
def check_type_allowed(self, command, allowed_types, tree):
arg_type = self.get_type(tree)
if arg_type not in allowed_types and not self.ignore_type(arg_type):
variable = tree.children[0]
raise exceptions.InvalidArgumentTypeException(command=command, invalid_type=arg_type,
invalid_argument=variable, allowed_types=allowed_types)
return arg_type
def get_type(self, tree):
# 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 == hash_var(name) and not entry.type_:
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 == hash_var(name)]
if matches:
# TODO: we should not just take the first match, take into account var reassignments
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)
else:
match.currently_inferring = True
try:
TypeValidator(self.lookup, self.level).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
# TODO: this could also use a default lark rule like AllAssignmentCommands does now
# TODO: maybe this could use meta (with v_args) instead of both inheritors?
class Filter(Transformer):
def __default__(self, args, children, meta):
return are_all_arguments_true(children)
def program(self, 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, args):
return True, ''.join([str(c) for c in args])
def random(self, args):
return True, 'random'
def punctuation(self, args):
return True, ''.join([c for c in args])
def number(self, args):
return True, ''.join([c for c in args])
def text(self, args):
return all(args), ''.join([c for c in args])
class UsesTurtle(Transformer):
# returns true if Forward or Turn are in the tree, false otherwise
def __default__(self, args, children, meta):
if len(children) == 0: # no children? you are a leaf that is not Turn or Forward, so you are no Turtle command
return False
else:
if all(type(c) == bool for c in children):
return any(children) # children? if any is true there is a Turtle leaf
else:
return False # some nodes like text and punctuation have text children (their letters) these are not turtles
def forward(self, args):
return True
def turn(self, args):
return True
# somehow tokens are not picked up by the default rule so they need their own rule
def INT(self, args):
return False
def NAME(self, args):
return False
def NUMBER(self, args):
return False
@v_args(meta=True)
class IsValid(Filter):
# all rules are valid except for the "Invalid" production rule
# this function is used to generate more informative error messages
# tree is transformed to a node of [Bool, args, command number]
def program(self, args, meta):
if len(args) == 0:
return False, InvalidInfo("empty program")
return super().program(args)
def invalid_space(self, args, meta):
# return space to indicate that line starts in a space
return False, InvalidInfo(" ", line=meta.line, column=meta.column)
def print_nq(self, args, meta):
# return error source to indicate what went wrong
return False, InvalidInfo("print without quotes", line=meta.line, column=meta.column)
def invalid(self, args, meta):
# TODO: this will not work for misspelling 'at', needs to be improved!
# TODO: add more information to the InvalidInfo
error = InvalidInfo('invalid command', args[0][1], [a[1] for a in args[1:]], meta.line, meta.column)
return False, error
def unsupported_number(self, args, meta):
error = InvalidInfo('unsupported number', arguments=[str(args[0])], line=meta.line, column=meta.column)
return False, error
#other rules are inherited from Filter
def valid_echo(ast):
commands = ast.children
command_names = [x.children[0].data for x in commands]
no_echo = not 'echo' in command_names
#no echo is always ok!
#otherwise, both have to be in the list and echo shold come after
return no_echo or ('echo' in command_names and 'ask' in command_names) and command_names.index('echo') > command_names.index('ask')
@v_args(meta=True)
class IsComplete(Filter):
def __init__(self, level):
self.level = level
# print, ask and echo can miss arguments and then are not complete
# used to generate more informative error messages
# tree is transformed to a node of [True] or [False, args, line_number]
def ask(self, args, meta):
# in level 1 ask without arguments means args == []
# in level 2 and up, ask without arguments is a list of 1, namely the var name
incomplete = (args == [] and self.level == 1) or (len(args) == 1 and self.level >= 2)
return not incomplete, ('ask', meta.line)
def print(self, args, meta):
return args != [], ('print', meta.line)
def input(self, args, meta):
return args != [], ('input', meta.line)
def length(self, args, meta):
return args != [], ('len', meta.line)
def print_nq(self, args, meta):
return args != [], ('print level 2', meta.line)
def echo(self, args, meta):
#echo may miss an argument
return True, ('echo', meta.line)
#other rules are inherited from Filter
def process_characters_needing_escape(value):
# defines what happens if a kids uses ' or \ in in a string
for c in characters_that_need_escaping:
value = value.replace(c, f'\\{c}')
return value
def get_allowed_types(command, level):
# get only the allowed types of the command for all levels before the requested level
allowed = [values for key, values in commands_and_types_per_level[command].items() if key <= level]
# use the allowed types of the highest level available
return allowed[-1] if allowed else []
# decorator used to store each class in the lookup table
def hedy_transpiler(level):
def decorator(c):
TRANSPILER_LOOKUP[level] = c
c.level = level
return c
return decorator
@hedy_transpiler(level=1)
class ConvertToPython_1(Transformer):
def __init__(self, punctuation_symbols, lookup):
self.punctuation_symbols = punctuation_symbols
self.lookup = lookup
__class__.level = 1
def get_fresh_var(self, name):
while is_variable(name, self.lookup):
name = '_' + name
return name
def program(self, args):
return '\n'.join([str(c) for c in args])
def command(self, args):
return args[0]
def text(self, args):
return ''.join([str(c) for c in args])
def integer(self, args):
return str(args[0])
def number(self, args):
return str(args[0])
def print(self, args):
# escape needed characters
argument = process_characters_needing_escape(args[0])
return "print('" + argument + "')"
def ask(self, args):
argument = process_characters_needing_escape(args[0])
return "answer = input('" + argument + "')"
def echo(self, args):
if len(args) == 0:
return "print(answer)" #no arguments, just print answer
argument = process_characters_needing_escape(args[0])
return "print('" + argument + " '+answer)"
def comment(self, args):
return f"#{''.join(args)}"
def forward(self, args):
if len(args) == 0:
return self.make_forward(50)
parameter = int(args[0])
return self.make_forward(parameter)
def make_forward(self, parameter):
return f"t.forward({parameter})""\ntime.sleep(0.1)"
def turn(self, args):
if len(args) == 0:
return "t.right(90)" # no arguments defaults to a right turn
arg = args[0]
if is_variable(arg, self.lookup) or arg.isnumeric():
return f"t.right({arg})"
elif arg == 'left':
return "t.left(90)"
elif arg == 'right':
return "t.right(90)"
else:
# the TypeValidator should protect against reaching this line:
raise exceptions.InvalidArgumentTypeException(command=Command.turn, invalid_type='', invalid_argument=arg,
allowed_types=get_allowed_types(Command.turn, self.level))
# todo: could be moved into the transpiler class
def is_variable(name, lookup):
all_names = [a.name for a in lookup]
return hash_var(name) in all_names
def process_variable(arg, lookup):
#processes a variable by hashing and escaping when needed
if is_variable(arg, lookup):
return hash_var(arg)
elif is_quoted(arg): #sometimes kids accidentally quote strings, then we do not want them quoted again
return f"{arg}"
else:
return f"'{arg}'"
def process_variable_for_fstring(name, lookup):
if is_variable(name, lookup):
return "{" + hash_var(name) + "}"
else:
return name
def process_variable_for_fstring_padded(name, lookup):
# used to transform variables in comparisons
if is_variable(name, lookup):
return f"str({hash_var(name)}).zfill(100)"
elif is_float(name):
return f"str({name}).zfill(100)"
else:
return f"'{name}'.zfill(100)"
@hedy_transpiler(level=2)
class ConvertToPython_2(ConvertToPython_1):
def ask_dep_2(self, args):
# ask is no longer usable this way, raise!
# ask_needs_var is an entry in lang.yaml in texts where we can add extra info on this error
raise hedy.exceptions.WrongLevelException(1, 'ask', "ask_needs_var")
def echo_dep_2(self, args):
# echo is no longer usable this way, raise!
# ask_needs_var is an entry in lang.yaml in texts where we can add extra info on this error
raise hedy.exceptions.WrongLevelException(1, 'echo', "echo_out")
def check_var_usage(self, args):
# this function checks whether arguments are valid
# we can proceed if all arguments are either quoted OR all variables
args_to_process = [a for a in args if not isinstance(a, Tree)]#we do not check trees (calcs) they are always ok
unquoted_args = [a for a in args_to_process if not is_quoted(a)]
unquoted_in_lookup = [is_variable(a, self.lookup) for a in unquoted_args]
if unquoted_in_lookup == [] or all(unquoted_in_lookup):
# all good? return for further processing
return args
else:
# return first name with issue
# note this is where issue #832 can be addressed by checking whether
# first_unquoted_var ius similar to something in the lookup list
first_unquoted_var = unquoted_args[0]
raise exceptions.UndefinedVarException(name=first_unquoted_var)
def punctuation(self, args):
return ''.join([str(c) for c in args])
def var(self, args):
name = args[0]
return hash_var(name)
def var_access(self, args):
name = args[0]
return hash_var(name)
def print(self, args):
argument_string = ""
i = 0
for argument in args:
# escape quotes if kids accidentally use them at level 2
argument = process_characters_needing_escape(argument)
# final argument and punctuation arguments do not have to be separated with a space, other do
if i == len(args)-1 or args[i+1] in self.punctuation_symbols:
space = ''
else:
space = " "
argument_string += process_variable_for_fstring(argument, self.lookup) + space
i = i + 1
return f"print(f'{argument_string}')"
def ask(self, args):
var = args[0]
all_parameters = ["'" + process_characters_needing_escape(a) + "'" for a in args[1:]]
return f'{var} = input(' + '+'.join(all_parameters) + ")"
def forward(self, args):
if len(args) == 0:
return self.make_forward(50)
if is_int(args[0]):
parameter = int(args[0])
else:
# if not an int, then it is a variable
parameter = args[0]
return self.make_forward(parameter)
def turn(self, args):
if len(args) == 0:
return "t.right(90)"
arg = args[0]
if is_variable(arg, self.lookup) or arg.isnumeric():
return f"t.right({arg})"
# the TypeValidator should protect against reaching this line:
raise exceptions.InvalidArgumentTypeException(command=Command.turn, invalid_type='', invalid_argument=arg,
allowed_types=get_allowed_types(Command.turn, self.level))
def assign(self, args):
parameter = args[0]
value = args[1]
#if the assigned value contains single quotes, escape them
value = process_characters_needing_escape(value)
return parameter + " = '" + value + "'"
def sleep(self, args):
if args == []:
return "time.sleep(1)"
else:
return f"time.sleep({args[0]})"
def is_quoted(s):
return s[0] == "'" and s[-1] == "'"
def make_f_string(args, lookup):
argument_string = ''
for argument in args:
if is_variable(argument, lookup):
# variables are placed in {} in the f string