summaryrefslogtreecommitdiff
path: root/lib/compiler/external_compiler.tcl
blob: 0b310d704d234b7235422b7855b304c34553bb32 (plain)
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
1001
1002
1003
1004
1005
1006
1007
1008
1009
1010
1011
1012
1013
1014
1015
1016
1017
1018
1019
1020
1021
1022
1023
1024
1025
1026
1027
1028
1029
1030
1031
1032
1033
1034
1035
1036
1037
1038
1039
1040
1041
1042
1043
1044
1045
1046
1047
1048
1049
1050
1051
1052
1053
1054
1055
1056
1057
1058
1059
1060
1061
1062
1063
1064
1065
1066
1067
1068
1069
1070
1071
1072
1073
1074
1075
1076
1077
1078
1079
1080
1081
1082
1083
1084
1085
1086
1087
1088
1089
1090
1091
1092
1093
1094
1095
1096
1097
1098
1099
1100
1101
1102
1103
1104
1105
1106
1107
1108
1109
1110
1111
1112
1113
1114
1115
1116
1117
1118
1119
1120
1121
1122
1123
1124
1125
1126
1127
1128
1129
1130
1131
1132
1133
1134
1135
1136
1137
1138
1139
1140
1141
1142
1143
1144
1145
1146
1147
1148
1149
1150
1151
1152
1153
1154
1155
1156
1157
1158
1159
#!/usr/bin/tclsh
# Part of MCU 8051 IDE ( http://http://www.moravia-microsystems.com/mcu8051ide )

############################################################################
#    Copyright (C) 2007, 2008, 2009, 2010, 2011, 2012 by Martin Ošmera     #
#    martin.osmera@gmail.com                                               #
#                                                                          #
#    Copyright (C) 2014 by Moravia Microsystems, s.r.o.                    #
#    martin.osmera@moravia-microsystems.com                                #
#                                                                          #
#    This program is free software; you can redistribute it and#or modify  #
#    it under the terms of the GNU General Public License as published by  #
#    the Free Software Foundation; either version 2 of the License, or     #
#    (at your option) any later version.                                   #
#                                                                          #
#    This program is distributed in the hope that it will be useful,       #
#    but WITHOUT ANY WARRANTY; without even the implied warranty of        #
#    MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the         #
#    GNU General Public License for more details.                          #
#                                                                          #
#    You should have received a copy of the GNU General Public License     #
#    along with this program; if not, write to the                         #
#    Free Software Foundation, Inc.,                                       #
#    59 Temple Place - Suite 330, Boston, MA  02111-1307, USA.             #
############################################################################

