Skip to content

Instantly share code, notes, and snippets.

@rui314
Created August 3, 2026 01:48
Show Gist options
  • Select an option

  • Save rui314/8836bf697321d1d9a355a15f9856eadf to your computer and use it in GitHub Desktop.

Select an option

Save rui314/8836bf697321d1d9a355a15f9856eadf to your computer and use it in GitHub Desktop.
from __future__ import annotations
import subprocess
from pathlib import Path
import pytest
from compiler import compile_forth
PROJECT_ROOT = Path(__file__).resolve().parent
RUNNER_C = PROJECT_ROOT / "runner.c"
def run_command(command: list[str]) -> subprocess.CompletedProcess[str]:
return subprocess.run(
command,
check=True,
capture_output=True,
text=True,
)
def compile_and_run(source: str, workdir: Path) -> str:
asm_path = workdir / "generated.s"
exe_path = workdir / "generated.exe"
asm_path.write_text(compile_forth(source), encoding="utf-8")
run_command(
[
"clang",
str(asm_path),
str(RUNNER_C),
"-o",
str(exe_path),
]
)
result = run_command([str(exe_path)])
return result.stdout.strip()
@pytest.mark.parametrize(
("source", "expected"),
[
("42", "42"),
("10 20 +", "30"),
("20 7 -", "13"),
("6 9 *", "54"),
("10 20 + 3 *", "90"),
],
)
def test_forth_program(
source: str,
expected: str,
tmp_path: Path,
) -> None:
assert compile_and_run(source, tmp_path) == expected
@pytest.mark.parametrize(
"source",
[
"",
"1 unknown-word",
"hello",
],
)
def test_compile_error(source: str) -> None:
with pytest.raises(SyntaxError):
compile_forth(source)
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment