forked from hedyorg/hedy
-
Notifications
You must be signed in to change notification settings - Fork 0
/
hedy.py
4066 lines (3286 loc) · 164 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
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 hedy
import hedy_error
import hedy_grammar
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
from prefixes.music import present_in_notes_mapping
from prefixes.normal import get_num_sys
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 = {}
MICROBIT_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']
LIBRARIES = ['time']
# Python keywords and function names need hashing when used as var names
reserved_words = set(PYTHON_BUILTIN_FUNCTIONS + PYTHON_KEYWORDS + LIBRARIES)
# 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))
def make_value_error(command, tip, lang, value='{}'):
return make_error_text(exceptions.RuntimeValueException(command=command, value=value, tip=tip), lang)
def make_values_error(command, tip, lang):
return make_error_text(exceptions.RuntimeValuesException(command=command, value='{}', tip=tip), lang)
def make_error_text(ex, lang):
# The error text is transpiled in f-strings with ", ' and ''' quotes. The only option is to use """.
return f'"""{hedy_error.get_error_text(ex, lang)}"""'
def translate_suggestion(suggestion_type):
# Right now we only have three types of suggestion
# In the future we might change this if the number increases
if suggestion_type == 'number':
return gettext('suggestion_number')
elif suggestion_type == 'color':
return gettext('suggestion_color')
elif suggestion_type == 'note':
return gettext('suggestion_note')
elif suggestion_type == 'numbers_or_strings':
return gettext('suggestion_numbers_or_strings')
return ''
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'
not_in_list = 'not in list'
equality = 'is (equality)'
repeat = 'repeat'
for_list = 'for in'
for_loop = 'for in range'
if_ = 'if'
else_ = 'else'
elif_ = 'elif'
addition = '+'
subtraction = '-'
multiplication = '*'
division = '/'
smaller = '<'
smaller_equal = '<='
bigger = '>'
bigger_equal = '>='
not_equal = '!='
pressed = 'pressed'
clear = 'clear'
define = 'define'
call = 'call'
returns = 'return'
play = 'play'
while_ = 'while'
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.not_in_list: ['not 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_boolean = (HedyType.input, HedyType.boolean)
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
def add_level(commands, level, add=None, remove=None):
# Adds the commands for the given level by taking the commands of the previous level
# and adjusting the list based on which keywords need to be added or/and removed
if not add:
add = []
if not remove:
remove = []
commands[level] = [c for c in commands[level - 1] if c not in remove] + add
# Commands per Hedy level which are used to suggest the closest command when kids make a mistake
commands_per_level = {1: ['ask', 'color', 'echo', 'forward', 'play', 'print', 'turn']}
add_level(commands_per_level, level=2, add=['is', 'sleep'], remove=['echo'])
add_level(commands_per_level, level=3, add=['add', 'at', 'from', 'random', 'remove', 'to'])
add_level(commands_per_level, level=4, add=['clear'])
add_level(commands_per_level, level=5, add=['else', 'if', 'if_pressed', 'in', 'not_in'])
add_level(commands_per_level, level=6)
add_level(commands_per_level, level=7, add=['repeat', 'times'])
add_level(commands_per_level, level=8)
add_level(commands_per_level, level=9)
add_level(commands_per_level, level=10, add=['for'])
add_level(commands_per_level, level=11, add=['range'], remove=['times'])
add_level(commands_per_level, level=12, add=['define', 'call'])
add_level(commands_per_level, level=13, add=['and', 'or'])
add_level(commands_per_level, level=14)
add_level(commands_per_level, level=15, add=['while'])
add_level(commands_per_level, level=16)
add_level(commands_per_level, level=17, add=['elif'])
add_level(commands_per_level, level=18, add=['input'], remove=['ask'])
command_turn_literals = ['right', 'left']
english_colors = ['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 english_colors]
return colors_local
def command_make_color_local(language):
if language == "en":
return english_colors
else:
return english_colors + 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, HedyType.list],
4: [HedyType.string, HedyType.integer, HedyType.input],
12: [HedyType.string, HedyType.integer, HedyType.input, HedyType.float],
15: [HedyType.string, HedyType.integer, HedyType.input, HedyType.float, HedyType.boolean],
16: [HedyType.string, HedyType.integer, HedyType.input, HedyType.float, HedyType.boolean, HedyType.list]
},
Command.ask: {
1: [HedyType.string, HedyType.integer, HedyType.input, HedyType.list],
4: [HedyType.string, HedyType.integer, HedyType.input],
12: [HedyType.string, HedyType.integer, HedyType.input, HedyType.float],
15: [HedyType.string, HedyType.integer, HedyType.input, HedyType.float, HedyType.boolean],
16: [HedyType.string, HedyType.integer, HedyType.input, HedyType.float, HedyType.boolean, HedyType.list]
},
Command.turn: {
1: command_turn_literals,
2: [HedyType.integer, HedyType.input],
12: [HedyType.integer, HedyType.input, HedyType.float]
},
Command.color: {
1: [english_colors, HedyType.list],
2: [english_colors, HedyType.string, HedyType.input, HedyType.list]},
Command.forward: {
1: [HedyType.integer, HedyType.input],
12: [HedyType.integer, HedyType.input, HedyType.float]
},
Command.sleep: {
1: [HedyType.integer, HedyType.input],
12: [HedyType.integer, HedyType.input, HedyType.float]
},
Command.list_access: {1: [HedyType.list]},
Command.in_list: {1: [HedyType.list]},
Command.not_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],
15: [HedyType.string, HedyType.integer, HedyType.input, HedyType.float, HedyType.list, HedyType.boolean]
},
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, HedyType.boolean]
},
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 == 'if_pressed': # TODO: this is a bit of a hack
command = 'pressed' # since in the yamls they are called pressed
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
if isinstance(var, LookupEntry):
var_name = var.name
return "_" + var_name if var_name in reserved_words else var_name
def style_command(command):
return f'<span class="command-highlighted">{command}</span>'
def closest_command(input_, known_commands, threshold=2):
# Find the closest command to the input, i.e. the one with the smallest distance within the threshold. Returns:
# (None, _) No suggestion. There is no command similar enough to the input. For example, the distance
# between 'eechoooo' and 'echo' is higher than the specified threshold.
# (False, _) Invalid suggestion. The suggested command is identical to the input, so it is not a suggestion.
# This is to prevent "print is not a command in Hedy level 3, did you mean print?" error message.
# (True, 'sug') Valid suggestion. A command is similar enough to the input but not identical, e.g. 'aks' -> 'ask'
# FH, early 2020: simple string distance, could be more sophisticated MACHINE LEARNING!
minimum_distance = 1000
result = None
for command in known_commands:
minimum_distance_for_command = calculate_minimum_distance(command, input_)
if minimum_distance_for_command < minimum_distance and minimum_distance_for_command <= threshold:
minimum_distance = minimum_distance_for_command
result = command
if result:
if result != input_:
return True, result # Valid suggestion
return False, '' # Invalid suggestion
return None, '' # No suggestion
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
definition_line: int
access_line: 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 NAME(self, args):
return ''.join([str(c) for c in args])
def NOT_LETTER_OR_NUMERAL(self, args):
return ''.join([str(c) for c in args])
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)])
def TRUE(self, args):
return Tree('true', [str(args)])
def FALSE(self, args):
return Tree('false', [str(args)])
def boolean(self, meta, args):
return args[0]
# level 2
def var(self, meta, args):
return Tree('var', [''.join([str(c) for c in args])], meta)
def list_access(self, meta, args):
if isinstance(args[1], Tree) and "random" in args[1].data:
return Tree('list_access', [args[0], 'random'], meta)
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 var_access(self, tree):
# variable_name = tree.children[0].children[0]
# # store the line of access (or string value) in the lookup table
# # so we know what variable is used where
# vars = [a for a in self.lookup if a.name == variable_name]
# if vars:
# corresponding_lookup_entry = vars[0]
# corresponding_lookup_entry.access_line = 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])
index = tree.children[1].children[0] if isinstance(tree.children[1], Tree) else tree.children[1]
try:
index = str(int(index)) # needed to convert non-latin numbers
name = f'{list_name}.data[int({index})-1]'
name_old = f'{list_name}[int({index})-1]'
except ValueError:
if index == 'random':
name = f'random.choice({list_name}.data)'
name_old = f'random.choice({list_name})'
else:
name = f'{list_name}.data[int({escape_var(index)}.data)-1]'
name_old = f'{list_name}[int({escape_var(index)})-1]'
if self.level > 5:
self.add_to_lookup(name, tree, tree.meta.line, True)
else:
self.add_to_lookup(name_old, 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):
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]
names = [x.name for x in self.lookup]
if function_name + "()" not in names:
raise exceptions.UndefinedFunctionException(function_name, tree.meta.line)
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, definition_line=None, access_line=None, skip_hashing=False):
entry = LookupEntry(name, tree, definition_line, access_line, 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}.data)'
else:
# We want list access to be 1-based instead of 0-based, hence the -1
name = f'{list_name}.data[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 not_in_list_check(self, tree):
self.validate_args_type_allowed(Command.not_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, input_to_boolean]
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):
t = tree.children[0] if tree.children else tree
return self.to_typed_tree(t, 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 true(self, tree):
return self.to_typed_tree(tree, HedyType.boolean)
def false(self, tree):
return self.to_typed_tree(tree, HedyType.boolean)
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, input_to_string]
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.
# var_access_print is identical to var_access and is introduced only to differentiate error messages.
# So, if it cannot be found in the lookup table, then it is an undefined variable for sure.
if tree.data in ['var_access', '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:
self.get_var_access_error(tree, var_name)
# 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 get_var_access_error(self, tree, var_name):
# var_access_print is a var_access used in print statements to provide the following better error messages
if tree.data == 'var_access_print':
# is there a variable that is mildly similar? if so, we probably meant that one
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)
# no variable which looks similar? Then, fall back to UnquotedTextException
raise hedy.exceptions.UnquotedTextException(
level=self.level, unquotedtext=var_name, line_number=tree.meta.line)
# for all other var_access instances, use UndefinedVarException
raise hedy.exceptions.UndefinedVarException(name=var_name, line_number=tree.meta.line)
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