flex-bison-in-action/main.py

48 lines
1.8 KiB
Python
Raw Blame History

This file contains ambiguous Unicode characters!

This file contains ambiguous Unicode characters that may be confused with others in your current locale. If your use case is intentional and legitimate, you can safely ignore this warning. Use the Escape button to highlight these characters.

import os
import subprocess
# ЭТИ ПУТИ НАДО ЗАДАТЬ ВРУЧНУЮ
# *.l и *.y файлы из директории ANALYZERS_DIR ДОЛЖНЫ НАЗЫВАТЬСЯ как basename этой директории!!!
ANALYZERS_DIR = r'C:\Users\user\Desktop\УЧЕБА\6_СЕМ\КОМПИЛЯТОРЫ\flex_bison_test\analyzers\c_analyzer'
FLEX_EXE_PATH = r"C:\tools\win_flex_bison\win_flex.exe"
BISON_EXE_PATH = r"C:\tools\win_flex_bison\win_bison.exe"
def main():
# Подготовка путей
analyzer_name = os.path.basename(ANALYZERS_DIR)
lexical_analyzer_path = fr"{ANALYZERS_DIR}\{analyzer_name}.l"
syntaxic_analyzer_path = fr"{ANALYZERS_DIR}\{analyzer_name}.y"
# Подготовка списка команд
cmds = [
f'{FLEX_EXE_PATH} {lexical_analyzer_path}',
f'{BISON_EXE_PATH} -d {syntaxic_analyzer_path}',
f'gcc lex.yy.c {analyzer_name}.tab.c -o {analyzer_name}.exe'
]
# Исполнение команд с выводом
for cmd in cmds:
print(f"\n\033[1mExecuting:\033[0m {cmd}")
try:
subprocess.run(
cmd,
shell=True,
check=True,
text=True,
stderr=subprocess.PIPE
)
print(f'\033[92mSuccessfully executed!\033[0m')
except subprocess.CalledProcessError as e:
print("\033[91mErrors:\033[0m")
print(e.stderr)
# Очистка промежуточных файлов (только если все команды успешны)
for path in ['lex.yy.c', f'{analyzer_name}.tab.c', f'{analyzer_name}.tab.h']:
try:
os.remove(path)
print(f"\033[1mRemoved:\033[0m {path}")
except FileNotFoundError:
pass
if __name__ == "__main__":
main()