forked from hedyorg/hedy
-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathhedy.py
1646 lines (1355 loc) · 61.8 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
from lark import Tree, Transformer, visitors
from os import path
import hedy
import utils
from collections import namedtuple
import hashlib
import re
from dataclasses import dataclass, field
# Some useful constants
HEDY_MAX_LEVEL = 23
MAX_LINES = 100
#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']
# type used in lookup table
Assignment = namedtuple('Assignment', ['name', 'type'])
# 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']
}
# Commands and their types per level (only partially filled!)
commands_and_types_per_level = {
1: {'print': ['string'],
'ask': ['string'],
'turn': ['string'],
'forward': ['string']},
2: {'at random': ['list']},
12: {'input': ['string']},
13: {'print': ['string', 'list']}
}
# 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 Assignment and name.type == 'operation') 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):
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 style_closest_command(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
class HedyException(Exception):
def __init__(self, message, **arguments):
self.error_code = message
self.arguments = arguments
class InvalidSpaceException(HedyException):
def __init__(self, level, line_number, fixed_code, has_turtle):
super().__init__('Invalid Space')
self.level = level
self.line_number = line_number
self.fixed_code = fixed_code
self.has_turtle = has_turtle
class ParseException(HedyException):
def __init__(self, level, location, keyword_found=None, character_found=None):
super().__init__('Parse')
self.level = level
self.location = location
self.keyword_found = keyword_found
self.character_found = character_found
class UndefinedVarException(HedyException):
def __init__(self, **arguments):
super().__init__('Var Undefined', **arguments)
class RequiredArgumentTypeException(HedyException):
def __init__(self, **arguments):
super().__init__('Required Argument Type', **arguments)
class InvalidArgumentTypeException(HedyException):
def __init__(self, **arguments):
super().__init__('Invalid Argument Type', **arguments)
class WrongLevelException(HedyException):
def __init__(self, **arguments):
super().__init__('Wrong Level', **arguments)
class InputTooBigException(HedyException):
def __init__(self, **arguments):
super().__init__('Too Big', **arguments)
class InvalidCommandException(HedyException):
def __init__(self, **arguments):
super().__init__('Invalid', **arguments)
class IncompleteCommandException(HedyException):
def __init__(self, **arguments):
super().__init__('Incomplete', **arguments)
class UnquotedTextException(HedyException):
def __init__(self, **arguments):
super().__init__('Unquoted Text', **arguments)
class EmptyProgramException(HedyException):
def __init__(self):
super().__init__('Empty Program')
class LonelyEchoException(HedyException):
def __init__(self):
super().__init__('Lonely Echo')
class CodePlaceholdersPresentException(HedyException):
def __init__(self):
super().__init__('Has Blanks')
class IndentationException(HedyException):
def __init__(self, **arguments):
super().__init__('Unexpected Indentation', **arguments)
class UnsupportedFloatException(HedyException):
def __init__(self, **arguments):
super().__init__('Unsupported Float', **arguments)
class LockedLanguageFeatureException(HedyException):
def __init__(self, **arguments):
super().__init__('Locked Language Feature', **arguments)
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])])
#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 index(self, args):
return ''.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])])
def number(self, args):
return Tree('number', ''.join([str(c) for c in args]))
class AllAssignmentCommands(Transformer):
# returns a list of variable and list access
# so these can be excluded when printing
# relevant nodes (list acces, ask, assign) are transformed into tuples of their name and type
# higher in the tree (through default rule), we filter on only string arguments, of lists with string arguments
def filter_ask_assign(self, args):
ask_assign = []
for a in args:
# strings (vars remaining in the tree) are added directly
if type(a) is Assignment:
ask_assign.append(a)
# lists are searched further for string members (vars)
elif type(a) is list:
sub_a_ask_assign = self.filter_ask_assign(a)
for sub_a in sub_a_ask_assign:
ask_assign.append(sub_a)
return ask_assign
# level 8
def repeat_list(self, args):
# for loop iterator is a var so should be added to the list of vars
iterator = str(args[0])
commands = args[1:]
# in level 8 always a string
return [Assignment(iterator, 'string')] + self.filter_ask_assign(commands)
# level 9
def for_loop(self, args):
# for loop iterator is a var so should be added to the list of vars
iterator = str(args[0])
commands = args[1:]
# for loop iterators can be numbers (for i in range... or strings (for dier in dieren)
return [Assignment(iterator, 'any')] + self.filter_ask_assign(commands)
def input(self, args):
# return left side of the =
return args[0]
def ask(self, args):
# try is needed cause in level 1 ask has no variable in front
try:
return Assignment(args[0], 'string')
except:
return None
def assign(self, args):
# todo now all assigns are strings, later (form 5) this should distinguish int and str
return Assignment(args[0], 'string')
def assign_list(self, args):
return Assignment(args[0], 'list')
# list access is accessing a variable, so must be escaped
# for example we print(dieren[1]) not print('dieren[1]')
def list_access(self, args):
listname = args[0]
if args[1] == 'random':
return Assignment('random.choice(' + listname + ')', 'operation')
else:
return Assignment(listname + '[' + args[1] + ']', 'operation')
# additions Laura, to be checked for higher levels:
def list_access_var(self, args):
return Assignment(args[0], 'operation')
def change_list_item(self, args):
return Assignment(args[0], 'operation')
def text(self, args):
# text never contains a variable
return None
def var_access(self, args):
# just accessing (printing) a variable does not count toward the lookup table
return None
def var(self, args):
# the var itself (when in an assignment) should be added
name = args[0]
return name
def punctuation(self, args):
# is never a variable (but should be removed from the tree or it will be seen as one!)
return None
def __default__(self, args, children, meta):
return self.filter_ask_assign(children)
class AllAssignmentCommandsHashed(Transformer):
# returns a list of variable and list access
# so these can be excluded when printing
Assignment = namedtuple('Assignment', ['name', 'type'])
# this version returns all hashed var names
def filter_ask_assign(self, args):
ask_assign = []
for a in args:
# strings (vars remaining in the tree) are added directly
if type(a) is Assignment:
ask_assign.append(a)
# lists are searched further for string members (vars)
elif type(a) is list:
sub_a_ask_assign = self.filter_ask_assign(a)
for sub_a in sub_a_ask_assign:
ask_assign.append(sub_a)
return ask_assign
# level 8
def repeat_list(self, args):
# for loop iterator is a var so should be added to the list of vars
iterator = str(args[0])
commands = args[1:]
# in level 8 always a string
return [Assignment(iterator, 'string')] + self.filter_ask_assign(commands)
# level 9
def for_loop(self, args):
# for loop iterator is a var so should be added to the list of vars
iterator = str(args[0])
commands = args[1:]
# for loop iterators can be numbers (for i in range... or strings (for dier in dieren)
return [Assignment(iterator, 'any')] + self.filter_ask_assign(commands)
def input(self, args):
# return left side of the =
return Assignment(hash_var(args[0]), 'string')
def ask(self, args):
# try is needed cause in level 1 ask has no variable in front
try:
return Assignment(hash_var(args[0]), 'string')
except:
return None
def assign(self, args):
return Assignment(hash_var(args[0]), 'string')
def assign_list(self, args):
return Assignment(hash_var(args[0]), 'list')
# list access is accessing a variable, so must be escaped
# for example we print(dieren[1]) not print('dieren[1]')
def list_access(self, args):
listname = hash_var(args[0])
if args[1] == 'random':
return Assignment('random.choice(' + listname + ')', 'operation')
else:
return Assignment(listname + '[' + args[1] + ']', 'operation')
# additions Laura, to be checked for higher levels:
def list_access_var(self, args):
return Assignment(hash_var(args[0]), 'operation')
def change_list_item(self, args):
return Assignment(hash_var(args[0]), 'operation')
def text(self, args):
# text never contains a variable
return None
def var_access(self, args):
# just accessing (printing) a variable does not count toward the lookup table
return None
def var(self, args):
# the var itself (when in an assignment) should be added
name = hash_var(args[0])
return name
def punctuation(self, args):
# is never a variable (but should be removed from the tree or it will be seen as one!)
return None
def __default__(self, args, children, meta):
return self.filter_ask_assign(children)
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
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:
command_num = 1
for a in args:
if not a[0]:
return False, a[1], command_num
command_num += 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 index(self, args):
return True, ''.join([str(c) for c in args])
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 type(children[0]) == bool:
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 a token (or only this token?) is not picked up by the default rule so it needs
# its own rule
def NUMBER(self, args):
return False
def NAME(self, args):
return False
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):
if len(args) == 0:
return False, InvalidInfo("empty program"), 1
return super().program(args)
def invalid_space(self, args):
# return space to indicate that line starts in a space
return False, InvalidInfo(" ")
def print_nq(self, args):
# return error source to indicate what went wrong
return False, InvalidInfo("print without quotes")
def invalid(self, args):
# 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:]])
return False, error
def unsupported_number(self, args):
error = InvalidInfo('unsupported number', arguments=[str(args[0])])
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')
class IsComplete(Filter):
def __init__(self, level):
self.level = level
# print, ask an 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):
# 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'
def print(self, args):
return args != [], 'print'
def input(self, args):
return args != [], 'input'
def length(self, args):
return args != [], 'len'
def print_nq(self, args):
return args != [], 'print level 2'
def echo(self, args):
#echo may miss an argument
return True, 'echo'
#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
# 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 print(self, args):
# escape needed characters
argument = process_characters_needing_escape(args[0])
return "print('" + 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 ask(self, args):
argument = process_characters_needing_escape(args[0])
return "answer = input('" + argument + "')"
def forward(self,args):
if len(args) == 0:
return self.make_forward(50)
try:
parameter = int(args[0])
except:
raise InvalidArgumentTypeException(command='forward', invalid_type='',
allowed_types=['number'],
invalid_argument=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 works, and means a right turn
argument = args[0]
if is_variable(argument, self.lookup): #is the argument a variable? if so, use that
return f"t.right({argument})"
elif argument.isnumeric(): #numbers can also be passed through
return f"t.right({argument})"
elif argument == 'left':
return "t.left(90)"
elif argument == 'right':
return "t.right(90)"
else:
raise InvalidArgumentTypeException(command='turn', invalid_type='',
allowed_types=['right', 'left', 'number'],
invalid_argument=argument)
def check_arg_types(self, args, command, level):
allowed_types = self.get_allowed_types(command, level)
for arg in args:
assignment = self.find_in_lookup(arg)
if assignment:
if assignment.type != 'operation' and assignment.type not in allowed_types:
# we first try to raise if we expect 1 thing exactly for more precise error messages
if len(allowed_types) == 1:
if allowed_types[0] == 'list':
raise hedy.RequiredArgumentTypeException(command=command, variable=assignment.name,
required_type=allowed_types[0])
# here of course we will have a long elif for different types, or maybe we have 1 required exception with a parameter?
if assignment.type == 'list':
raise hedy.InvalidArgumentTypeException(command=command, invalid_type=assignment.type,
invalid_argument='', allowed_types=allowed_types)
# same elif here for different types
def get_allowed_types(self, command, level):
# get only the allowed types of the command for all levels before the requested level
allowed = [values[command] for key, values in commands_and_types_per_level.items()
if command in values and key <= level]
# use the allowed types of the highest level available
return allowed[-1] if allowed else []
def find_in_lookup(self, variable):
lookup_vars = [a for a in self.lookup if a.name == variable]
# this now grabs the last occurrence, once we have slicing we want to be more precise!
return lookup_vars[-1] if lookup_vars else None
# todo: could be moved into the transpiler class
def is_variable(name, lookup):
all_names = [a.name for a in lookup]
return name in all_names
def process_variable(name, lookup):
#processes a variable by hashing and escaping when needed
if is_variable(name, lookup):
return hash_var(name)
else:
return f"'{name}'"
def process_variable_for_fstring(name, lookup):
if is_variable(name, lookup):
return "{" + hash_var(name) + "}"
else:
return name
@hedy_transpiler(level=2)
class ConvertToPython_2(ConvertToPython_1):
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
unquoted_args = [a for a in args 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 UndefinedVarException(name=first_unquoted_var)
def punctuation(self, args):
return ''.join([str(c) for c in args])
def var(self, args):
name = ''.join(args)
name = args[0]
return hash_var(name)
# return "_" + name if name in reserved_words else name
def print(self, args):
# grab the allowed arguments from the dictionary
self.check_arg_types(args, 'print', self.level)
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 forward(self, args):
if len(args) == 0:
return self.make_forward(50)
# if the parameter is a number, use it as is
# otherwise, see if we got a defined variable. if not, give an error
try:
parameter = int(args[0])
except:
if is_variable(args[0], self.lookup):
parameter = args[0]
else:
raise InvalidArgumentTypeException(command='forward', invalid_type='',
allowed_types=['number'],
invalid_argument=args[0])
return self.make_forward(parameter)
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 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 assign_list(self, args):
parameter = args[0]
values = ["'" + a + "'" for a in args[1:]]
return parameter + " = [" + ", ".join(values) + "]"
def list_access(self, args):
# check the arguments (except when they are random or numbers, that is not quoted nor a var but is allowed)
self.check_var_usage(a for a in args if a != 'random' and not a.isnumeric())
self.check_arg_types(args, 'at random', self.level)
if args[1] == 'random':
return 'random.choice(' + args[0] + ')'
else:
return args[0] + '[' + args[1] + ']'
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
argument_string += "{" + hash_var(argument) + "}"
else:
# strings are written regularly
# however we no longer need the enclosing quotes in the f-string
# the quotes are only left on the argument to check if they are there.
argument_string += argument.replace("'", '')
return f"print(f'{argument_string}')"
#TODO: punctuation chars not be needed for level2 and up anymore, could be removed
@hedy_transpiler(level=3)
class ConvertToPython_3(ConvertToPython_2):
def var_access(self, args):
name = args[0]
return hash_var(name)
def text(self, args):
return ''.join([str(c) for c in args])
def check_print_arguments(self, args):
# this function checks whether arguments of a print are valid
# we can print if all arguments are either quoted OR they are all variables
unquoted_args = [a for a in args 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 UndefinedVarException(name=first_unquoted_var)
def print(self, args):
args = self.check_print_arguments(args)
self.check_arg_types(args, 'print', self.level)
argument_string = ''
for argument in args:
argument = argument.replace("'", '') #no quotes needed in fstring
argument_string += process_variable_for_fstring(argument, self.lookup)
return f"print(f'{argument_string}')"
def print_nq(self, args):
return ConvertToPython_2.print(self, args)
def ask(self, args):
args_new = []
var = args[0]
remaining_args = args[1:]
self.check_arg_types(remaining_args, 'ask', self.level)
return f'{var} = input(' + '+'.join(remaining_args) + ")"
def indent(s):
lines = s.split('\n')
return '\n'.join([' ' + l for l in lines])
@hedy_transpiler(level=4)
class ConvertToPython_4(ConvertToPython_3):
def list_access_var(self, args):
var = hash_var(args[0])
if args[2].data == 'random':
return var + '=random.choice(' + args[1] + ')'
else:
return var + '=' + args[1] + '[' + args[2].children[0] + ']'
def ifs(self, args):
return f"""if {args[0]}:
{indent(args[1])}"""
def ifelse(self, args):
return f"""if {args[0]}:
{indent(args[1])}
else:
{indent(args[2])}"""
def condition(self, args):
return ' and '.join(args)
def equality_check(self, args):
arg0 = process_variable(args[0], self.lookup)
arg1 = process_variable(args[1], self.lookup)
return f"{arg0} == {arg1}" #no and statements
def in_list_check(self, args):
arg0 = process_variable(args[0], self.lookup)
arg1 = process_variable(args[1], self.lookup)
return f"{arg0} in {arg1}"
@hedy_transpiler(level=5)
class ConvertToPython_5(ConvertToPython_4):
def print(self, args):
# we only check non-Tree (= non calculation) arguments
self.check_var_usage([a for a in args if not type(a) is Tree])
self.check_arg_types(args, 'print', self.level)
#force all to be printed as strings (since there can not be int arguments)
args_new = []
for a in args:
if type(a) is Tree:
args_new.append("{" + a.children + "}")
else:
a = a.replace("'", "") #no quotes needed in fstring
args_new.append(process_variable_for_fstring(a, self.lookup))
arguments = ''.join(args_new)
return "print(f'" + arguments + "')"
#we can now have ints as types so chck must force str
def equality_check(self, args):
arg0 = process_variable(args[0], self.lookup)
arg1 = process_variable(args[1], self.lookup)
#TODO if we start using fstrings here, this str can go
if len(args) == 2:
return f"str({arg0}) == str({arg1})" #no and statements
else:
return f"str({arg0}) == str({arg1}) and {args[2]}"
def assign(self, args):
if len(args) == 2:
parameter = args[0]
value = args[1]
if type(value) is Tree:
return parameter + " = " + value.children
else:
return parameter + " = '" + value + "'"
else:
parameter = args[0]
values = args[1:]
return parameter + " = [" + ", ".join(values) + "]"
def process_token_or_tree(self, argument):
if type(argument) is Tree:
return f'{str(argument.children)}'
else:
return f'int({argument})'
def process_calculation(self, args, operator):
# arguments of a sum are either a token or a
# tree resulting from earlier processing
# for trees we need to grap the inner string
# for tokens we add int around them
args = [self.process_token_or_tree(a) for a in args]
return Tree('sum', f'{args[0]} {operator} {args[1]}')
def addition(self, args):
return self.process_calculation(args, '+')
def substraction(self, args):
return self.process_calculation(args, '-')
def multiplication(self, args):
return self.process_calculation(args, '*')
def division(self, args):
return self.process_calculation(args, '//')
@hedy_transpiler(level=6)
class ConvertToPython_6(ConvertToPython_5):
def number(self, args):
return ''.join(args)
def repeat(self, args):
var_name = self.get_fresh_var('i')
times = process_variable(args[0], self.lookup)
command = args[1]
return f"""for {var_name} in range(int({str(times)})):
{indent(command)}"""