-
Notifications
You must be signed in to change notification settings - Fork 1
/
parser_instructions.py
1371 lines (1056 loc) · 62.9 KB
/
parser_instructions.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 re
import os
import generic_regexes
import flow_chart_graphics
import collections
import remi.gui as gui
"""
This parses dat and src files
analyzed instructions
"""
instructions_defs = {
'dat begin': generic_regexes.line_begin + "(DEFDAT +)" + generic_regexes.dat_name + "( +PUBLIC)?" + generic_regexes.line_end, #creates a dat parser
'dat end': generic_regexes.a_line_containing("ENDDAT"),
'procedure begin': generic_regexes.line_begin + generic_regexes.global_def + "(DEF +)" + generic_regexes.function_name + " *\( *(" + generic_regexes.parameters_declaration + ")* *\)" + generic_regexes.line_end, #creates a procedure parser
'function begin': generic_regexes.line_begin + generic_regexes.global_def + "(DEFFCT +)" + "([^ ]+) +" + generic_regexes.function_name + " *\( *(" + generic_regexes.parameters_declaration + ")* *\)" + generic_regexes.line_end, #creates a function parser
'meta instruction': r"(?:^ *\& *)",
'procedure end': generic_regexes.a_line_containing("END"),
'function end': generic_regexes.a_line_containing("ENDFCT"),
'function return': generic_regexes.a_line_containing("RETURN" + "(?: +(.+))?"),
'exit': generic_regexes.a_line_containing("EXIT"),
'halt': generic_regexes.a_line_containing("HALT"),
'switch': generic_regexes.line_begin + "SWITCH *(.*)",
'case': generic_regexes.line_begin + "CASE +(.*)",
'default': generic_regexes.a_line_containing("DEFAULT"),
'endswitch': generic_regexes.a_line_containing("ENDSWITCH"),
'lin': generic_regexes.a_line_containing("LIN(?:_rel)? +(.+)"),
'ptp': generic_regexes.a_line_containing("PTP +(.+)"),
'circ': generic_regexes.a_line_containing("CIRC +(.+)"),
'struc declaration': generic_regexes.line_begin + generic_regexes.global_def + "(STRUC +)%s +([^ ,]+) +"%(generic_regexes.struct_name,),
'if begin': generic_regexes.a_line_containing("IF +" + "(.+)" + " +THEN"),
'else': generic_regexes.a_line_containing("ELSE"),
'if end': generic_regexes.a_line_containing("ENDIF"),
'for begin': generic_regexes.a_line_containing("FOR +" + "(.+)" + " +TO +((?:(?!STEP).)+)(?: +STEP +(.+))? *"),
'for end': generic_regexes.a_line_containing("ENDFOR"),
'while begin': generic_regexes.a_line_containing("WHILE +" + "(.+)"),
'while end': generic_regexes.a_line_containing("ENDWHILE"),
'repeat': generic_regexes.a_line_containing("REPEAT"),
'until': generic_regexes.a_line_containing("until +(.+)"),
'loop begin': generic_regexes.a_line_containing("LOOP"),
'loop end': generic_regexes.a_line_containing("ENDLOOP"),
'interrupt decl': generic_regexes.a_line_containing( generic_regexes.global_def + "INTERRUPT +DECL +" + generic_regexes.int_or_real_number + " +WHEN +(.+) +DO +(.+)" ),
'interrupt on': generic_regexes.a_line_containing("INTERRUPT +ON +" + generic_regexes.int_or_real_number ),
'interrupt off': generic_regexes.a_line_containing("INTERRUPT +OFF +" + generic_regexes.int_or_real_number ),
'resume': generic_regexes.a_line_containing("RESUME"),
'trigger distance': generic_regexes.a_line_containing( "TRIGGER +WHEN +DISTANCE *= *(0|1) +DELAY *= *" + generic_regexes.int_or_real_number + " +DO +(.+)" ),
'trigger path': generic_regexes.a_line_containing( "TRIGGER +WHEN +PATH *= *(.+) +DELAY *= *" + generic_regexes.int_or_real_number + " +DO +(.+)" ),
'variable assignment': generic_regexes.a_line_containing( generic_regexes.global_def + "(DECL +)?(?:" + generic_regexes.variable_name + " +)?" + generic_regexes.variable_name + " *= *([^;]+)" ),
'variable declaration': generic_regexes.a_line_containing( generic_regexes.global_def + "(DECL +)?([^ =\(]+) +(([^ =\(]+"+generic_regexes.c(generic_regexes.index_3d)+"?)( *, *[^ =]+" + generic_regexes.c(generic_regexes.index_3d) + "?)*)" ),
'function call': generic_regexes.a_line_containing( generic_regexes.variable_name + " *\( *(.*) *\)" ),
'enum definition': generic_regexes.a_line_containing( generic_regexes.global_def + "ENUM +([^ ]+) +.*" ),
'wait sec': generic_regexes.a_line_containing( "WAIT +SEC +" + generic_regexes.int_or_real_number ),
'wait for': generic_regexes.a_line_containing( "WAIT +FOR +" + "([^;]+)" ),
'ext': generic_regexes.line_begin + "EXTP? +([^ \(]+) *\(",
'extfct': generic_regexes.line_begin + "EXTFCTP? +([^ ]+) +([^ \(]+) *\(",
'signal decl': generic_regexes.a_line_containing( generic_regexes.global_def + r"SIGNAL +([^ ]+) +((?:[^ \[]+)(?:\[ *[0-9]* *\])?)(?: +TO +((?:[^ \[]+)(?:\[ *[0-9]* *\])?))?" ),
'continue': generic_regexes.a_line_containing( "CONTINUE" ), #in KRL Prevention of advance run stops.
}
#adds global functions, procedures, variables, structures to a single file that will be imported by all user modules
def init_user_global_def():
with open('./global_defs_user.py', 'w+') as f:
f.writelines('#auto generated\nimport global_defs\n')
def add_user_global_def(content):
with open('./global_defs_user.py', 'a+') as f:
f.writelines(content + '\n')
uuid = 0
class KRLGenericParser(flow_chart_graphics.FlowInstruction):
stop_statement_found = False
permissible_instructions_dictionary = None
indent_comments = True
def __init__(self, permissible_instructions_dictionary):
self.permissible_instructions_dictionary = collections.OrderedDict(permissible_instructions_dictionary)
standard_permissible_instructions = ['function return','meta instruction','halt','switch','lin','ptp','circ','if begin','for begin','while begin','repeat','loop begin','interrupt decl','interrupt on','interrupt off','trigger distance','trigger path','variable assignment','function call','wait sec','wait for', 'ext', 'extfct', 'signal decl','continue','resume',]
self.permissible_instructions_dictionary.update({k:v for k,v in instructions_defs.items() if k in standard_permissible_instructions})
flow_chart_graphics.FlowInstruction.__init__(self)
def get_parent_function(self):
if issubclass(type(self), KRLProcedureParser) or issubclass(type(self), KRLFunctionParser):
return self
if not self.get_parent() is None:
if issubclass(type(self.get_parent()), KRLGenericParser):
return self.get_parent().get_parent_function()
return None
def get_parent_module_file(self):
import parser_module
if self.__class__ == parser_module.KRLModuleDatFileParser or self.__class__ == parser_module.KRLModuleSrcFileParser:
return self
if not self.get_parent() is None:
return self.get_parent().get_parent_module_file()
return None
def parse(self, file_lines):
""" Parses the file lines up to the procedure end
"""
translation_result = [] #here are stored the results of instructions translations from krl to python
while len(file_lines) and not self.stop_statement_found:
code_line_original = file_lines.pop(0)
code_line, endofline_comment_to_append = generic_regexes.prepare_instruction_for_parsing(code_line_original)
code_line = generic_regexes.replace_enum_value(code_line)
instruction_name, match_groups = generic_regexes.check_regex_match(code_line, self.permissible_instructions_dictionary)
#here is called the specific parser
translation_result_tmp, file_lines = self.parse_single_instruction(code_line_original, code_line, instruction_name, match_groups, file_lines)
if endofline_comment_to_append.startswith(';'):
endofline_comment_to_append = '//' + endofline_comment_to_append
if len(translation_result_tmp)>0:
if '[,]' in translation_result_tmp[0]:
translation_result_tmp[0] = re.sub('\[,\]', '[:]', translation_result_tmp[0])
translation_result_tmp[0] = translation_result_tmp[0] + endofline_comment_to_append
translation_result.extend(translation_result_tmp)
else:
if len(endofline_comment_to_append)>0:
translation_result.append((' ' if self.indent_comments else '') + endofline_comment_to_append + '\n')
return translation_result, file_lines
def parse_single_instruction(self, code_line_original, code_line, instruction_name, match_groups, file_lines):
global uuid
translation_result_tmp = []
if "profileRobotMeasures" in code_line_original:
print("brakepoint")
if ':' in code_line:
if instruction_name in ['variable assignment', 'function call', 'return', 'lin', 'ptp', 'circ']:
code_line = generic_regexes.replace_geometric_operator(code_line)
if instruction_name == 'meta instruction':
return translation_result_tmp, file_lines
if instruction_name == 'halt':
translation_result_tmp.append("assert(false); # halt")
node = flow_chart_graphics.FlowInstruction('HALT')
self.append(node)
if instruction_name == 'switch':
value_to_switch = match_groups[0]
node = KRLStatementSwitch( value_to_switch )
self.append(node)
_translation_result_tmp, file_lines = node.parse(file_lines)
if len(_translation_result_tmp):
translation_result_tmp.extend(_translation_result_tmp)
if instruction_name == 'lin':
position = match_groups[0].strip().lower()
position = position.replace(" c_dis", ", c_dis")
position = position.replace(" c_ptp", ", c_ptp")
position = position.replace(" c_ori", ", c_ori")
translation_result_tmp.append("robot.lin(%s)"%position)
node = flow_chart_graphics.FlowInstruction('LIN %s'%position)
self.append(node)
if instruction_name == 'ptp':
position = match_groups[0].strip()
position = position.replace(" c_dis", ", c_dis")
position = position.replace(" c_ptp", ", c_ptp")
position = position.replace(" c_ori", ", c_ori")
translation_result_tmp.append("robot.ptp(%s)"%position)
node = flow_chart_graphics.FlowInstruction('PTP %s'%position)
self.append(node)
if instruction_name == 'circ':
position = match_groups[0].strip().lower()
position = position.replace(" c_dis", ", c_dis")
position = position.replace(" c_ptp", ", c_ptp")
position = position.replace(" c_ori", ", c_ori")
translation_result_tmp.append("robot.circ(%s)"%position)
node = flow_chart_graphics.FlowInstruction('CIRC %s'%position)
self.append(node)
if instruction_name == 'struc declaration':
is_global = not match_groups[0] is None
struc_name = match_groups[2]
variables_names = code_line.split(struc_name, maxsplit=1)[1]
variables_names = [x.strip() for x in variables_names.split(',')]
variables_names_with_types = {}
type_name = ""
for x in variables_names:
#remove multiple spaces
while " " in x:
x = x.replace(" ", " ")
if " " in x:
#type name
type_name, var_name = x.split(" ")
variables_names_with_types[var_name] = type_name
else:
variables_names_with_types[x] = type_name
#now we create a class
# class struc_name():
# var_name = type_name()
translation_result_tmp.append("struct %s{"%struc_name)
#if the variable (struc field) is an array, we replace the type with a multi_dimensional_array
for var, type_name in variables_names_with_types.items():
var, size, subindex, is_array = generic_regexes.split_varname_index(var)
if is_array:
#translation_result_tmp.append(" multi_dimensional_array<%s> %s%s;"%(type_name, var, size))
translation_result_tmp.append(" %s %s%s;"%(type_name, var, size))
else:
translation_result_tmp.append(" %s %s;"%(type_name, var))
translation_result_tmp.append("};")
if is_global:
#translation_result_tmp.append("global_defs.%s = %s"%(struc_name, struc_name))
add_user_global_def("%s = %s"%(struc_name, struc_name))
if instruction_name == 'if begin':
condition = match_groups[0].strip()
translation_result_tmp.append("if( " + condition + " ){")
node = KRLStatementIf(condition)
self.append(node)
_translation_result_tmp, file_lines = node.parse(file_lines)
if len(_translation_result_tmp):
translation_result_tmp.extend(_translation_result_tmp)
if instruction_name == 'for begin':
"""
re.search(re_for, "for $potato=1 to 20 step +1", re.IGNORECASE).groups()
('$potato=1', '20', '+1')
"""
initialization = match_groups[0].strip()
initialization_variable = initialization.split('=')[0].strip()
initialization_value = initialization.split('=')[1].strip()
value_end = match_groups[1].strip()
step = match_groups[2]
if not step is None:
translation_result_tmp.append("for( %(varname)s=%(init_val)s; %(varname)s<%(end_val)s; %(varname)s+=%(step)s){"%{"varname":initialization_variable, "init_val":initialization_value, "end_val":value_end, "step":step.strip()})
else:
translation_result_tmp.append("for( %(varname)s=%(init_val)s; %(varname)s<%(end_val)s; %(varname)s++){"%{"varname":initialization_variable, "init_val":initialization_value, "end_val":value_end})
node = KRLStatementFor(initialization_variable, initialization_value, value_end, step)
self.append(node)
_translation_result_tmp, file_lines = node.parse(file_lines)
if len(_translation_result_tmp):
translation_result_tmp.extend(_translation_result_tmp)
if instruction_name == 'while begin':
condition = match_groups[0].strip()
translation_result_tmp.append("while( " + condition + " ){")
node = KRLStatementWhile(condition)
self.append(node)
_translation_result_tmp, file_lines = node.parse(file_lines)
if len(_translation_result_tmp):
translation_result_tmp.extend(_translation_result_tmp)
if instruction_name == 'repeat':
translation_result_tmp.append("while( true ){")
node = KRLStatementRepeatUntil()
self.append(node)
_translation_result_tmp, file_lines = node.parse(file_lines)
if len(_translation_result_tmp):
translation_result_tmp.extend(_translation_result_tmp)
if instruction_name == 'loop begin':
translation_result_tmp.append("while( true ){")
node = KRLStatementLoop()
self.append(node)
_translation_result_tmp, file_lines = node.parse(file_lines)
if len(_translation_result_tmp):
translation_result_tmp.extend(_translation_result_tmp)
if instruction_name == 'interrupt decl':
interrupt_declaration_template = \
"auto fcond%(interrupt_name)s = [&](){" \
" if(interrupt_flags[%(interrupt_number)s])\n" \
" return (%(condition)s);\n" \
" return false;\n" \
"};\n" \
"auto fcall%(interrupt_name)s = [&](){\n" \
" %(instruction)s;\n" \
"};\n" \
"interrupts[%(interrupt_number)s] = InterruptData(fcall%(interrupt_name)s, fcond%(interrupt_name)s);\n"
is_global, interrupt_number, condition, instruction = match_groups
is_global = not is_global is None
node = InterruptObject(interrupt_number, is_global, condition, instruction)
self.get_parent_function().append(node)
interrupt_declaration = interrupt_declaration_template%{'interrupt_number':interrupt_number, 'condition':condition, 'instruction':instruction, 'interrupt_name':'_interrupt%s'%interrupt_number}
translation_result_tmp.extend(interrupt_declaration.split('\n'))
#translation_result_tmp.append('interrupts[%s] = """if %s:%s""" '%(interrupt_number, condition, instruction)] #to be evaluated cyclically with eval
if instruction_name == 'interrupt on':
interrupt_number = match_groups[0]
translation_result_tmp.append('interrupt_flags[%s] = true;'%interrupt_number)
node = flow_chart_graphics.FlowInstruction('INTERRUPT ON %s'%interrupt_number)
self.append(node)
if instruction_name == 'interrupt off':
interrupt_number = match_groups[0]
translation_result_tmp.append('interrupt_flags[%s] = false;'%interrupt_number)
node = flow_chart_graphics.FlowInstruction('INTERRUPT OFF %s'%interrupt_number)
self.append(node)
if instruction_name == 'resume':
translation_result_tmp.append("robot.resume_interrupt();")
node = flow_chart_graphics.FlowInstruction('RESUME')
self.append(node)
if instruction_name == 'trigger distance':
trigger_distance_declaration_template = \
"def %(trigger_name)s():\n" \
" %(instruction)s\n" \
"threading.Timer(%(delay)s, %(trigger_name)s).start()\n"
distance, delay, instruction = match_groups
trigger_func_name = 'trigger_func%s'%uuid
uuid = uuid + 1
trigger_declaration = trigger_distance_declaration_template%{'trigger_name':trigger_func_name, 'instruction':instruction, 'delay':delay}
translation_result_tmp.extend(trigger_declaration.split('\n'))
node = flow_chart_graphics.FlowInstruction('TRIGGER WHEN DISTANCE=%s DELAY=%s DO %s'%(distance, delay, instruction))
self.append(node)
if instruction_name == 'trigger path':
trigger_path_declaration_template = \
"#this should be scheduled at path=%(path)s, to be implemented\n" \
"def %(trigger_name)s():\n" \
" %(instruction)s\n" \
"threading.Timer(%(delay)s, %(trigger_name)s).start()\n"
path, delay, instruction = match_groups
trigger_func_name = 'trigger_func%s'%uuid
uuid = uuid + 1
trigger_declaration = trigger_path_declaration_template%{'trigger_name':trigger_func_name, 'instruction':instruction, 'delay':delay, 'path':path}
translation_result_tmp.extend(trigger_declaration.split('\n'))
node = flow_chart_graphics.FlowInstruction('TRIGGER WHEN PATH=%s DELAY=%s DO %s'%(path, delay, instruction))
self.append(node)
if instruction_name == 'variable declaration':
"""
re.search(re_variable_decl, "global decl e6POS potato[ 123], cips", re.IGNORECASE).groups()
('global ', 'decl ', 'e6POS', 'potato[ 123]', 'cips')
>>>
"""
is_global = not match_groups[0] is None
type_name = match_groups[2]
variables_names = code_line.split(type_name, maxsplit=1)[1] #match_groups[3].split(',')
variables_names = re.split(r" *, *(?!\]|[0-9])", variables_names) #split with a comma not inside an index definition [,]
variables_names = [x.strip() for x in variables_names]
for var in variables_names:
#if the variable is not declared as parameter, declare it in procedure/function body
#if actual_code_block is None or (not re.sub(generic_regexes.index_3d, '', var) in actual_code_block.param_names):
parent_function = self.get_parent_function()
var, size, subindex, is_array = generic_regexes.split_varname_index(var)
if not parent_function is None:
parent_function.local_variables[var] = type_name
res = ''
if parent_function is None or not var in parent_function.param_names:
#check if it is an array
if is_array:
#translation_result_tmp.append(("global_defs." if is_global else "")+"%s = multi_dimensional_array(%s, %s)"%(var,type_name,size))
#res = "multi_dimensional_array<%s> %s%s;"%(type_name, var, size)
res = "%s %s%s;"%(type_name, var, size)
else:
#translation_result_tmp.append(("global_defs." if is_global else "")+"%s = %s()"%(var,type_name))
res = "%s %s;"%(type_name, var)
if is_global:
#translation_result_tmp.append("from global_defs import %s"%(var))
add_user_global_def(res)
else:
pass
# #if the variable decl is a function parameter it have to be not declared again
# # and we discard also an end of line comment
# if not parent_function is None:
# parent_function.pass_to_be_added = True
#endofline_comment_to_append = ""
#if not parent_function is None: #if variable declaration is a procedure paramter
# if not is_array: #this is intended to recreate enum, arrays are already transferred correctly
# res = "%(var)s = %(typ)s(%(var)s)"%{'var':var,'typ':type_name}
translation_result_tmp.append(res)
if is_global:
add_user_global_def(res)
if instruction_name == 'variable assignment':
result = re.search(instructions_defs['variable assignment'], code_line, re.IGNORECASE)
elements = result.groups()
#(None, 'decl ', 'circ_type', 'def_circ_typ', 'system_constants.base')
#print(elements)
is_global = not elements[0] is None
is_decl = not elements[1] is None
type_name = elements[2]
var = elements[3].strip()
value = elements[4].strip()
var, size, subindex, is_array = generic_regexes.split_varname_index(var)
parent_function = self.get_parent_function()
res = ''
if not type_name is None:
type_name = type_name.strip()
res = "%s %s%s%s = %s;"%(type_name, var, size, subindex, value)
#if there is a parent function, the variable name have to be appended to local_variables dictionary
if not parent_function is None:
parent_function.local_variables[var] = type_name
else:
if not parent_function is None:
if not (generic_regexes.var_without_pointed_field(var)[0] in parent_function.local_variables):
parent_function.global_variables.append(generic_regexes.var_without_pointed_field(var)[0])
if is_array:
res = """%(var)s%(size)s%(subindex)s = %(value)s;"""%{'var':var, 'size':size, 'subindex':subindex, 'value':value}
else:
res = """%(var)s%(subindex)s = %(value)s;"""%{'var':var, 'subindex':subindex, 'value':value}
if is_global:
add_user_global_def(res)
translation_result_tmp.extend(res.split('\n'))
node = flow_chart_graphics.FlowInstruction('%s%s = %s'%(var if not is_array else "%s%s"%(var, size), subindex, value))
self.append(node)
if instruction_name == 'function call':
self.get_parent_function().calling_list.append(match_groups[0])
translation_result_tmp.append(code_line.strip() + ";")
node = flow_chart_graphics.FlowInstruction('CALL %s'%code_line.strip())
self.append(node)
if instruction_name == 'enum definition':
is_global = not match_groups[0] is None
enum_name = match_groups[1].strip()
elements = code_line.split(enum_name)[1]
element_list = elements.split(',')
i = 1
element_list_with_values = []
for elem in element_list:
elem = elem.strip()
element_list_with_values.append("'%s':%s"%(elem, i))
i = i + 1
#translation_result_tmp.append('%s = global_defs.enum(%s, "%s", %s)'%(enum_name, 'global_defs' if is_global else 'sys.modules[__name__]', enum_name, ', '.join(element_list_with_values)))
enum_template = \
"enum %(enum_name)s {%(values)s};"
#translation_result_tmp.append('%s = global_defs.enum(%s, "%s")'%(enum_name, ', '.join(element_list_with_values)))
res = enum_template%{'enum_name': enum_name, 'values':', '.join(element_list_with_values)}
translation_result_tmp.append(res)
if is_global:
add_user_global_def(res)
if instruction_name == 'wait sec':
t = match_groups[0]
translation_result_tmp.append('robot.wait_sec(%s);'%t)
node = flow_chart_graphics.FlowInstruction('WAIT SEC %s'%t)
self.append(node)
if instruction_name == 'wait for':
condition = match_groups[0]
translation_result_tmp.append('while( !(%s) )sleep(0.1);'%condition)
node = flow_chart_graphics.FlowInstruction('WAIT FOR %s'%condition)
self.append(node)
if instruction_name == 'ext':
procedure_name = match_groups[0]
r = re.search(generic_regexes.line_begin+"EXTP", code_line, re.IGNORECASE)
module_name = procedure_name #normally a function imported by EXT has the same name of the module in which it is contained. This seems not valid for EXTP
if not r is None:
module_name = 'kuka_internals'
translation_result_tmp.append( "from %s import %s"%( module_name, procedure_name ) )
if instruction_name == 'extfct':
return_type, function_name = match_groups[0], match_groups[1]
r = re.search(generic_regexes.line_begin+" *EXTFCTP", code_line, re.IGNORECASE)
module_name = function_name #normally a function imported by EXT has the same name of the module in which it is contained. This seems not valid for EXTP
if not r is None:
module_name = 'kuka_internals'
translation_result_tmp.append( "from %s import %s"%( module_name, function_name ) )
if instruction_name == 'signal decl':
is_global, signal_name, signal_start, signal_end = match_groups
is_global = not is_global is None
res = ''
if signal_end is None:
res = "signal %s(&%s);"%(signal_name, signal_start)
else:
res = "signal %s(&%s, &%s);"%(signal_name, signal_start, signal_end)
translation_result_tmp.append(res)
if is_global:
add_user_global_def(res)
if instruction_name == 'function return':
value = match_groups[0]
translation_result_tmp.append("return;" if value is None else ("return " + value + ";"))
node = flow_chart_graphics.FlowInstruction('RETURN %s'%value)
self.append(node)
if instruction_name == 'continue':
translation_result_tmp.append('global_defs.robot.do_not_stop_ADVANCE_on_next_IO()')
node = flow_chart_graphics.FlowInstruction('CONTINUE')
self.append(node)
return translation_result_tmp, file_lines
class KRLStatementRepeatUntil(KRLGenericParser):
condition = ""
pass_to_be_added = True
def __init__(self):
permissible_instructions = ['until']
permissible_instructions_dictionary = {k:v for k,v in instructions_defs.items() if k in permissible_instructions}
KRLGenericParser.__init__(self, permissible_instructions_dictionary)
def parse_single_instruction(self, code_line_original, code_line, instruction_name, match_groups, file_lines):
translation_result_tmp = []
if not instruction_name in ['until','']:
self.pass_to_be_added = False
if instruction_name == 'until':
self.condition = match_groups[0].strip()
#translation_result_tmp.append(" if %s:"%self.condition)
#translation_result_tmp.append(" " + "break")
translation_result_tmp.append("}while( %s );"%self.condition)
self.pass_to_be_added = False
self.stop_statement_found = True
self.box_text_content = 'UNTIL %s'%(self.condition)
_translation_result_tmp, file_lines = KRLGenericParser.parse_single_instruction(self, code_line_original, code_line, instruction_name, match_groups, file_lines)
if len(_translation_result_tmp):
translation_result_tmp.extend(generic_regexes.indent_lines(_translation_result_tmp, 1))
return translation_result_tmp, file_lines
def recalc_size_and_arrange_children(self):
w, h = super(KRLStatementRepeatUntil, self).recalc_size_and_arrange_children()
self.box_height = 100
#the box is at the bottom
h = h + self.box_height
h = h + 30*2 #height is increased by 30 for bottom lines
w = w + 30*2 #to give margins to return and endfor lines
gui._MixinSvgSize.set_size(self, w, h)
self.set_viewbox(-w/2, 0, w, h)
return w, h
def draw(self):
line_length = 30
self.box_height = line_length
self.box_width = max( len(self.box_text_content) * self.text_letter_width, 200 )
w, h = self.recalc_size_and_arrange_children()
#top vertical line
self.drawings_keys.append( self.append(gui.SvgLine(0, 0, 0, line_length), 'line_top') )
#middle vertical line
self.drawings_keys.append( self.append(gui.SvgLine(0, h-self.box_height-line_length*2, 0, h-self.box_height-line_length*1), 'line_middle') )
#central box line
self.drawings_keys.append( self.append(flow_chart_graphics.RomboidBox(-self.box_width/2, h-self.box_height-line_length*1, self.box_width, self.box_height, self.box_text_content), 'box') )
#line returns
poly = gui.SvgPolyline(10)
poly.add_coord(-self.box_width/2, h-self.box_height/2-line_length*1)
poly.add_coord(-w/2, h-self.box_height/2-line_length*1)
poly.add_coord(-w/2, line_length)
poly.add_coord(0, line_length)
self.drawings_keys.append( self.append(poly, 'lret') )
#arrow
polygon = gui.SvgPolygon(10)
polygon.add_coord(0, line_length)
polygon.add_coord(-10, line_length+5)
polygon.add_coord(-10, line_length-5)
self.drawings_keys.append( self.append(polygon, 'arrow') )
self.children['arrow'].set_stroke(1, 'black')
self.children['arrow'].set_fill('black')
poly = gui.SvgPolyline(10)
poly.add_coord(0, h-line_length*1)
poly.add_coord(0, h)
self.drawings_keys.append( self.append(poly, 'lendfor') )
self.children['line_middle'].set_stroke(1, 'black')
self.children['line_top'].set_stroke(1, 'black')
self.children['lret'].set_stroke(1, 'black')
self.children['lret'].set_fill('transparent')
self.children['lendfor'].set_stroke(1, 'black')
self.children['lendfor'].set_fill('transparent')
self.children['box'].set_stroke(1, 'black')
class KRLStatementWhile(KRLGenericParser):
condition = ""
pass_to_be_added = True
def __init__(self, condition):
self.condition = condition
permissible_instructions = ['while end']
permissible_instructions_dictionary = {k:v for k,v in instructions_defs.items() if k in permissible_instructions}
KRLGenericParser.__init__(self, permissible_instructions_dictionary)
self.box_text_content = 'WHILE %s'%(condition)
def parse_single_instruction(self, code_line_original, code_line, instruction_name, match_groups, file_lines):
translation_result_tmp = []
if not instruction_name in ['while end','']:
self.pass_to_be_added = False
if instruction_name == 'while end':
self.pass_to_be_added = False
self.stop_statement_found = True
translation_result_tmp.append("}")
_translation_result_tmp, file_lines = KRLGenericParser.parse_single_instruction(self, code_line_original, code_line, instruction_name, match_groups, file_lines)
if len(_translation_result_tmp):
translation_result_tmp.extend(generic_regexes.indent_lines(_translation_result_tmp, 1))
return translation_result_tmp, file_lines
def recalc_size_and_arrange_children(self):
w, h = super(KRLStatementWhile, self).recalc_size_and_arrange_children()
h = h + 30*3 #height is increased by 30 for bottom lines
w = w + 30*2 #to give margins to return and endfor lines
gui._MixinSvgSize.set_size(self, w, h)
self.set_viewbox(-w/2, 0, w, h)
return w, h
def draw(self):
self.box_height = 100
self.box_width = max( len(self.box_text_content) * self.text_letter_width, 200 )
w, h = self.recalc_size_and_arrange_children()
line_length = 30
#top vertical line
self.drawings_keys.append( self.append(gui.SvgLine(0, 0, 0, line_length), 'line_top') )
#central box line
self.drawings_keys.append( self.append(flow_chart_graphics.RomboidBox(-self.box_width/2, line_length, self.box_width, self.box_height-line_length, self.box_text_content), 'box') )
#line returns
poly = gui.SvgPolyline(10)
poly.add_coord(0, h-line_length*3)
poly.add_coord(0, h-line_length*2)
poly.add_coord(-w/2, h-line_length*2)
poly.add_coord(-w/2, (self.box_height-line_length)/2 + line_length)
poly.add_coord(-self.box_width/2, (self.box_height-line_length)/2 + line_length)
self.drawings_keys.append( self.append(poly, 'lret') )
poly = gui.SvgPolyline(10)
poly.add_coord(self.box_width/2, (self.box_height-line_length)/2 + line_length)
poly.add_coord(w/2, (self.box_height-line_length)/2 + line_length)
poly.add_coord(w/2, h-line_length*1)
poly.add_coord(0, h-line_length*1)
poly.add_coord(0, h)
self.drawings_keys.append( self.append(poly, 'lendfor') )
polygon = gui.SvgPolygon(10)
polygon.add_coord(-self.box_width/2, (self.box_height-line_length)/2 + line_length)
polygon.add_coord(-self.box_width/2-10, (self.box_height-line_length)/2 + line_length-5)
polygon.add_coord(-self.box_width/2-10, (self.box_height-line_length)/2 + line_length+5)
self.drawings_keys.append( self.append(polygon, 'arrow') )
self.children['arrow'].set_stroke(1, 'black')
self.children['arrow'].set_fill('black')
self.children['line_top'].set_stroke(1, 'black')
self.children['lret'].set_stroke(1, 'black')
self.children['lret'].set_fill('transparent')
self.children['lendfor'].set_stroke(1, 'black')
self.children['lendfor'].set_fill('transparent')
self.children['box'].set_stroke(1, 'black')
class KRLStatementLoop(KRLGenericParser):
pass_to_be_added = True
def __init__(self):
permissible_instructions = ['loop end']
permissible_instructions_dictionary = {k:v for k,v in instructions_defs.items() if k in permissible_instructions}
KRLGenericParser.__init__(self, permissible_instructions_dictionary)
self.box_text_content = 'LOOP infinite'
def parse_single_instruction(self, code_line_original, code_line, instruction_name, match_groups, file_lines):
translation_result_tmp = []
if not instruction_name in ['loop end','']:
self.pass_to_be_added = False
if instruction_name == 'loop end':
self.pass_to_be_added = False
self.stop_statement_found = True
translation_result_tmp.append("}")
_translation_result_tmp, file_lines = KRLGenericParser.parse_single_instruction(self, code_line_original, code_line, instruction_name, match_groups, file_lines)
if len(_translation_result_tmp):
translation_result_tmp.extend(generic_regexes.indent_lines(_translation_result_tmp, 1))
return translation_result_tmp, file_lines
def recalc_size_and_arrange_children(self):
w, h = super(KRLStatementLoop, self).recalc_size_and_arrange_children()
h = h + 30*1 #height is increased by 30 for bottom lines
w = w + 30*2 #to give margins to return and endfor lines
gui._MixinSvgSize.set_size(self, w, h)
self.set_viewbox(-w/2, 0, w, h)
return w, h
def draw(self):
self.box_height = 100
self.box_width = max( len(self.box_text_content) * self.text_letter_width, 200 )
w, h = self.recalc_size_and_arrange_children()
line_length = 30
#top vertical line
self.drawings_keys.append( self.append(gui.SvgLine(0, 0, 0, line_length), 'line_top') )
#central box line
self.drawings_keys.append( self.append(flow_chart_graphics.RomboidBox(-self.box_width/2, line_length, self.box_width, self.box_height-line_length, self.box_text_content), 'box') )
#line returns
poly = gui.SvgPolyline(10)
poly.add_coord(0, h-line_length*1)
poly.add_coord(0, h)
poly.add_coord(-w/2, h)
poly.add_coord(-w/2, (self.box_height-line_length)/2 + line_length)
poly.add_coord(-self.box_width/2, (self.box_height-line_length)/2 + line_length)
self.drawings_keys.append( self.append(poly, 'line') )
#arrow
polygon = gui.SvgPolygon(10)
polygon.add_coord(-self.box_width/2, (self.box_height-line_length)/2 + line_length)
polygon.add_coord(-self.box_width/2-10, (self.box_height-line_length)/2 + line_length-5)
polygon.add_coord(-self.box_width/2-10, (self.box_height-line_length)/2 + line_length+5)
self.drawings_keys.append( self.append(polygon, 'arrow') )
self.children['arrow'].set_stroke(1, 'black')
self.children['arrow'].set_fill('black')
self.children['line_top'].set_stroke(1, 'black')
self.children['line'].set_stroke(1, 'black')
self.children['line'].set_fill('transparent')
self.children['box'].set_stroke(1, 'black')
class KRLStatementFor(KRLGenericParser):
variable = ""
value_begin = ""
value_end = ""
value_step = ""
pass_to_be_added = True
def __init__(self, variable, value_begin, value_end, value_step = None):
self.variable = variable
self.value_begin = value_begin
self.value_end = value_end
self.value_step = value_step
permissible_instructions = ['for end']
permissible_instructions_dictionary = {k:v for k,v in instructions_defs.items() if k in permissible_instructions}
KRLGenericParser.__init__(self, permissible_instructions_dictionary)
self.box_text_content = 'FOR %s=%s TO %s%s'%(variable, value_begin, value_end, '' if value_step is None else 'STEP %s'%value_step)
def parse_single_instruction(self, code_line_original, code_line, instruction_name, match_groups, file_lines):
translation_result_tmp = []
if not instruction_name in ['for end', '']:
self.pass_to_be_added = False
if instruction_name == 'for end':
self.pass_to_be_added = False
self.stop_statement_found = True
translation_result_tmp.append("}")
_translation_result_tmp, file_lines = KRLGenericParser.parse_single_instruction(self, code_line_original, code_line, instruction_name, match_groups, file_lines)
if len(_translation_result_tmp):
translation_result_tmp.extend(generic_regexes.indent_lines(_translation_result_tmp, 1))
return translation_result_tmp, file_lines
def recalc_size_and_arrange_children(self):
w, h = super(KRLStatementFor, self).recalc_size_and_arrange_children()
h = h + 30*3 #height is increased by 30 for bottom lines
w = w + 30*2 #to give margins to return and endfor lines
gui._MixinSvgSize.set_size(self, w, h)
self.set_viewbox(-w/2, 0, w, h)
return w, h
def draw(self):
self.box_height = 100
self.box_width = max( len(self.box_text_content) * self.text_letter_width, 200 )
w, h = self.recalc_size_and_arrange_children()
line_length = 30
#top vertical line
self.drawings_keys.append( self.append(gui.SvgLine(0, 0, 0, line_length), 'line_top') )
#central box line
self.drawings_keys.append( self.append(flow_chart_graphics.ForBox(-self.box_width/2, line_length, self.box_width, self.box_height-line_length, self.box_text_content), 'box') )
#line returns
poly = gui.SvgPolyline(10)
poly.add_coord(0, h-line_length*3)
poly.add_coord(0, h-line_length*2)
poly.add_coord(-w/2, h-line_length*2)
poly.add_coord(-w/2, (self.box_height-line_length)/2 + line_length)
poly.add_coord(-self.box_width/2, (self.box_height-line_length)/2 + line_length)
self.drawings_keys.append( self.append(poly, 'lret') )
#arrow
polygon = gui.SvgPolygon(10)
polygon.add_coord(-self.box_width/2, (self.box_height-line_length)/2 + line_length)
polygon.add_coord(-self.box_width/2-10, (self.box_height-line_length)/2 + line_length-5)
polygon.add_coord(-self.box_width/2-10, (self.box_height-line_length)/2 + line_length+5)
self.drawings_keys.append( self.append(polygon, 'arrow') )
self.children['arrow'].set_stroke(1, 'black')
self.children['arrow'].set_fill('black')
poly = gui.SvgPolyline(10)
poly.add_coord(self.box_width/2, (self.box_height-line_length)/2 + line_length)
poly.add_coord(w/2, (self.box_height-line_length)/2 + line_length)
poly.add_coord(w/2, h-line_length*1)
poly.add_coord(0, h-line_length*1)
poly.add_coord(0, h)
self.drawings_keys.append( self.append(poly, 'lendfor') )
self.children['line_top'].set_stroke(1, 'black')
self.children['lret'].set_stroke(1, 'black')
self.children['lret'].set_fill('transparent')
self.children['lendfor'].set_stroke(1, 'black')
self.children['lendfor'].set_fill('transparent')
self.children['box'].set_stroke(1, 'black')
class KRLStatementIf(KRLGenericParser):
condition = ""
pass_to_be_added = True
nodes_yes = None
nodes_no = None
yes_done = False
def __init__(self, condition):
self.condition = condition
permissible_instructions = ['else','if end']
permissible_instructions_dictionary = {k:v for k,v in instructions_defs.items() if k in permissible_instructions}
self.nodes_yes = []
self.nodes_no = []
KRLGenericParser.__init__(self, permissible_instructions_dictionary)
self.box_text_content = 'IF %s'%(condition)
def append(self, v, *args, **kwargs):
if not self.yes_done:
self.nodes_yes.append(v)
else:
self.nodes_no.append(v)
return super(KRLStatementIf, self).append(v, *args, **kwargs)
def parse_single_instruction(self, code_line_original, code_line, instruction_name, match_groups, file_lines):
translation_result_tmp = []
if not instruction_name in ['else','if end','']:
self.pass_to_be_added = False
if instruction_name == 'else':
self.yes_done = True
#if self.pass_to_be_added:
# translation_result_tmp.append(' pass')
translation_result_tmp.append("}else{")
self.pass_to_be_added = True
if instruction_name == 'if end':
#if self.pass_to_be_added:
# translation_result_tmp.append(' pass')
translation_result_tmp.append("}")
self.pass_to_be_added = False
self.stop_statement_found = True
_translation_result_tmp, file_lines = KRLGenericParser.parse_single_instruction(self, code_line_original, code_line, instruction_name, match_groups, file_lines)
if len(_translation_result_tmp):
translation_result_tmp.extend(generic_regexes.indent_lines(_translation_result_tmp, 1))
return translation_result_tmp, file_lines
def recalc_size_and_arrange_children(self):
#remove all drawings prior to redraw it
for k in self.drawings_keys:
self.remove_child(self.children[k])
self.drawings_keys = []
box_text_size = max( len(self.box_text_content) * self.text_letter_width, 100 )
h = self.box_height
w_max = box_text_size
#estimate self width
for k in self._render_children_list:
v = self.children[k]
v.draw()
w_max = max(w_max, float(v.attr_width))
total_width = (w_max*2+box_text_size)
h_yes = h
for v in self.nodes_yes:
v.set_position(-w_max/2+total_width/2-float(v.attr_width)/2 , h_yes)
h_yes = h_yes + float(v.attr_height)
h_no = h
for v in self.nodes_no:
v.set_position(-total_width/2 + w_max/2 - float(v.attr_width)/2, h_no)
h_no = h_no + float(v.attr_height)
#w_max = w_max * 2 + box_text_size #the width is x3 because it has components at left and at right
h = max(h_yes, h_no)
h = h + 30 #height is increased by 30 for bottom lines
gui._MixinSvgSize.set_size(self, total_width, h)
total_width = (w_max*2+box_text_size)
self.set_viewbox(-total_width/2, 0, total_width, h)
return box_text_size, w_max, total_width, h
def draw(self):
self.box_height = 200
box_text_size, w_max, w, h = self.recalc_size_and_arrange_children()
line_length = 30
#top vertical line
self.drawings_keys.append( gui.SvgSubcontainer.append(self, gui.SvgLine(0, 0, 0, line_length), 'line_top') )
romboid_h = self.box_height-(line_length)
romboid_w = box_text_size
#right horizontal line
self.drawings_keys.append( gui.SvgSubcontainer.append(self, gui.SvgLine(romboid_w/2, romboid_h/2+line_length, w/2-w_max/2 , romboid_h/2+line_length), 'line_right_h') )