Initial PROTEL 2026 toolchain import

This commit is contained in:
2026-06-08 18:04:03 -05:00
commit 98a0bb329d
125 changed files with 12223 additions and 0 deletions
+109
View File
@@ -0,0 +1,109 @@
"""Reference Manual section and keyword coverage registry (oflpr TOC)."""
from __future__ import annotations
from pathlib import Path
ROOT = Path(__file__).resolve().parent.parent
EXAMPLES = ROOT / "examples"
REF = EXAMPLES / "ref"
# Every numbered Reference Manual section maps to at least one example or test corpus file.
REFERENCE_MANUAL_SECTIONS: dict[str, list[str]] = {
"1.0": ["ref/ref_1_0_introduction.protel"],
"2.0": ["ref/ref_9_1_expressions.protel"],
"3.0": ["ref/ref_3_0_lexical.protel"],
"3.1": ["ref/ref_3_0_lexical.protel"],
"3.2": ["ref/ref_3_0_lexical.protel"],
"3.3": ["ref/ref_3_0_lexical.protel"],
"3.4": ["ref/ref_3_0_lexical.protel"],
"4.0": ["ref/ref_4_0_data_elements.protel"],
"4.1": ["ref/ref_4_0_data_elements.protel"],
"4.2": ["ref/ref_4_0_data_elements.protel"],
"4.3": ["ref/ref_4_0_data_elements.protel"],
"4.4": ["ref/ref_4_0_data_elements.protel"],
"4.5": ["ref/ref_4_0_data_elements.protel"],
"5.0": [
"ref/ref_5_0_compilation_unit.protel",
"ref/ref_5_0_directives.aa01",
"Hello.aa01",
],
"6.0": ["ref/ref_6_0_module_types.protel"],
"7.0": ["ref/ref_7_0_declarations.protel"],
"7.1": ["ref/ref_7_1_1_simple_types.protel", "ref/ref_7_1_2_aggregates.protel"],
"7.1.1": ["ref/ref_7_1_1_simple_types.protel"],
"7.1.1.1": ["ref/ref_7_1_1_simple_types.protel"],
"7.1.1.2": ["intro_2_1_types.protel"],
"7.1.1.3": ["ref/ref_7_1_1_simple_types.protel", "intro_2_1_types.protel"],
"7.1.1.4": ["ref/ref_7_1_1_simple_types.protel"],
"7.1.1.5": ["ref/ref_7_1_1_simple_types.protel"],
"7.1.2": ["ref/ref_7_1_2_aggregates.protel"],
"7.1.2.1": ["ref/ref_7_1_2_aggregates.protel"],
"7.1.2.2": ["ref/ref_7_1_2_aggregates.protel", "ref_8_1_task_block_struct.protel"],
"7.1.2.3": ["intro_2_1_types.protel", "intro_3_2_6_sum_table.protel"],
"7.1.2.4": ["intro_2_1_types.protel"],
"7.1.2.5": ["ref/ref_7_1_2_aggregates.protel"],
"7.1.3": ["ref/ref_7_1_3_procedures.protel"],
"7.1.3.1": ["ref/ref_7_1_3_procedures.protel"],
"7.1.3.2": ["ref/ref_7_1_3_procedures.protel"],
"7.2": ["ref/ref_7_2_data_declarations.protel"],
"7.2.1": ["ref/ref_7_2_data_declarations.protel"],
"7.2.2": ["intro_2_2_calculate_average.protel"],
"7.2.3": ["ref/ref_7_2_data_declarations.protel"],
"7.3": ["ref/ref_7_3_overlays.protel"],
"8.0": ["ref/ref_8_0_scope.protel"],
"8.1": ["ref/ref_8_0_scope.protel"],
"8.2": ["ref/ref_8_0_scope.protel"],
"9.0": ["ref/ref_9_0_statements.protel"],
"9.1": ["ref/ref_9_1_expressions.protel"],
"9.1.1": ["ref/ref_9_1_expressions.protel"],
"9.1.1.1": ["ref/ref_4_0_data_elements.protel"],
"9.1.1.2": ["ref/ref_9_1_expressions.protel"],
"9.1.1.3": ["ref/ref_7_1_3_procedures.protel"],
"9.1.2": ["ref/ref_9_1_expressions.protel"],
"9.2": ["ref/ref_9_2_return.protel", "intro_5_5_2_args_exit.protel"],
"9.3": ["ref/ref_9_3_if.protel"],
"9.4": ["ref/ref_9_4_case.protel", "intro_3_2_4_case.protel"],
"9.5": ["ref/ref_9_5_select.protel"],
"9.6": ["ref/ref_9_6_exit.protel"],
"9.7": [
"ref/ref_9_7_iterative.protel",
"intro_1_3_factorial.protel",
"intro_1_3_factorial_cli.protel",
"intro_3_2_6_sum_table.protel",
],
"10.0": ["ref/ref_10_0_bind_with.protel"],
"11.0": ["ref/ref_11_0_type_compat.protel"],
"11.1": ["ref/ref_11_0_type_compat.protel"],
"11.2": ["ref/ref_11_0_type_compat.protel"],
"11.3": ["ref/ref_11_0_type_compat.protel"],
"12.0": ["ref/ref_12_0_intrinsic.protel"],
"13.0": [
"ref/ref_13_0_descriptors.protel",
"interop/protel_for_python.protel",
"interop/protel_calls_python.protel",
"Hello.protel",
],
"14.0": ["ref/ref_14_0_keyword_exercise.protel"],
"15.0": ["tests/test_parser.py"],
"16.0": ["tests/ref_manual_manifest.py"],
"OO": ["ref/ref_oo_classes.protel", "ref_oo_class_with_var.protel", "ref_oo_class_method_invoke.protel"],
}
# Keywords exercised outside .protel examples (preprocessor / tooling).
KEYWORD_EXTERNAL_SOURCES: dict[str, list[str]] = {
"$EJECT": ["ref/ref_5_0_directives.aa01", "tests/test_pb.py"],
"$LI": ["ref/ref_5_0_directives.aa01", "vdi.aa01", "tests/test_pb.py"],
"$OBJECT": ["ref/ref_oo_classes.protel", "ref_oo_class_with_var.protel"],
"$REFDESC": ["ref/ref_9_1_expressions.protel"],
"$TYPEDESC": ["ref/ref_9_1_expressions.protel"],
"$UNIVERSAL_PTR": ["ref/ref_9_1_expressions.protel"],
"$VARDESC": ["ref/ref_9_1_expressions.protel"],
}
# All ref_* and intro_* example files that must parse.
REF_EXAMPLE_SOURCES: list[str] = sorted(
p.relative_to(EXAMPLES).as_posix()
for p in EXAMPLES.rglob("*.protel")
if p.is_file() and not p.name.endswith("~")
)
+73
View File
@@ -0,0 +1,73 @@
"""ENTRY argc/argv and RETURN exit status (Introductory Manual §5.5.2)."""
import subprocess
from pathlib import Path
import pytest
from src.cpp_transpiler import transpile_to_cpp
from src.parser import parse_protel
from src.transpiler import TranspileError
ROOT = Path(__file__).resolve().parent.parent
EXAMPLE = ROOT / "examples" / "intro_5_5_2_args_exit.protel"
PROTEL = ROOT / "protel"
PYTHON = ROOT / ".venv" / "bin" / "python"
def test_parse_entry_with_unix_argv_parms():
tree = parse_protel(
"SECTION demo;\n"
"TYPE integer {-1 TO 1};\n"
"TYPE char {0 TO 255};\n"
"DCL Start PROC(argc integer, argv PTR TO PTR TO char) IS ENTRY;\n"
)
decl = tree[0].declarations[-1]
assert decl.entry
assert decl.name == "Start"
assert len(decl.parms) == 2
def test_entry_unix_argv_emits_main_with_forwarding():
source = EXAMPLE.read_text(encoding="utf-8")
cpp = transpile_to_cpp(parse_protel(source), source_name=EXAMPLE.name)
assert "int main(int argc, char** argv)" in cpp
assert "return protel_generated::ArgsExit::Start(argc, argv);" in cpp
assert "int16_t Start(int16_t argc, char * * argv)" in cpp
def test_entry_parm_mismatch_raises():
with pytest.raises(TranspileError, match="parameters must match"):
transpile_to_cpp(
parse_protel(
"SECTION s;\n"
"TYPE integer {-1 TO 1};\n"
"TYPE char {0 TO 255};\n"
"DCL Start PROC(argc integer, argv PTR TO PTR TO char) IS ENTRY;\n"
"DCL Start PROC() RETURNS integer IS BLOCK RETURN 0; ENDBLOCK;\n"
)
)
def test_args_exit_compiles_prints_and_returns_argc():
binary = ROOT / "build" / "ArgsExit_test"
result = subprocess.run(
[
str(PYTHON),
str(PROTEL),
str(EXAMPLE),
"-o",
str(binary),
"--run",
"--",
"one",
"two",
],
capture_output=True,
text=True,
cwd=ROOT,
)
assert result.returncode == 3, result.stderr
lines = [line for line in result.stdout.splitlines() if line.strip()]
assert lines[-2:] == ["one", "two"]
assert lines[0].endswith("ArgsExit_test") or "ArgsExit" in lines[0]
+118
View File
@@ -0,0 +1,118 @@
"""C++ transpiler and Hello World tests."""
import os
import stat
import subprocess
from pathlib import Path
from src.parser import parse_protel
from src.cpp_transpiler import transpile_to_cpp
ROOT = Path(__file__).resolve().parent.parent
EXAMPLES = ROOT / "examples"
PROTEL = ROOT / "protel"
def _transpile_hello() -> str:
source = (EXAMPLES / "Hello.protel").read_text(encoding="utf-8")
tree = parse_protel(source)
return transpile_to_cpp(tree, source_name="Hello.protel")
def test_cpp_hello_emits_namespace_and_main():
cpp = _transpile_hello()
assert "namespace protel_generated" in cpp
assert "namespace Hello" in cpp
assert "IS ENTRY" in (EXAMPLES / "Hello.protel").read_text(encoding="utf-8")
assert "void Start()" in cpp
assert 'extern "C"' in cpp
assert "void writeln(const char* msg)" in cpp
assert "<iostream>" not in cpp
assert "IS INTRINSIC" not in (EXAMPLES / "Hello.protel").read_text(encoding="utf-8")
assert "EXTERNAL" in (EXAMPLES / "Hello.protel").read_text(encoding="utf-8")
assert "int main()" in cpp
assert "protel_generated::Hello::Start()" in cpp
assert "(const char[]){" in cpp
assert ", 0 }" in cpp
assert '"Hello, World!"' not in cpp
def test_cpp_hello_class_uses_this():
source = (EXAMPLES / "ref_oo_class_with_var.protel").read_text(encoding="utf-8")
cpp = transpile_to_cpp(parse_protel(source), source_name="ref_oo_class_with_var.protel")
assert "class class_with_var" in cpp
assert "static int16_t class_var" in cpp
assert "class_with_var::class_method" in cpp
assert "class_with_var::class_var = 5" in cpp
assert "void class_with_var::instance_method" in cpp
assert "this->instance_var" in cpp
def test_hello_compiles_and_runs():
result = subprocess.run(
[
str(ROOT / ".venv/bin/python"),
str(PROTEL),
str(EXAMPLES / "Hello.protel"),
"-o",
str(ROOT / "build" / "Hello"),
"--run",
],
capture_output=True,
text=True,
cwd=ROOT,
)
assert result.returncode == 0, result.stderr
assert "Hello, World!" in result.stdout
def test_hello_shebang_direct_execution():
hello = EXAMPLES / "Hello.protel"
assert hello.read_text(encoding="utf-8").startswith("#!/usr/bin/env protel-run")
mode = hello.stat().st_mode
hello.chmod(mode | stat.S_IXUSR | stat.S_IXGRP | stat.S_IXOTH)
env = dict(os.environ)
env["PATH"] = f"{ROOT}:{env.get('PATH', '')}"
result = subprocess.run(
[str(hello.resolve())],
capture_output=True,
text=True,
cwd=ROOT,
env=env,
)
assert result.returncode == 0, result.stderr
assert "Hello, World!" in result.stdout
def test_hello_compiles_and_runs_a_out():
result = subprocess.run(
[str(ROOT / ".venv/bin/python"), str(PROTEL), "examples/Hello.protel", "--run"],
capture_output=True,
text=True,
cwd=ROOT,
)
assert result.returncode == 0, result.stderr
assert "Hello, World!" in result.stdout
assert (ROOT / "a.out").exists()
def test_cpp_oo_examples_compile():
from src.compile import check_cpp_syntax
for name in ("ref_oo_class_with_var.protel", "ref_oo_class_method_invoke.protel"):
source = EXAMPLES / name
tree = parse_protel(source.read_text(encoding="utf-8"))
cpp = transpile_to_cpp(tree, source_name=name)
cpp_path = ROOT / "build" / f"{name.replace('.protel', '.cpp')}"
cpp_path.parent.mkdir(parents=True, exist_ok=True)
cpp_path.write_text(cpp, encoding="utf-8")
check_cpp_syntax(cpp_path)
def test_parse_external_proc():
tree = parse_protel(
"SECTION s;\nDCL writeln PROC(msg PTR TO char) EXTERNAL;\n"
)
decl = tree[0].declarations[0]
assert decl.external
assert decl.name == "writeln"
+92
View File
@@ -0,0 +1,92 @@
"""PROTEL file extension conventions (Emacs mode + compiler driver)."""
import re
import subprocess
from pathlib import Path
import pytest
from src.cpp_transpiler import transpile_to_cpp
from src.extensions import format_suffix_list, is_pls_suffix, is_protel_source, is_protel_suffix
from src.parser import parse_protel
ROOT = Path(__file__).resolve().parent.parent
EXAMPLES = ROOT / "examples"
MODE_EL = ROOT / "emacs" / "protel-mode.el"
PROTEL = ROOT / "protel"
@pytest.mark.parametrize(
"name,expected",
[
("Hello.protel", True),
("Hello.P", True),
("Hello.p", True),
("Hello.pt", True),
("Hello.ptl", True),
("vdi.aa01", True),
("module.AB18", True),
("module.ZZ99", True),
("module.aa00", True),
("readme.txt", False),
("bad.A1", False),
("bad.ABC1", False),
("bad.1A01", False),
("bad.AA1", False),
],
)
def test_is_protel_source_recognizes_fixed_and_pls_suffixes(name, expected):
assert is_protel_source(name) is expected
def test_is_pls_suffix_matches_letter_digit_pattern():
assert is_pls_suffix(".aa01")
assert is_pls_suffix(".AB99")
assert not is_pls_suffix(".protel")
def test_format_suffix_list_mentions_pls_range():
text = format_suffix_list()
assert ".AA01" in text
assert ".ZZ99" in text
def test_protel_mode_registers_legacy_p_extension():
source = MODE_EL.read_text(encoding="utf-8")
assert re.search(r'auto-mode-alist.*\\\.P\\', source)
def test_protel_mode_font_locks_shebang_as_comment():
source = MODE_EL.read_text(encoding="utf-8")
assert '(list "^#![^\\n]*" 0 \'font-lock-comment-face)' in source
def test_protel_mode_registers_pls_edition_suffixes():
source = MODE_EL.read_text(encoding="utf-8")
assert "PLS edition suffixes" in source
assert "[A-Za-z][A-Za-z][0-9][0-9]" in source
def test_hello_p_transpiles():
legacy = (EXAMPLES / "Hello.P").read_text(encoding="utf-8")
cpp = transpile_to_cpp(parse_protel(legacy), source_name="Hello.P")
assert "protel_generated::Hello::Start()" in cpp
assert "writeln(" in cpp
def test_hello_pls_transpiles():
pls = (EXAMPLES / "Hello.aa01").read_text(encoding="utf-8")
cpp = transpile_to_cpp(parse_protel(pls), source_name="Hello.aa01")
assert "protel_generated::Hello::Start()" in cpp
assert "writeln(" in cpp
def test_protel_driver_accepts_pls_suffix_without_warning():
result = subprocess.run(
[str(ROOT / ".venv/bin/python"), str(PROTEL), str(EXAMPLES / "Hello.aa01"), "--emit-c"],
cwd=ROOT,
capture_output=True,
text=True,
)
assert result.returncode == 0
assert "does not use a PROTEL extension" not in result.stderr
+55
View File
@@ -0,0 +1,55 @@
"""ENTRY procedure tests (Introductory Manual 5.5.2)."""
import pytest
from src.cpp_transpiler import transpile_to_cpp
from src.parser import parse_protel
from src.transpiler import TranspileError
def test_parse_entry_declaration():
tree = parse_protel("SECTION demo;\nDCL Start PROC() IS ENTRY;\n")
decl = tree[0].declarations[0]
assert decl.entry
assert decl.name == "Start"
assert decl.body is None
def test_entry_emits_c_main_wrapper():
source = """
SECTION Hello;
DCL Start PROC() IS ENTRY;
DCL Start PROC() IS BLOCK ENDBLOCK;
"""
cpp = transpile_to_cpp(parse_protel(source), source_name="Hello.protel")
assert "/* ENTRY Start */" in cpp
assert "void Start()" in cpp
assert "int main()" in cpp
assert "protel_generated::Hello::Start();" in cpp
assert "return 0;" in cpp
def test_procedure_named_main_without_entry_has_no_c_main():
source = """
SECTION demo;
DCL main PROC() IS BLOCK ENDBLOCK;
"""
cpp = transpile_to_cpp(parse_protel(source), source_name="demo.protel")
assert "void main()" in cpp
assert "int main()" not in cpp
def test_missing_entry_body_raises():
with pytest.raises(TranspileError, match="has no procedure body"):
transpile_to_cpp(parse_protel("SECTION s;\nDCL Start PROC() IS ENTRY;\n"))
def test_multiple_entry_raises():
with pytest.raises(TranspileError, match="multiple ENTRY"):
transpile_to_cpp(
parse_protel(
"SECTION s;\n"
"DCL Start PROC() IS ENTRY;\n"
"DCL Other PROC() IS ENTRY;\n"
)
)
+76
View File
@@ -0,0 +1,76 @@
"""Factorial CLI example: USES §1.3 module + printf/atoi C interop."""
import subprocess
from pathlib import Path
from src.cpp_transpiler import transpile_to_cpp
from src.parser import parse_protel
ROOT = Path(__file__).resolve().parent.parent
EXAMPLE = ROOT / "examples" / "intro_1_3_factorial_cli.protel"
FACTORIAL = ROOT / "examples" / "intro_1_3_factorial.protel"
PROTEL = ROOT / "protel"
PYTHON = ROOT / ".venv" / "bin" / "python"
def test_factorial_cli_transpile_uses_and_externals():
source = EXAMPLE.read_text(encoding="utf-8")
cpp = transpile_to_cpp(
parse_protel(source),
source_name=EXAMPLE.name,
source_path=EXAMPLE,
)
assert "/* USES: factorial_demo */" in cpp
assert "using factorial_demo::factorial;" in cpp
assert "int16_t factorial(int16_t n)" in cpp
assert "#include <cstdio>" in cpp
assert "#include <cstdlib>" in cpp
assert "int main(int argc, char** argv)" in cpp
def test_factorial_source_unchanged():
text = FACTORIAL.read_text(encoding="utf-8")
assert "SECTION factorial_demo;" in text
assert "IS ENTRY" not in text
assert "USES" not in text
def test_factorial_cli_compiles_and_prints_result():
binary = ROOT / "build" / "factorial_cli_test"
result = subprocess.run(
[
str(PYTHON),
str(PROTEL),
str(EXAMPLE),
"-o",
str(binary),
"--run",
"--",
"5",
],
capture_output=True,
text=True,
cwd=ROOT,
)
assert result.returncode == 0, result.stderr
assert "5! = 120" in result.stdout
def test_factorial_cli_usage_exit_status():
binary = ROOT / "build" / "factorial_cli_usage"
result = subprocess.run(
[
str(PYTHON),
str(PROTEL),
str(EXAMPLE),
"-o",
str(binary),
"--run",
"--",
],
capture_output=True,
text=True,
cwd=ROOT,
)
assert result.returncode == 1, result.stderr
assert "Usage: factorial N" in result.stdout
+56
View File
@@ -0,0 +1,56 @@
"""Java interop example tests (transpile + optional link)."""
import shutil
import subprocess
from pathlib import Path
import pytest
from src.cpp_transpiler import transpile_to_cpp
from src.parser import parse_protel
ROOT = Path(__file__).resolve().parent.parent
INTEROP = ROOT / "examples" / "interop"
def _java_runtime_available() -> bool:
if shutil.which("javac") is None or shutil.which("java") is None:
return False
try:
subprocess.run(["java", "-version"], capture_output=True, check=True)
return True
except (subprocess.CalledProcessError, FileNotFoundError):
return False
def test_protel_calls_java_emits_external_java_greet():
source = (INTEROP / "protel_calls_java.protel").read_text(encoding="utf-8")
cpp = transpile_to_cpp(parse_protel(source), source_name="protel_calls_java.protel")
assert 'extern "C"' in cpp
assert "void java_greet(const char* name, int16_t value)" in cpp
assert "java_greet(" in cpp
assert "protel_generated::protel_calls_java::Start()" in cpp
def test_protel_for_java_exports_c_linkage():
source = (INTEROP / "protel_for_java.protel").read_text(encoding="utf-8")
cpp = transpile_to_cpp(parse_protel(source), source_name="protel_for_java.protel")
assert "/* EXPORT protel_add" in cpp
assert "int16_t protel_add(int16_t a, int16_t b)" in cpp
assert "return (a + b)" in cpp
assert "int main()" not in cpp
def test_java_calls_protel_uses_jni_bridge():
bridge = (INTEROP / "java_calls_protel.c").read_text(encoding="utf-8")
java_src = (INTEROP / "JavaCallsProtel.java").read_text(encoding="utf-8")
assert "Java_JavaCallsProtel_protelAdd" in bridge
assert "protel_add" in bridge
assert "System.loadLibrary" in java_src
assert "native short protelAdd" in java_src
@pytest.mark.skipif(not _java_runtime_available(), reason="JDK not installed")
def test_java_interop_examples_build_and_run():
script = INTEROP / "build_interop_java.sh"
subprocess.run(["bash", str(script)], cwd=ROOT, check=True, text=True)
+158
View File
@@ -0,0 +1,158 @@
"""Parser tests correlated to PROTEL 2026 manuals."""
from pathlib import Path
import pytest
from src.parser import parse_protel
from src import ast_nodes as ast
EXAMPLES = Path(__file__).resolve().parent.parent / "examples"
def _read(name: str) -> str:
return (EXAMPLES / name).read_text(encoding="utf-8")
def test_parse_section_uses_and_of():
tree = parse_protel(
"SECTION ref_provider;\n"
"SECTION ref_consumer OF ref_provider USES ref_provider;\n"
)
assert tree[1].of_modules == ["ref_provider"]
assert tree[1].uses_modules == ["ref_provider"]
def test_parse_factorial_example():
tree = parse_protel(_read("intro_1_3_factorial.protel"))
assert len(tree) == 1
section = tree[0]
assert isinstance(section, ast.Section)
assert section.name == "factorial_demo"
proc = next(d for d in section.declarations if isinstance(d, ast.ProcDecl))
assert proc.name == "factorial"
assert proc.return_type is not None
assert isinstance(proc.body, ast.Block)
assert any(isinstance(s, ast.LoopStmt) for s in proc.body.statements)
def test_parse_types_example():
tree = parse_protel(_read("intro_2_1_types.protel"))
section = tree[0]
type_names = {d.names[0] for d in section.declarations if isinstance(d, ast.TypeDecl)}
assert "integer" in type_names
assert "digit_register" in type_names
assert "features_table" in type_names
def test_parse_calculate_average():
tree = parse_protel(_read("intro_2_2_calculate_average.protel"))
proc = next(
d for d in tree[0].declarations if isinstance(d, ast.ProcDecl)
)
assert proc.name == "calculate_average"
assert len(proc.parms) == 1
assert proc.parms[0][0] == ["number_1", "number_2"]
def test_classical_keyword_casing():
source = """
section demo;
type integer {-32768 to 32767};
dcl x integer;
"""
tree = parse_protel(source, classical=True)
assert tree[0].name == "demo"
type_decl = next(d for d in tree[0].declarations if isinstance(d, ast.TypeDecl))
assert type_decl.names == ["integer"]
def test_parse_case_statement():
tree = parse_protel(_read("intro_3_2_4_case.protel"))
proc = next(d for d in tree[0].declarations if isinstance(d, ast.ProcDecl))
case_stmt = proc.body.statements[0]
assert isinstance(case_stmt, ast.CaseStmt)
assert len(case_stmt.arms) == 3
assert case_stmt.out_statements == []
def test_parse_for_loop_with_upb():
tree = parse_protel(_read("intro_3_2_6_sum_table.protel"))
proc = next(d for d in tree[0].declarations if isinstance(d, ast.ProcDecl))
for_stmt = next(s for s in proc.body.statements if isinstance(s, ast.ForStmt))
assert for_stmt.var == "i"
assert isinstance(for_stmt.to_expr, ast.BuiltinExpr)
assert for_stmt.to_expr.name == "UPB"
def test_parse_struct_type():
tree = parse_protel(_read("ref_8_1_task_block_struct.protel"))
task_block = next(
d for d in tree[0].declarations
if isinstance(d, ast.TypeDecl) and d.names == ["task_block"]
)
assert isinstance(task_block.type_spec, ast.StructType)
assert len(task_block.type_spec.fields) == 5
def test_var_init_not_wrapped_in_tree():
tree = parse_protel(_read("intro_2_1_types.protel"))
primes = next(d for d in tree[0].declarations if isinstance(d, ast.VarDecl) and "primes" in d.names)
assert isinstance(primes.init, ast.TupleLit)
def test_parse_class_type_with_operations():
tree = parse_protel(_read("ref_oo_class_with_var.protel"))
section = tree[0]
assert section.section_kind == "INTERFACE"
class_decl = next(
d for d in section.declarations
if isinstance(d, ast.TypeDecl) and d.names == ["class_with_var"]
)
spec = class_decl.type_spec
assert isinstance(spec, ast.ClassType)
assert spec.end_name == "class_with_var"
assert spec.base.name == "$OBJECT"
assert len(spec.data_parts) == 2
assert spec.data_parts[0].access_attrs == ["PROTECTED"]
method = spec.operations[0].methods[0]
assert method.names == ["class_method"]
assert method.attrs == ["CLASS"]
assert len(section.class_impls) == 1
assert section.class_impls[0].class_name == "class_with_var"
def test_parse_class_method_invocation():
tree = parse_protel(_read("ref_oo_class_method_invoke.protel"))
proc = next(d for d in tree[0].declarations if isinstance(d, ast.ProcDecl))
assert isinstance(proc.body.statements[0], ast.MethodCall)
assert proc.body.statements[0].name == "class_method"
assert isinstance(proc.body.statements[1], ast.MethodCall)
def test_parse_self_member_assignment():
tree = parse_protel(_read("ref_oo_class_with_var.protel"))
impl = tree[0].class_impls[0]
stmt = impl.declarations[0].body.statements[0]
assert isinstance(stmt, ast.AssignExpr)
assert isinstance(stmt.target, ast.MemberRef)
assert stmt.target.member == "class_var"
def test_assignment_expression_chaining():
source = """
SECTION demo;
TYPE integer {-32768 TO 32767};
DCL p PROC() IS
BLOCK
DCL a, b, c integer;
1 -> a -> b -> c;
ENDBLOCK;
"""
tree = parse_protel(source)
proc = next(d for d in tree[0].declarations if isinstance(d, ast.ProcDecl))
stmt = proc.body.statements[0]
assert isinstance(stmt, ast.AssignExpr)
assert isinstance(stmt.target, ast.VarRef)
assert stmt.target.name == "c"
+48
View File
@@ -0,0 +1,48 @@
"""Pb beautifier tests."""
import importlib.util
import sys
from pathlib import Path
from types import ModuleType
ROOT = Path(__file__).resolve().parent.parent
def _load_pb() -> ModuleType:
path = ROOT / "Pb"
spec = importlib.util.spec_from_loader("pb_module", loader=None)
module = importlib.util.module_from_spec(spec)
exec(compile(path.read_text(encoding="utf-8"), str(path), "exec"), module.__dict__)
return module
def test_dollar_li_line_is_fully_uppercased():
pb = _load_pb()
source = "section VDI;\n$li modentry restart\nDCL x BOOL;\n"
result = pb.beautify_protel(source)
assert "$LI MODENTRY RESTART\n" in result
assert "$li modentry" not in result
assert "DCL" in result
def test_dollar_li_line_with_leading_whitespace():
pb = _load_pb()
source = " $Li modentry restart\n"
result = pb.beautify_protel(source)
assert result == " $LI MODENTRY RESTART\n"
def test_pb_preserves_shebang_first_line():
pb = _load_pb()
source = "#!/usr/bin/env protel-run\nsection s;\nDCL x BOOL;\n"
result = pb.beautify_protel(source)
assert result.startswith("#!/usr/bin/env protel-run\n")
assert "SECTION" in result
assert "DCL" in result
def test_vdi_aa01_dollar_li_directive():
pb = _load_pb()
vdi = (ROOT / "vdi.aa01").read_text(encoding="utf-8")
result = pb.beautify_protel(vdi)
assert "$LI MODENTRY RESTART" in result
+37
View File
@@ -0,0 +1,37 @@
"""Preprocessor shebang stripping (Introductory Manual §7.0.5)."""
from pathlib import Path
from src.parser import parse_protel
from src.preprocess import normalize_keywords, strip_shebang
ROOT = Path(__file__).resolve().parent.parent
HELLO = ROOT / "examples" / "Hello.protel"
def test_strip_shebang_removes_first_line():
source = "#!/usr/bin/env -S protel --run --\nSECTION s;\n"
assert strip_shebang(source) == "SECTION s;\n"
def test_strip_shebang_passthrough_without_hash_bang():
source = "% comment\nSECTION s;\n"
assert strip_shebang(source) == source
def test_normalize_keywords_strips_shebang_before_parse():
source = "#!/usr/bin/env protel --run\n% hi\nSECTION s;\n"
norm = normalize_keywords(source)
assert "#!" not in norm
assert "SECTION" in norm
def test_hello_protel_parses_with_shebang():
tree = parse_protel(HELLO.read_text(encoding="utf-8"))
assert tree[0].name == "Hello"
entries = [
decl
for decl in tree[0].declarations
if hasattr(decl, "entry") and decl.entry
]
assert entries and entries[0].name == "Start"
+44
View File
@@ -0,0 +1,44 @@
"""Python interop example tests (transpile + optional link)."""
import shutil
import subprocess
import sys
from pathlib import Path
import pytest
from src.cpp_transpiler import transpile_to_cpp
from src.parser import parse_protel
ROOT = Path(__file__).resolve().parent.parent
INTEROP = ROOT / "examples" / "interop"
def test_protel_calls_python_emits_external_python_greet():
source = (INTEROP / "protel_calls_python.protel").read_text(encoding="utf-8")
cpp = transpile_to_cpp(parse_protel(source), source_name="protel_calls_python.protel")
assert 'extern "C"' in cpp
assert "void python_greet(const char* name, int16_t value)" in cpp
assert "python_greet(" in cpp
assert "protel_generated::protel_calls_python::Start()" in cpp
def test_protel_for_python_exports_c_linkage():
source = (INTEROP / "protel_for_python.protel").read_text(encoding="utf-8")
cpp = transpile_to_cpp(parse_protel(source), source_name="protel_for_python.protel")
assert "/* EXPORT protel_add" in cpp
assert "int16_t protel_add(int16_t a, int16_t b)" in cpp
assert "return (a + b)" in cpp
assert "int main()" not in cpp
def test_python_calls_protel_script_mentions_ctypes():
script = (INTEROP / "python_calls_protel.py").read_text(encoding="utf-8")
assert "ctypes.CDLL" in script
assert "protel_add" in script
@pytest.mark.skipif(shutil.which("python3") is None, reason="python3 not installed")
def test_python_interop_examples_build_and_run():
script = INTEROP / "build_interop_python.sh"
subprocess.run(["bash", str(script)], cwd=ROOT, check=True, text=True)
+108
View File
@@ -0,0 +1,108 @@
"""Reference Manual section and keyword coverage tests."""
from __future__ import annotations
import re
from pathlib import Path
import pytest
from src.cpp_transpiler import transpile_to_cpp
from src.keywords import PROTEL_KEYWORDS
from src.parser import parse_protel
from tests.ref_manual_manifest import (
EXAMPLES,
KEYWORD_EXTERNAL_SOURCES,
REFERENCE_MANUAL_SECTIONS,
REF_EXAMPLE_SOURCES,
ROOT,
)
_KEYWORD_BOUNDARY = re.compile(
r"(?<![A-Za-z0-9_$])("
+ "|".join(re.escape(k) for k in sorted(PROTEL_KEYWORDS, key=len, reverse=True))
+ r")(?![A-Za-z0-9_$])",
re.IGNORECASE,
)
def _corpus_files() -> list[Path]:
patterns = (
"examples/**/*.protel",
"examples/**/*.aa01",
"examples/**/*.P",
"vdi.aa01",
"Pb",
"tests/test_pb.py",
"tests/test_vdi_aa01.py",
"tests/ref_manual_manifest.py",
)
files: list[Path] = []
for pattern in patterns:
files.extend(ROOT.glob(pattern))
return sorted({p.resolve() for p in files if p.is_file()})
def _file_contains_keyword(path: Path, keyword: str) -> bool:
try:
text = path.read_text(encoding="utf-8", errors="replace")
except OSError:
return False
return bool(_KEYWORD_BOUNDARY.search(text))
@pytest.mark.parametrize("section", sorted(REFERENCE_MANUAL_SECTIONS))
def test_reference_manual_section_has_example_mapping(section: str):
mapped = REFERENCE_MANUAL_SECTIONS[section]
assert mapped, f"section {section} has no mapped sources"
for rel in mapped:
if rel.startswith("tests/"):
assert (ROOT / rel).is_file(), f"missing test corpus for §{section}: {rel}"
else:
assert (EXAMPLES / rel).is_file() or (ROOT / rel).is_file(), (
f"missing example for §{section}: {rel}"
)
@pytest.mark.parametrize("rel_source", REF_EXAMPLE_SOURCES)
def test_example_parses(rel_source: str):
source = (EXAMPLES / rel_source).read_text(encoding="utf-8")
tree = parse_protel(source)
assert tree
@pytest.mark.parametrize("rel_source", [s for s in REF_EXAMPLE_SOURCES if s.startswith("ref/")])
def test_ref_example_transpiles(rel_source: str):
path = EXAMPLES / rel_source
source = path.read_text(encoding="utf-8")
tree = parse_protel(source)
cpp = transpile_to_cpp(tree, source_name=path.name)
assert "Generated by PROTEL" in cpp
@pytest.mark.parametrize("keyword", sorted(PROTEL_KEYWORDS))
def test_reserved_keyword_exercised_in_corpus(keyword: str):
if keyword in KEYWORD_EXTERNAL_SOURCES:
for rel in KEYWORD_EXTERNAL_SOURCES[keyword]:
path = ROOT / rel if (ROOT / rel).exists() else EXAMPLES / rel
assert path.is_file(), f"missing external keyword source for {keyword}: {rel}"
assert _file_contains_keyword(path, keyword), (
f"keyword {keyword!r} not found in {rel}"
)
return
for path in _corpus_files():
if _file_contains_keyword(path, keyword):
return
pytest.fail(f"reserved keyword {keyword!r} not found in examples or test corpus")
def test_keyword_manifest_covers_all_keywords():
covered = set(KEYWORD_EXTERNAL_SOURCES)
for path in _corpus_files():
text = path.read_text(encoding="utf-8", errors="replace")
for match in _KEYWORD_BOUNDARY.finditer(text):
covered.add(match.group(1).upper())
missing = PROTEL_KEYWORDS - {k.upper() for k in covered}
assert not missing, f"keywords missing from corpus: {sorted(missing)}"
+37
View File
@@ -0,0 +1,37 @@
"""Rust interop example tests (transpile + optional link)."""
import shutil
import subprocess
from pathlib import Path
import pytest
from src.cpp_transpiler import transpile_to_cpp
from src.parser import parse_protel
ROOT = Path(__file__).resolve().parent.parent
INTEROP = ROOT / "examples" / "interop"
def test_protel_calls_rust_emits_external_rust_greet():
source = (INTEROP / "protel_calls_rust.protel").read_text(encoding="utf-8")
cpp = transpile_to_cpp(parse_protel(source), source_name="protel_calls_rust.protel")
assert 'extern "C"' in cpp
assert "void rust_greet(const char* name, int16_t value)" in cpp
assert "rust_greet(" in cpp
assert "protel_generated::protel_calls_rust::Start()" in cpp
def test_protel_for_rust_exports_c_linkage():
source = (INTEROP / "protel_for_rust.protel").read_text(encoding="utf-8")
cpp = transpile_to_cpp(parse_protel(source), source_name="protel_for_rust.protel")
assert "/* EXPORT protel_add" in cpp
assert "int16_t protel_add(int16_t a, int16_t b)" in cpp
assert "return (a + b)" in cpp
assert "int main()" not in cpp
@pytest.mark.skipif(shutil.which("rustc") is None, reason="rustc not installed")
def test_rust_interop_examples_build_and_run():
script = INTEROP / "build_interop_rust.sh"
subprocess.run(["bash", str(script)], cwd=ROOT, check=True, text=True)
+42
View File
@@ -0,0 +1,42 @@
"""PROTEL string tuple codegen (no implicit NUL termination)."""
from pathlib import Path
from src.cpp_transpiler import transpile_to_cpp
from src.parser import parse_protel
EXAMPLES = Path(__file__).resolve().parent.parent / "examples"
def test_string_literal_emits_char_tuple_not_c_string():
tree = parse_protel(
"SECTION s;\n"
"DCL writeln PROC(m PTR TO char) EXTERNAL;\n"
"DCL Start PROC() IS ENTRY;\n"
"DCL Start PROC() IS BLOCK writeln({'Hi', 0}); ENDBLOCK;\n"
)
cpp = transpile_to_cpp(tree)
assert '"Hi"' not in cpp
assert "(const char[]){ 'H', 'i', 0 }" in cpp
def test_string_without_nul_emits_no_trailing_zero():
tree = parse_protel(
"SECTION s;\n"
"DCL writeln PROC(m PTR TO char) EXTERNAL;\n"
"DCL Start PROC() IS ENTRY;\n"
"DCL Start PROC() IS BLOCK writeln({'Hi'}); ENDBLOCK;\n"
)
cpp = transpile_to_cpp(tree)
assert "(const char[]){ 'H', 'i' }" in cpp
assert ", 0 }" not in cpp
def test_hello_uses_explicit_nul_suffix():
source = (EXAMPLES / "Hello.protel").read_text(encoding="utf-8")
assert "{'Hello, World!', 0}" in source
cpp = transpile_to_cpp(parse_protel(source), source_name="Hello.protel")
assert "(const char[]){" in cpp
assert "'!'" in cpp
assert ", 0 }" in cpp
assert '"Hello, World!"' not in cpp
+37
View File
@@ -0,0 +1,37 @@
"""Swift interop example tests (transpile + optional link)."""
import shutil
import subprocess
from pathlib import Path
import pytest
from src.cpp_transpiler import transpile_to_cpp
from src.parser import parse_protel
ROOT = Path(__file__).resolve().parent.parent
INTEROP = ROOT / "examples" / "interop"
def test_protel_calls_swift_emits_external_swift_greet():
source = (INTEROP / "protel_calls_swift.protel").read_text(encoding="utf-8")
cpp = transpile_to_cpp(parse_protel(source), source_name="protel_calls_swift.protel")
assert 'extern "C"' in cpp
assert "void swift_greet(const char* name, int16_t value)" in cpp
assert "swift_greet(" in cpp
assert "protel_generated::protel_calls_swift::Start()" in cpp
def test_protel_for_swift_exports_c_linkage():
source = (INTEROP / "protel_for_swift.protel").read_text(encoding="utf-8")
cpp = transpile_to_cpp(parse_protel(source), source_name="protel_for_swift.protel")
assert "/* EXPORT protel_add" in cpp
assert "int16_t protel_add(int16_t a, int16_t b)" in cpp
assert "return (a + b)" in cpp
assert "int main()" not in cpp
@pytest.mark.skipif(shutil.which("swiftc") is None, reason="swiftc not installed")
def test_interop_examples_build_and_run():
script = INTEROP / "build_interop.sh"
subprocess.run(["bash", str(script)], cwd=ROOT, check=True, text=True)
+75
View File
@@ -0,0 +1,75 @@
"""Transpiler tests correlated to PROTEL 2026 manuals."""
from pathlib import Path
from src.parser import parse_protel
from src.transpiler import transpile_to_c
EXAMPLES = Path(__file__).resolve().parent.parent / "examples"
def _transpile_example(name: str) -> str:
source = (EXAMPLES / name).read_text(encoding="utf-8")
tree = parse_protel(source)
return transpile_to_c(tree, source_name=name)
def test_transpile_factorial_contains_procedure():
c = _transpile_example("intro_1_3_factorial.protel")
assert "int16_t factorial(" in c
assert "while (" in c
assert "return result;" in c
def test_transpile_types_emits_typedefs():
c = _transpile_example("intro_2_1_types.protel")
assert "typedef int16_t integer;" in c
assert "typedef int16_t digit_register[16];" in c
assert "seconds_per_hour" in c
def test_transpile_assignment_maps_arrow_to_equals():
c = _transpile_example("intro_2_2_calculate_average.protel")
assert "average =" in c
assert "return average;" in c
def test_transpile_case_emits_switch():
c = _transpile_example("intro_3_2_4_case.protel")
assert "switch (n)" in c
assert "case 0:" in c
assert "default:" not in c
def test_transpile_for_emits_c_for_loop():
c = _transpile_example("intro_3_2_6_sum_table.protel")
assert "for (int32_t i = 0;" in c
assert "return sum;" in c
def test_transpile_struct_emits_fields():
c = _transpile_example("ref_8_1_task_block_struct.protel")
assert "typedef struct {" in c
assert "uint8_t priority;" in c
assert "uint8_t completed;" in c
assert "task_block * next_task;" in c
def test_transpile_class_type_emits_static_class_var():
c = _transpile_example("ref_oo_class_with_var.protel")
assert "typedef struct class_with_var_t" in c
assert "static int16_t class_with_var_class_var" in c
assert "void class_with_var_class_method(int16_t parameter)" in c
assert "class_with_var_class_var = 5" in c
def test_transpile_class_method_invocation():
c = _transpile_example("ref_oo_class_method_invoke.protel")
assert "class_with_class_method_class_method(5)" in c
assert "class_with_class_method_class_method(6)" in c
def test_transpile_emits_header():
c = _transpile_example("intro_1_3_factorial.protel")
assert "Generated by PROTEL 2026 transpiler" in c
assert "#include <stdint.h>" in c
+75
View File
@@ -0,0 +1,75 @@
"""Type error examples and strong typing tests (Reference Manual §11.3)."""
from pathlib import Path
import pytest
from src.cpp_transpiler import transpile_to_cpp
from src.parser import parse_protel
from src.type_checker import TypeCheckError
ROOT = Path(__file__).resolve().parent.parent
ERRORS = ROOT / "examples" / "errors"
def _read(name: str) -> str:
return (ERRORS / name).read_text(encoding="utf-8")
@pytest.mark.parametrize(
"filename,message_fragment",
[
("err_assign_integer_to_char.protel", "cannot assign integer to char"),
(
"err_assign_integer_to_packed_byte.protel",
"packed byte-sized type",
),
("err_assign_integer_to_bool.protel", "cannot assign"),
("err_constant_out_of_range.protel", "out of range"),
("err_assign_incompatible_pointer.protel", "cannot assign"),
("err_return_type_mismatch.protel", "RETURN type"),
],
)
def test_error_examples_fail_type_check(filename: str, message_fragment: str):
source = _read(filename)
tree = parse_protel(source)
with pytest.raises(TypeCheckError, match=message_fragment):
transpile_to_cpp(tree, source_name=filename)
def test_ok_char_literal_transpiles():
source = _read("ok_assign_char_literal.protel")
tree = parse_protel(source)
cpp = transpile_to_cpp(tree, source_name="ok_assign_char_literal.protel")
assert "Generated by PROTEL" in cpp
def test_protel_driver_reports_type_error():
import subprocess
result = subprocess.run(
[
str(ROOT / ".venv" / "bin" / "python"),
str(ROOT / "protel"),
str(ERRORS / "err_assign_integer_to_char.protel"),
"--parse-only",
],
capture_output=True,
text=True,
cwd=ROOT,
)
assert result.returncode == 0
result = subprocess.run(
[
str(ROOT / ".venv" / "bin" / "python"),
str(ROOT / "protel"),
str(ERRORS / "err_assign_integer_to_char.protel"),
],
capture_output=True,
text=True,
cwd=ROOT,
)
assert result.returncode == 1
assert "protel: type error" in result.stderr
assert "cannot assign integer to char" in result.stderr
+51
View File
@@ -0,0 +1,51 @@
"""Legacy PLS module vdi.aa01 parse and compile tests."""
import subprocess
from pathlib import Path
from src.cpp_transpiler import transpile_to_cpp
from src.parser import parse_protel
from src.preprocess import normalize_keywords
ROOT = Path(__file__).resolve().parent.parent
VDI = ROOT / "vdi.aa01"
PROTEL = ROOT / "protel"
def test_preprocess_strips_dollar_li_directive():
norm = normalize_keywords(VDI.read_text(encoding="utf-8"), classical=True)
assert "$LI" not in norm
assert "modentry" not in norm
assert "DCL" in norm
assert "vdi_debugging_flag" in norm
assert "BOOL IS TRUE" in norm
def test_vdi_aa01_parses():
tree = parse_protel(VDI.read_text(encoding="utf-8"), classical=True)
assert len(tree) == 1
section = tree[0]
assert section.name == "VDI"
assert len(section.declarations) == 1
assert section.declarations[0].names == ["vdi_debugging_flag"]
def test_vdi_aa01_transpiles_debug_flag():
tree = parse_protel(VDI.read_text(encoding="utf-8"), classical=True)
cpp = transpile_to_cpp(tree, source_name="vdi.aa01", classical=True)
assert "bool vdi_debugging_flag = true;" in cpp
assert "namespace VDI" in cpp
def test_vdi_aa01_compiles_to_object():
out = ROOT / "build" / "test_vdi.aa01.o"
if out.exists():
out.unlink()
subprocess.run(
[str(ROOT / ".venv/bin/python"), str(PROTEL), str(VDI), "-c", "-o", str(out)],
cwd=ROOT,
check=True,
text=True,
)
assert out.is_file()
assert out.stat().st_size > 0