🐐 Compiler

This commit is contained in:
2026-04-10 13:06:34 +02:00
parent e2688b49ea
commit 4937a95f70
12 changed files with 1280 additions and 36 deletions

34
cent
View File

@@ -2,15 +2,20 @@
"""
Usage:
cent (-h|--help)
cent (-i|-c) FILE
cent -i FILE
cent -c [--keep-c] FILE
Options:
-h --help Print this help screen
-i Run the interpreter
-c Run the compiler
--keep-c Keep the generated C file alongside the binary
FILE The file to compile/interpret
"""
import os
import subprocess
import sys
import tempfile
from docopt import docopt
from rply.errors import LexingError
@@ -19,6 +24,7 @@ from centvrion.errors import CentvrionError
from centvrion.lexer import Lexer
from centvrion.parser import Parser
from centvrion.ast_nodes import Program
from centvrion.compiler.emitter import compile_program
def main():
args = docopt(__doc__)
@@ -44,7 +50,31 @@ def main():
except CentvrionError as e:
sys.exit(f"CENTVRION error: {e}")
else:
raise Exception("Compiler not implemented")
c_source = compile_program(program)
runtime_c = os.path.join(
os.path.dirname(__file__),
"centvrion", "compiler", "runtime", "cent_runtime.c"
)
out_path = os.path.splitext(file_path)[0]
if args["--keep-c"]:
tmp_path = out_path + ".c"
with open(tmp_path, "w") as f:
f.write(c_source)
subprocess.run(
["gcc", "-O2", tmp_path, runtime_c, "-o", out_path],
check=True,
)
else:
with tempfile.NamedTemporaryFile(suffix=".c", delete=False, mode="w") as tmp:
tmp.write(c_source)
tmp_path = tmp.name
try:
subprocess.run(
["gcc", "-O2", tmp_path, runtime_c, "-o", out_path],
check=True,
)
finally:
os.unlink(tmp_path)
else:
raise Exception("Output not of type 'Program'", type(program))