forked from hedyorg/hedy
-
Notifications
You must be signed in to change notification settings - Fork 0
/
hedy.py
968 lines (813 loc) · 34 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
from lark import Lark
from lark.exceptions import VisitError, LarkError, UnexpectedEOF
from lark import Tree, Transformer, Visitor
from os import path
import sys
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']
#
# Commands per Hedy level which are used to suggest the closest command when kids make a mistake
#
commands_per_level = {1: ['print', 'ask', 'echo'] ,
2: ['print', 'ask', 'echo', 'is'],
3: ['print', 'ask', 'is'],
4: ['print', 'ask', 'is', 'if'],
5: ['print', 'ask', 'is', 'if', 'repeat'],
6: ['print', 'ask', 'is', 'if', 'repeat'],
7: ['print', 'ask', 'is', 'if', 'repeat'],
8: ['print', 'ask', 'is', 'if', 'for'],
9: ['print', 'ask', 'is', 'if', 'for', 'elif'],
10: ['print', 'ask', 'is', 'if', 'for', 'elif'],
11: ['print', 'ask', 'is', 'if', 'for', 'elif'],
12: ['print', 'ask', 'is', 'if', 'for', 'elif'],
13: ['print', 'ask', 'is', 'if', 'for', 'elif']
}
#
# 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.
#
def closest_command(invalid_command, known_commands):
# First search for 100% match of known commands
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 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):
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]
class HedyException(Exception):
def __init__(self, message, **arguments):
self.error_code = message
self.arguments = 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:
return Tree('list_access', [args[0], 'random'])
else:
return Tree('list_access', [args[0], args[1]])
#level 5
def number(self, args):
return Tree('number', ''.join([str(c) for c in args]))
def flatten(args):
flattened_args = []
if isinstance(args, str):
return args
elif isinstance(args, Tree):
return args
else:
for a in args:
if type(a) is list:
for x in a:
flattened_args.append(flatten(x))
else:
flattened_args.append(a)
return flattened_args
class AllAssignmentCommands(Transformer):
# returns only variable assignments AND places where variables are accessed
# so these can be excluded when printing
def program(self, args):
return flatten(args)
def repeat(self, args):
commands = args[1:]
return flatten(commands)
def command(self, args):
return flatten(args)
def for_loop(self, args):
commands = args[1:]
return flatten(commands)
def ask(self, args):
#todo: this also uses this arg for level 1, where it should not be used
#(since then it has no var as 1st argument)
#we should actually loop the level in here to distinguish on
return args[0].children
def assign(self, args):
return args[0].children
def assign_list(self, args):
return args[0].children
def list_access_var(self, args):
return args[0].children
def var_access(self,args):
return args[0].children
def change_list_item(self, args):
return args[0].children
#list access is accessing a variable, so must be escaped
def list_access(self, args):
listname = args[0].children[0]
if args[1] == 'random':
return 'random.choice(' + listname + ')'
else:
return listname + '[' + args[1] + ']'
def print(self, args):
return args
def input(self,args):
return args[0].children
def create_parser(level):
with open(f"grammars/level{str(level)}.lark", "r", encoding="utf-8") as file:
grammar = file.read()
return Lark(grammar)
def all_arguments_true(args):
bool_arguments = [x[0] for x in args]
arguments_of_false_nodes = [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
class Filter(Transformer):
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
def command(self, args):
return all_arguments_true(args)
def assign(self, args):
return all_arguments_true(args)
def assign_list(self, args):
return all_arguments_true(args)
def assign_sum(self, args):
return all_arguments_true(args)
def list_access(self, args):
return all_arguments_true(args)
# level 4 commands
def list_access_var(self, args):
return all_arguments_true(args)
def ifs(self, args):
return all_arguments_true(args)
def valid_command(self, args):
return all_arguments_true(args)
def ifelse(self, args):
return all_arguments_true(args)
def condition(self, args):
return all_arguments_true(args)
def equality_check(self, args):
return all_arguments_true(args)
def in_list_check(self, args):
return all_arguments_true(args)
# level 5 command
def repeat(self, args):
return all_arguments_true(args)
# level 6
def addition(self, args):
return all_arguments_true(args)
def substraction(self, args):
return all_arguments_true(args)
def multiplication(self, args):
return all_arguments_true(args)
def division(self, args):
return all_arguments_true(args)
#level 7
def elses(self, args):
return all_arguments_true(args)
# level 8
def for_loop(self, args):
return all_arguments_true(args)
# level 9
def elifs(self, args):
return all_arguments_true(args)
# level 12
def change_list_item(self, args):
return all_arguments_true(args)
#leafs are treated differently, they are True + their arguments flattened
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 invalid(self, args):
# return the first argument to place in the error message
# TODO: this will not work for misspelling 'at', needs to be improved!
return False, args[0][1]
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, linenumber]
#would be lovely if there was some sort of default rule! Not sure Lark supports that
# note! If this function errors out with:
# Error trying to process rule "program" Tree object not subscriptable
# that means you added a production rule but did not add a method for the rule here
def ask(self, args):
return all_arguments_true(args)
def print(self, args):
return all_arguments_true(args)
def echo(self, args):
return all_arguments_true(args)
def for_loop(self, args):
return all_arguments_true(args)
#leafs with tokens need to be all true
def var(self, args):
return all(args), ''.join([c for c in args])
def text(self, args):
return all(args), ''.join([c for c in args])
def addition(self, args):
return all(args), ''.join([c for c in args])
def invalid_space(self, args):
# return space to indicate that line starts in a space
return False, " "
def print_nq(self, args):
# return error source to indicate what went wrong
return False, "print without quotes"
def input(self, args):
return all_arguments_true(args)
class IsComplete(Filter):
# 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]
#would be lovely if there was some sort of default rule! Not sure Lark supports that
# note! If this function errors out with:
# Error trying to process rule "program" Tree object not subscriptable
# that means you added a production rule but did not add a method for the rule here
def ask(self, args):
return args != [], 'ask'
def print(self, args):
return args != [], 'print'
def print_nq(self, args):
return args != [], 'print level 2'
def echo(self, args):
#echo may miss an argument
return True, 'echo'
#leafs with tokens need to be all true
def var(self, args):
return all(args), ''.join([c for c in args])
def text(self, args):
return all(args), ''.join([c for c in args])
def addition(self, args):
return all(args), ''.join([c for c in args])
def input(self, args):
return args != [], 'input'
class ConvertToPython_1(Transformer):
def process_single_quote(self, value):
# defines what happens if a kids uses ' in a string
value = value.replace("'", "\\'")
return value
def __init__(self, punctuation_symbols, lookup):
self.punctuation_symbols = punctuation_symbols
self.lookup = lookup
def program(self, args):
return '\n'.join([str(c) for c in args])
def command(self, args):
return args
def text(self, args):
return ''.join([str(c) for c in args])
def print(self, args):
# escape quotes if kids accidentally use them at level 1
argument = self.process_single_quote(args[0])
return "print('" + argument + "')"
def echo(self, args):
if len(args) == 0:
return "print(answer)" #no arguments, just print answer
argument = self.process_single_quote(args[0])
return "print('" + argument + "'+answer)"
def ask(self, args):
argument = self.process_single_quote(args[0])
return "answer = input('" + argument + "')"
def wrap_non_var_in_quotes(argument, lookup):
if argument in lookup:
return argument
else:
return "'" + argument + "'"
class ConvertToPython_2(ConvertToPython_1):
def punctuation(self, args):
return ''.join([str(c) for c in args])
def var(self, args):
name = ''.join(args)
return "_" + name if name in reserved_words else name
def print(self, args):
all_arguments_converted = []
i = 0
for argument in args:
# escape quotes if kids accidentally use them at level 2
argument = self.process_single_quote(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 = "+' '"
all_arguments_converted.append(wrap_non_var_in_quotes(argument, self.lookup) + space)
i = i + 1
return 'print(' + '+'.join(all_arguments_converted) + ')'
def ask(self, args):
var = args[0]
all_parameters = ["'" + self.process_single_quote(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 = self.process_single_quote(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):
if args[1] == 'random':
return 'random.choice(' + args[0] + ')'
else:
return args[0] + '[' + args[1] + ']'
#TODO: lookuptable and punctuation chars not be needed for level2 and up anymore, could be removed
class ConvertToPython_3(ConvertToPython_2):
def text(self, args):
return ''.join([str(c) for c in args])
def print(self, args):
#opzoeken is nu niet meer nodig
return "print(" + '+'.join(args) + ')'
def print_nq(self, args):
return ConvertToPython_2.print(self, args)
def indent(s):
lines = s.split('\n')
return '\n'.join([' ' + l for l in lines])
class ConvertToPython_4(ConvertToPython_3):
def list_access_var(self, args):
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 = wrap_non_var_in_quotes(args[0], self.lookup)
arg1 = wrap_non_var_in_quotes(args[1], self.lookup)
return f"{arg0} == {arg1}" #no and statements
def in_list_check(self, args):
arg0 = wrap_non_var_in_quotes(args[0], self.lookup)
arg1 = wrap_non_var_in_quotes(args[1], self.lookup)
return f"{arg0} in {arg1}"
class ConvertToPython_5(ConvertToPython_4):
def number(self, args):
return ''.join(args)
def repeat(self, args):
times = wrap_non_var_in_quotes(args[0], self.lookup)
command = args[1]
return f"""for i in range(int({str(times)})):
{indent(command)}"""
class ConvertToPython_6(ConvertToPython_5):
def print(self, args):
#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(f'str({a.children})')
elif "'" not in a:
args_new.append(f'str({a})')
else:
args_new.append(a)
return "print(" + '+'.join(args_new) + ')'
#we can now have ints as types so chck must force str
def equality_check(self, args):
arg0 = wrap_non_var_in_quotes(args[0], self.lookup)
arg1 = wrap_non_var_in_quotes(args[1], self.lookup)
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 addition(self, args):
return Tree('sum', f'int({str(args[0])}) + int({str(args[1])})')
def substraction(self, args):
return Tree('sum', f'int({str(args[0])}) - int({str(args[1])})')
def multiplication(self, args):
return Tree('sum', f'int({str(args[0])}) * int({str(args[1])})')
def division(self, args):
return Tree('sum', f'int({str(args[0])}) // int({str(args[1])})')
class ConvertToPython_7(ConvertToPython_6):
def __init__(self, punctuation_symbols, lookup):
self.punctuation_symbols = punctuation_symbols
self.lookup = lookup
def command(self, args):
return "".join(args)
def repeat(self, args):
all_lines = [indent(x) for x in args[1:]]
return "for i in range(int(" + str(args[0]) + ")):\n" + "\n".join(all_lines)
def ifs(self, args):
args = [a for a in args if a != ""] # filter out in|dedent tokens
all_lines = [indent(x) for x in args[1:]]
return "if " + args[0] + ":\n" + "\n".join(all_lines)
def elses(self, args):
args = [a for a in args if a != ""] # filter out in|dedent tokens
all_lines = [indent(x) for x in args]
return "\nelse:\n" + "\n".join(all_lines)
def assign(self, args): # TODO: needs to be merged with 6, when 6 is improved to with printing expressions directly
if len(args) == 2:
parameter = args[0]
value = args[1]
if type(value) is Tree:
return parameter + " = " + value.children
else:
if "'" in value or 'random.choice' in value: # TODO: should be a call to wrap nonvarargument is quotes!
return parameter + " = " + value
else:
return parameter + " = '" + value + "'"
else:
parameter = args[0]
values = args[1:]
return parameter + " = [" + ", ".join(values) + "]"
def var_access(self, args):
if len(args) == 1: #accessing a var
return wrap_non_var_in_quotes(args[0], self.lookup)
# this was used to produce better error messages, but needs more work
# (because plain text strings are now also var_access and not textwithoutspaces
# since we no longer have priority rules
# if args[0] in self.lookup:
# return args[0]
# else:
# raise HedyException('VarUndefined', level=7, name=args[0])
else:
# dit was list_access
return args[0] + "[" + str(args[1]) + "]" if type(args[1]) is not Tree else "random.choice(" + str(args[0]) + ")"
class ConvertToPython_8(ConvertToPython_7):
def for_loop(self, args):
args = [a for a in args if a != ""] # filter out in|dedent tokens
all_lines = [indent(x) for x in args[3:]]
return "for " + args[0] + " in range(" + "int(" + args[1] + ")" + ", " + "int(" + args[2] + ")+1" + "):\n"+"\n".join(all_lines)
class ConvertToPython_9_10(ConvertToPython_8):
def elifs(self, args):
args = [a for a in args if a != ""] # filter out in|dedent tokens
all_lines = [indent(x) for x in args[1:]]
return "\nelif " + args[0] + ":\n" + "\n".join(all_lines)
class ConvertToPython_11(ConvertToPython_9_10):
def input(self, args):
var = args[0]
all_parameters = [a for a in args[1:]]
return f'{var} = input(' + '+'.join(all_parameters) + ")"
class ConvertToPython_12_13(ConvertToPython_11):
def assign_list(self, args):
parameter = args[0]
values = [a for a in args[1:]]
return parameter + " = [" + ", ".join(values) + "]"
def list_access_var(self, args):
var = args[0]
if not isinstance(args[2], str):
if args[2].data == 'random':
return var + '=random.choice(' + args[1] + ')'
else:
return var + '=' + args[1] + '[' + args[2] + '-1]'
def list_access(self, args):
if args[1] == 'random':
return 'random.choice(' + args[0] + ')'
else:
return args[0] + '[' + args[1] + '-1]'
def change_list_item(self, args):
return args[0] + '[' + args[1] + '-1] = ' + args[2]
# Custom transformer that can both be used bottom-up or top-down
class ConvertTo():
def __default_child_call(self, name, children):
return self._call_children(children)
def _call_children(self, children):
result = []
for x in children:
if type(x) == Tree:
try:
method = getattr(self, x.data)
except AttributeError:
result.append(self.__default_child_call(x.data, x.children))
else:
result.append(method(x.children))
else:
result.append(x)
return result
def transform(self, tree):
return getattr(self, tree.data)(tree.children)
class ConvertToPython(ConvertTo):
def start(self, children):
return "".join(self._call_children(children))
def if_statement(self, children):
args = self._call_children(children)
return "if " + args[0] + ":\n" + args[1]
def elif_statement(self, children):
args = self._call_children(children)
return "elif " + args[0] + ":\n" + args[1]
def else_statement(self, children):
args = self._call_children(children)
return "else:\n" + args[0]
def repeat(self, children):
args = self._call_children(children)
return "for _ in range(" + args[0] + "):\n" + args[1]
def ranged_loop(self, children):
args = self._call_children(children)
return "for " + args[0] + " in range(" + args[1] + ", " + args[2] + "):\n" + args[3]
def assignment(self, children):
args = self._call_children(children)
return args[0] + " = " + args[1] + "\n"
def eq(self, children):
args = self._call_children(children)
return args[0] + " == " + args[1]
def ne(self, children):
args = self._call_children(children)
return args[0] + " != " + args[1]
def le(self, children):
args = self._call_children(children)
return args[0] + " <= " + args[1]
def ge(self, children):
args = self._call_children(children)
return args[0] + " >= " + args[1]
def lt(self, children):
args = self._call_children(children)
return args[0] + " < " + args[1]
def gt(self, children):
args = self._call_children(children)
return args[0] + " > " + args[1]
def addition(self, children):
args = self._call_children(children)
return args[0] + " + " + args[1]
def substraction(self, children):
args = self._call_children(children)
return args[0] + " - " + args[1]
def multiplication(self, children):
args = self._call_children(children)
return args[0] + " * " + args[1]
def division(self, children):
args = self._call_children(children)
return args[0] + " / " + args[1]
def modulo(self, children):
args = self._call_children(children)
return args[0] + " % " + args[1]
def unary_plus(self, children):
args = self._call_children(children)
return args[0]
def unary_minus(self, children):
args = self._call_children(children)
return "-" + args[0]
def parenthesis(self, children):
args = self._call_children(children)
return "(" + args[0] + ")"
def list_access(self, children):
args = self._call_children(children)
return args[0] + "[" + args[1] + "]" if args[1] != "random" else "random.choice(" + args[0] + ")"
def list(self, children):
args = self._call_children(children)
return "[" + ", ".join(args) + "]"
def print(self, children):
args = self._call_children(children)
return "print(" + ", ".join(args) + ")\n"
def ask(self, children):
args = self._call_children(children)
return "input(" + " + ".join(args) + ")"
def create_grammar(level):
# Load Lark grammars relative to directory of current file
script_dir = path.abspath(path.dirname(__file__))
with open(path.join(script_dir, "grammars", "level" + str(level) + ".lark"), "r", encoding="utf-8") as file:
return file.read()
def transpile(input_string, level):
try:
return transpile_inner(input_string, level)
except Exception as E:
# This is the 'fall back' transpilation
# that should surely be improved!!
# we retry HedyExceptions of the type Parse (and Lark Errors) but we raise Invalids
if E.args[0] == 'Parse':
#try 1 level lower
if level > 1:
try:
new_level = level - 1
result = transpile_inner(input_string, new_level)
except (LarkError, HedyException) as innerE:
# Parse at `level - 1` failed as well, just re-raise original error
raise E
# If the parse at `level - 1` succeeded, then a better error is "wrong level"
raise HedyException('Wrong Level', correct_code=result, original_level=level, working_level=new_level) from E
raise E
def repair(input_string):
#the only repair we can do now is remove leading spaces, more can be added!
return '\n'.join([x.lstrip() for x in input_string.split('\n')])
def translate_characters(s):
# this method is used to make it more clear to kids what is meant in error messages
# for example ' ' is hard to read, space is easier
# this could (should?) be localized so we can call a ' "Hoge komma" for example (Felienne, dd Feb 25, 2021)
if s == ' ':
return 'space'
elif s == ',':
return 'comma'
elif s == '?':
return 'question mark'
elif s == '\\n':
return 'newline'
elif s == '.':
return 'period'
elif s == '!':
return 'exclamation mark'
elif s == '*':
return 'star'
elif s == "'":
return 'single quotes'
elif s == '"':
return 'double quotes'
elif s == '/':
return 'slash'
elif s == '-':
return 'dash'
elif s >= 'a' and s <= 'z' or s >= 'A' and s <= 'Z':
return s
else:
return s
def filter_and_translate_terminals(list):
# in giving error messages, it does not make sense to include
# ANONs, and some things like EOL need kid friendly translations
new_terminals = []
for terminal in list:
if terminal[:4] == "ANON":
continue
if terminal == "EOL":
new_terminals.append("Newline")
break
#not translated or filtered out? simply add as is:
new_terminals.append(terminal)
return new_terminals
def beautify_parse_error(error_message):
character_found = error_message.split("'")[1]
character_found = translate_characters(character_found)
return character_found
def find_indent_length(line):
number_of_spaces = 0
for x in line:
if x == ' ':
number_of_spaces += 1
else:
break
return number_of_spaces
def preprocess_blocks(code):
processed_code = []
lines = code.split("\n")
current_indent = 0
previous_block = 0
for line in lines:
leading_spaces = find_indent_length(line)
if leading_spaces > previous_block:
current_indent += 1
previous_block = leading_spaces
elif leading_spaces < previous_block:
#we springen 'terug' dus er moet een block in!
processed_code.append('end-block')
current_indent -=1
previous_block = leading_spaces
#if indent remains the same, do nothing, just add line
processed_code.append(line)
# if the last line is indented, the end of the program is also the end of all indents
# so close all blocks
for i in range(current_indent):
processed_code.append('end-block')
return "\n".join(processed_code)
def transpile_inner(input_string, level):
punctuation_symbols = ['!', '?', '.']
level = int(level)
parser = Lark(create_grammar(level))
if level >= 8:
input_string = preprocess_blocks(input_string)
try:
program_root = parser.parse(input_string+ '\n').children[0] # getting rid of the root could also be done in the transformer would be nicer
abstract_syntaxtree = ExtractAST().transform(program_root)
lookup_table = AllAssignmentCommands().transform(abstract_syntaxtree)
except Exception as e:
try:
location = e.line, e.column
characters_expected = str(e.allowed)
character_found = beautify_parse_error(e.args[0])
# print(e.args[0])
# print(location, character_found, characters_expected)
raise HedyException('Parse', level=level, location=location, character_found=character_found, characters_expected=characters_expected) from e
except UnexpectedEOF:
# this one can't be beautified (for now), so give up :)
raise e
is_valid = IsValid().transform(program_root)
if not is_valid[0]:
if is_valid[1] == ' ':
line = is_valid[2]
#the error here is a space at the beginning of a line, we can fix that!
fixed_code = repair(input_string)
if fixed_code != input_string: #only if we have made a successful fix
result = transpile_inner(fixed_code, level)
raise HedyException('Invalid Space', level=level, line_number=line, fixed_code = result)
elif is_valid[1] == 'print without quotes':
# grammar rule is ignostic of line number so we can't easily return that here
raise HedyException('Unquoted Text', level=level)
else:
invalid_command = is_valid[1]
closest = closest_command(invalid_command, commands_per_level[level])
if closest == None: #we couldn't find a suggestion because the command itself was found
# clearly the error message here should be better or it should be a different one!
raise HedyException('Parse', level=level, location=["?", "?"], characters_expected="?")
raise HedyException('Invalid', invalid_command=invalid_command, level=level, guessed_command=closest)
is_complete = IsComplete().transform(program_root)
if not is_complete[0]:
incomplete_command = is_complete[1]
line = is_complete[2]
raise HedyException('Incomplete', incomplete_command=incomplete_command, level=level, line_number=line)
if level == 1:
python = ConvertToPython_1(punctuation_symbols, lookup_table).transform(abstract_syntaxtree)
return python
elif level == 2:
python = ConvertToPython_2(punctuation_symbols, lookup_table).transform(abstract_syntaxtree)
return python
elif level == 3:
python = ConvertToPython_3(punctuation_symbols, lookup_table).transform(abstract_syntaxtree)
return python
elif level == 4:
python = ConvertToPython_4(punctuation_symbols, lookup_table).transform(abstract_syntaxtree)
return python
elif level == 5:
python = ConvertToPython_5(punctuation_symbols, lookup_table).transform(abstract_syntaxtree)
return python
elif level == 6:
python = ConvertToPython_6(punctuation_symbols, lookup_table).transform(abstract_syntaxtree)
return python
elif level == 7:
python = ConvertToPython_7(punctuation_symbols, lookup_table).transform(abstract_syntaxtree)
return python
elif level == 8:
python = ConvertToPython_8(punctuation_symbols, lookup_table).transform(abstract_syntaxtree)
return python
elif level == 9:
python = ConvertToPython_9_10(punctuation_symbols, lookup_table).transform(abstract_syntaxtree)
return python
elif level == 10:
# Code does not change for nesting
python = ConvertToPython_9_10(punctuation_symbols, lookup_table).transform(abstract_syntaxtree)
return python
elif level == 11:
python = ConvertToPython_11(punctuation_symbols, lookup_table).transform(abstract_syntaxtree)
return python
elif level == 12:
python = ConvertToPython_12_13(punctuation_symbols, lookup_table).transform(abstract_syntaxtree)
return python
elif level == 13:
# Code does not change for level 13 only grammar
python = ConvertToPython_12_13(punctuation_symbols, lookup_table).transform(abstract_syntaxtree)
return python
#Laura & Thera: hier kun je code voor de nieuwe levels toevoegen
else:
raise Exception('Levels over 7 are not implemented yet')
def execute(input_string, level):
python = transpile(input_string, level)
exec(python)
# f = open('output.py', 'w+')
# f.write(python)
# f.close()