# >>> File inclusion guard
if { ! [ info exists _EXTERNAL_COMPILER_TCL ] } {
set _EXTERNAL_COMPILER_TCL _
# <<< File inclusion guard

# --------------------------------------------------------------------------
# DESCRIPTION
# Implements interface to external compilers
# --------------------------------------------------------------------------

namespace eval ExternalCompiler {
	variable input_filename	;# String: Name of file to compile (without extension)
	variable compiler_used	;# Int: Compiler ID (1 == ASEM-51; 2 == ASL; 3 == AS31, other values have no meaning)
	variable project_dir	;# String: Project directory
	variable working_dir	;# String: Compiler working directory
	variable input_file_base;# String: Full file name of the primary source file

	## Int: Preffered assembler
	 # 0 - Native MCU 8051 IDE assembler
	 # 1 - ASEM-51
	 # 2 - ASL
	 # 3 - AS31
	variable selected_assembler	0
	variable selected_assembler_def	0	;# Int: Default value for $selected_assembler

	#
	## External assembler configuration
	#

	## ASEM-51
	 # Default ASEM-51 assembler configuration
	variable assembler_ASEM51_config_def {
		--omf-51	0
		--columns	0
		--verbose	1
		-i		{}
		custom		{}
	}
	 # Current ASEM-51 assembler configuration
	variable assembler_ASEM51_config
	 # Default ASEM-51 additional configuration
	variable assembler_ASEM51_addcfg_def {
		adf		1
	}
	 # Current ASEM-51 additional configuration
	variable assembler_ASEM51_addcfg

	## ASL
	 # Array: ASL additional configuration
	variable assembler_ASL_addcfg
	 # Default ASL assembler configuration
	variable assembler_ASL_config_def {
		-A	0		-a	0
		-C	0		-c	0
		-h	0		-I	1
		-L	1		-M	0
		-P	0		-n	0
		-quiet	0		-s	1
		-u	0		-U	0
		-w	0		-x	0

		-r	{}		-i	{}
		-g	{MAP}		-cpu	{8051}
		custom	{}
	}
	 # Current ASL assembler configuration
	variable assembler_ASL_config
	 # Default ASL additional configuration
	variable assembler_ASL_addcfg_def {
		ihex		1
		adf		1
	}
	 # Current ASL additional configuration
	variable assembler_ASL_addcfg

	## AS31
	 # Array: AS31 additional configuration
	variable assembler_AS31_addcfg
	 # Default AS31 assembler configuration
	variable assembler_AS31_config_def {
		-l	1		-F	{hex}
		-A	{}		custom	{}
	}
	 # Current AS31 assembler configuration
	variable assembler_AS31_config
	 # Default AS31 additional configuration
	variable assembler_AS31_addcfg_def {
		adf		1
	}
	 # Current ASL additional configuration
	variable assembler_AS31_addcfg

	## SDCC
	 # Default SDCC boolean options
	variable sdcc_bool_options_def {
		--verbose			1
		-V				1
		-S				0
		--compile-only			0
		--preprocessonly		0
		--c1mode			0
		--print-search-dirs		0
		--use-stdout			0
		--nostdlib			0
		--nostdinc			0
		--less-pedantic			0
		--debug				1
		--cyclomatic			0
		--fdollars-in-identifiers	0
		--funsigned-char		0
		--xstack			0
		--int-long-reent		0
		--float-reent			0
		--main-return			0
		--xram-movc			0
		--profile			0
		--fommit-frame-pointer		0
		--all-callee-saves		0
		--stack-probe			0
		--parms-in-bank1		0
		--no-xinit-opt			0
		--no-c-code-in-asm		0
		--no-peep-comments		0
		--fverbose-asm			0
		--short-is-8bits		0
		--stack-auto			0
		--nooverlay			1
		--nogcse			0
		--nolabelopt			0
		--noinvariant			0
		--noinduction			1
		--nojtbound			0
		--noloopreverse			0
		--no-peep			0
		--no-reg-params			0
		--peep-asm			0
		--opt-code-speed		0
		--opt-code-size			0
		--out-fmt-ihx			0
		--out-fmt-s19			0
	}
	 # Current SDCC boolean options
	variable sdcc_bool_options
	 # Default SDCC string options
	variable sdcc_string_options_def {
		model		--model-small
		standard	--std-sdcc89
		stack           {}
		custom		{}
	}
	 # Current SDCC string options
	variable sdcc_string_options
	 # Default SDCC optional string options
	variable sdcc_optional_string_options_def {
		--codeseg	{}
		--constseg	{}
		--lib-path	{}
		--xram-loc	{}
		--xstack-loc	{}
		--code-loc	{}
		--stack-loc	{}
		--data-loc	{}
		--stack-size	{}
	}
	 # Current SDCC optional string options
	variable sdcc_optional_string_options
	 # Default semicolon separated optional string options
	variable sdcc_scs_string_options_def {
		-I			{}
		-l			{}
		-L			{}
		--disable-warning	{}
	}
	 # Current semicolon separated optional string options
	variable sdcc_scs_string_options

	## Make utility
	 # General options, this is an array!
	variable makeutil_config
	 # Default values for the eneral options
	variable makeutil_config_def {
		c_ena	0
		c_file	{}
		co_file	{}
		ct_file	{}
	}

	## Make backup copies for files with the given extensions and remove original files
	 # (input_filename.extension -> input_filename.extension~)*
	 # @parm List suffixes - List of file extensions (e.g. {asm c h})
	 # @return void
	proc backup_and_remove {suffixes} {
		variable input_filename	;# String: Name of file to compile (without extension)

		foreach ext $suffixes {
			catch {
				file rename -force -- "$input_filename.$ext" "$input_filename.$ext~"
			}
		}
	}

	## Start SDCC (ANSI C compiler)
	 # @parm String work_dir	- Current working directory
	 # @parm String input_file	- C source file to compile
	 # @parm Int iram		- Amount of internal data memory
	 # @parm Int xram		- Amount of external data memory
	 # @parm Int code		- Amount of overall program memory
	 # @return Int - Compiler PID
	proc compile_C {work_dir input_file iram xram code} {
		variable input_filename	;# String: Name of file to compile (without extension)
		variable compiler_used	;# Int: Compiler ID (1 == ASEM-51; 2 == ASL; 3 == AS31, other values have no meaning)
		variable makeutil_config;# Make utility - general options

		set compiler_used 0
		set input_filename [file rootname $input_file]
		backup_and_remove {asm cdb ihx}
		set sdcc_opts [determinate_sdcc_options]
		if {${::PROGRAM_AVAILABLE(sdcc-sdcc)}} {
			set sdcc_cmd {sdcc-sdcc}
		} else {
			set sdcc_cmd {sdcc}
		}

		# Normal way (POSIX)
		if {!$::MICROSOFT_WINDOWS} {
			# Start GNU make
			if {$makeutil_config(c_ena) && ${::PROGRAM_AVAILABLE(make)}} {
				::X::messages_text_append [::Compiler::msgc {S}][mc "\n\nStarting make ..."]
				::X::messages_text_append "\ncd \"${work_dir}\"\nmake -f \"${makeutil_config(c_file)}\" ${makeutil_config(co_file)} ${makeutil_config(ct_file)}"

			# Start SDCC
			} else {
				::X::messages_text_append [::Compiler::msgc {S}][mc "\n\nStarting compiler ..."]
				::X::messages_text_append "\ncd \"${work_dir}\"\n${sdcc_cmd} -mmcs51 --iram-size ${iram} --xram-size ${xram} --code-size ${code} ${sdcc_opts} \"${input_file}\""
			}
		# Microsoft Windows way
		} else {
			regsub -all {/} $work_dir "\\\\\\\\" work_dir
			regsub -all {/} $input_file "\\\\\\\\" input_file

			::X::messages_text_append [::Compiler::msgc {S}][mc "\n\nStarting compiler ..."]
			::X::messages_text_append "\ncd \"${work_dir}\"\n${sdcc_cmd} -mmcs51 --iram-size ${iram} --xram-size ${xram} --code-size ${code} ${sdcc_opts} \"${input_file}\""
		}
		if {[catch {
			cd $work_dir
		}]} then {
			::X::messages_text_append [::Compiler::msgc {E}][mc "\nError: Unable to change working directory to '%s'" $work_dir]
		}
		if {!$::MICROSOFT_WINDOWS} {	;# Normal way (POSIX)
			# Start GNU make
			if {$makeutil_config(c_ena) && ${::PROGRAM_AVAILABLE(make)}} {
				return [exec -- /bin/sh -c "make -f \"${makeutil_config(c_file)}\" ${makeutil_config(co_file)} ${makeutil_config(ct_file)}" |&	\
						tclsh "${::LIB_DIRNAME}/external_command.tcl"		\
						[tk appname]						\
						{::ExternalCompiler::ext_compilation_complete 1}	\
						::X::compilation_message &				\
				]

			# Start SDCC
			} else {
				return [exec -- /bin/sh -c "$sdcc_cmd -mmcs51	\
					--iram-size $iram			\
					--xram-size $xram			\
					--code-size $code 			\
					$sdcc_opts \"$input_file\"" |&		\
						tclsh "${::LIB_DIRNAME}/external_command.tcl"	\
						[tk appname]					\
						{::ExternalCompiler::ext_compilation_complete 1}\
						::X::compilation_message &			\
				]
			}
		} else { ;# Microsoft Windows way
			eval [subst -nocommands {
				return [exec -- "${::INSTALLATION_DIR}/startsdcc.bat"		\
					"${work_dir}"						\
					$sdcc_opts						\
					"${input_file}"						\
						|&						\
					"${::INSTALLATION_DIR}/external_command.bat"		\
					"${::INSTALLATION_DIR}/external_command.exe"		\
					"[tk appname]"						\
					{::ExternalCompiler::ext_compilation_complete 1}	\
					::X::compilation_message &				\
				]
			}]
		}
	}

	## Start AS31 (Assembler)
	 # @parm String work_dir		- Current working directory
	 # @parm String input_file		- Assembler source file to compile
	 # @parm String project_directory	- Project directory (for debug file)
	 # @return Int - Compiler PID
	proc as31_compile {work_dir input_file project_directory} {
		variable project_dir	;# String: Project directory
		variable compiler_used	;# Int: Compiler ID (1 == ASEM-51; 2 == ASL; 3 == AS31, other values have no meaning)
		variable input_filename	;# String: Name of file to compile (without extension)
		variable working_dir	;# String: Compiler working directory
		variable input_file_base;# String: Full file name of the primary source file
		global argv

		set compiler_used 3
		set project_dir $project_directory
		set input_file_base [file normalize [file join $work_dir $input_file]]
		set input_filename [file rootname $input_file_base]
		set working_dir $work_dir

		set as31_options [determinate_as31_options]
		::X::messages_text_append [::Compiler::msgc {S}][mc "\n\nStarting compiler ..."]
		::X::messages_text_append "\ncd \"$work_dir\"\nas31 $as31_options \"$input_file\""
		if {[catch {
			cd $work_dir
		}]} then {
			::X::messages_text_append [::Compiler::msgc {E}][mc "\nError: Unable to change working directory to '%s'" $work_dir]
		}
		backup_and_remove {adf hex lst}

		return [exec -- /bin/sh -c "as31 $as31_options \"$input_file\"" |&	\
			tclsh "${::LIB_DIRNAME}/external_command.tcl" "[tk appname]"	\
			::ExternalCompiler::ext_compilation_complete ::X::compilation_message &	\
		]
	}

	## Start ASEM-51 (Assembler)
	 # @parm String work_dir		- Current working directory
	 # @parm String input_file		- Assembler source file to compile
	 # @parm String project_directory	- Project directory (for debug file)
	 # @return Int - Compiler PID
	proc asem51_compile {work_dir input_file project_directory} {
		variable project_dir	;# String: Project directory
		variable compiler_used	;# Int: Compiler ID (1 == ASEM-51; 2 == ASL; 3 == AS31, other values have no meaning)
		variable input_filename	;# String: Name of file to compile (without extension)
		variable working_dir	;# String: Compiler working directory
		variable input_file_base;# String: Full file name of the primary source file
		global argv

		set compiler_used 1
		set project_dir $project_directory
		set input_file_base [file normalize [file join $work_dir $input_file]]
		set input_filename [file rootname $input_file_base]
		set working_dir $work_dir

		::X::messages_text_append [::Compiler::msgc {S}][mc "\n\nStarting compiler ..."]

		set asem51_options [determinate_asem51_options]
		if {$::MICROSOFT_WINDOWS} {
			regsub -all -- {--verbose} $asem51_options {} asem51_options
			regsub -all -- {--} $asem51_options {/} asem51_options
			regsub -all -- {=} $asem51_options {:} asem51_options
			regsub -all -- {;} $asem51_options { /includes:} asem51_options
			regsub -all {/} $work_dir "\\\\\\\\" work_dir
			regsub -all {/} $input_file "\\\\\\\\" input_file
			::X::messages_text_append "\ncd \"$work_dir\"\nasem \"$input_file\" $asem51_options"
		} else {
			::X::messages_text_append "\ncd \"$work_dir\"\nasem $asem51_options \"$input_file\""
		}
		if {[catch {
			cd $work_dir
		}]} then {
			::X::messages_text_append [::Compiler::msgc {E}][mc "\nError: Unable to change working directory to '%s'" $work_dir]
		}
		backup_and_remove {adf hex lst omf}

		if {!$::MICROSOFT_WINDOWS} {	;# Normal way (POSIX)
			return [exec -- /bin/sh -c "asem $asem51_options \"$input_file\"" |&	\
				tclsh "${::LIB_DIRNAME}/external_command.tcl" "[tk appname]"	\
				::ExternalCompiler::ext_compilation_complete ::X::compilation_message &	\
			]
		} else { ;# Microsoft Windows way
			eval [subst -nocommands {
				return [exec -- "${::INSTALLATION_DIR}/startasem.bat"		\
					"${work_dir}"						\
					"${input_file}"						\
					$asem51_options						\
						|&						\
					"${::INSTALLATION_DIR}/external_command.bat"		\
					"${::INSTALLATION_DIR}/external_command.exe"		\
					"[tk appname]"						\
					{::ExternalCompiler::ext_compilation_complete 1}	\
					::X::compilation_message &				\
				]
			}]
		}
	}

	## Start ASL (Assembler)
	 # @parm String work_dir		- Current working directory
	 # @parm String input_file		- Assembler source file to compile
	 # @parm String project_directory	- Project directory (for debug file)
	 # @return Int - Compiler PID
	proc asl_compile {work_dir input_file project_directory} {
		variable project_dir		;# String: Project directory
		variable compiler_used		;# Int: Compiler ID (1 == ASEM-51; 2 == ASL; 3 == AS31, other values have no meaning)
		variable input_filename		;# String: Name of file to compile (without extension)
		variable assembler_ASL_addcfg	;# Current ASL additional configuration
		global argv

		set compiler_used 2
		set project_dir $project_directory
		set input_filename [file join $work_dir [file rootname $input_file]]
		backup_and_remove {hex lst map adf}
		set asl_opts [determinate_asl_options]
		set additional_commands {}
		if {$assembler_ASL_addcfg(ihex)} {
			append additional_commands {&& p2hex "} $input_filename.p {" "} $input_filename.hex {"}
		}

		::X::messages_text_append [::Compiler::msgc {S}][mc "\n\nStarting compiler ..."]
		::X::messages_text_append "\ncd \"$work_dir\"\nasl $asl_opts \"$input_file\""
		if {[catch {
			cd $work_dir
		}]} then {
			::X::messages_text_append [::Compiler::msgc {E}][mc "\nError: Unable to change working directory to '%s'" $work_dir]
		}
		return [exec -- /bin/sh -c "asl $asl_opts \"$input_file\" $additional_commands" |&	\
			tclsh "${::LIB_DIRNAME}/external_command.tcl" "[tk appname]"	\
			::ExternalCompiler::ext_compilation_complete ::X::compilation_message &	\
		]
	}

	## Create file containg MD5 hashes of source files
	 # Suitable for C language only!
	 # This file will be later used to chech wheter any of these files was changed or not.
	 # @return void
	proc create_hashes_file {} {
		variable input_filename		;# String: Name of file to compile (without extension)

		# List of files included files in the main file
		set included_files [list]

		set cbd_file {}	;# We will set this variable later ...

		# Open C DeBug file generated by SDCC compiler
		if {[catch {
			set cdb_file [open $input_filename.cdb r]
		}]} then {
			::X::messages_text_append [::Compiler::msgc {E}][mc "\nUnable to find \"%s\"" [file rootname $input_filename].cdb]
			return
		}

		# Open the hashes file for writing (possibly create the file)
		if {[catch {
			set hs_file [open $input_filename.hashes w 0640]
		}]} then {
			::X::messages_text_append [::Compiler::msgc {E}][mc "\nUnable to create \"%s\"" [file rootname $input_filename].hashes]
			catch {close $cbd_file}
			return
		}

		# Iterate over lines in the C DeBug file and list all included source files
		while {![eof $cdb_file]} {
			set line [gets $cdb_file]

			if {[string first {L:C$} $line]} {
				continue
			}

			set line [string replace $line 0 3]
			set line [string replace $line [string first {$} $line] end]

			if {[lsearch -ascii -exact $included_files $line] == -1} {
				lappend included_files $line
			}
		}

		# Compute MD5 hash for each of the included files
		foreach filename $included_files {
			catch {
				puts $hs_file "[::md5::md5 -hex -file $filename] \"$filename\" "
			}
		}

		# Clean up
		catch {close $cdb_file}
		catch {close $hs_file}
	}

	## This function must be called after exteral compiler finished its work
	 # @parm Int action=0 - Action to perform after successfull compilation
	 #	0 - No action
	 #	1 - Copy <file>.ihx to <file>.hex
	 # @return void
	proc ext_compilation_complete {{action 0}} {
		variable input_filename		;# String: Name of file to compile (without extension)
		variable compiler_used		;# Int: Compiler ID (1 == ASEM-51; 2 == ASL; 3 == AS31, other values have no meaning)
		variable assembler_ASEM51_addcfg;# Current ASEM-51 assembler configuration
		variable assembler_ASL_addcfg	;# Current ASL additional configuration
		variable assembler_AS31_addcfg	;# Current AS31 additional configuration

		# Compilation successfull
		if {$::X::compilation_successfull} {

			# Create MCU 8051 IDE assembler debug file -
			switch -- $compiler_used {
				1 {	;# - from ASEM-51 code listing (*.lst)
					if {$assembler_ASEM51_addcfg(adf) && ![asem_51_analyze]} {
						::X::messages_text_append [::Compiler::msgc {E}][mc "\nUnable to find \"%s\"\n\tMCU 8051 IDE debug file (*.adf) could not be generated\n\tPLEASE CHECK YOUR %s CONFIGURATION" [file rootname $input_filename].lst {ASEM-51}]
					}
				}
				2 {	;# - from ASL native debug file (*.map)
					if {$assembler_ASL_addcfg(adf) && ![asl_analyze]} {
						::X::messages_text_append [::Compiler::msgc {E}][mc "\nUnable to find \"%s\"\n\tMCU 8051 IDE debug file (*.adf) could not be generated\n\tPLEASE CHECK YOUR %s CONFIGURATION" [file rootname $input_filename].map {ASL}]
					}
				}
				3 {	;# - from AS31 code listing file (*.lst)
					if {$assembler_ASL_addcfg(adf) && ![as31_analyze]} {
						::X::messages_text_append [::Compiler::msgc {E}][mc "\nUnable to find \"%s\"\n\tMCU 8051 IDE debug file (*.adf) could not be generated\n\tPLEASE CHECK YOUR %s CONFIGURATION" [file rootname $input_filename].lst {AS31}]
					}
				}
				0 {	;# SDCC used: Create .hashes file from .cdb file
					create_hashes_file
				}
			}

			if {$::X::compilation_successfull} {
				::X::messages_text_append [::Compiler::msgc {S}][mc "\nCompilation successful"]
			}

			# Perform specified after successfull compilation
			switch -- $action {
				0 {	;# No action
				}
				1 {	;# Copy <file>.ihx to <file>.hex
					catch {
						file rename -force -- "$input_filename.hex" "$input_filename.hex~"
					}
					catch {
						file copy -force -- "$input_filename.ihx" "$input_filename.hex"
					}
				}
			}
		}

		# Compilation failed
		if {!$::X::compilation_successfull} {
			::X::messages_text_append [::Compiler::msgc {E}][mc "\nCompilation FAILED"]
		}
		::X::ext_compilation_complete
	}

	## Create MCU 8051 IDE assembler debug file from AS31 code listing
	 # @return Bool - 1 == success; 0 == failure
	proc as31_analyze {} {
		variable project_dir	;# String: Project directory
		variable working_dir	;# String: Compiler working directory
		variable input_filename	;# String: Name of file to compile (without extension)
		variable input_file_base;# String: Full file name of the primary source file

		# Local variables
		set line_number		0	;# Line number in LST file
		set adf_line		0	;# Line number to record in ADF file
		set adf_code		{}	;# Processor code in decimal representation (for ADF file)
		set address		{}	;# Address in code memory
		set processor_code	{}	;# Processor code read from LST file

		# Try to open code listing file and some tempotary debug file
		if {[catch {
			set lst_file [open $input_filename.lst r]
			set adf_file [open $input_filename.adf w 0640]
		} result]} then {
			::X::messages_text_append [::Compiler::msgc {E}][mc "File access error:\n%s" $result]
			return 0
		}

		# Write file header
		puts $adf_file "# Assembler Debug File created by ${::APPNAME}"
		puts $adf_file "# Used assembler: AS31"

		# Write MD5 of the source file
		puts -nonewline $adf_file [::md5::md5 -hex -file $input_file_base]
		puts -nonewline $adf_file { }
		puts -nonewline $adf_file [string replace $input_file_base 0 [string length $project_dir]]

		# One pass compilation LST -> ADF
		while {![eof $lst_file]} {
			incr line_number

			# Read one line from the code listing
			set line [string range [gets $lst_file] 0 17]

			# Lines which does not contain address or code will be ignored
			#+ but line number counter must be still incremented on these lines
			if {[regexp {^\s*$} $line]} {
				continue
			}

			set address [string trim [string range $line 0 3]]
			set code [string trim [string range $line 6 17]]

			# If there is no processor code then skip the line
			if {$code == {}} {
				continue
			}

			# Convert processor code to format suitable for this application,
			#+ that means convert list of HH to list of DDD
			if {[catch {
				set adf_code {}
				foreach h $code {
					scan $h %x h
					lappend adf_code $h
				}
			}]} then {
				::X::messages_text_append [::Compiler::msgc {E}][mc "Unable to understand formulation at %s in file %s" $line_number $input_filename.lst]
				close $lst_file
				close $adf_file
				return 0
			}

			# If there is no address then append the current code to the last ADF record
			if {$address == {}} {
				puts -nonewline $adf_file { }
				puts -nonewline $adf_file $adf_code
			} else {
				if {[catch {
					scan $address %x address
				}]} then {
					::X::messages_text_append [::Compiler::msgc {E}][mc "Unable to understand formulation at %s in file %s" $line_number $input_filename.lst]
					close $lst_file
					close $adf_file
					return 0
				}
				set adf_line $line_number

				puts -nonewline $adf_file "\n0 $adf_line $address $adf_code"
			}
		}

		# Close all files and finalize ...
		puts $adf_file {}
		close $lst_file
		close $adf_file
		return 1
	}

	## Create MCU 8051 IDE assembler debug file from ASEM-51 code listing
	 # @return Bool - 1 == success; 0 == failure
	proc asem_51_analyze {} {
		variable project_dir	;# String: Project directory
		variable working_dir	;# String: Compiler working directory
		variable input_filename	;# String: Name of file to compile (without extension)
		variable input_file_base;# String: Full file name of the primary source file

		# Local variables
		array set line_number	{}	;# Array of Int: Line number within certain inslusion level
		set inclusion_level	0	;# Int: Current inclusion level
		set file_number		0	;# Int: Current file number (number of included file in $included_files)
		set file_number_changed	0	;# Bool: Next line includes new file
		set address		0	;# Int(H|D): Address in machine code
		set code		{}	;# List of Int(H|D): Machine code
		set included_files	[list $input_file_base]	;# List of all included files (unique, unsorted)

		# Try to open code listing file and some tempotary debug file
		if {[catch {
			set lst_file [open $input_filename.lst r]
			set adf_file [open $input_filename._adf w 0640]
		} result]} then {
			::X::messages_text_append [::Compiler::msgc {E}][mc "File access error:\n%s" $result]
			return 0
		}

		# Initialize line number counter
		for {set i 0} {$i < 100} {incr i} {
			set line_number($i) 0
		}

		# One pass compilation LST -> ADF
		while {![eof $lst_file]} {
			# Read 1 line
			set line [gets $lst_file]

			# Normal line corresponding to certain line in source code
			if {[regexp {^ *\d+:(..)?} $line inclusion_level]} {
				# Extract numbers after "line_num: inc_lvl "
				set line [string range $line [string length $inclusion_level] end]
				regexp {^[0-9a-fA-F\s]+} $line code

				# Determinate address and machine code
				set address [lindex $code 0]
				set code [lrange $code 1 end]

				# Determinate inclusion level
				set inclusion_level [string trim [string range $inclusion_level end-1 end]]
				if {$inclusion_level == {} || [string index $inclusion_level end] == {:}} {
					set inclusion_level 0
					set file_number 0
				}
				incr line_number($inclusion_level)

			# Continuation of previous unfinished line
			} elseif {![string first {	  } $line]} {
				set address [lindex $line 0]
				set code [lrange $line 1 end]

			# Other lines
			} else {
				continue
			}

			# Detect directive "$INCLUDE(file)"
			if {[regexp -nocase -- {.*\$include\s*\([^\(\)]+\)} $line line]} {
				regsub {;.+$} $line {} line
				set line [string trim $line]
				regexp -nocase --  {\$include\s*\([^\(\)]+\)} $line line
				if {$line == {}} {
					continue
				}
				set line [string replace $line 0 7]
				set line [string trim $line {( )}]
				set line [file normalize [file join $working_dir $line]]
				set file_number_changed 1
				set file_number [lsearch -ascii -exact $included_files $line]
				if {$file_number == -1} {
					set file_number [llength $included_files]
					lappend included_files $line
				}
				continue
			}

			# Next file included -> Reset lines counter
			if {$file_number_changed} {
				set line_number($inclusion_level) 1
				set file_number_changed 0
			}

			# Convert machine code from hexadecimal to decimal value
			set code_dec {}
			foreach byte $code {
				if {[string length $byte] != 2 || ![string is xdigit -strict $byte]} {
					break
				}
				scan $byte %x byte
				lappend code_dec $byte
			}

			# Machine code must not be empty
			if {$code_dec == {}} {continue}

			# Check for valid address
			if {[string length $address] != 4 || ![string is xdigit -strict $address]} {
				continue
			}

			# Write line to tempotary debug file
			scan $address %x address
			puts -nonewline $adf_file [list $file_number $line_number($inclusion_level) $address]
			puts -nonewline $adf_file { }
			puts $adf_file $code_dec
		}
		close $adf_file

		# Open final debug file
		if {[catch {
			set adf_file [open $input_filename.adf w 0640]
		} result]} then {
			::X::messages_text_append [::Compiler::msgc {E}][mc "File access error:\n%s" $result]
			return 0
		}
		# Write file header
		puts $adf_file "# Assembler Debug File created by ${::APPNAME}"
		puts $adf_file "# Used assembler: ASEM-51"
		# Create list of included files with MD5 hashes
		set hashes_and_files {}
		set project_dir_len [string length $project_dir]
		foreach filename $included_files {
			if {[catch {
				lappend hashes_and_files [::md5::md5 -hex -file $filename]
			} result]} then {
				lappend hashes_and_files 0
				::X::messages_text_append [::Compiler::msgc {E}][mc "File access error:\n%s" $result]
			}
			if {![string first $project_dir $filename]} {
				set filename [string replace $filename 0 $project_dir_len]
			}
			lappend hashes_and_files $filename
		}
		# Write list of included files
		puts $adf_file $hashes_and_files
		# Copy content of tempotary debug file to final debug file
		if {[catch {
			set adf__file [open $input_filename._adf r]
		} result]} then {
			::X::messages_text_append [::Compiler::msgc {E}][mc "File access error:\n%s" $result]
			return 0
		}
		while {![eof $adf__file]} {
			puts $adf_file [gets $adf__file]
		}

		# Close all files and delete tempotary file
		close $adf__file
		close $lst_file
		close $adf_file
		file delete -force $input_filename._adf
		return 1
	}

	## Create MCU 8051 IDE assembler debug file from ASL code listing
	 # @return Bool - 1 == success; 0 == fail
	proc asl_analyze {} {
		variable project_dir	;# String: Project directory
		variable input_filename	;# String: Name of file to compile (without extension)

		# Try to open all required files
		if {[catch {
			set map_file [open $input_filename.map r]	;# ASL debug file
			set hex_file [open $input_filename.hex r]	;# Machine code
			set adf_file [open $input_filename.adf w 0640]	;# MCU 8051 IDE debug file
		} result]} then {
			::X::messages_text_append [::Compiler::msgc {E}][mc "File access error:\n%s" $result]
			return 0
		}

		# Load machine code
		::IHexTools::free_resources
		if {![::IHexTools::load_hex_data [read $hex_file]]} {
			::X::messages_text_append [::Compiler::msgc {E}][mc "Compilation error:\nFile \"%s\" is not a valid Intel® HEX 8 file" $input_filename.hex]
			return 0
		}
		close $hex_file

		# Initialize local variables
		set filenames		{}
		set hashes_and_files	{}
		set filename		{}
		set project_dir_len	[string length $project_dir]
		set read_values		0

		## 1st pass
		 # Determinate list of included files (and list of files and MD5 hashes)
		while {![eof $map_file]} {
			# Get significant line from the code
			set line [gets $map_file]
			if {$line == {Segment CODE}} {
				set read_values 1
				continue
			}
			if {$line == {}} {
				break
			}
			if {!$read_values} {
				continue
			}

			# Ignore lines which doesn't start with "File "
			if {[string first {File } $line]} {
				continue
			}

			# Determinate raw name of included file
			set filename [string replace $line 0 4]

			# Adjust list of included files
			if {[lsearch $filenames $filename] != -1} {
				lappend filenames $filename
				continue
			}

			# Determinate final file name and its MD5 hash
			lappend filenames $filename
			set filename [file join $project_dir [file normalize $filename]]
			if {[catch {
				lappend hashes_and_files [::md5::md5 -hex -file $filename]
			} result]} then {
				::X::messages_text_append [::Compiler::msgc {E}][mc "\nFile access error:\n%s" $result]
				lappend hashes_and_files {0}
			}
			if {![string first $project_dir $filename]} {
				set filename [string replace $filename 0 $project_dir_len]
			}

			# Adjust list of files and MD5 hashes
			lappend hashes_and_files $filename
			continue
		}

		# Create ADF file header
		seek $map_file 0
		puts $adf_file "# Assembler Debug File created by ${::APPNAME}"
		puts $adf_file "# Used assembler: ASL"
		puts $adf_file $hashes_and_files
		unset hashes_and_files

		## 2nd (final) pass
		 # Create ADF (Assembler Debug File)
		set last_line		-1	;#
		set last_address	-1	;#
		set last_file_num	0	;#
		set line_number		0	;#
		set file_number		0	;#
		set read_values		0	;#
		while {![eof $map_file]} {
			# Get significant line from the code
			set line [gets $map_file]
			if {$line == {Segment CODE}} {
				set read_values 1
				continue
			}
			if {$line == {}} {
				break
			}
			if {!$read_values} {
				continue
			}

			# Change file number
			if {![string first {File } $line]} {
				set file_number [lsearch $filenames [string replace $line 0 4]]
				continue
			}

			# Create ADF record(s)
			foreach item $line {
				# Determinate line number and address
				set item [split $item {:}]
				set line_number [lindex $item 0]
				scan [lindex $item 1] %x address

				# Handle firts record (first of all)
				if {$last_line == -1} {
					set last_line $line_number
					set last_address $address
					set last_file_num $file_number
					continue
				}

				# Write record
				write_to_adf_from_hex $adf_file $last_address	\
					[expr {$address - 1}] $last_line $last_file_num
				set last_line $line_number
				set last_address $address
				set last_file_num $file_number
			}
		}

		# Write last record (last of all)
		if {$last_line != -1} {
			write_to_adf_from_hex $adf_file $last_address	\
				${::IHexTools::highest_addr}	\
				$last_line $last_file_num
		}

		# Clean up
		::IHexTools::free_resources
		close $map_file
		close $adf_file
		return 1
	}

	## Write record to MCU 8051 IDE assembler debug file (*.adf)
	 # Auxiliary procedure for procedure asl_analyze
	 # @parm Chanel adf_file	- Target file
	 # @parm Int start_address	- Starting address in machine code
	 # @parm Int end_address	- End address in machine code
	 # @parm Int linenum		- Line number
	 # @parm Int filenum		- File number (ID of included file)
	 # @return void
	proc write_to_adf_from_hex {adf_file start_address end_address linenum filenum} {
		# Get machine code from NS ::IHexTools
		set code {}
		for {set i $start_address} {$i <= $end_address} {incr i} {
			set val [::IHexTools::get_value $i]
			if {$val > -1} {
				lappend code [expr "0x$val"]
			} else {
				lappend code 0
			}
		}

		# Write to file
		if {$linenum == {}} {
			set linenum 0
		}
		puts -nonewline $adf_file [list $filenum $linenum $start_address]
		puts -nonewline $adf_file { }
		puts $adf_file $code
	}

	## Determinate CLI options for external compiler sdcc
	 # @return String - Options for sdcc
	proc determinate_sdcc_options {} {
		variable sdcc_bool_options		;# Default SDCC boolean options
		variable sdcc_string_options		;# Default SDCC string options
		variable sdcc_optional_string_options	;# Default SDCC optional string options
		variable sdcc_scs_string_options	;# Default semicolon separated optional string options

		set result {}

		# Boolean options
		foreach key [array names sdcc_bool_options] {
			if {$sdcc_bool_options($key)} {
				append result { } $key
			}
		}

		# String options
		foreach key [array names sdcc_string_options] {
			append result { } [regsub -all {\n} $sdcc_string_options($key) {}]
		}

		# Optional string options
		foreach key [array names sdcc_optional_string_options] {
			set value $sdcc_optional_string_options($key)
			if {$value != {}} {
				if {[regexp {\s} $value]} {
					append result { } $key { } "\"" $value "\""
				} else {
					append result { } $key { } $value
				}
			}
		}

		# Semicolon separated optional string options
		foreach key [array names sdcc_scs_string_options] {
			set values $sdcc_scs_string_options($key)
			foreach value [split $values {;}] {
				if {$value != {}} {
					if {[regexp {\s} $value]} {
						append result { } $key { } "\"" $value "\""
					} else {
						append result { } $key { } $value
					}
				}
			}
		}

		return $result
	}

	## Determinate CLI options for external assembler ASEM-51
	 # @return String - Options for ASEM-51
	proc determinate_asem51_options {} {
		variable assembler_ASEM51_config	;# Current ASEM-51 assembler configuration

		set result $assembler_ASEM51_config(custom)
		if {$assembler_ASEM51_config(-i) != {}} {
			append result " --includes=$assembler_ASEM51_config(-i)"
		}
		foreach opt {--omf-51 --columns --verbose} {
			if {$assembler_ASEM51_config($opt)} {
				append result { } $opt
			}
		}

		return $result
	}

	## Determinate CLI options for external assembler AS31
	 # @return String - Options for AS31
	proc determinate_as31_options {} {
		variable assembler_AS31_config		;# Current AS31 assembler configuration

		set result {}
		if {$assembler_AS31_config(custom) != {}} {
			append result { } ${assembler_AS31_config(custom)}
		}
		foreach opt {-l} {
			if {$assembler_AS31_config($opt)} {
				append result { } $opt
			}
		}
		foreach opt {-F -A} {
			if {$assembler_AS31_config($opt) != {}} {
				append result { } $opt $assembler_AS31_config($opt)
			}
		}

		return $result
	}

	## Determinate CLI options for external assembler ASL
	 # @return String - Options for ASL
	proc determinate_asl_options {} {
		variable assembler_ASL_config		;# Current ASL assembler configuration

		set result {-gnuerrors}
		if {$assembler_ASL_config(custom) != {}} {
			append result { } ${assembler_ASL_config(custom)}
		}
		foreach opt {-A -a -C -c -h -I -L -M -P -n -quiet -s -u -U -w -x} {
			if {$assembler_ASL_config($opt)} {
				append result { } $opt
			}
		}
		foreach opt {-r -i -g -cpu} {
			if {$assembler_ASL_config($opt) != {}} {
				append result { } $opt { "} $assembler_ASL_config($opt) {"}
			}
		}

		return $result
	}

	## Initialize NS variables
	 # @return void
	proc initialize {} {
		# Assembler
		array set ::ExternalCompiler::assembler_ASEM51_addcfg		\
			$::ExternalCompiler::assembler_ASEM51_addcfg_def
		array set ::ExternalCompiler::assembler_ASEM51_config		\
			$::ExternalCompiler::assembler_ASEM51_config_def
		array set ::ExternalCompiler::assembler_ASL_addcfg		\
			$::ExternalCompiler::assembler_ASL_addcfg_def
		array set ::ExternalCompiler::assembler_ASL_config		\
			$::ExternalCompiler::assembler_ASL_config_def
		array set ::ExternalCompiler::assembler_AS31_addcfg		\
			$::ExternalCompiler::assembler_AS31_addcfg_def
		array set ::ExternalCompiler::assembler_AS31_config		\
			$::ExternalCompiler::assembler_AS31_config_def

		# SDCC
		array set ::ExternalCompiler::sdcc_bool_options			\
			$::ExternalCompiler::sdcc_bool_options_def
		array set ::ExternalCompiler::sdcc_string_options		\
			$::ExternalCompiler::sdcc_string_options_def
		array set ::ExternalCompiler::sdcc_optional_string_options	\
			$::ExternalCompiler::sdcc_optional_string_options_def
		array set ::ExternalCompiler::sdcc_scs_string_options		\
			$::ExternalCompiler::sdcc_scs_string_options_def

		# Make utility
		foreach {key value} ${::ExternalCompiler::makeutil_config_def} {
			set ::ExternalCompiler::makeutil_config($key) $value
		}
	}
}

# Initialize NS variables
ExternalCompiler::initialize

# >>> File inclusion guard
}
# <<< File inclusion guard