[IDE Tool] ToASM

Working on new editor enhancements?
AZJIO
Addict
Addict
Posts: 2154
Joined: Sun May 14, 2017 1:48 am

[IDE Tool] ToASM

Post by AZJIO »

ToASM

Download: yandex, upload.ee

Image

A tool that simplifies obtaining the source code in the form of ASM or C-Backend

The settings can be passed via the command line.
15 "%FILE" "%TEMPFILE"
where 15 is a set of flags:
1 - ASM is the direction of conversion, 1 - ASM, 0 -C-Backend
2 - Rename - rename the file to the source name.
4 - Start - after creation, open the file in the associated editor
8 - Close - automatically close the window after clicking OK.
16 - Debugger - adds debugger strings
32 - LineNum - adds line numbers

The settings can be stored in ToASM.ini.
ASM = 1
Rename = 1
Start = 1
Close = 1
Debugger = 0
LineNum = 0

Code: Select all

;- TOP
; AZJIO
; https://www.purebasic.fr/english/viewtopic.php?t=86542
; Для Linux требуется пакет "xdg-utils"
EnableExplicit

;- Language
Define UserIntLang

CompilerSelect #PB_Compiler_OS
	CompilerCase #PB_OS_Windows
		Define *Lang
		If OpenLibrary(0, "kernel32.dll")
			*Lang = GetFunction(0, "GetUserDefaultUILanguage")
			If *Lang And CallFunctionFast(*Lang) = 1049 ; ru (embed your language natively)
				UserIntLang = 1
			EndIf
			CloseLibrary(0)
		EndIf
	CompilerCase #PB_OS_Linux
		If ExamineEnvironmentVariables()
			While NextEnvironmentVariable()
				If Left(EnvironmentVariableName(), 4) = "LANG" And Left(EnvironmentVariableValue(), 2) = "ru" ; (embed your language natively)
					; LANG=ru_RU.UTF-8
					; LANGUAGE=ru
					UserIntLang = 1
					Break
				EndIf
			Wend
		EndIf
CompilerEndSelect

;- En
#CountStrLang = 10
Global Dim Lng.s(#CountStrLang)
Lng(1) = "Debugger (not recommended)"
Lng(2) = "Line numbers (not recommended)"
Lng(3) = "Rename"
Lng(4) = "Launch"
Lng(5) = "Close window automatically"
Lng(6) = "Only for comparing the added code"
Lng(7) = "Unable to delete:"
Lng(8) = "Error"
Lng(9) = "File not found:"
Lng(10) = "One cause of the problem is that the source contains errors, causing the compiler to refuse to process it"

;- Ru
If UserIntLang
	Lng(1) = "Отладчик (не рекомендуется)"
	Lng(2) = "Номера строк (не рекоменд.)"
	Lng(3) = "Переименовать"
	Lng(4) = "Запуск"
	Lng(5) = "Закрывать окно автоматически"
	Lng(6) = "Только для сравнения привнесённого кода"
	Lng(7) = "Не удаётся удалить:"
	Lng(8) = "Ошибка"
	Lng(9) = "Не найден файл:"
	Lng(10) = "Одна из причин проблемы - исходник содержит ошибки, из-за чего компилятор отказывается его обрабатывать"
EndIf

XIncludeFile "ForToASM.pb"
Declare OK()

;- ● Global / Define
Global PureBasicHome$, InputFile$, filename$
Global ini$

Define Count, i, flag, tmp$

Define ini_ASM = 1
Define ini_Rename = 1
Define ini_Start = 1
Define ini_Close = 1
Define ini_Debugger = 0
Define ini_LineNum = 0


CompilerIf #PB_Compiler_Debugger
	; 	compiler$ = #PB_Compiler_Home + "Compilers\pbcompiler.exe"
	PureBasicHome$ = #PB_Compiler_Home
CompilerElse
	; 	compiler$ = GetEnvironmentVariable("PB_TOOL_Compiler")
	PureBasicHome$ = GetEnvironmentVariable("PUREBASIC_HOME")
CompilerEndIf


; 	Добавляем параметоры ком строки чтобы использовать как инструмент
Count = CountProgramParameters()
For i = 1 To Count
	tmp$ = ProgramParameter()
	If Not flag And IsDigital(@tmp$)
		flag = Val(tmp$)
	EndIf
	; Если несохранённый файл, то его путь пустой.
	; Проверяем что файл существует, что расширение pb*, что путь ещё не принят (если принят, то второй раз не берём)
	If Asc(tmp$) And FileSize(tmp$) > 3 And Left(GetExtensionPart(tmp$), 2) = "pb" And Not Asc(InputFile$)
		InputFile$ = tmp$
		If flag ; это не обязательно, но игнорирует последующие параметры, если всё получено
			Break
		EndIf
	EndIf
Next


If flag
	ini_ASM = flag & 1
	ini_Rename = flag & 2
	ini_Start = flag & 4
	ini_Close = flag & 8
	ini_Debugger = flag & 16
	ini_LineNum = flag & 32
Else
	;- ini
	ini$ = GetPathPart(ProgramFilename()) + "ToASM.ini"
	If OpenPreferences(ini$)
		ini_ASM = ReadPreferenceInteger("ASM", ini_ASM)
		ini_Rename = ReadPreferenceInteger("Rename", ini_Rename)
		ini_Start = ReadPreferenceInteger("Start", ini_Start)
		ini_Close = ReadPreferenceInteger("Close", ini_Close)
		ini_Debugger = ReadPreferenceInteger("Debugger", ini_Debugger)
		ini_LineNum = ReadPreferenceInteger("LineNum", ini_LineNum)
		ClosePreferences()
	EndIf
EndIf

#Window = 0
; #Menu = 0

Enumeration
	#btnOK
	#OptASM
	#OptC
	#ChRename
	#ChStart
	#ChClose
	#ChDebugger
	#ChLineNum
EndEnumeration

Enumeration Menu_items
	#mOK
	#mClose
EndEnumeration


CompilerIf #PB_Compiler_Debugger
	InputFile$ = #PB_Compiler_File
CompilerEndIf

filename$ = GetFilePart(InputFile$, #PB_FileSystem_NoExtension)


If FileSize(InputFile$) < 0
	End
EndIf

; Debug InputFile$
; Debug filename$

;-┌──GUI──┐
If OpenWindow(#Window, 0, 0, 270, 204, "ToASM: " + filename$, #PB_Window_SystemMenu | #PB_Window_ScreenCentered)

	OptionGadget(#OptASM, 80, 10, 99, 22, "ASM")
	OptionGadget(#OptC, 80, 32, 99, 22, "C-Backend")

	If ini_ASM
		SetGadgetState(#OptASM, #True)
	Else
		SetGadgetState(#OptC, #True)
	EndIf
	CheckBoxGadget(#ChDebugger, 10, 54, 250, 22, Lng(1))
	CheckBoxGadget(#ChLineNum, 10, 76, 250, 22, Lng(2))
	CheckBoxGadget(#ChRename, 10, 98, 130, 22, Lng(3))
	CheckBoxGadget(#ChStart, 10, 120, 99, 22, Lng(4))
	CheckBoxGadget(#ChClose, 10, 142, 250, 22, Lng(5))

	GadgetToolTip(#ChDebugger, Lng(6))
	GadgetToolTip(#ChLineNum, Lng(6))

	If ini_Rename
		SetGadgetState(#ChRename, #True)
	EndIf
	If ini_Start
		SetGadgetState(#ChStart, #True)
	EndIf
	If ini_Close
		SetGadgetState(#ChClose, #True)
	EndIf
	If ini_Debugger
		SetGadgetState(#ChDebugger, #True)
	EndIf
	If ini_LineNum
		SetGadgetState(#ChLineNum, #True)
	EndIf

	ButtonGadget(#btnOK, (270 - 88) / 2, 170, 88, 26, "OK", #PB_Button_Default)
	GadgetToolTip(#btnOK, "Enter")

	; 	If CreatePopupMenu(#Menu)
	; 		MenuItem(#mOK, "OK" + #TAB$ + "Enter")
	; 		MenuItem(#mClose, "Close" + #TAB$ + "Esc")
	; 	EndIf

	AddKeyboardShortcut(#Window, #PB_Shortcut_Return, #mOK)
	AddKeyboardShortcut(#Window, #PB_Shortcut_Escape, #mClose)

	;-┌──Loop──┐
	Repeat
		Select WaitWindowEvent()
			Case #PB_Event_Menu
				Select EventMenu()
					Case #mOK
						OK()
					Case #mClose
						CloseWindow(#Window)
						End
				EndSelect
			Case #PB_Event_Gadget
				Select EventGadget()
					Case #btnOK
						OK()
				EndSelect
			Case #PB_Event_CloseWindow
				CloseWindow(#Window)
				End
		EndSelect
	ForEver
	;-└──Loop──┘
EndIf


Procedure OK()
	Protected Ext$, OutputFile$, compiler$, tmp$, Debugger$, LineNum$, WorkDir$
	CompilerIf #PB_Compiler_OS = #PB_OS_Windows
		If GetGadgetState(#OptASM) & 1
			Ext$ = ".asm"
			compiler$ = PureBasicHome$ + "Compilers\pbcompiler.exe"
		Else
			Ext$ = ".c"
			compiler$ = PureBasicHome$ + "Compilers\pbcompilerc.exe"
		EndIf
	CompilerElse
		If GetGadgetState(#OptASM) & 1
			Ext$ = ".asm"
			compiler$ = PureBasicHome$ + "compilers/pbcompiler"
		Else
			Ext$ = ".c"
			compiler$ = PureBasicHome$ + "compilers/pbcompilerc"
		EndIf
	CompilerEndIf
	If GetGadgetState(#ChDebugger) & #PB_Checkbox_Checked
		Debugger$ = "-d "
	EndIf
	If GetGadgetState(#ChLineNum) & #PB_Checkbox_Checked
		LineNum$ = "-l "
	EndIf
	; 	-q (/QUIET) - отключает вывод в консоль
	; 	-c (/COMMENTED) - создаёт ASM
	; 	-d (/DEBUGGER) - добавляет данные отладки

	; MessageRequester("", InputFile$)

	; 	Переименование исходника, чтобы избавиться от путаницы для несохранённых файлов.
; 	Можно задать дату время или выдать диалог ввода имени
; 	If Left(filename$, 18) = "PureBasic_TempFile"
; 		tmp$ = TmpFile("", "New_", ".pb")
; 		If CopyFile(InputFile$, tmp$)
; 			InputFile$ = tmp$
; 		EndIf
; 	EndIf
	WorkDir$ = GetPathPart(InputFile$)
	OutputFile$ = WorkDir$ + "purebasic" + Ext$
	; 	Удаляем purebasic.asm (purebasic.c), так как если RunProgram() отработает неуспешно,
	; 	то этот файл оставшийся от старой обработки будет использоваться как результат,
	; 	но это будет ложный файл и он будет вводить в заблуждение
	If FileSize(OutputFile$) > -1 And Not DeleteFile(OutputFile$, #PB_FileSystem_Force)
		MessageRequester("Error", Lng(7) + #CRLF$ + #CRLF$ + OutputFile$)
	EndIf
	RunProgram(compiler$,
	           "-q -c " + Debugger$ + LineNum$ + #DQUOTE$ + InputFile$ + #DQUOTE$, WorkDir$,
	           #PB_Program_Wait) ; #PB_Program_Hide - error output problem

	If GetGadgetState(#ChRename) & #PB_Checkbox_Checked
		tmp$ = Left(InputFile$, Len(InputFile$) - Len(GetExtensionPart(InputFile$)) - 1) + Ext$
		tmp$ = GetCopyName(tmp$, 1)
		If CopyFile(OutputFile$, tmp$)
			; удаляем purebasic.asm (purebasic.c) если копирование прошло успешно, тем самым не оставляем мусор в папке.
			DeleteFile(OutputFile$, #PB_FileSystem_Force)
			OutputFile$ = tmp$
		EndIf
	EndIf
	If GetGadgetState(#ChStart) & #PB_Checkbox_Checked
		SetGadgetState(#ChStart, #True)
	EndIf
	If FileSize(OutputFile$) > 0
		CompilerIf #PB_Compiler_OS = #PB_OS_Windows
			RunProgram(OutputFile$)
		CompilerElse
			RunProgram("xdg-open", OutputFile$, GetPathPart(OutputFile$))
		CompilerEndIf
	Else
		MessageRequester(Lng(8), Lng(9) + #CRLF$ + #CRLF$ + OutputFile$ + #CRLF$ + #CRLF$ +
		                           Lng(10))
	EndIf
	If GetGadgetState(#ChClose) & #PB_Checkbox_Checked
		CloseWindow(#Window)
		End
	EndIf
EndProcedure
Last edited by AZJIO on Tue Mar 18, 2025 2:02 am, edited 2 times in total.
Quin
Addict
Addict
Posts: 1132
Joined: Thu Mar 31, 2022 7:03 pm
Location: Colorado, United States
Contact:

Re: [IDE Tool] ToASM

Post by Quin »

Very cool, thanks for sharing!
AZJIO
Addict
Addict
Posts: 2154
Joined: Sun May 14, 2017 1:48 am

Re: [IDE Tool] ToASM

Post by AZJIO »

0.2 (17.03.2025)
Debugger and LineNum added
Improved button prompts and messages
Fixed behavior for unsaved files by adding working directory.
Deleting intermediate files and making sure they are not present.

18.03.2025
Adaptation for linux added
Post Reply