Initial PROTEL 2026 toolchain import
This commit is contained in:
@@ -0,0 +1,3 @@
|
||||
"""PROTEL 2026 parser and transpiler."""
|
||||
|
||||
__version__ = "0.1.0"
|
||||
@@ -0,0 +1,294 @@
|
||||
"""AST node definitions for PROTEL 2026."""
|
||||
|
||||
from __future__ import annotations
|
||||
|
||||
from dataclasses import dataclass, field
|
||||
from typing import Any
|
||||
|
||||
|
||||
@dataclass
|
||||
class Section:
|
||||
module_type: str
|
||||
section_kind: str
|
||||
name: str
|
||||
of_modules: list[str] = field(default_factory=list)
|
||||
uses_modules: list[str] = field(default_factory=list)
|
||||
declarations: list[Any] = field(default_factory=list)
|
||||
statements: list[Any] = field(default_factory=list)
|
||||
class_impls: list[Any] = field(default_factory=list)
|
||||
|
||||
|
||||
@dataclass
|
||||
class TypeDecl:
|
||||
names: list[str]
|
||||
type_spec: Any
|
||||
|
||||
|
||||
@dataclass
|
||||
class VarDecl:
|
||||
names: list[str]
|
||||
type_spec: Any
|
||||
init: Any | None = None
|
||||
storage_class: str | None = None
|
||||
ovly_fields: list[tuple[Any, list[str], Any]] | None = None
|
||||
|
||||
|
||||
@dataclass
|
||||
class ProcDecl:
|
||||
name: str
|
||||
parms: list[tuple[list[str], Any, Any]]
|
||||
return_type: Any | None
|
||||
body: Any | None
|
||||
pclass: str | None = None
|
||||
intrinsic: bool = False
|
||||
forward: bool = False
|
||||
external: bool = False
|
||||
entry: bool = False
|
||||
export: bool = False
|
||||
|
||||
|
||||
@dataclass
|
||||
class ClassDataPart:
|
||||
access_attrs: list[str]
|
||||
fields: list[tuple[list[str], Any]]
|
||||
|
||||
|
||||
@dataclass
|
||||
class MethodDecl:
|
||||
names: list[str]
|
||||
parms: list[tuple[list[str], Any, bool]]
|
||||
return_type: Any | None
|
||||
attrs: list[str] = field(default_factory=list)
|
||||
|
||||
|
||||
@dataclass
|
||||
class MethodSection:
|
||||
attrs: list[str]
|
||||
methods: list[MethodDecl]
|
||||
|
||||
|
||||
@dataclass
|
||||
class ClassType:
|
||||
end_name: str
|
||||
base: Any | None
|
||||
data_parts: list[ClassDataPart]
|
||||
operations: list[MethodSection]
|
||||
|
||||
|
||||
@dataclass
|
||||
class MethodImplDecl:
|
||||
name: str
|
||||
body: Any
|
||||
|
||||
|
||||
@dataclass
|
||||
class ClassImplSection:
|
||||
class_name: str
|
||||
declarations: list[Any]
|
||||
statements: list[Any] = field(default_factory=list)
|
||||
|
||||
|
||||
@dataclass
|
||||
class Block:
|
||||
declarations: list[Any]
|
||||
statements: list[Any]
|
||||
|
||||
|
||||
@dataclass
|
||||
class IfStmt:
|
||||
condition: Any
|
||||
then_part: list[Any]
|
||||
else_part: list[Any] = field(default_factory=list)
|
||||
|
||||
|
||||
@dataclass
|
||||
class LoopStmt:
|
||||
while_expr: Any | None
|
||||
body: list[Any]
|
||||
|
||||
|
||||
@dataclass
|
||||
class ForStmt:
|
||||
var: str
|
||||
from_expr: Any | None
|
||||
to_expr: Any | None
|
||||
direction: str | None
|
||||
by_expr: Any | None
|
||||
while_expr: Any | None
|
||||
over_type: Any | None
|
||||
body: list[Any]
|
||||
|
||||
|
||||
@dataclass
|
||||
class OverStmt:
|
||||
over_type: Any
|
||||
body: list[Any]
|
||||
|
||||
|
||||
@dataclass
|
||||
class CaseArm:
|
||||
labels: Any
|
||||
statements: list[Any]
|
||||
|
||||
|
||||
@dataclass
|
||||
class CaseStmt:
|
||||
selector: Any
|
||||
arms: list[CaseArm]
|
||||
out_statements: list[Any]
|
||||
is_select: bool = False
|
||||
|
||||
|
||||
@dataclass
|
||||
class ExitStmt:
|
||||
pass
|
||||
|
||||
|
||||
@dataclass
|
||||
class BindStmt:
|
||||
bindings: list[tuple[str, Any, Any | None]]
|
||||
|
||||
|
||||
@dataclass
|
||||
class WithStmt:
|
||||
refs: list[Any]
|
||||
|
||||
|
||||
@dataclass
|
||||
class CastExpr:
|
||||
operand: Any
|
||||
target_type: Any
|
||||
|
||||
|
||||
@dataclass
|
||||
class AreaType:
|
||||
options: list[str]
|
||||
size_expr: Any
|
||||
fields: list[tuple[list[str], Any]]
|
||||
|
||||
|
||||
@dataclass
|
||||
class ReturnStmt:
|
||||
value: Any | None = None
|
||||
|
||||
|
||||
@dataclass
|
||||
class AssignExpr:
|
||||
value: Any
|
||||
target: Any
|
||||
|
||||
|
||||
@dataclass
|
||||
class BinExpr:
|
||||
op: str
|
||||
left: Any
|
||||
right: Any
|
||||
|
||||
|
||||
@dataclass
|
||||
class UnaryExpr:
|
||||
op: str
|
||||
operand: Any
|
||||
|
||||
|
||||
@dataclass
|
||||
class BuiltinExpr:
|
||||
name: str
|
||||
operand: Any
|
||||
|
||||
|
||||
@dataclass
|
||||
class VarRef:
|
||||
name: str
|
||||
indices: list[Any] = field(default_factory=list)
|
||||
is_self: bool = False
|
||||
is_super: bool = False
|
||||
|
||||
|
||||
@dataclass
|
||||
class MemberRef:
|
||||
base: Any
|
||||
member: str
|
||||
|
||||
|
||||
@dataclass
|
||||
class MethodCall:
|
||||
receiver: Any | None
|
||||
name: str
|
||||
args: list[Any] = field(default_factory=list)
|
||||
|
||||
|
||||
@dataclass
|
||||
class ProcCall:
|
||||
name: str
|
||||
args: list[Any] = field(default_factory=list)
|
||||
|
||||
|
||||
@dataclass
|
||||
class Literal:
|
||||
kind: str
|
||||
value: Any
|
||||
|
||||
|
||||
@dataclass
|
||||
class TupleLit:
|
||||
elements: list[Any]
|
||||
|
||||
|
||||
@dataclass
|
||||
class RangeType:
|
||||
low: Any
|
||||
high: Any
|
||||
packed: int | None = None
|
||||
|
||||
|
||||
@dataclass
|
||||
class SymbolicRange:
|
||||
members: list[str]
|
||||
|
||||
|
||||
@dataclass
|
||||
class DefinedType:
|
||||
name: str
|
||||
|
||||
|
||||
@dataclass
|
||||
class BoolType:
|
||||
packed: int | None = None
|
||||
|
||||
|
||||
@dataclass
|
||||
class PtrType:
|
||||
target: Any
|
||||
|
||||
|
||||
@dataclass
|
||||
class SetType:
|
||||
member_type: Any
|
||||
|
||||
|
||||
@dataclass
|
||||
class StructType:
|
||||
fields: list[tuple[list[str], Any]]
|
||||
|
||||
|
||||
@dataclass
|
||||
class TableType:
|
||||
low: Any
|
||||
high: Any
|
||||
element_type: Any
|
||||
packed: int | None = None
|
||||
|
||||
|
||||
@dataclass
|
||||
class DescType:
|
||||
low: Any | None
|
||||
high: Any | None
|
||||
element_type: Any
|
||||
|
||||
|
||||
@dataclass
|
||||
class ProcTypeSig:
|
||||
parms: list[tuple[list[str], Any, Any]]
|
||||
return_type: Any | None
|
||||
pclass: str | None = None
|
||||
+103
@@ -0,0 +1,103 @@
|
||||
"""Compile and link PROTEL-generated C++ on macOS / Linux."""
|
||||
|
||||
from __future__ import annotations
|
||||
|
||||
import shutil
|
||||
import subprocess
|
||||
from pathlib import Path
|
||||
|
||||
_ROOT = Path(__file__).resolve().parent.parent
|
||||
_RUNTIME_DIR = Path(__file__).resolve().parent / "runtime"
|
||||
_RUNTIME_IO_C = _RUNTIME_DIR / "protel_io.c"
|
||||
|
||||
|
||||
def find_cxx_compiler() -> str | None:
|
||||
for name in ("g++", "c++", "clang++"):
|
||||
path = shutil.which(name)
|
||||
if path:
|
||||
return path
|
||||
return None
|
||||
|
||||
|
||||
def compile_cpp(
|
||||
cpp_source: Path,
|
||||
output: Path,
|
||||
*,
|
||||
compile_only: bool = False,
|
||||
debug: bool = False,
|
||||
link_runtime: bool = True,
|
||||
extra_flags: list[str] | None = None,
|
||||
) -> None:
|
||||
compiler = find_cxx_compiler()
|
||||
if compiler is None:
|
||||
raise RuntimeError("no C++ compiler found (tried g++, c++, clang++)")
|
||||
|
||||
output.parent.mkdir(parents=True, exist_ok=True)
|
||||
cmd = [
|
||||
compiler,
|
||||
"-std=c++20",
|
||||
"-Wall",
|
||||
"-Wextra",
|
||||
f"-I{_RUNTIME_DIR}",
|
||||
]
|
||||
if debug:
|
||||
cmd.append("-g")
|
||||
if extra_flags:
|
||||
cmd.extend(extra_flags)
|
||||
|
||||
src = str(cpp_source.resolve())
|
||||
if compile_only:
|
||||
cmd.extend(["-c", src, "-o", str(output.resolve())])
|
||||
else:
|
||||
cmd.append(src)
|
||||
if link_runtime and _RUNTIME_IO_C.exists():
|
||||
cmd.append(str(_RUNTIME_IO_C.resolve()))
|
||||
cmd.extend(["-o", str(output.resolve())])
|
||||
|
||||
result = subprocess.run(cmd, capture_output=True, text=True, cwd=_ROOT)
|
||||
if result.returncode != 0:
|
||||
msg = result.stderr.strip() or result.stdout.strip() or "compile failed"
|
||||
raise RuntimeError(msg)
|
||||
|
||||
|
||||
def check_cpp_syntax(
|
||||
cpp_source: Path,
|
||||
*,
|
||||
extra_flags: list[str] | None = None,
|
||||
) -> None:
|
||||
compiler = find_cxx_compiler()
|
||||
if compiler is None:
|
||||
raise RuntimeError("no C++ compiler found (tried g++, c++, clang++)")
|
||||
|
||||
cmd = [
|
||||
compiler,
|
||||
"-std=c++20",
|
||||
"-Wall",
|
||||
"-Wextra",
|
||||
f"-I{_RUNTIME_DIR}",
|
||||
"-fsyntax-only",
|
||||
str(cpp_source.resolve()),
|
||||
]
|
||||
if extra_flags:
|
||||
cmd.extend(extra_flags)
|
||||
result = subprocess.run(cmd, capture_output=True, text=True, cwd=_ROOT)
|
||||
if result.returncode != 0:
|
||||
msg = result.stderr.strip() or result.stdout.strip() or "syntax check failed"
|
||||
raise RuntimeError(msg)
|
||||
|
||||
|
||||
def run_executable(
|
||||
path: Path,
|
||||
program_args: list[str] | None = None,
|
||||
) -> tuple[int, str, str]:
|
||||
exe = path.resolve()
|
||||
cmd = [str(exe)]
|
||||
if program_args:
|
||||
cmd.extend(program_args)
|
||||
result = subprocess.run(
|
||||
cmd,
|
||||
capture_output=True,
|
||||
text=True,
|
||||
cwd=exe.parent,
|
||||
)
|
||||
return result.returncode, result.stdout, result.stderr
|
||||
@@ -0,0 +1,755 @@
|
||||
"""PROTEL 2026 to C++ transpiler (namespaces, classes, this)."""
|
||||
|
||||
from __future__ import annotations
|
||||
|
||||
from dataclasses import dataclass
|
||||
from pathlib import Path
|
||||
from typing import Any
|
||||
|
||||
from . import ast_nodes as ast
|
||||
from .transpiler import CTranspiler, TranspileError
|
||||
|
||||
_CPP_RESERVED_TYPE_NAMES = frozenset({
|
||||
"bool", "char", "double", "float", "int", "long", "short", "void",
|
||||
})
|
||||
|
||||
_LIBC_EXTERNAL_HEADERS: dict[str, str] = {
|
||||
"printf": "<cstdio>",
|
||||
"atoi": "<cstdlib>",
|
||||
}
|
||||
|
||||
|
||||
@dataclass(frozen=True)
|
||||
class _EntryPointInfo:
|
||||
namespace: str
|
||||
name: str
|
||||
parms: list[tuple[list[str], Any, bool]]
|
||||
return_type: Any | None
|
||||
returns_integer: bool
|
||||
unix_argv: bool
|
||||
|
||||
|
||||
def _sanitize_namespace(name: str) -> str:
|
||||
out = []
|
||||
for ch in name:
|
||||
if ch.isalnum() or ch == "_":
|
||||
out.append(ch)
|
||||
else:
|
||||
out.append("_")
|
||||
if not out or out[0].isdigit():
|
||||
out.insert(0, "_")
|
||||
return "".join(out)
|
||||
|
||||
|
||||
class CppTranspiler(CTranspiler):
|
||||
def __init__(self, *, classical: bool = False, source_name: str = "input.protel"):
|
||||
super().__init__(classical=classical, source_name=source_name)
|
||||
self._cpp = True
|
||||
self._current_namespace: str | None = None
|
||||
self._namespace_stack: list[str] = []
|
||||
self._entry_point: _EntryPointInfo | None = None
|
||||
self._section_class_bodies: list[tuple[str, ast.ClassType]] = []
|
||||
self._section_method_impls: list[
|
||||
tuple[str, ast.MethodImplDecl, ast.MethodDecl | None]
|
||||
] = []
|
||||
self._external_procs: list[ast.ProcDecl] = []
|
||||
|
||||
def transpile(self, compilation_unit: list[ast.Section]) -> str:
|
||||
self.lines = []
|
||||
self._method_impls = []
|
||||
self._class_methods = {}
|
||||
self._class_vars = {}
|
||||
self._var_types = {}
|
||||
self._entry_point = None
|
||||
self._section_class_bodies = []
|
||||
self._section_method_impls = []
|
||||
self._external_procs = []
|
||||
|
||||
self._section_by_name = {section.name: section for section in compilation_unit}
|
||||
self._entry_point = self._resolve_entry_point(compilation_unit)
|
||||
self._exported_procs = self._resolve_exported_procedures(compilation_unit)
|
||||
self._exported_body_names = {proc.name for proc in self._exported_procs}
|
||||
|
||||
self.emit("/* Generated by PROTEL 2026 C++ transpiler */")
|
||||
self.emit(f"/* Source: {self.source_name} */")
|
||||
self.emit("/* EXTERNAL C linkage for I/O; minimal runtime (protel_io.c). */")
|
||||
self.emit('#include <cstdint>')
|
||||
|
||||
self._collect_external_procs(compilation_unit)
|
||||
libc_headers = sorted(
|
||||
{
|
||||
_LIBC_EXTERNAL_HEADERS[proc.name]
|
||||
for proc in self._external_procs
|
||||
if proc.name in _LIBC_EXTERNAL_HEADERS
|
||||
}
|
||||
)
|
||||
for header in libc_headers:
|
||||
self.emit(f"#include {header}")
|
||||
self.emit("")
|
||||
|
||||
declared_externals = [
|
||||
proc
|
||||
for proc in self._external_procs
|
||||
if proc.name not in _LIBC_EXTERNAL_HEADERS
|
||||
]
|
||||
if declared_externals:
|
||||
self.emit('extern "C" {')
|
||||
self.indent += 1
|
||||
for proc in declared_externals:
|
||||
self.emit(f"{self._cpp_external_proc_signature(proc)};")
|
||||
self.indent -= 1
|
||||
self.emit("}")
|
||||
self.emit("")
|
||||
|
||||
self.emit("namespace protel_generated {")
|
||||
|
||||
for section in compilation_unit:
|
||||
self._emit_cpp_section(section)
|
||||
|
||||
self.emit("} // namespace protel_generated")
|
||||
self.emit("")
|
||||
|
||||
if self._exported_procs:
|
||||
self.emit('extern "C" {')
|
||||
self.indent += 1
|
||||
for proc in self._exported_procs:
|
||||
self._emit_cpp_exported_procedure(proc)
|
||||
self.indent -= 1
|
||||
self.emit("}")
|
||||
self.emit("")
|
||||
|
||||
if self._entry_point:
|
||||
self._emit_cpp_main_wrapper(self._entry_point)
|
||||
|
||||
return "\n".join(self.lines) + "\n"
|
||||
|
||||
def _emit_cpp_main_wrapper(self, entry: _EntryPointInfo) -> None:
|
||||
ns, name = entry.namespace, entry.name
|
||||
call = f"protel_generated::{ns}::{name}"
|
||||
if entry.unix_argv:
|
||||
self.emit("int main(int argc, char** argv) {")
|
||||
self.indent += 1
|
||||
if entry.returns_integer:
|
||||
self.emit(f"return {call}(argc, argv);")
|
||||
else:
|
||||
self.emit(f"{call}(argc, argv);")
|
||||
self.emit("return 0;")
|
||||
else:
|
||||
self.emit("int main() {")
|
||||
self.indent += 1
|
||||
if entry.returns_integer:
|
||||
self.emit(f"return {call}();")
|
||||
else:
|
||||
self.emit(f"{call}();")
|
||||
self.emit("return 0;")
|
||||
self.indent -= 1
|
||||
self.emit("}")
|
||||
self.emit("")
|
||||
|
||||
def _resolve_entry_point(
|
||||
self, compilation_unit: list[ast.Section]
|
||||
) -> _EntryPointInfo | None:
|
||||
entries: list[tuple[ast.Section, ast.ProcDecl]] = []
|
||||
for section in compilation_unit:
|
||||
for decl in section.declarations:
|
||||
if isinstance(decl, ast.ProcDecl) and decl.entry:
|
||||
entries.append((section, decl))
|
||||
|
||||
if not entries:
|
||||
return None
|
||||
if len(entries) > 1:
|
||||
names = ", ".join(decl.name for _, decl in entries)
|
||||
raise TranspileError(
|
||||
f"multiple ENTRY procedures ({names}); only one ENTRY per module"
|
||||
)
|
||||
|
||||
entry_section, entry_decl = entries[0]
|
||||
if entry_decl.return_type or entry_decl.body:
|
||||
raise TranspileError(
|
||||
f"ENTRY procedure {entry_decl.name!r} must be declared as "
|
||||
f"PROC[(argc integer, argv PTR TO PTR TO char)] IS ENTRY or PROC() IS ENTRY"
|
||||
)
|
||||
|
||||
body_section: ast.Section | None = None
|
||||
body_decl: ast.ProcDecl | None = None
|
||||
for section in compilation_unit:
|
||||
for decl in section.declarations:
|
||||
if (
|
||||
isinstance(decl, ast.ProcDecl)
|
||||
and decl.name == entry_decl.name
|
||||
and decl.body is not None
|
||||
and not decl.entry
|
||||
):
|
||||
if body_decl is not None:
|
||||
raise TranspileError(
|
||||
f"duplicate body for ENTRY procedure {entry_decl.name!r}"
|
||||
)
|
||||
body_section = section
|
||||
body_decl = decl
|
||||
|
||||
if body_decl is None:
|
||||
raise TranspileError(
|
||||
f"ENTRY procedure {entry_decl.name!r} has no procedure body in this module"
|
||||
)
|
||||
if not self._entry_parm_lists_match(entry_decl.parms, body_decl.parms):
|
||||
raise TranspileError(
|
||||
f"ENTRY procedure {entry_decl.name!r} declaration parameters must "
|
||||
f"match the procedure body signature"
|
||||
)
|
||||
if body_decl.return_type is not None and not self._is_integer_return_type(
|
||||
body_decl.return_type
|
||||
):
|
||||
raise TranspileError(
|
||||
f"ENTRY procedure {entry_decl.name!r} may RETURNS integer only "
|
||||
f"(shell exit status)"
|
||||
)
|
||||
unix_argv = self._is_unix_argv_entry_parms(entry_decl.parms)
|
||||
if entry_decl.parms and not unix_argv:
|
||||
raise TranspileError(
|
||||
f"ENTRY procedure {entry_decl.name!r} parameters must be "
|
||||
f"(argc integer, argv PTR TO PTR TO char) for UNIX command-line hosts"
|
||||
)
|
||||
if body_section is not entry_section:
|
||||
raise TranspileError(
|
||||
f"ENTRY procedure {entry_decl.name!r} must be declared and defined "
|
||||
f"in the same section ({entry_section.name!r})"
|
||||
)
|
||||
|
||||
returns_integer = body_decl.return_type is not None
|
||||
return _EntryPointInfo(
|
||||
namespace=_sanitize_namespace(body_section.name),
|
||||
name=entry_decl.name,
|
||||
parms=entry_decl.parms,
|
||||
return_type=body_decl.return_type,
|
||||
returns_integer=returns_integer,
|
||||
unix_argv=unix_argv,
|
||||
)
|
||||
|
||||
def _unwrap_entry_type(self, spec: Any) -> Any:
|
||||
from lark import Tree
|
||||
|
||||
while isinstance(spec, Tree):
|
||||
if spec.children:
|
||||
spec = spec.children[0]
|
||||
else:
|
||||
break
|
||||
return spec
|
||||
|
||||
def _is_integer_type(self, spec: Any) -> bool:
|
||||
spec = self._unwrap_entry_type(spec)
|
||||
if isinstance(spec, ast.DefinedType):
|
||||
return spec.name == "integer"
|
||||
if isinstance(spec, ast.RangeType):
|
||||
return True
|
||||
return False
|
||||
|
||||
def _is_ptr_to_ptr_to_char(self, spec: Any) -> bool:
|
||||
spec = self._unwrap_entry_type(spec)
|
||||
if not isinstance(spec, ast.PtrType):
|
||||
return False
|
||||
target = self._unwrap_entry_type(spec.target)
|
||||
if not isinstance(target, ast.PtrType):
|
||||
return False
|
||||
inner = self._unwrap_entry_type(target.target)
|
||||
return isinstance(inner, ast.DefinedType) and inner.name == "char"
|
||||
|
||||
def _is_unix_argv_entry_parms(
|
||||
self, parms: list[tuple[list[str], Any, bool]]
|
||||
) -> bool:
|
||||
if len(parms) != 2:
|
||||
return False
|
||||
_, argc_type, _ = parms[0]
|
||||
_, argv_type, _ = parms[1]
|
||||
return self._is_integer_type(argc_type) and self._is_ptr_to_ptr_to_char(
|
||||
argv_type
|
||||
)
|
||||
|
||||
def _entry_parm_lists_match(
|
||||
self,
|
||||
left: list[tuple[list[str], Any, bool]],
|
||||
right: list[tuple[list[str], Any, bool]],
|
||||
) -> bool:
|
||||
if len(left) != len(right):
|
||||
return False
|
||||
for (_, left_type, left_ref), (_, right_type, right_ref) in zip(left, right):
|
||||
if left_ref != right_ref:
|
||||
return False
|
||||
if not self._entry_parm_types_equal(left_type, right_type):
|
||||
return False
|
||||
return True
|
||||
|
||||
def _entry_parm_types_equal(self, left: Any, right: Any) -> bool:
|
||||
left = self._unwrap_entry_type(left)
|
||||
right = self._unwrap_entry_type(right)
|
||||
if type(left) is not type(right):
|
||||
return False
|
||||
if isinstance(left, ast.DefinedType):
|
||||
return left.name == right.name
|
||||
if isinstance(left, ast.PtrType):
|
||||
return self._entry_parm_types_equal(left.target, right.target)
|
||||
if isinstance(left, ast.RangeType):
|
||||
return (
|
||||
self._c_expr(left.low) == self._c_expr(right.low)
|
||||
and self._c_expr(left.high) == self._c_expr(right.high)
|
||||
)
|
||||
return left == right
|
||||
|
||||
def _is_integer_return_type(self, spec: Any) -> bool:
|
||||
return self._is_integer_type(spec)
|
||||
|
||||
def _resolve_exported_procedures(
|
||||
self, compilation_unit: list[ast.Section]
|
||||
) -> list[ast.ProcDecl]:
|
||||
exports: dict[str, tuple[ast.Section, ast.ProcDecl]] = {}
|
||||
for section in compilation_unit:
|
||||
for decl in section.declarations:
|
||||
if isinstance(decl, ast.ProcDecl) and decl.export:
|
||||
if decl.name in exports:
|
||||
raise TranspileError(
|
||||
f"duplicate EXPORT declaration for {decl.name!r}"
|
||||
)
|
||||
exports[decl.name] = (section, decl)
|
||||
|
||||
if not exports:
|
||||
return []
|
||||
|
||||
bodies: dict[str, ast.ProcDecl] = {}
|
||||
body_sections: dict[str, ast.Section] = {}
|
||||
for section in compilation_unit:
|
||||
for decl in section.declarations:
|
||||
if (
|
||||
isinstance(decl, ast.ProcDecl)
|
||||
and decl.name in exports
|
||||
and decl.body is not None
|
||||
and not decl.export
|
||||
):
|
||||
if decl.name in bodies:
|
||||
raise TranspileError(
|
||||
f"duplicate body for EXPORT procedure {decl.name!r}"
|
||||
)
|
||||
bodies[decl.name] = decl
|
||||
body_sections[decl.name] = section
|
||||
|
||||
resolved: list[ast.ProcDecl] = []
|
||||
for name, (export_section, export_decl) in exports.items():
|
||||
body = bodies.get(name)
|
||||
if body is None:
|
||||
raise TranspileError(
|
||||
f"EXPORT procedure {name!r} has no procedure body in this module"
|
||||
)
|
||||
if body_sections[name] is not export_section:
|
||||
raise TranspileError(
|
||||
f"EXPORT procedure {name!r} must be declared and defined "
|
||||
f"in the same section ({export_section.name!r})"
|
||||
)
|
||||
if (
|
||||
body.parms != export_decl.parms
|
||||
or body.return_type != export_decl.return_type
|
||||
or body.pclass != export_decl.pclass
|
||||
):
|
||||
raise TranspileError(
|
||||
f"EXPORT declaration and body signatures differ for {name!r}"
|
||||
)
|
||||
resolved.append(body)
|
||||
return resolved
|
||||
|
||||
def _emit_cpp_exported_procedure(self, proc: ast.ProcDecl):
|
||||
self.emit(self._cpp_proc_signature(proc))
|
||||
self.emit("{")
|
||||
self.indent += 1
|
||||
self._emit_block_body(proc.body)
|
||||
self.indent -= 1
|
||||
self.emit("}")
|
||||
self.emit("")
|
||||
|
||||
def _collect_external_procs(self, compilation_unit: list[ast.Section]) -> None:
|
||||
self._external_procs = []
|
||||
for section in compilation_unit:
|
||||
for decl in section.declarations:
|
||||
if isinstance(decl, ast.ProcDecl) and decl.external:
|
||||
self._external_procs.append(decl)
|
||||
|
||||
def _embedded_module_names(self, section: ast.Section) -> list[str]:
|
||||
names: list[str] = []
|
||||
seen: set[str] = set()
|
||||
for module_name in (*section.of_modules, *section.uses_modules):
|
||||
if module_name not in seen:
|
||||
seen.add(module_name)
|
||||
names.append(module_name)
|
||||
return names
|
||||
|
||||
def _emit_embedded_usings(self, section: ast.Section) -> None:
|
||||
for module_name in self._embedded_module_names(section):
|
||||
embedded_ns = _sanitize_namespace(module_name)
|
||||
embedded = self._section_by_name.get(module_name)
|
||||
if embedded is None:
|
||||
continue
|
||||
symbols: list[str] = []
|
||||
for decl in embedded.declarations:
|
||||
if isinstance(decl, ast.VarDecl):
|
||||
symbols.extend(decl.names)
|
||||
elif isinstance(decl, ast.ProcDecl):
|
||||
if (
|
||||
decl.external
|
||||
or decl.forward
|
||||
or decl.entry
|
||||
or decl.export
|
||||
or decl.intrinsic
|
||||
):
|
||||
continue
|
||||
symbols.append(decl.name)
|
||||
for symbol in symbols:
|
||||
self.emit(f"using {embedded_ns}::{symbol};")
|
||||
if symbols:
|
||||
self.emit("")
|
||||
|
||||
def _emit_cpp_section(self, section: ast.Section):
|
||||
ns = _sanitize_namespace(section.name)
|
||||
self._current_namespace = ns
|
||||
self._namespace_stack.append(ns)
|
||||
self._section_class_bodies = []
|
||||
self._section_method_impls = []
|
||||
self.emit(f"namespace {ns} {{")
|
||||
self.indent += 1
|
||||
self.emit(f"/* {section.module_type} {section.section_kind} */")
|
||||
if section.uses_modules:
|
||||
self.emit(f"/* USES: {', '.join(section.uses_modules)} */")
|
||||
if section.of_modules:
|
||||
self.emit(f"/* OF: {', '.join(section.of_modules)} */")
|
||||
self.emit("")
|
||||
|
||||
self._emit_embedded_usings(section)
|
||||
|
||||
for decl in section.declarations:
|
||||
self._emit_cpp_toplevel_decl(decl)
|
||||
for impl in section.class_impls:
|
||||
self._queue_class_impl(impl)
|
||||
for stmt in section.statements:
|
||||
self._emit_stmt(stmt)
|
||||
|
||||
for class_name, spec in self._section_class_bodies:
|
||||
self._emit_cpp_class_definitions(class_name, spec)
|
||||
for class_name, impl, method_decl in self._section_method_impls:
|
||||
self._emit_cpp_method_impl(class_name, impl, method_decl)
|
||||
|
||||
self.indent -= 1
|
||||
self.emit(f"}} // namespace {ns}")
|
||||
self.emit("")
|
||||
self._namespace_stack.pop()
|
||||
self._current_namespace = self._namespace_stack[-1] if self._namespace_stack else None
|
||||
|
||||
def _emit_cpp_toplevel_decl(self, decl):
|
||||
if isinstance(decl, ast.TypeDecl):
|
||||
self.types.declare(decl.names, decl.type_spec)
|
||||
for name in decl.names:
|
||||
self.emit(f"/* TYPE {name} */")
|
||||
if isinstance(decl.type_spec, ast.ClassType):
|
||||
self._emit_cpp_class_declaration(decl.names[0], decl.type_spec)
|
||||
elif isinstance(decl.type_spec, ast.StructType):
|
||||
self._emit_cpp_struct(decl.names[0], decl.type_spec)
|
||||
elif isinstance(decl.type_spec, ast.SymbolicRange):
|
||||
self._emit_symbolic_typedef(decl.names[0], decl.type_spec)
|
||||
else:
|
||||
for name in decl.names:
|
||||
if name in _CPP_RESERVED_TYPE_NAMES:
|
||||
self.emit(
|
||||
f"/* TYPE {name} -> {self._cpp_type(decl.type_spec)} */"
|
||||
)
|
||||
else:
|
||||
self.emit(f"using {name} = {self._cpp_type(decl.type_spec)};")
|
||||
self.emit("")
|
||||
elif isinstance(decl, ast.VarDecl):
|
||||
type_name = self._decl_type_name(decl.type_spec)
|
||||
for name in decl.names:
|
||||
if type_name:
|
||||
self._var_types[name] = type_name
|
||||
line = f"{self._cpp_type_decl(decl.type_spec, name)}"
|
||||
if decl.init is not None:
|
||||
line += f" = {self._c_init(decl.init)}"
|
||||
line += ";"
|
||||
self.emit(line)
|
||||
self.emit("")
|
||||
elif isinstance(decl, ast.ProcDecl):
|
||||
if decl.intrinsic:
|
||||
return
|
||||
if decl.forward:
|
||||
self.emit(f"/* FORWARD {decl.name} */")
|
||||
self.emit(self._cpp_proc_signature(decl) + ";")
|
||||
self.emit("")
|
||||
return
|
||||
if decl.external:
|
||||
self._external_procs.append(decl)
|
||||
return
|
||||
if decl.entry:
|
||||
self.emit(f"/* ENTRY {decl.name} */")
|
||||
forward = ast.ProcDecl(
|
||||
name=decl.name,
|
||||
parms=decl.parms,
|
||||
return_type=(
|
||||
self._entry_point.return_type
|
||||
if self._entry_point is not None
|
||||
and self._entry_point.name == decl.name
|
||||
else None
|
||||
),
|
||||
body=None,
|
||||
pclass=decl.pclass,
|
||||
entry=True,
|
||||
)
|
||||
self.emit(self._cpp_proc_signature(forward) + ";")
|
||||
self.emit("")
|
||||
return
|
||||
if decl.export:
|
||||
self.emit(f"/* EXPORT {decl.name} (defined with C linkage below) */")
|
||||
self.emit("")
|
||||
return
|
||||
if decl.body and decl.name in self._exported_body_names:
|
||||
return
|
||||
if decl.body:
|
||||
self._emit_cpp_procedure(decl)
|
||||
else:
|
||||
self.emit(self._cpp_proc_signature(decl) + ";")
|
||||
self.emit("")
|
||||
|
||||
def _cpp_type(self, spec) -> str:
|
||||
spec = self._unwrap_type(spec)
|
||||
spec = self.types.resolve(spec)
|
||||
if isinstance(spec, ast.BoolType):
|
||||
return "bool"
|
||||
if isinstance(spec, ast.DefinedType) and spec.name in _CPP_RESERVED_TYPE_NAMES:
|
||||
resolved = self.types.resolve(spec)
|
||||
if resolved is not spec:
|
||||
return self._cpp_type(resolved)
|
||||
return self._c_type(spec)
|
||||
|
||||
def _cpp_type_decl(self, spec, name: str) -> str:
|
||||
spec = self._unwrap_type(spec)
|
||||
if isinstance(spec, ast.TableType):
|
||||
elem = self._cpp_type(spec.element_type)
|
||||
count = self._table_count(spec.low, spec.high)
|
||||
return f"std::array<{elem}, {count}> {name}"
|
||||
return f"{self._cpp_type(spec)} {name}"
|
||||
|
||||
def _emit_cpp_struct(self, name: str, spec: ast.StructType):
|
||||
self.types.declare([name], spec)
|
||||
self.emit(f"struct {name} {{")
|
||||
self.indent += 1
|
||||
for field_names, field_type in spec.fields:
|
||||
for field_name in field_names:
|
||||
self.emit(f"{self._cpp_type_decl(field_type, field_name)};")
|
||||
self.indent -= 1
|
||||
self.emit("};")
|
||||
|
||||
def _emit_cpp_class_declaration(self, name: str, spec: ast.ClassType):
|
||||
self.types.declare([name], spec)
|
||||
method_map: dict[str, ast.MethodDecl] = {}
|
||||
class_vars: set[str] = set()
|
||||
self.emit(f"class {name} {{")
|
||||
self.emit("public:")
|
||||
self.indent += 1
|
||||
for part in spec.data_parts:
|
||||
if self._is_class_var_segment(part.access_attrs):
|
||||
for field_names, field_type in part.fields:
|
||||
for field_name in field_names:
|
||||
class_vars.add(field_name)
|
||||
self.emit(f"static {self._cpp_type(field_type)} {field_name};")
|
||||
continue
|
||||
for field_names, field_type in part.fields:
|
||||
for field_name in field_names:
|
||||
self.emit(f"{self._cpp_type_decl(field_type, field_name)};")
|
||||
for section in spec.operations:
|
||||
for method in section.methods:
|
||||
for method_name in method.names:
|
||||
method_map[method_name] = method
|
||||
self.emit(self._cpp_method_declaration(name, method_name, method) + ";")
|
||||
self.indent -= 1
|
||||
self.emit("};")
|
||||
self.emit("")
|
||||
self._class_vars[name] = class_vars
|
||||
self._class_methods[name] = method_map
|
||||
self._section_class_bodies.append((name, spec))
|
||||
|
||||
def _emit_cpp_class_definitions(self, name: str, spec: ast.ClassType):
|
||||
for part in spec.data_parts:
|
||||
if not self._is_class_var_segment(part.access_attrs):
|
||||
continue
|
||||
for field_names, field_type in part.fields:
|
||||
for field_name in field_names:
|
||||
self.emit(
|
||||
f"{self._cpp_type(field_type)} {name}::{field_name} = 0;"
|
||||
)
|
||||
self.emit("")
|
||||
|
||||
def _cpp_method_declaration(self, class_name: str, method_name: str, method: ast.MethodDecl) -> str:
|
||||
ret = self._cpp_type(method.return_type) if method.return_type else "void"
|
||||
args = self._cpp_method_parm_list(class_name, method)
|
||||
if self._method_is_class_method(method):
|
||||
return f"static {ret} {method_name}({args})"
|
||||
return f"{ret} {method_name}({args})"
|
||||
|
||||
def _cpp_method_parm_list(self, class_name: str, method: ast.MethodDecl) -> str:
|
||||
if self._method_is_class_method(method):
|
||||
return self._cpp_parm_list(method.parms)
|
||||
return self._cpp_parm_list(method.parms)
|
||||
|
||||
def _cpp_parm_list(self, parms: list[tuple[list[str], Any, bool]]) -> str:
|
||||
if not parms:
|
||||
return ""
|
||||
parts: list[str] = []
|
||||
for names, type_spec, by_ref in parms:
|
||||
cpp_type = self._cpp_type(type_spec)
|
||||
for pname in names:
|
||||
if by_ref:
|
||||
parts.append(f"{cpp_type}& {pname}")
|
||||
else:
|
||||
parts.append(f"{cpp_type} {pname}")
|
||||
return ", ".join(parts)
|
||||
|
||||
def _cpp_external_parm_type(self, type_spec) -> str:
|
||||
spec = self._unwrap_type(type_spec)
|
||||
if isinstance(spec, ast.PtrType):
|
||||
target = self._unwrap_type(spec.target)
|
||||
if isinstance(target, ast.DefinedType) and target.name == "char":
|
||||
return "const char*"
|
||||
return self._cpp_type(type_spec)
|
||||
|
||||
def _cpp_external_parm_list(self, parms: list[tuple[list[str], Any, bool]]) -> str:
|
||||
if not parms:
|
||||
return ""
|
||||
parts: list[str] = []
|
||||
for names, type_spec, by_ref in parms:
|
||||
cpp_type = self._cpp_external_parm_type(type_spec)
|
||||
for pname in names:
|
||||
if by_ref:
|
||||
parts.append(f"{cpp_type}& {pname}")
|
||||
else:
|
||||
parts.append(f"{cpp_type} {pname}")
|
||||
return ", ".join(parts)
|
||||
|
||||
def _cpp_external_proc_signature(self, proc: ast.ProcDecl) -> str:
|
||||
ret = self._cpp_type(proc.return_type) if proc.return_type else "void"
|
||||
args = self._cpp_external_parm_list(proc.parms)
|
||||
return f"{ret} {proc.name}({args})"
|
||||
|
||||
def _cpp_proc_signature(self, proc: ast.ProcDecl) -> str:
|
||||
ret = self._cpp_type(proc.return_type) if proc.return_type else "void"
|
||||
args = self._cpp_parm_list(proc.parms)
|
||||
return f"{ret} {proc.name}({args})"
|
||||
|
||||
def _emit_cpp_procedure(self, proc: ast.ProcDecl):
|
||||
self.emit(self._cpp_proc_signature(proc))
|
||||
self.emit("{")
|
||||
self.indent += 1
|
||||
self._emit_block_body(proc.body)
|
||||
self.indent -= 1
|
||||
self.emit("}")
|
||||
self.emit("")
|
||||
|
||||
def _emit_cpp_method_impl(self, class_name: str, impl: ast.MethodImplDecl, method_decl: ast.MethodDecl | None):
|
||||
self._current_class = class_name
|
||||
is_class_method = method_decl is not None and self._method_is_class_method(method_decl)
|
||||
self._current_self = "this"
|
||||
if method_decl is not None:
|
||||
ret = self._cpp_type(method_decl.return_type) if method_decl.return_type else "void"
|
||||
args = self._cpp_method_parm_list(class_name, method_decl)
|
||||
self.emit(f"{ret} {class_name}::{impl.name}({args})")
|
||||
else:
|
||||
self.emit(f"void {class_name}::{impl.name}()")
|
||||
self.emit("{")
|
||||
self.indent += 1
|
||||
if is_class_method:
|
||||
pass
|
||||
self._emit_block_body(impl.body)
|
||||
self.indent -= 1
|
||||
self.emit("}")
|
||||
self.emit("")
|
||||
self._current_class = None
|
||||
self._current_self = "this"
|
||||
|
||||
def _c_member_ref(self, expr: ast.MemberRef) -> str:
|
||||
if (
|
||||
isinstance(expr.base, ast.VarRef)
|
||||
and expr.base.is_self
|
||||
and self._current_class
|
||||
and expr.member in self._class_vars.get(self._current_class, set())
|
||||
):
|
||||
return f"{self._current_class}::{expr.member}"
|
||||
if isinstance(expr.base, ast.VarRef) and expr.base.is_self:
|
||||
return f"this->{expr.member}"
|
||||
return f"{self._c_expr(expr.base)}.{expr.member}"
|
||||
|
||||
def _c_expr(self, expr) -> str:
|
||||
if isinstance(expr, ast.MethodCall):
|
||||
args = ", ".join(self._c_expr(a) for a in expr.args)
|
||||
class_name = self._method_class_name(expr)
|
||||
if class_name and class_name in self._class_methods:
|
||||
method_decl = self._class_methods[class_name].get(expr.name)
|
||||
if method_decl is not None:
|
||||
if self._method_is_class_method(method_decl):
|
||||
return f"{class_name}::{expr.name}({args})"
|
||||
receiver = self._c_expr(expr.receiver) if expr.receiver is not None else "this"
|
||||
if args:
|
||||
return f"{receiver}.{expr.name}({args})"
|
||||
return f"{receiver}.{expr.name}()"
|
||||
if expr.receiver is not None:
|
||||
receiver = self._c_expr(expr.receiver)
|
||||
return f"{receiver}.{expr.name}({args})"
|
||||
return super()._c_expr(expr)
|
||||
|
||||
def _method_call_args(self, call: ast.MethodCall, args: str) -> str:
|
||||
return args
|
||||
|
||||
def _queue_class_impl(self, impl: ast.ClassImplSection):
|
||||
self.emit(f"/* IN {impl.class_name} */")
|
||||
method_map = self._class_methods.get(impl.class_name, {})
|
||||
for decl in impl.declarations:
|
||||
if isinstance(decl, ast.MethodImplDecl):
|
||||
method_decl = method_map.get(decl.name)
|
||||
self._section_method_impls.append((impl.class_name, decl, method_decl))
|
||||
else:
|
||||
self._emit_cpp_toplevel_decl(decl)
|
||||
for stmt in impl.statements:
|
||||
self._emit_stmt(stmt)
|
||||
self.emit("")
|
||||
|
||||
def _method_class_name(self, call: ast.MethodCall) -> str | None:
|
||||
if isinstance(call.receiver, ast.VarRef):
|
||||
if call.receiver.name in self._var_types:
|
||||
return self._var_types[call.receiver.name]
|
||||
if call.receiver.name in self._class_methods:
|
||||
return call.receiver.name
|
||||
return super()._method_class_name(call)
|
||||
|
||||
|
||||
def transpile_to_cpp(
|
||||
compilation_unit,
|
||||
*,
|
||||
classical: bool = False,
|
||||
source_name: str = "input.protel",
|
||||
source_path: Path | None = None,
|
||||
) -> str:
|
||||
from .module_resolver import resolve_compilation_unit
|
||||
from .type_checker import check_types
|
||||
|
||||
if source_path is not None and not isinstance(source_path, Path):
|
||||
source_path = Path(source_path)
|
||||
compilation_unit = resolve_compilation_unit(
|
||||
compilation_unit,
|
||||
source_path=source_path,
|
||||
classical=classical,
|
||||
)
|
||||
check_types(compilation_unit, source_name=source_name)
|
||||
return CppTranspiler(classical=classical, source_name=source_name).transpile(
|
||||
compilation_unit
|
||||
)
|
||||
|
||||
|
||||
def transpile_file_cpp(
|
||||
source: str,
|
||||
*,
|
||||
classical: bool = False,
|
||||
source_name: str = "input.protel",
|
||||
) -> str:
|
||||
from .parser import parse_protel
|
||||
|
||||
tree = parse_protel(source, classical=classical)
|
||||
return transpile_to_cpp(tree, classical=classical, source_name=source_name)
|
||||
@@ -0,0 +1,37 @@
|
||||
"""PROTEL source file extension recognition (2026 + legacy PLS naming)."""
|
||||
|
||||
from __future__ import annotations
|
||||
|
||||
import re
|
||||
from pathlib import Path
|
||||
|
||||
# Modern / distribution suffixes (case-insensitive except where noted).
|
||||
_FIXED_SUFFIXES = frozenset({".protel", ".pt", ".ptl", ".p"})
|
||||
|
||||
# PLS edition suffix: .AA01 .. .ZZ99 (two letters + two digits).
|
||||
_PLS_SUFFIX_RE = re.compile(r"\.[A-Za-z]{2}\d{2}$")
|
||||
|
||||
PLS_SUFFIX_DESCRIPTION = ".AA01 through .ZZ99 (two letters + two digits)"
|
||||
|
||||
|
||||
def is_pls_suffix(suffix: str) -> bool:
|
||||
"""True when suffix matches legacy PLS edition form (e.g. .AA01, .aa01)."""
|
||||
return bool(_PLS_SUFFIX_RE.match(suffix))
|
||||
|
||||
|
||||
def is_protel_suffix(suffix: str) -> bool:
|
||||
"""True when suffix is a recognized PROTEL source extension."""
|
||||
if suffix.lower() in _FIXED_SUFFIXES:
|
||||
return True
|
||||
return is_pls_suffix(suffix)
|
||||
|
||||
|
||||
def is_protel_source(path: str | Path) -> bool:
|
||||
"""True when path name uses a recognized PROTEL source extension."""
|
||||
return is_protel_suffix(Path(path).suffix)
|
||||
|
||||
|
||||
def format_suffix_list() -> str:
|
||||
"""Human-readable suffix list for CLI messages."""
|
||||
fixed = ", ".join(sorted(_FIXED_SUFFIXES))
|
||||
return f"{fixed}, {PLS_SUFFIX_DESCRIPTION}"
|
||||
@@ -0,0 +1,408 @@
|
||||
// PROTEL 2026 grammar (Reference Manual + Introductory Manual 2026)
|
||||
// Keywords are uppercased by the preprocessor before parsing.
|
||||
|
||||
%import common.WS
|
||||
%ignore WS
|
||||
|
||||
?start: compilation_unit
|
||||
|
||||
compilation_unit: unit_item+
|
||||
|
||||
unit_item: section_head
|
||||
| in_impl_block
|
||||
| declaration
|
||||
| statement
|
||||
|
||||
section_head: section_kind IDENT ";" -> section_plain
|
||||
| section_kind IDENT "USES" id_list ";" -> section_uses
|
||||
| section_kind IDENT "OF" id_list ";" -> section_of
|
||||
| section_kind IDENT "OF" id_list "USES" id_list ";" -> section_of_uses
|
||||
| module_type section_kind IDENT ";" -> section_plain
|
||||
| module_type section_kind IDENT "USES" id_list ";" -> section_uses
|
||||
| module_type section_kind IDENT "OF" id_list ";" -> section_of
|
||||
| module_type section_kind IDENT "OF" id_list "USES" id_list ";" -> section_of_uses
|
||||
|
||||
module_type: "FAST"
|
||||
| "SWAPPABLE"
|
||||
| "PERPROCESS"
|
||||
| "DEFINITIONS"
|
||||
|
||||
section_kind: "INTERFACE" -> interface_kind
|
||||
| "SECTION" -> section_kind_kw
|
||||
|
||||
in_impl_block: "IN" IDENT in_impl_item+ -> class_impl_section
|
||||
|
||||
in_impl_item: method_impl_dcl
|
||||
| declaration
|
||||
| statement
|
||||
|
||||
method_impl_dcl: "DCL" IDENT "METHOD" "IS" block ";"
|
||||
|
||||
declaration: type_dcl_stmt
|
||||
| variable_dcl_stmt
|
||||
| proc_dcl_stmt
|
||||
|
||||
type_dcl_stmt: "TYPE" type_dcl (";" | type_dcl_list_tail)
|
||||
type_dcl_list_tail: "," type_dcl (";" | type_dcl_list_tail)
|
||||
|
||||
type_dcl: id_list type_spec
|
||||
|
||||
variable_dcl_stmt: "DCL" variable_dcl (";" | variable_dcl_list_tail)
|
||||
variable_dcl_list_tail: "," variable_dcl (";" | variable_dcl_list_tail)
|
||||
|
||||
variable_dcl: "OVLY" type_spec ovly_body "ENDOVLY" -> variable_dcl_ovly
|
||||
| id_list "LITERAL" type_spec variable_init_tail -> variable_dcl_literal
|
||||
| id_list "VARIABLE" type_spec variable_init_tail -> variable_dcl_variable
|
||||
| id_list type_spec variable_init_tail
|
||||
| id_list type_spec
|
||||
|
||||
variable_init_tail: "INIT" expr -> variable_init_init
|
||||
| "IS" init_value -> variable_init_is
|
||||
|
||||
init_value: expr
|
||||
| block
|
||||
|
||||
proc_dcl_stmt: "DCL" proc_dcl ";"
|
||||
|
||||
proc_dcl: id_list proc_sig "IS" block
|
||||
| id_list proc_sig "IS" "INTRINSIC" -> proc_dcl_intrinsic
|
||||
| id_list proc_sig "IS" "FORWARD" -> proc_dcl_forward
|
||||
| id_list proc_sig "EXTERNAL" -> proc_dcl_external
|
||||
| id_list proc_sig "EXPORT" -> proc_dcl_export
|
||||
| id_list proc_sig "IS" "ENTRY" -> proc_dcl_entry
|
||||
| id_list proc_sig
|
||||
|
||||
proc_sig: "QUICK" "PROC" paren_parms "RETURNS" type_spec
|
||||
| "OPERAND" "PROC" paren_parms "RETURNS" type_spec
|
||||
| "PROC" paren_parms "RETURNS" type_spec
|
||||
| "QUICK" "PROC" paren_parms
|
||||
| "OPERAND" "PROC" paren_parms
|
||||
| "PROC" paren_parms
|
||||
|
||||
paren_parms: "(" ")"
|
||||
| "(" parm_list ")"
|
||||
|
||||
parm_list: parm ("," parm)*
|
||||
|
||||
parm: "UPDATES" id_list type_spec -> parm_updates
|
||||
| "REF" id_list type_spec
|
||||
| id_list type_spec
|
||||
|
||||
block: "BLOCK" block_innards "ENDBLOCK"
|
||||
|
||||
block_innards: declaration* statement*
|
||||
|
||||
statement: if_stmt
|
||||
| loop_stmt
|
||||
| for_stmt
|
||||
| over_stmt
|
||||
| case_stmt
|
||||
| select_stmt
|
||||
| exit_stmt
|
||||
| return_stmt
|
||||
| bind_stmt
|
||||
| with_stmt
|
||||
| block
|
||||
| expr_stmt
|
||||
|
||||
bind_stmt: "BIND" bind_list ";"
|
||||
with_stmt: "WITH" with_ref_list ";"
|
||||
|
||||
bind_list: bind_item ("," bind_item)*
|
||||
bind_item: IDENT "TO" qualified_ref opt_as_clause
|
||||
|
||||
opt_as_clause: | "AS" type_spec
|
||||
|
||||
with_ref_list: qualified_ref ("," qualified_ref)*
|
||||
|
||||
if_stmt: "IF" expr "THEN" statement_list "ENDIF" ";"
|
||||
| "IF" expr "THEN" statement_list "ELSE" statement_list "ENDIF" ";"
|
||||
|
||||
loop_stmt: "WHILE" expr "DO" statement_list "ENDDO" ";"
|
||||
| "DO" statement_list "ENDDO" ";"
|
||||
|
||||
for_stmt: "FOR" IDENT for_range "DO" statement_list "ENDDO" ";"
|
||||
|
||||
for_range: "OVER" type_spec -> for_over_range
|
||||
| from_to_parts -> for_index_range
|
||||
|
||||
from_to_parts: opt_from_clause to_clause opt_by_clause opt_while_clause
|
||||
|
||||
opt_from_clause: | "FROM" expr
|
||||
to_clause: | "UP" "TO" expr -> up_to_clause
|
||||
| "DOWN" "TO" expr -> down_to_clause
|
||||
opt_by_clause: | "BY" expr
|
||||
opt_while_clause: | "WHILE" expr
|
||||
|
||||
over_stmt: "OVER" type_spec "DO" statement_list "ENDDO" ";"
|
||||
|
||||
case_stmt: "CASE" expr "IN" case_body "ENDCASE" ";"
|
||||
select_stmt: "SELECT" expr "IN" case_body "ENDSELECT" ";"
|
||||
|
||||
case_body: case_list out_case?
|
||||
|
||||
case_list: case_item
|
||||
| case_list case_item
|
||||
|
||||
case_item: tuple ":" case_arm_nonempty -> case_item_nonempty
|
||||
| tuple ":" -> case_item_empty
|
||||
|
||||
case_arm_nonempty: case_arm_stmt+
|
||||
|
||||
case_arm_stmt: if_stmt
|
||||
| loop_stmt
|
||||
| for_stmt
|
||||
| over_stmt
|
||||
| case_stmt
|
||||
| select_stmt
|
||||
| exit_stmt
|
||||
| return_stmt
|
||||
| block
|
||||
| expr_stmt
|
||||
|
||||
out_case: "OUT" -> out_case_empty
|
||||
| "OUT" out_arm_stmt+ -> out_case_with_stmts
|
||||
|
||||
out_arm_stmt: if_stmt
|
||||
| loop_stmt
|
||||
| for_stmt
|
||||
| over_stmt
|
||||
| case_stmt
|
||||
| select_stmt
|
||||
| exit_stmt
|
||||
| return_stmt
|
||||
| block
|
||||
| expr_stmt
|
||||
|
||||
exit_stmt: "EXIT" ";"
|
||||
|
||||
return_stmt: "RETURN" ";"
|
||||
| "RETURN" expr ";"
|
||||
|
||||
expr_stmt: expr ";"
|
||||
|
||||
statement_list: statement+
|
||||
|
||||
// --- Types ---
|
||||
|
||||
type_spec: pack_type
|
||||
| val_type
|
||||
| unpacked_type
|
||||
|
||||
pack_type: "PACK" "(" constant_expr ")" unpacked_type
|
||||
val_type: "VAL" unpacked_type
|
||||
|
||||
unpacked_type: range_type
|
||||
| symbolic_range
|
||||
| bool_type
|
||||
| ptr_type
|
||||
| set_type
|
||||
| struct_type
|
||||
| class_type
|
||||
| table_type
|
||||
| desc_type
|
||||
| area_type
|
||||
| defined_type
|
||||
|
||||
area_type: area_option* "AREA" "(" constant_expr ")" area_field_list "ENDAREA"
|
||||
|
||||
area_option: "UNRESTRICTED" -> area_unrestricted
|
||||
| "NONTRANSPARENT" -> area_nontransparent
|
||||
|
||||
area_field_list: area_field ("," area_field)*
|
||||
area_field: id_list type_spec
|
||||
|
||||
ovly_body: ovly_field ("," ovly_field)*
|
||||
ovly_field: tuple ":" id_list type_spec
|
||||
|
||||
range_type: "{" constant_subrange "}"
|
||||
|
||||
symbolic_range: "{" id_list "}"
|
||||
|
||||
bool_type: "BOOL"
|
||||
|
||||
ptr_type: "PTR" "TO" type_spec
|
||||
|
||||
set_type: "SET" simple_type
|
||||
|
||||
simple_type: range_type
|
||||
| symbolic_range
|
||||
| bool_type
|
||||
| defined_type
|
||||
|
||||
struct_type: "STRUCT" struct_field_list "ENDSTRUCT"
|
||||
|
||||
struct_field_list: struct_field ("," struct_field)*
|
||||
|
||||
struct_field: id_list type_spec
|
||||
|
||||
class_type: "CLASS" opt_refines class_data_sections operations_section "ENDCLASS" IDENT
|
||||
|
||||
opt_refines: | "REFINES" defined_type
|
||||
|
||||
class_data_sections: class_data_section*
|
||||
|
||||
class_data_section: segment_flags ":" class_field_list
|
||||
|
||||
segment_flags: "{" segment_attr_list "}"
|
||||
|
||||
segment_attr_list: | segment_attr ("," segment_attr)*
|
||||
|
||||
segment_attr: "PROTECTED" -> seg_protected
|
||||
| "SHARED" -> seg_shared
|
||||
| "PRIVATE" -> seg_private
|
||||
| "EXCLUSIVE" -> seg_exclusive
|
||||
| "READABLE" -> seg_readable
|
||||
| "WRITABLE" -> seg_writable
|
||||
|
||||
class_field_list: class_field ("," class_field)*
|
||||
|
||||
class_field: id_list type_spec opt_field_semi
|
||||
|
||||
opt_field_semi: | ";"
|
||||
|
||||
operations_section: "OPERATIONS" method_section_list
|
||||
|
||||
method_section_list: method_section*
|
||||
|
||||
method_section: method_segment_flags ":" method_group_list
|
||||
|
||||
method_segment_flags: "{" method_attr_list "}"
|
||||
|
||||
method_attr_list: | method_attr ("," method_attr)*
|
||||
|
||||
method_attr: "ABSTRACT" -> meth_abstract
|
||||
| "CLASS" -> meth_class
|
||||
| "CREATE" -> meth_create
|
||||
| "EXCLUSIVE" -> meth_exclusive
|
||||
| "FIXED" -> meth_fixed
|
||||
| "HIDDEN" -> meth_hidden
|
||||
| "OVERRIDING" -> meth_overriding
|
||||
|
||||
method_group_list: method_group ("," method_group)*
|
||||
|
||||
method_group: method_id_list method_decl_sig
|
||||
|
||||
method_id_list: IDENT ("," IDENT)*
|
||||
|
||||
method_decl_sig: "METHOD" opt_method_parms opt_method_returns
|
||||
| opt_method_parms opt_method_returns
|
||||
|
||||
opt_method_parms: | paren_parms
|
||||
opt_method_returns: | "RETURNS" type_spec
|
||||
|
||||
table_type: "TABLE" bounds "OF" type_spec
|
||||
|
||||
desc_type: "DESC" "OF" type_spec
|
||||
| "DESC" bounds "OF" type_spec
|
||||
|
||||
bounds: "[" constant_subrange "]"
|
||||
|
||||
defined_type: IDENT
|
||||
|
||||
constant_subrange: constant_expr "TO" constant_expr
|
||||
|
||||
// --- Expressions ---
|
||||
|
||||
?expr: assign_expr
|
||||
|
||||
?assign_expr: or_expr assign_tail*
|
||||
|
||||
assign_tail: "->" qualified_ref
|
||||
|
||||
?or_expr: or_expr "|" and_expr -> bin_or
|
||||
| and_expr
|
||||
|
||||
?and_expr: and_expr "&" xor_expr -> bin_and
|
||||
| xor_expr
|
||||
|
||||
?xor_expr: xor_expr "^" eq_expr -> bin_xor
|
||||
| eq_expr
|
||||
|
||||
?incl_expr: incl_expr "INCL" rel_expr -> bin_incl
|
||||
| incl_expr "NOTINCL" rel_expr -> bin_notincl
|
||||
| rel_expr
|
||||
|
||||
?eq_expr: eq_expr "=" incl_expr -> bin_eq
|
||||
| eq_expr "^=" incl_expr -> bin_ne
|
||||
| incl_expr
|
||||
|
||||
?rel_expr: rel_expr ">" add_expr -> bin_gt
|
||||
| rel_expr ">=" add_expr -> bin_ge
|
||||
| rel_expr "<" add_expr -> bin_lt
|
||||
| rel_expr "<=" add_expr -> bin_le
|
||||
| add_expr
|
||||
|
||||
?add_expr: add_expr "+" mul_expr -> bin_add
|
||||
| add_expr "-" mul_expr -> bin_sub
|
||||
| mul_expr
|
||||
|
||||
?mul_expr: mul_expr "*" unary_expr -> bin_mul
|
||||
| mul_expr "/" unary_expr -> bin_div
|
||||
| mul_expr "MOD" unary_expr -> bin_mod
|
||||
| unary_expr
|
||||
|
||||
?unary_expr: "!" unary_expr
|
||||
| "-" unary_expr
|
||||
| "UPB" unary_expr -> upb_expr
|
||||
| "TDSIZE" unary_expr -> tdsize_expr
|
||||
| "TYPEDESC" unary_expr -> typedesc_expr
|
||||
| "VARDESC" unary_expr -> vardesc_expr
|
||||
| "REFDESC" unary_expr -> refdesc_expr
|
||||
| "CAST" unary_expr "AS" type_spec -> cast_expr
|
||||
| primary
|
||||
|
||||
?primary: literal
|
||||
| qualified_ref
|
||||
| tuple
|
||||
| "(" expr ")"
|
||||
|
||||
qualified_ref: ref_segment qual_suffix*
|
||||
|
||||
ref_segment: IDENT
|
||||
| "SELF" -> self_ref
|
||||
| "SUPER" -> super_ref
|
||||
|
||||
qual_suffix: index_suffix -> qual_index
|
||||
| dot_suffix
|
||||
| call_suffix
|
||||
|
||||
dot_suffix: "." IDENT
|
||||
|
||||
call_suffix: "(" ")"
|
||||
| "(" actual_list ")"
|
||||
|
||||
index_suffix: "[" expr "]"
|
||||
| "[" expr "TO" expr "]"
|
||||
|
||||
actual_list: expr ("," expr)*
|
||||
|
||||
literal: NUMBER
|
||||
| "TRUE" -> true_lit
|
||||
| "FALSE" -> false_lit
|
||||
| "NIL" -> nil_lit
|
||||
| STRING
|
||||
|
||||
tuple: "{" "}"
|
||||
| "{" tuple_body_list "}"
|
||||
|
||||
tuple_body_list: tuple_elem ("," tuple_elem)*
|
||||
|
||||
tuple_elem: expr
|
||||
|
||||
?constant_expr: constant_expr_atom
|
||||
|
||||
constant_expr_atom: NUMBER
|
||||
| "TRUE" -> true_lit
|
||||
| "FALSE" -> false_lit
|
||||
| "NIL" -> nil_lit
|
||||
| STRING
|
||||
| "{" constant_tuple_body "}"
|
||||
|
||||
constant_tuple_body: constant_expr_atom ("," constant_expr_atom)*
|
||||
|
||||
id_list: IDENT ("," IDENT)*
|
||||
|
||||
IDENT: /[A-Za-z_$][A-Za-z0-9_$]*/
|
||||
NUMBER: /-?\d+/
|
||||
STRING: /'(?:''|[^'])*'/
|
||||
+105
@@ -0,0 +1,105 @@
|
||||
"""PROTEL reserved keywords (Reference Manual Appendix A / oflpr / oflpi)."""
|
||||
|
||||
PROTEL_KEYWORDS = frozenset({
|
||||
"$EJECT",
|
||||
"$LI",
|
||||
"$OBJECT",
|
||||
"$REFDESC",
|
||||
"$TYPEDESC",
|
||||
"$UNIVERSAL_PTR",
|
||||
"$VARDESC",
|
||||
"ABSTRACT",
|
||||
"AREA",
|
||||
"AS",
|
||||
"BIND",
|
||||
"BLOCK",
|
||||
"BOOL",
|
||||
"BY",
|
||||
"CASE",
|
||||
"CAST",
|
||||
"CLASS",
|
||||
"CREATE",
|
||||
"DCL",
|
||||
"DEFINITIONS",
|
||||
"DESC",
|
||||
"DO",
|
||||
"DOWN",
|
||||
"ELSE",
|
||||
"ENDAREA",
|
||||
"ENDBLOCK",
|
||||
"ENDCASE",
|
||||
"ENDCLASS",
|
||||
"ENDDO",
|
||||
"ENDIF",
|
||||
"ENDOVLY",
|
||||
"ENDSELECT",
|
||||
"ENDSTRUCT",
|
||||
"ENTRY",
|
||||
"EXIT",
|
||||
"EXTERNAL",
|
||||
"EXPORT",
|
||||
"EXCLUSIVE",
|
||||
"FALSE",
|
||||
"FIXED",
|
||||
"FAST",
|
||||
"FOR",
|
||||
"FORWARD",
|
||||
"FROM",
|
||||
"HIDDEN",
|
||||
"IF",
|
||||
"IN",
|
||||
"INCL",
|
||||
"INIT",
|
||||
"INTERFACE",
|
||||
"INTRINSIC",
|
||||
"IS",
|
||||
"LITERAL",
|
||||
"METHOD",
|
||||
"MOD",
|
||||
"NIL",
|
||||
"NONTRANSPARENT",
|
||||
"NOTINCL",
|
||||
"OF",
|
||||
"OPERAND",
|
||||
"OPERATIONS",
|
||||
"OUT",
|
||||
"OVERRIDING",
|
||||
"OVER",
|
||||
"OVLY",
|
||||
"PACK",
|
||||
"PERPROCESS",
|
||||
"PRIVATE",
|
||||
"PROC",
|
||||
"PROTECTED",
|
||||
"PTR",
|
||||
"QUICK",
|
||||
"REF",
|
||||
"REFDESC",
|
||||
"REFINES",
|
||||
"RETURN",
|
||||
"RETURNS",
|
||||
"SECTION",
|
||||
"SELECT",
|
||||
"SELF",
|
||||
"SET",
|
||||
"SUPER",
|
||||
"SHARED",
|
||||
"STRUCT",
|
||||
"TABLE",
|
||||
"TDSIZE",
|
||||
"THEN",
|
||||
"TO",
|
||||
"TRUE",
|
||||
"TYPE",
|
||||
"TYPEDESC",
|
||||
"UNRESTRICTED",
|
||||
"UP",
|
||||
"UPB",
|
||||
"UPDATES",
|
||||
"USES",
|
||||
"VAL",
|
||||
"VARDESC",
|
||||
"VARIABLE",
|
||||
"WHILE",
|
||||
"WITH",
|
||||
})
|
||||
@@ -0,0 +1,158 @@
|
||||
"""Resolve USES module links and merge embedded PROTEL sections."""
|
||||
|
||||
from __future__ import annotations
|
||||
|
||||
import sys
|
||||
from pathlib import Path
|
||||
|
||||
from . import ast_nodes as ast
|
||||
from .extensions import is_protel_source
|
||||
from .parser import parse_protel
|
||||
from .transpiler import TranspileError
|
||||
|
||||
_ROOT = Path(__file__).resolve().parent.parent
|
||||
_SECTION_INDEX: dict[str, Path] | None = None
|
||||
|
||||
|
||||
def _search_dirs(source_path: Path | None) -> list[Path]:
|
||||
dirs: list[Path] = []
|
||||
if source_path is not None:
|
||||
dirs.append(source_path.parent.resolve())
|
||||
examples = _ROOT / "examples"
|
||||
if examples.is_dir():
|
||||
dirs.append(examples.resolve())
|
||||
return dirs
|
||||
|
||||
|
||||
def _build_section_index(search_dirs: list[Path]) -> dict[str, Path]:
|
||||
index: dict[str, Path] = {}
|
||||
for base in search_dirs:
|
||||
if not base.is_dir():
|
||||
continue
|
||||
for path in sorted(base.rglob("*")):
|
||||
if not path.is_file() or not is_protel_source(path):
|
||||
continue
|
||||
try:
|
||||
text = path.read_text(encoding="utf-8", errors="replace")
|
||||
except OSError:
|
||||
continue
|
||||
for line in text.splitlines():
|
||||
stripped = line.strip()
|
||||
if not stripped or stripped.startswith("%"):
|
||||
continue
|
||||
upper = stripped.upper()
|
||||
if upper.startswith("SECTION ") or upper.startswith("INTERFACE "):
|
||||
parts = stripped.split()
|
||||
if len(parts) >= 2:
|
||||
name = parts[1].rstrip(";")
|
||||
index.setdefault(name, path.resolve())
|
||||
break
|
||||
return index
|
||||
|
||||
|
||||
def _find_module_path(
|
||||
module_name: str,
|
||||
*,
|
||||
source_path: Path | None,
|
||||
index: dict[str, Path],
|
||||
) -> Path | None:
|
||||
if module_name in index:
|
||||
return index[module_name]
|
||||
for base in _search_dirs(source_path):
|
||||
candidate = base / f"{module_name}.protel"
|
||||
if candidate.is_file():
|
||||
return candidate.resolve()
|
||||
return None
|
||||
|
||||
|
||||
def _load_named_section(
|
||||
path: Path,
|
||||
module_name: str,
|
||||
*,
|
||||
classical: bool,
|
||||
) -> ast.Section:
|
||||
try:
|
||||
source = path.read_text(encoding="utf-8", errors="replace")
|
||||
except OSError as exc:
|
||||
raise TranspileError(
|
||||
f"cannot read USES module {module_name!r} from '{path}': {exc}"
|
||||
) from exc
|
||||
try:
|
||||
sections = parse_protel(source, classical=classical)
|
||||
except Exception as exc:
|
||||
raise TranspileError(
|
||||
f"parse error in USES module {module_name!r} ({path.name}): {exc}"
|
||||
) from exc
|
||||
for section in sections:
|
||||
if section.name == module_name:
|
||||
return section
|
||||
names = ", ".join(section.name for section in sections) or "(none)"
|
||||
raise TranspileError(
|
||||
f"USES module {module_name!r} not found in '{path.name}' "
|
||||
f"(sections: {names})"
|
||||
)
|
||||
|
||||
|
||||
def _collect_uses_modules(sections: list[ast.Section]) -> list[str]:
|
||||
ordered: list[str] = []
|
||||
seen: set[str] = set()
|
||||
for section in sections:
|
||||
for module_name in section.uses_modules:
|
||||
if module_name not in seen:
|
||||
seen.add(module_name)
|
||||
ordered.append(module_name)
|
||||
return ordered
|
||||
|
||||
|
||||
def resolve_compilation_unit(
|
||||
sections: list[ast.Section],
|
||||
*,
|
||||
source_path: Path | None = None,
|
||||
classical: bool = False,
|
||||
) -> list[ast.Section]:
|
||||
"""Expand USES links by loading embedded sections from other PROTEL sources."""
|
||||
uses = _collect_uses_modules(sections)
|
||||
if not uses:
|
||||
return sections
|
||||
|
||||
search_dirs = _search_dirs(source_path)
|
||||
index = _build_section_index(search_dirs)
|
||||
|
||||
merged: list[ast.Section] = []
|
||||
merged_names: set[str] = set()
|
||||
visiting: set[str] = set()
|
||||
|
||||
def embed(module_name: str) -> None:
|
||||
if module_name in merged_names:
|
||||
return
|
||||
if module_name in visiting:
|
||||
raise TranspileError(
|
||||
f"circular USES imbedding involving module {module_name!r}"
|
||||
)
|
||||
visiting.add(module_name)
|
||||
path = _find_module_path(module_name, source_path=source_path, index=index)
|
||||
if path is None:
|
||||
print(
|
||||
f"protel: warning: USES module {module_name!r} not found; "
|
||||
f"skipping embed",
|
||||
file=sys.stderr,
|
||||
)
|
||||
visiting.remove(module_name)
|
||||
return
|
||||
section = _load_named_section(path, module_name, classical=classical)
|
||||
for dep in section.uses_modules:
|
||||
embed(dep)
|
||||
if module_name not in merged_names:
|
||||
merged.append(section)
|
||||
merged_names.add(module_name)
|
||||
visiting.remove(module_name)
|
||||
|
||||
for module_name in uses:
|
||||
embed(module_name)
|
||||
|
||||
for section in sections:
|
||||
if section.name not in merged_names:
|
||||
merged.append(section)
|
||||
merged_names.add(section.name)
|
||||
|
||||
return merged
|
||||
+996
@@ -0,0 +1,996 @@
|
||||
"""PROTEL 2026 Lark parser and AST builder."""
|
||||
|
||||
from __future__ import annotations
|
||||
|
||||
from pathlib import Path
|
||||
|
||||
from lark import Lark, Transformer, Tree
|
||||
|
||||
from . import ast_nodes as ast
|
||||
from .preprocess import normalize_keywords
|
||||
|
||||
_GRAMMAR_PATH = Path(__file__).parent / "grammar" / "protel.lark"
|
||||
|
||||
|
||||
def _token_values(children) -> list:
|
||||
out = []
|
||||
for child in children:
|
||||
if isinstance(child, str):
|
||||
out.append(child)
|
||||
elif hasattr(child, "type") and child.type not in {"RULE"}:
|
||||
out.append(str(child))
|
||||
elif isinstance(child, list):
|
||||
out.extend(_token_values(child))
|
||||
elif isinstance(child, Tree):
|
||||
out.extend(_token_values(child.children))
|
||||
return out
|
||||
|
||||
|
||||
def _only_nodes(children):
|
||||
return [c for c in children if not isinstance(c, str) and not hasattr(c, "type")]
|
||||
|
||||
|
||||
class ProtelASTBuilder(Transformer):
|
||||
def compilation_unit(self, children):
|
||||
sections: list[ast.Section] = []
|
||||
current: ast.Section | None = None
|
||||
for item in children:
|
||||
if isinstance(item, dict) and "section_kind" in item:
|
||||
current = ast.Section(
|
||||
module_type=item["module_type"],
|
||||
section_kind=item["section_kind"],
|
||||
name=item["name"],
|
||||
of_modules=item.get("of_modules", []),
|
||||
uses_modules=item.get("uses_modules", []),
|
||||
)
|
||||
sections.append(current)
|
||||
elif current is None:
|
||||
raise ValueError("PROTEL declaration or statement appears before SECTION/INTERFACE header")
|
||||
elif isinstance(item, ast.ClassImplSection):
|
||||
current.class_impls.append(item)
|
||||
elif isinstance(item, (ast.TypeDecl, ast.VarDecl, ast.ProcDecl)):
|
||||
current.declarations.append(item)
|
||||
else:
|
||||
current.statements.append(item)
|
||||
return sections
|
||||
|
||||
def unit_item(self, children):
|
||||
return children[0]
|
||||
|
||||
def interface_kind(self, _children=None):
|
||||
return "INTERFACE"
|
||||
|
||||
def section_kind_kw(self, _children=None):
|
||||
return "SECTION"
|
||||
|
||||
def module_type(self, children):
|
||||
return str(children[0]) if children else "FAST"
|
||||
|
||||
def _section_head_meta(
|
||||
self,
|
||||
children,
|
||||
*,
|
||||
of_modules: list[str] | None = None,
|
||||
uses_modules: list[str] | None = None,
|
||||
) -> dict:
|
||||
module_type = "FAST"
|
||||
section_kind = "SECTION"
|
||||
name = ""
|
||||
for child in children:
|
||||
if isinstance(child, list):
|
||||
continue
|
||||
text = str(child)
|
||||
if text in {"FAST", "SWAPPABLE", "PERPROCESS", "DEFINITIONS"}:
|
||||
module_type = text
|
||||
elif text in {"INTERFACE", "SECTION"}:
|
||||
section_kind = text
|
||||
elif not name:
|
||||
name = text
|
||||
return {
|
||||
"module_type": module_type,
|
||||
"section_kind": section_kind,
|
||||
"name": name,
|
||||
"of_modules": of_modules or [],
|
||||
"uses_modules": uses_modules or [],
|
||||
}
|
||||
|
||||
def section_plain(self, children):
|
||||
return self._section_head_meta(children)
|
||||
|
||||
def section_uses(self, children):
|
||||
id_lists = [c for c in children if isinstance(c, list)]
|
||||
return self._section_head_meta(children, uses_modules=id_lists[0])
|
||||
|
||||
def section_of(self, children):
|
||||
id_lists = [c for c in children if isinstance(c, list)]
|
||||
return self._section_head_meta(children, of_modules=id_lists[0])
|
||||
|
||||
def section_of_uses(self, children):
|
||||
id_lists = [c for c in children if isinstance(c, list)]
|
||||
return self._section_head_meta(
|
||||
children,
|
||||
of_modules=id_lists[0],
|
||||
uses_modules=id_lists[1],
|
||||
)
|
||||
|
||||
def declaration(self, children):
|
||||
return children[0]
|
||||
|
||||
def type_dcl_stmt(self, children):
|
||||
return children[-1]
|
||||
|
||||
def type_dcl_list_tail(self, children):
|
||||
return children[-1]
|
||||
|
||||
def type_dcl(self, children):
|
||||
return ast.TypeDecl(names=list(children[0]), type_spec=children[1])
|
||||
|
||||
def variable_dcl_stmt(self, children):
|
||||
return children[-1]
|
||||
|
||||
def variable_dcl_list_tail(self, children):
|
||||
return children[-1]
|
||||
|
||||
def variable_init_init(self, children):
|
||||
return ("INIT", children[0])
|
||||
|
||||
def variable_init_is(self, children):
|
||||
return ("IS", children[0])
|
||||
|
||||
def _var_decl_from_parts(
|
||||
self,
|
||||
names,
|
||||
type_spec,
|
||||
*,
|
||||
storage_class: str | None = None,
|
||||
init_tail=None,
|
||||
):
|
||||
init = None
|
||||
if init_tail is not None:
|
||||
kind, value = init_tail
|
||||
if kind == "INIT":
|
||||
init = value
|
||||
else:
|
||||
init = value
|
||||
return ast.VarDecl(
|
||||
names=list(names),
|
||||
type_spec=type_spec,
|
||||
init=init,
|
||||
storage_class=storage_class,
|
||||
)
|
||||
|
||||
def variable_dcl_literal(self, children):
|
||||
init_tail = children[2] if len(children) > 2 else None
|
||||
return self._var_decl_from_parts(
|
||||
children[0],
|
||||
children[1],
|
||||
storage_class="LITERAL",
|
||||
init_tail=init_tail,
|
||||
)
|
||||
|
||||
def variable_dcl_variable(self, children):
|
||||
init_tail = children[2] if len(children) > 2 else None
|
||||
return self._var_decl_from_parts(
|
||||
children[0],
|
||||
children[1],
|
||||
storage_class="VARIABLE",
|
||||
init_tail=init_tail,
|
||||
)
|
||||
|
||||
def variable_dcl_ovly(self, children):
|
||||
return ast.VarDecl(
|
||||
names=[],
|
||||
type_spec=children[0],
|
||||
ovly_fields=list(children[1]),
|
||||
)
|
||||
|
||||
def variable_dcl(self, children):
|
||||
if len(children) == 3 and isinstance(children[2], tuple):
|
||||
return self._var_decl_from_parts(
|
||||
children[0], children[1], init_tail=children[2]
|
||||
)
|
||||
names = list(children[0])
|
||||
type_spec = children[1]
|
||||
return ast.VarDecl(names=names, type_spec=type_spec)
|
||||
|
||||
def proc_dcl_stmt(self, children):
|
||||
return children[-1]
|
||||
|
||||
def proc_dcl_intrinsic(self, children):
|
||||
names = children[0]
|
||||
proc_sig = children[1]
|
||||
return ast.ProcDecl(
|
||||
name=names[0],
|
||||
parms=proc_sig["parms"],
|
||||
return_type=proc_sig["return_type"],
|
||||
body=None,
|
||||
pclass=proc_sig.get("pclass"),
|
||||
intrinsic=True,
|
||||
)
|
||||
|
||||
def proc_dcl_external(self, children):
|
||||
names = children[0]
|
||||
proc_sig = children[1]
|
||||
return ast.ProcDecl(
|
||||
name=names[0],
|
||||
parms=proc_sig["parms"],
|
||||
return_type=proc_sig["return_type"],
|
||||
body=None,
|
||||
pclass=proc_sig.get("pclass"),
|
||||
external=True,
|
||||
)
|
||||
|
||||
def proc_dcl_forward(self, children):
|
||||
names = children[0]
|
||||
proc_sig = children[1]
|
||||
return ast.ProcDecl(
|
||||
name=names[0],
|
||||
parms=proc_sig["parms"],
|
||||
return_type=proc_sig["return_type"],
|
||||
body=None,
|
||||
pclass=proc_sig.get("pclass"),
|
||||
forward=True,
|
||||
)
|
||||
|
||||
def proc_dcl_entry(self, children):
|
||||
names = children[0]
|
||||
proc_sig = children[1]
|
||||
return ast.ProcDecl(
|
||||
name=names[0],
|
||||
parms=proc_sig["parms"],
|
||||
return_type=None,
|
||||
body=None,
|
||||
pclass=proc_sig.get("pclass"),
|
||||
entry=True,
|
||||
)
|
||||
|
||||
def proc_dcl_export(self, children):
|
||||
names = children[0]
|
||||
proc_sig = children[1]
|
||||
return ast.ProcDecl(
|
||||
name=names[0],
|
||||
parms=proc_sig["parms"],
|
||||
return_type=proc_sig["return_type"],
|
||||
body=None,
|
||||
pclass=proc_sig.get("pclass"),
|
||||
export=True,
|
||||
)
|
||||
|
||||
def proc_dcl(self, children):
|
||||
names = children[0]
|
||||
proc_sig = children[1]
|
||||
body = children[-1] if len(children) > 2 else None
|
||||
if body == proc_sig or isinstance(body, str):
|
||||
body = None
|
||||
return ast.ProcDecl(
|
||||
name=names[0],
|
||||
parms=proc_sig["parms"],
|
||||
return_type=proc_sig["return_type"],
|
||||
body=body,
|
||||
pclass=proc_sig.get("pclass"),
|
||||
intrinsic=False,
|
||||
)
|
||||
|
||||
def proc_sig(self, children):
|
||||
return self._build_proc_sig(children)
|
||||
|
||||
def paren_parms(self, children):
|
||||
for child in children:
|
||||
if isinstance(child, list) and child and isinstance(child[0], tuple):
|
||||
return child
|
||||
if isinstance(child, list) and (not child or not isinstance(child[0], str)):
|
||||
return child
|
||||
return []
|
||||
|
||||
def _build_proc_sig(self, children):
|
||||
tokens = _token_values(children)
|
||||
pclass = None
|
||||
if tokens and tokens[0] in {"QUICK", "OPERAND"}:
|
||||
pclass = tokens[0]
|
||||
parms: list = []
|
||||
return_type = None
|
||||
for child in children:
|
||||
if isinstance(child, list) and child and isinstance(child[0], tuple):
|
||||
parms = child
|
||||
elif not isinstance(child, (str, list)) and child is not None:
|
||||
if not isinstance(child, dict):
|
||||
return_type = child
|
||||
return {"pclass": pclass, "parms": parms, "return_type": return_type}
|
||||
|
||||
def parm_list(self, children):
|
||||
return list(children)
|
||||
|
||||
def parm_updates(self, children):
|
||||
return (list(children[0]), children[1], "UPDATES")
|
||||
|
||||
def parm(self, children):
|
||||
if children[0] == "REF":
|
||||
return (list(children[1]), children[2], True)
|
||||
return (list(children[0]), children[1], False)
|
||||
|
||||
def bind_stmt(self, children):
|
||||
return ast.BindStmt(bindings=list(children[0]))
|
||||
|
||||
def bind_list(self, children):
|
||||
return list(children)
|
||||
|
||||
def bind_item(self, children):
|
||||
name = str(children[0])
|
||||
ref = children[1]
|
||||
as_type = children[2] if len(children) > 2 else None
|
||||
return (name, ref, as_type)
|
||||
|
||||
def opt_as_clause(self, children):
|
||||
return children[0] if children else None
|
||||
|
||||
def with_stmt(self, children):
|
||||
return ast.WithStmt(refs=list(children[0]))
|
||||
|
||||
def with_ref_list(self, children):
|
||||
return list(children)
|
||||
|
||||
def block(self, children):
|
||||
innards = children[-1]
|
||||
decls, stmts = innards
|
||||
return ast.Block(declarations=list(decls), statements=list(stmts))
|
||||
|
||||
def block_innards(self, children):
|
||||
decls = []
|
||||
stmts = []
|
||||
for item in children:
|
||||
if isinstance(item, (ast.TypeDecl, ast.VarDecl, ast.ProcDecl)):
|
||||
decls.append(item)
|
||||
else:
|
||||
stmts.append(item)
|
||||
return decls, stmts
|
||||
|
||||
def if_stmt(self, children):
|
||||
condition = children[0]
|
||||
then_part = list(children[1])
|
||||
else_part = list(children[2]) if len(children) > 2 else []
|
||||
return ast.IfStmt(condition=condition, then_part=then_part, else_part=else_part)
|
||||
|
||||
def statement_list(self, children):
|
||||
return list(children)
|
||||
|
||||
def loop_stmt(self, children):
|
||||
if len(children) >= 2 and not isinstance(children[0], list):
|
||||
return ast.LoopStmt(while_expr=children[0], body=list(children[-1]))
|
||||
return ast.LoopStmt(while_expr=None, body=list(children[-1]))
|
||||
|
||||
def for_over_range(self, children):
|
||||
return {"over_type": children[0]}
|
||||
|
||||
def for_index_range(self, children):
|
||||
parts = children[0]
|
||||
return {
|
||||
"from_expr": parts[0],
|
||||
"direction": parts[1][0] if parts[1] else None,
|
||||
"to_expr": parts[1][1] if parts[1] else None,
|
||||
"by_expr": parts[2],
|
||||
"while_expr": parts[3],
|
||||
"over_type": None,
|
||||
}
|
||||
|
||||
def from_to_parts(self, children):
|
||||
from_expr = None
|
||||
to_part = None
|
||||
by_expr = None
|
||||
while_expr = None
|
||||
idx = 0
|
||||
if idx < len(children):
|
||||
if isinstance(children[idx], tuple) and children[idx][0] in {"UP", "DOWN"}:
|
||||
to_part = children[idx]
|
||||
idx += 1
|
||||
else:
|
||||
from_expr = children[idx]
|
||||
idx += 1
|
||||
if idx < len(children):
|
||||
to_part = children[idx]
|
||||
idx += 1
|
||||
if idx < len(children):
|
||||
by_expr = children[idx]
|
||||
idx += 1
|
||||
if idx < len(children):
|
||||
while_expr = children[idx]
|
||||
return (from_expr, to_part, by_expr, while_expr)
|
||||
|
||||
def opt_from_clause(self, children):
|
||||
return children[0] if children else None
|
||||
|
||||
def up_to_clause(self, children):
|
||||
return ("UP", children[0])
|
||||
|
||||
def down_to_clause(self, children):
|
||||
return ("DOWN", children[0])
|
||||
|
||||
def opt_by_clause(self, children):
|
||||
return children[0] if children else None
|
||||
|
||||
def opt_while_clause(self, children):
|
||||
return children[0] if children else None
|
||||
|
||||
def for_stmt(self, children):
|
||||
var = str(children[0])
|
||||
range_info = children[1]
|
||||
body = list(children[-1])
|
||||
if range_info.get("over_type") is not None:
|
||||
return ast.ForStmt(
|
||||
var=var,
|
||||
from_expr=None,
|
||||
to_expr=None,
|
||||
direction=None,
|
||||
by_expr=None,
|
||||
while_expr=None,
|
||||
over_type=range_info["over_type"],
|
||||
body=body,
|
||||
)
|
||||
return ast.ForStmt(
|
||||
var=var,
|
||||
from_expr=range_info.get("from_expr"),
|
||||
to_expr=range_info.get("to_expr"),
|
||||
direction=range_info.get("direction"),
|
||||
by_expr=range_info.get("by_expr"),
|
||||
while_expr=range_info.get("while_expr"),
|
||||
over_type=None,
|
||||
body=body,
|
||||
)
|
||||
|
||||
def over_stmt(self, children):
|
||||
return ast.OverStmt(over_type=children[0], body=list(children[-1]))
|
||||
|
||||
def case_list(self, children):
|
||||
if len(children) == 1:
|
||||
item = children[0]
|
||||
return [item] if isinstance(item, ast.CaseArm) else list(item)
|
||||
left = children[0]
|
||||
right = children[1]
|
||||
if not isinstance(left, list):
|
||||
left = [left]
|
||||
return left + [right]
|
||||
|
||||
def case_body(self, children):
|
||||
arms = children[0] if children else []
|
||||
if isinstance(arms, ast.CaseArm):
|
||||
arms = [arms]
|
||||
out_statements: list = []
|
||||
if len(children) > 1:
|
||||
out_statements = children[1] if isinstance(children[1], list) else []
|
||||
return list(arms), out_statements
|
||||
|
||||
def case_item_empty(self, children):
|
||||
return ast.CaseArm(labels=children[0], statements=[])
|
||||
|
||||
def case_item_nonempty(self, children):
|
||||
return ast.CaseArm(labels=children[0], statements=list(children[1]))
|
||||
|
||||
def case_arm_nonempty(self, children):
|
||||
return list(children)
|
||||
|
||||
def out_case_empty(self, children):
|
||||
return []
|
||||
|
||||
def out_case_with_stmts(self, children):
|
||||
return list(children)
|
||||
|
||||
def case_stmt(self, children):
|
||||
arms, out_statements = children[1]
|
||||
return ast.CaseStmt(selector=children[0], arms=arms, out_statements=out_statements, is_select=False)
|
||||
|
||||
def select_stmt(self, children):
|
||||
arms, out_statements = children[1]
|
||||
return ast.CaseStmt(selector=children[0], arms=arms, out_statements=out_statements, is_select=True)
|
||||
|
||||
def exit_stmt(self, children):
|
||||
return ast.ExitStmt()
|
||||
|
||||
def upb_expr(self, children):
|
||||
return ast.BuiltinExpr(name="UPB", operand=children[0])
|
||||
|
||||
def tdsize_expr(self, children):
|
||||
return ast.BuiltinExpr(name="TDSIZE", operand=children[0])
|
||||
|
||||
def typedesc_expr(self, children):
|
||||
return ast.BuiltinExpr(name="TYPEDESC", operand=children[0])
|
||||
|
||||
def vardesc_expr(self, children):
|
||||
return ast.BuiltinExpr(name="VARDESC", operand=children[0])
|
||||
|
||||
def refdesc_expr(self, children):
|
||||
return ast.BuiltinExpr(name="REFDESC", operand=children[0])
|
||||
|
||||
def cast_expr(self, children):
|
||||
return ast.CastExpr(operand=children[0], target_type=children[1])
|
||||
|
||||
def bin_incl(self, children):
|
||||
return self._bin("INCL", children)
|
||||
|
||||
def bin_notincl(self, children):
|
||||
return self._bin("NOTINCL", children)
|
||||
|
||||
def return_stmt(self, children):
|
||||
if not children:
|
||||
return ast.ReturnStmt(value=None)
|
||||
return ast.ReturnStmt(value=children[0])
|
||||
|
||||
def expr_stmt(self, children):
|
||||
return children[0]
|
||||
|
||||
def id_list(self, children):
|
||||
return [str(c) for c in children]
|
||||
|
||||
def statement(self, children):
|
||||
return children[0]
|
||||
|
||||
def unpacked_type(self, children):
|
||||
return children[0]
|
||||
|
||||
|
||||
|
||||
def pack_type(self, children):
|
||||
width_child = children[0]
|
||||
if isinstance(width_child, ast.Literal) and width_child.kind == "int":
|
||||
width = int(width_child.value)
|
||||
else:
|
||||
width = int(str(width_child))
|
||||
unpacked = children[1]
|
||||
if isinstance(unpacked, ast.BoolType):
|
||||
unpacked.packed = width
|
||||
elif isinstance(unpacked, ast.TableType):
|
||||
unpacked.packed = width
|
||||
elif isinstance(unpacked, ast.RangeType):
|
||||
unpacked.packed = width
|
||||
return unpacked
|
||||
|
||||
def val_type(self, children):
|
||||
return children[0]
|
||||
|
||||
def type_spec(self, children):
|
||||
return children[0]
|
||||
|
||||
def range_type(self, children):
|
||||
low, high = children[0]
|
||||
return ast.RangeType(low=low, high=high)
|
||||
|
||||
def symbolic_range(self, children):
|
||||
return ast.SymbolicRange(members=list(children[0]))
|
||||
|
||||
def bool_type(self, children):
|
||||
return ast.BoolType()
|
||||
|
||||
def ptr_type(self, children):
|
||||
return ast.PtrType(target=children[-1])
|
||||
|
||||
def set_type(self, children):
|
||||
return ast.SetType(member_type=children[-1])
|
||||
|
||||
def area_unrestricted(self, _children=None):
|
||||
return "UNRESTRICTED"
|
||||
|
||||
def area_nontransparent(self, _children=None):
|
||||
return "NONTRANSPARENT"
|
||||
|
||||
def area_field(self, children):
|
||||
return (list(children[0]), children[1])
|
||||
|
||||
def area_field_list(self, children):
|
||||
return list(children)
|
||||
|
||||
def area_type(self, children):
|
||||
options: list[str] = []
|
||||
idx = 0
|
||||
while idx < len(children) and isinstance(children[idx], str):
|
||||
options.append(children[idx])
|
||||
idx += 1
|
||||
size_expr = children[idx]
|
||||
fields = children[idx + 1]
|
||||
return ast.AreaType(options=options, size_expr=size_expr, fields=fields)
|
||||
|
||||
def ovly_field(self, children):
|
||||
return (children[0], list(children[1]), children[2])
|
||||
|
||||
def ovly_body(self, children):
|
||||
return list(children)
|
||||
|
||||
def struct_type(self, children):
|
||||
return ast.StructType(fields=list(children[0]))
|
||||
|
||||
def struct_field_list(self, children):
|
||||
return list(children)
|
||||
|
||||
def struct_field(self, children):
|
||||
return (list(children[0]), children[1])
|
||||
|
||||
def opt_refines(self, children):
|
||||
return children[0] if children else None
|
||||
|
||||
def seg_protected(self, _children=None):
|
||||
return "PROTECTED"
|
||||
|
||||
def seg_shared(self, _children=None):
|
||||
return "SHARED"
|
||||
|
||||
def seg_private(self, _children=None):
|
||||
return "PRIVATE"
|
||||
|
||||
def seg_exclusive(self, _children=None):
|
||||
return "EXCLUSIVE"
|
||||
|
||||
def seg_readable(self, _children=None):
|
||||
return "READABLE"
|
||||
|
||||
def seg_writable(self, _children=None):
|
||||
return "WRITABLE"
|
||||
|
||||
def segment_attr_list(self, children):
|
||||
return [str(c) for c in children]
|
||||
|
||||
def meth_abstract(self, _children=None):
|
||||
return "ABSTRACT"
|
||||
|
||||
def meth_class(self, _children=None):
|
||||
return "CLASS"
|
||||
|
||||
def meth_create(self, _children=None):
|
||||
return "CREATE"
|
||||
|
||||
def meth_exclusive(self, _children=None):
|
||||
return "EXCLUSIVE"
|
||||
|
||||
def meth_fixed(self, _children=None):
|
||||
return "FIXED"
|
||||
|
||||
def meth_hidden(self, _children=None):
|
||||
return "HIDDEN"
|
||||
|
||||
def meth_overriding(self, _children=None):
|
||||
return "OVERRIDING"
|
||||
|
||||
def segment_flags(self, children):
|
||||
return list(children[0]) if children else []
|
||||
|
||||
def class_field(self, children):
|
||||
return (list(children[0]), children[1])
|
||||
|
||||
def class_field_list(self, children):
|
||||
return list(children)
|
||||
|
||||
def class_data_section(self, children):
|
||||
return ast.ClassDataPart(access_attrs=list(children[0]), fields=list(children[1]))
|
||||
|
||||
def class_data_sections(self, children):
|
||||
return list(children)
|
||||
|
||||
def method_attr_list(self, children):
|
||||
return [str(c) for c in children]
|
||||
|
||||
def method_segment_flags(self, children):
|
||||
return list(children[0]) if children else []
|
||||
|
||||
def method_id_list(self, children):
|
||||
return [str(c) for c in children]
|
||||
|
||||
def opt_method_parms(self, children):
|
||||
return children[0] if children else []
|
||||
|
||||
def opt_method_returns(self, children):
|
||||
return children[0] if children else None
|
||||
|
||||
def method_decl_sig(self, children):
|
||||
parms = []
|
||||
return_type = None
|
||||
for child in children:
|
||||
if isinstance(child, list) and (not child or isinstance(child[0], tuple)):
|
||||
parms = child
|
||||
elif child is not None and not isinstance(child, str):
|
||||
return_type = child
|
||||
return {"parms": parms, "return_type": return_type}
|
||||
|
||||
def method_group(self, children):
|
||||
names = list(children[0])
|
||||
sig = children[1]
|
||||
return ast.MethodDecl(
|
||||
names=names,
|
||||
parms=sig["parms"],
|
||||
return_type=sig["return_type"],
|
||||
)
|
||||
|
||||
def method_group_list(self, children):
|
||||
return list(children)
|
||||
|
||||
def method_section(self, children):
|
||||
attrs = list(children[0])
|
||||
methods = list(children[1])
|
||||
for method in methods:
|
||||
method.attrs = attrs
|
||||
return ast.MethodSection(attrs=attrs, methods=methods)
|
||||
|
||||
def method_section_list(self, children):
|
||||
return list(children)
|
||||
|
||||
def operations_section(self, children):
|
||||
return list(children[0]) if children else []
|
||||
|
||||
def class_type(self, children):
|
||||
if len(children) == 3:
|
||||
base = None
|
||||
data_parts, operations, end_name = children
|
||||
else:
|
||||
base, data_parts, operations, end_name = children
|
||||
return ast.ClassType(
|
||||
end_name=str(end_name),
|
||||
base=base,
|
||||
data_parts=list(data_parts),
|
||||
operations=list(operations),
|
||||
)
|
||||
|
||||
def class_impl_section(self, children):
|
||||
class_name = str(children[0])
|
||||
decls: list = []
|
||||
stmts: list = []
|
||||
for item in children[1:]:
|
||||
if isinstance(item, ast.MethodImplDecl):
|
||||
decls.append(item)
|
||||
elif isinstance(item, (ast.TypeDecl, ast.VarDecl, ast.ProcDecl)):
|
||||
decls.append(item)
|
||||
else:
|
||||
stmts.append(item)
|
||||
return ast.ClassImplSection(class_name=class_name, declarations=decls, statements=stmts)
|
||||
|
||||
def in_impl_item(self, children):
|
||||
return children[0]
|
||||
|
||||
def method_impl_dcl(self, children):
|
||||
return ast.MethodImplDecl(name=str(children[0]), body=children[1])
|
||||
|
||||
def init_value(self, children):
|
||||
return children[0]
|
||||
|
||||
def table_type(self, children):
|
||||
low, high = children[0]
|
||||
return ast.TableType(low=low, high=high, element_type=children[1])
|
||||
|
||||
def desc_type(self, children):
|
||||
if len(children) == 1:
|
||||
return ast.DescType(low=None, high=None, element_type=children[0])
|
||||
low, high = children[0]
|
||||
return ast.DescType(low=low, high=high, element_type=children[1])
|
||||
|
||||
def bounds(self, children):
|
||||
return children[0]
|
||||
|
||||
def defined_type(self, children):
|
||||
if not children:
|
||||
return ast.DefinedType(name="")
|
||||
return ast.DefinedType(name=str(children[0]))
|
||||
|
||||
def constant_subrange(self, children):
|
||||
if len(children) >= 3:
|
||||
return self._const_value(children[0]), self._const_value(children[2])
|
||||
return self._const_value(children[0]), self._const_value(children[1])
|
||||
|
||||
def constant_expr_atom(self, children):
|
||||
return self._const_value(children[0])
|
||||
|
||||
def _const_value(self, node):
|
||||
if isinstance(node, ast.Literal):
|
||||
return node
|
||||
if isinstance(node, Tree):
|
||||
return self._const_value(node.children[0])
|
||||
return self.literal([node])
|
||||
|
||||
def assign_expr(self, children):
|
||||
expr = children[0]
|
||||
for tail in children[1:]:
|
||||
expr = ast.AssignExpr(value=expr, target=tail)
|
||||
return expr
|
||||
|
||||
def assign_tail(self, children):
|
||||
return children[-1]
|
||||
|
||||
def or_expr(self, children):
|
||||
expr = children[0]
|
||||
for rhs in children[1:]:
|
||||
expr = ast.BinExpr(op="|", left=expr, right=rhs)
|
||||
return expr
|
||||
|
||||
def and_expr(self, children):
|
||||
expr = children[0]
|
||||
for rhs in children[1:]:
|
||||
expr = ast.BinExpr(op="&", left=expr, right=rhs)
|
||||
return expr
|
||||
|
||||
def xor_expr(self, children):
|
||||
expr = children[0]
|
||||
for rhs in children[1:]:
|
||||
expr = ast.BinExpr(op="^", left=expr, right=rhs)
|
||||
return expr
|
||||
|
||||
def _bin(self, op: str, children):
|
||||
return ast.BinExpr(op=op, left=children[0], right=children[1])
|
||||
|
||||
def bin_or(self, c):
|
||||
return self._bin("|", c)
|
||||
|
||||
def bin_and(self, c):
|
||||
return self._bin("&", c)
|
||||
|
||||
def bin_xor(self, c):
|
||||
return self._bin("^", c)
|
||||
|
||||
def bin_eq(self, c):
|
||||
return self._bin("=", c)
|
||||
|
||||
def bin_ne(self, c):
|
||||
return self._bin("^=", c)
|
||||
|
||||
def bin_gt(self, c):
|
||||
return self._bin(">", c)
|
||||
|
||||
def bin_ge(self, c):
|
||||
return self._bin(">=", c)
|
||||
|
||||
def bin_lt(self, c):
|
||||
return self._bin("<", c)
|
||||
|
||||
def bin_le(self, c):
|
||||
return self._bin("<=", c)
|
||||
|
||||
def bin_add(self, c):
|
||||
return self._bin("+", c)
|
||||
|
||||
def bin_sub(self, c):
|
||||
return self._bin("-", c)
|
||||
|
||||
def bin_mul(self, c):
|
||||
return self._bin("*", c)
|
||||
|
||||
def bin_div(self, c):
|
||||
return self._bin("/", c)
|
||||
|
||||
def bin_mod(self, c):
|
||||
return self._bin("MOD", c)
|
||||
|
||||
def unary_expr(self, children):
|
||||
if len(children) == 1:
|
||||
return children[0]
|
||||
return ast.UnaryExpr(op=str(children[0]), operand=children[1])
|
||||
|
||||
def ref_segment(self, children):
|
||||
name = str(children[0])
|
||||
if name == "SELF":
|
||||
return ast.VarRef(name="SELF", is_self=True)
|
||||
if name == "SUPER":
|
||||
return ast.VarRef(name="SUPER", is_super=True)
|
||||
return ast.VarRef(name=name)
|
||||
|
||||
def self_ref(self, _children=None):
|
||||
return ast.VarRef(name="SELF", is_self=True)
|
||||
|
||||
def super_ref(self, _children=None):
|
||||
return ast.VarRef(name="SUPER", is_super=True)
|
||||
|
||||
def qual_index(self, children):
|
||||
return ("index", children[0])
|
||||
|
||||
def dot_suffix(self, children):
|
||||
return ("dot", str(children[0]))
|
||||
|
||||
def call_suffix(self, children):
|
||||
if not children:
|
||||
return ("call", [])
|
||||
return ("call", list(children[0]))
|
||||
|
||||
def _normalize_suffix(self, suffix):
|
||||
if isinstance(suffix, tuple):
|
||||
return suffix
|
||||
if isinstance(suffix, Tree):
|
||||
if suffix.data == "dot_suffix":
|
||||
return ("dot", str(suffix.children[0]))
|
||||
if suffix.data in {"qual_index", "index_suffix"}:
|
||||
return ("index", suffix.children[0])
|
||||
if suffix.data == "call_suffix":
|
||||
if not suffix.children:
|
||||
return ("call", [])
|
||||
args = suffix.children[0]
|
||||
return ("call", list(args) if isinstance(args, list) else [])
|
||||
return suffix
|
||||
|
||||
def _flatten_suffixes(self, nodes):
|
||||
out = []
|
||||
for node in nodes:
|
||||
if isinstance(node, Tree) and node.data == "qual_suffix":
|
||||
out.extend(self._flatten_suffixes(node.children))
|
||||
else:
|
||||
out.append(self._normalize_suffix(node))
|
||||
return out
|
||||
|
||||
def qualified_ref(self, children):
|
||||
root = children[0]
|
||||
suffixes = self._flatten_suffixes(children[1:])
|
||||
if suffixes and isinstance(suffixes[-1], tuple) and suffixes[-1][0] == "call":
|
||||
args = suffixes[-1][1]
|
||||
path = suffixes[:-1]
|
||||
if not path:
|
||||
name = root.name if isinstance(root, ast.VarRef) else "?"
|
||||
return ast.ProcCall(name=name, args=args)
|
||||
if path[-1][0] != "dot":
|
||||
return ast.ProcCall(name="?", args=args)
|
||||
method_name = path[-1][1]
|
||||
receiver = self._build_qualified(root, path[:-1])
|
||||
return ast.MethodCall(receiver=receiver, name=method_name, args=args)
|
||||
return self._build_qualified(root, suffixes)
|
||||
|
||||
def _build_qualified(self, root, suffixes):
|
||||
result = root
|
||||
for suffix in suffixes:
|
||||
if not isinstance(suffix, tuple):
|
||||
continue
|
||||
if suffix[0] == "dot":
|
||||
result = ast.MemberRef(base=result, member=suffix[1])
|
||||
elif suffix[0] == "index" and isinstance(result, ast.VarRef):
|
||||
result.indices.append(suffix[1])
|
||||
return result
|
||||
|
||||
def index_suffix(self, children):
|
||||
if len(children) == 1:
|
||||
return children[0]
|
||||
return (children[0], children[1])
|
||||
|
||||
def actual_list(self, children):
|
||||
return list(children)
|
||||
|
||||
def true_lit(self, _children=None):
|
||||
return ast.Literal(kind="true", value="TRUE")
|
||||
|
||||
def false_lit(self, _children=None):
|
||||
return ast.Literal(kind="false", value="FALSE")
|
||||
|
||||
def nil_lit(self, _children=None):
|
||||
return ast.Literal(kind="nil", value="NIL")
|
||||
|
||||
def literal(self, children):
|
||||
text = str(children[0])
|
||||
if text.startswith("'"):
|
||||
return ast.Literal(kind="string", value=text)
|
||||
if any(ch in text for ch in ".eE"):
|
||||
return ast.Literal(kind="float", value=text)
|
||||
return ast.Literal(kind="int", value=text)
|
||||
|
||||
def tuple(self, children):
|
||||
if not children:
|
||||
return ast.TupleLit(elements=[])
|
||||
return ast.TupleLit(elements=list(children[0]))
|
||||
|
||||
def tuple_body_list(self, children):
|
||||
return list(children)
|
||||
|
||||
def tuple_elem(self, children):
|
||||
return children[0]
|
||||
|
||||
def NUMBER(self, token):
|
||||
return str(token)
|
||||
|
||||
def STRING(self, token):
|
||||
return str(token)
|
||||
|
||||
def IDENT(self, token):
|
||||
return str(token)
|
||||
|
||||
|
||||
class ProtelParser:
|
||||
def __init__(self, *, classical: bool = False):
|
||||
self.classical = classical
|
||||
grammar = _GRAMMAR_PATH.read_text(encoding="utf-8")
|
||||
# Earley is required for CASE/SELECT bodies with multiple labelled arms.
|
||||
self._lark = Lark(grammar, start="start", parser="earley", lexer="basic")
|
||||
self._transformer = ProtelASTBuilder()
|
||||
|
||||
def parse(self, source: str):
|
||||
normalized = normalize_keywords(source, classical=self.classical)
|
||||
tree = self._lark.parse(normalized)
|
||||
return self._transformer.transform(tree)
|
||||
|
||||
|
||||
def parse_protel(source: str, *, classical: bool = False):
|
||||
return ProtelParser(classical=classical).parse(source)
|
||||
@@ -0,0 +1,111 @@
|
||||
"""Lexical preprocessing for PROTEL source before parsing."""
|
||||
|
||||
from __future__ import annotations
|
||||
|
||||
import re
|
||||
|
||||
from .keywords import PROTEL_KEYWORDS
|
||||
|
||||
_DOLLAR_DIRECTIVES = frozenset(k for k in PROTEL_KEYWORDS if k.startswith("$"))
|
||||
|
||||
KEYWORD_RE = re.compile(
|
||||
r"\b(" + "|".join(sorted(PROTEL_KEYWORDS, key=len, reverse=True)) + r")\b",
|
||||
re.IGNORECASE,
|
||||
)
|
||||
|
||||
TOKEN_SPEC = [
|
||||
("STRING", r"'(?:''|[^'])*'"),
|
||||
("IDENT", r"[A-Za-z_$][A-Za-z0-9_$]*"),
|
||||
("NUMBER", r"\d+(?:\.\d+)?(?:[eE][+-]?\d+)?"),
|
||||
("OP_SYM", r"->|::=|[<>=!&|/*%+-]+|[\(\)\[\]\{\},;:\.\^]"),
|
||||
("WHITESPACE", r"[ \t\r\n]+"),
|
||||
("OTHER", r"."),
|
||||
]
|
||||
|
||||
TOKEN_RE = re.compile(
|
||||
"|".join(f"(?P<{name}>{pattern})" for name, pattern in TOKEN_SPEC),
|
||||
re.DOTALL,
|
||||
)
|
||||
|
||||
|
||||
def _find_comment_start(line: str) -> int:
|
||||
in_string = False
|
||||
i = 0
|
||||
while i < len(line):
|
||||
ch = line[i]
|
||||
if ch == "'":
|
||||
in_string = not in_string
|
||||
if in_string and i + 1 < len(line) and line[i + 1] == "'":
|
||||
i += 1
|
||||
elif ch == "%" and not in_string:
|
||||
return i
|
||||
i += 1
|
||||
return -1
|
||||
|
||||
|
||||
def _is_dollar_directive_line(code_part: str) -> bool:
|
||||
"""True for linker control lines such as ``$li modentry restart``."""
|
||||
for match in TOKEN_RE.finditer(code_part):
|
||||
kind = match.lastgroup
|
||||
if kind == "WHITESPACE":
|
||||
continue
|
||||
if kind == "IDENT":
|
||||
return match.group().upper() in _DOLLAR_DIRECTIVES
|
||||
return False
|
||||
return False
|
||||
|
||||
|
||||
def strip_shebang(source: str) -> str:
|
||||
"""
|
||||
Remove a UNIX shebang (``#!...``) from the first line when present.
|
||||
|
||||
The shebang is host metadata for direct execution; it is not PROTEL syntax.
|
||||
"""
|
||||
if source.startswith("#!"):
|
||||
_, _, rest = source.partition("\n")
|
||||
return rest
|
||||
return source
|
||||
|
||||
|
||||
def normalize_keywords(source: str, *, classical: bool = False) -> str:
|
||||
"""
|
||||
Uppercase reserved keywords outside comments and strings.
|
||||
|
||||
In modern mode, keywords are normalized to UPPERCASE before parsing.
|
||||
In classical mode, the same normalization applies but identifiers remain
|
||||
case-sensitive when not matching reserved words.
|
||||
"""
|
||||
del classical # reserved for future classical-only identifier rules
|
||||
source = strip_shebang(source)
|
||||
output_parts: list[str] = []
|
||||
|
||||
for line in source.splitlines(keepends=True):
|
||||
comment_pos = _find_comment_start(line)
|
||||
if comment_pos != -1:
|
||||
code_part = line[:comment_pos]
|
||||
# Drop comments before parse; the transpiler re-emits source file name.
|
||||
else:
|
||||
code_part = line
|
||||
|
||||
if _is_dollar_directive_line(code_part):
|
||||
continue
|
||||
|
||||
line_out: list[str] = []
|
||||
for match in TOKEN_RE.finditer(code_part):
|
||||
kind = match.lastgroup
|
||||
token = match.group()
|
||||
if kind == "STRING":
|
||||
line_out.append(token)
|
||||
elif kind == "IDENT":
|
||||
upper = token.upper()
|
||||
line_out.append(upper if upper in PROTEL_KEYWORDS else token)
|
||||
else:
|
||||
line_out.append(token)
|
||||
|
||||
normalized = "".join(line_out)
|
||||
if normalized.strip():
|
||||
if not normalized.endswith("\n"):
|
||||
normalized += "\n"
|
||||
output_parts.append(normalized)
|
||||
|
||||
return "".join(output_parts)
|
||||
@@ -0,0 +1,28 @@
|
||||
/* Minimal PROTEL 2026 I/O runtime: POSIX write(2) only, no iostream. */
|
||||
#include <stddef.h>
|
||||
#include <unistd.h>
|
||||
|
||||
#include "protel_io.h"
|
||||
|
||||
static void write_cstr(const char* s)
|
||||
{
|
||||
size_t n = 0;
|
||||
while (s[n] != '\0') {
|
||||
n++;
|
||||
}
|
||||
if (n > 0) {
|
||||
(void)write(1, s, n);
|
||||
}
|
||||
}
|
||||
|
||||
void writeln(const char* msg)
|
||||
{
|
||||
if (msg == NULL) {
|
||||
msg = "";
|
||||
}
|
||||
write_cstr(msg);
|
||||
{
|
||||
const char nl = '\n';
|
||||
(void)write(1, &nl, 1);
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,11 @@
|
||||
#pragma once
|
||||
|
||||
#ifdef __cplusplus
|
||||
extern "C" {
|
||||
#endif
|
||||
|
||||
void writeln(const char* msg); /* EXTERNAL C I/O */
|
||||
|
||||
#ifdef __cplusplus
|
||||
}
|
||||
#endif
|
||||
@@ -0,0 +1,822 @@
|
||||
"""PROTEL 2026 to C transpiler."""
|
||||
|
||||
from __future__ import annotations
|
||||
|
||||
import textwrap
|
||||
from typing import Any, TextIO
|
||||
|
||||
from . import ast_nodes as ast
|
||||
|
||||
|
||||
class TranspileError(Exception):
|
||||
"""Raised when PROTEL source cannot be transpiled."""
|
||||
|
||||
|
||||
class TypeContext:
|
||||
def __init__(self):
|
||||
self.aliases: dict[str, Any] = {}
|
||||
self.predefined = {
|
||||
"integer": ast.RangeType(
|
||||
low=ast.Literal(kind="int", value="-32768"),
|
||||
high=ast.Literal(kind="int", value="32767"),
|
||||
)
|
||||
}
|
||||
|
||||
def declare(self, names: list[str], spec):
|
||||
for name in names:
|
||||
self.aliases[name] = spec
|
||||
|
||||
def resolve(self, spec):
|
||||
if isinstance(spec, ast.DefinedType):
|
||||
if spec.name in self.aliases:
|
||||
return self.aliases[spec.name]
|
||||
if spec.name in self.predefined:
|
||||
return self.predefined[spec.name]
|
||||
return spec
|
||||
|
||||
|
||||
class CTranspiler:
|
||||
def __init__(self, *, classical: bool = False, source_name: str = "input.protel"):
|
||||
self.classical = classical
|
||||
self.source_name = source_name
|
||||
self.types = TypeContext()
|
||||
self.indent = 0
|
||||
self.lines: list[str] = []
|
||||
self._proc_decls: list[ast.ProcDecl] = []
|
||||
self._method_impls: list[tuple[str, ast.MethodImplDecl, ast.MethodDecl | None]] = []
|
||||
self._class_methods: dict[str, dict[str, ast.MethodDecl]] = {}
|
||||
self._class_vars: dict[str, set[str]] = {}
|
||||
self._var_types: dict[str, str] = {}
|
||||
self._current_class: str | None = None
|
||||
self._current_self: str = "self"
|
||||
|
||||
def emit(self, line: str = ""):
|
||||
if line:
|
||||
self.lines.append(" " * 4 * self.indent + line)
|
||||
else:
|
||||
self.lines.append("")
|
||||
|
||||
def transpile(self, compilation_unit: list[ast.Section]) -> str:
|
||||
self.lines = []
|
||||
self._proc_decls = []
|
||||
self._method_impls = []
|
||||
self._class_methods = {}
|
||||
self._class_vars = {}
|
||||
self._var_types = {}
|
||||
self.emit("/* Generated by PROTEL 2026 transpiler */")
|
||||
self.emit(f"/* Source: {self.source_name} */")
|
||||
self.emit('#include <stdint.h>')
|
||||
self.emit('#include <stdbool.h>')
|
||||
self.emit("")
|
||||
|
||||
for section in compilation_unit:
|
||||
self._emit_section(section)
|
||||
|
||||
for proc in self._proc_decls:
|
||||
if proc.body:
|
||||
self._emit_procedure(proc)
|
||||
|
||||
for class_name, impl, method_decl in self._method_impls:
|
||||
self._emit_method_impl(class_name, impl, method_decl)
|
||||
|
||||
return "\n".join(self.lines) + "\n"
|
||||
|
||||
def _emit_section(self, section: ast.Section):
|
||||
self.emit(f"/* SECTION {section.name} ({section.module_type} {section.section_kind}) */")
|
||||
if section.uses_modules:
|
||||
self.emit(f"/* USES: {', '.join(section.uses_modules)} */")
|
||||
if section.of_modules:
|
||||
self.emit(f"/* OF: {', '.join(section.of_modules)} */")
|
||||
self.emit("")
|
||||
|
||||
for decl in section.declarations:
|
||||
self._emit_toplevel_decl(decl)
|
||||
for impl in section.class_impls:
|
||||
self._queue_class_impl(impl)
|
||||
for stmt in section.statements:
|
||||
self._emit_stmt(stmt)
|
||||
|
||||
def _emit_toplevel_decl(self, decl):
|
||||
if isinstance(decl, ast.TypeDecl):
|
||||
self.types.declare(decl.names, decl.type_spec)
|
||||
for name in decl.names:
|
||||
self.emit(f"/* TYPE {name} */")
|
||||
if isinstance(decl.type_spec, ast.StructType):
|
||||
self._emit_struct_typedef(decl.names[0], decl.type_spec)
|
||||
elif isinstance(decl.type_spec, ast.ClassType):
|
||||
self._emit_class_typedef(decl.names[0], decl.type_spec)
|
||||
elif isinstance(decl.type_spec, ast.SymbolicRange):
|
||||
self._emit_symbolic_typedef(decl.names[0], decl.type_spec)
|
||||
elif isinstance(decl.type_spec, ast.AreaType):
|
||||
for name in decl.names:
|
||||
self._emit_area_typedef(name, decl.type_spec)
|
||||
else:
|
||||
for name in decl.names:
|
||||
self.emit(f"typedef {self._c_type_decl(decl.type_spec, name)};")
|
||||
self.emit("")
|
||||
elif isinstance(decl, ast.VarDecl):
|
||||
if decl.ovly_fields is not None:
|
||||
self.emit("/* OVLY overlay declaration */")
|
||||
for labels, names, field_type in decl.ovly_fields:
|
||||
for name in names:
|
||||
self.emit(
|
||||
f"/* OVLY {self._c_expr(labels)}: "
|
||||
f"{self._c_type_decl(field_type, name)} */"
|
||||
)
|
||||
self.emit("")
|
||||
return
|
||||
type_name = self._decl_type_name(decl.type_spec)
|
||||
for name in decl.names:
|
||||
if type_name:
|
||||
self._var_types[name] = type_name
|
||||
prefix = ""
|
||||
if decl.storage_class:
|
||||
prefix = f"/* {decl.storage_class} */ "
|
||||
line = f"{prefix}{self._c_type_decl(decl.type_spec, name)}"
|
||||
if decl.init is not None:
|
||||
line += f" = {self._c_init(decl.init)}"
|
||||
line += ";"
|
||||
self.emit(line)
|
||||
self.emit("")
|
||||
elif isinstance(decl, ast.ProcDecl):
|
||||
if decl.intrinsic:
|
||||
return
|
||||
if decl.forward:
|
||||
self.emit(f"/* FORWARD {decl.name} */")
|
||||
self.emit(self._proc_signature(decl) + ";")
|
||||
self.emit("")
|
||||
return
|
||||
if decl.external:
|
||||
self.emit(f"extern {self._proc_signature(decl)};")
|
||||
self.emit("")
|
||||
return
|
||||
self._proc_decls.append(decl)
|
||||
self.emit(self._proc_signature(decl) + ";")
|
||||
self.emit("")
|
||||
|
||||
def _proc_signature(self, proc: ast.ProcDecl) -> str:
|
||||
ret = self._c_type(proc.return_type) if proc.return_type else "void"
|
||||
args = self._c_parm_list(proc.parms)
|
||||
return f"{ret} {proc.name}({args})"
|
||||
|
||||
def _c_parm_list(self, parms: list[tuple[list[str], Any, bool]]) -> str:
|
||||
if not parms:
|
||||
return "void"
|
||||
parts: list[str] = []
|
||||
for names, type_spec, parm_mode in parms:
|
||||
c_type = self._c_type(type_spec)
|
||||
for name in names:
|
||||
if parm_mode is True:
|
||||
parts.append(f"{c_type} *{name}")
|
||||
elif parm_mode == "UPDATES":
|
||||
parts.append(f"{c_type} *{name} /* UPDATES */")
|
||||
else:
|
||||
parts.append(f"{c_type} {name}")
|
||||
return ", ".join(parts)
|
||||
|
||||
def _emit_procedure(self, proc: ast.ProcDecl):
|
||||
self.emit(self._proc_signature(proc))
|
||||
self.emit("{")
|
||||
self.indent += 1
|
||||
self._emit_block_body(proc.body)
|
||||
self.indent -= 1
|
||||
self.emit("}")
|
||||
self.emit("")
|
||||
|
||||
def _emit_block_body(self, block: ast.Block):
|
||||
for decl in block.declarations:
|
||||
if isinstance(decl, ast.VarDecl):
|
||||
c_type = self._c_type(decl.type_spec)
|
||||
for name in decl.names:
|
||||
init = f" = {self._c_expr(decl.init)}" if decl.init is not None else ""
|
||||
self.emit(f"{c_type} {name}{init};")
|
||||
elif isinstance(decl, ast.TypeDecl):
|
||||
self.types.declare(decl.names, decl.type_spec)
|
||||
for stmt in block.statements:
|
||||
self._emit_stmt(stmt)
|
||||
|
||||
def _emit_stmt(self, stmt):
|
||||
if isinstance(stmt, ast.Block):
|
||||
self.emit("{")
|
||||
self.indent += 1
|
||||
self._emit_block_body(stmt)
|
||||
self.indent -= 1
|
||||
self.emit("}")
|
||||
elif isinstance(stmt, ast.IfStmt):
|
||||
self.emit(f"if ({self._c_expr(stmt.condition)}) {{")
|
||||
self.indent += 1
|
||||
for s in stmt.then_part:
|
||||
self._emit_stmt(s)
|
||||
self.indent -= 1
|
||||
self.emit("}")
|
||||
if stmt.else_part:
|
||||
self.emit("else {")
|
||||
self.indent += 1
|
||||
for s in stmt.else_part:
|
||||
self._emit_stmt(s)
|
||||
self.indent -= 1
|
||||
self.emit("}")
|
||||
elif isinstance(stmt, ast.LoopStmt):
|
||||
if stmt.while_expr is not None:
|
||||
self.emit(f"while ({self._c_expr(stmt.while_expr)}) {{")
|
||||
else:
|
||||
self.emit("while (1) {")
|
||||
self.indent += 1
|
||||
for s in stmt.body:
|
||||
self._emit_stmt(s)
|
||||
self.indent -= 1
|
||||
self.emit("}")
|
||||
elif isinstance(stmt, ast.ForStmt):
|
||||
self._emit_for(stmt)
|
||||
elif isinstance(stmt, ast.OverStmt):
|
||||
self._emit_over(stmt)
|
||||
elif isinstance(stmt, ast.CaseStmt):
|
||||
self._emit_case(stmt)
|
||||
elif isinstance(stmt, ast.ExitStmt):
|
||||
self.emit("break;")
|
||||
elif isinstance(stmt, ast.ReturnStmt):
|
||||
if stmt.value is None:
|
||||
self.emit("return;")
|
||||
else:
|
||||
self.emit(f"return {self._c_expr(stmt.value)};")
|
||||
elif isinstance(stmt, ast.BindStmt):
|
||||
for name, ref, as_type in stmt.bindings:
|
||||
cast = f" AS {self._c_type(as_type)}" if as_type is not None else ""
|
||||
self.emit(
|
||||
f"/* BIND {name} TO {self._c_expr(ref)}{cast} */"
|
||||
)
|
||||
elif isinstance(stmt, ast.WithStmt):
|
||||
refs = ", ".join(self._c_expr(ref) for ref in stmt.refs)
|
||||
self.emit(f"/* WITH {refs} */")
|
||||
else:
|
||||
expr_code = self._c_expr(stmt)
|
||||
if expr_code:
|
||||
self.emit(f"{expr_code};")
|
||||
|
||||
def _unwrap_type(self, spec):
|
||||
from lark import Tree
|
||||
|
||||
while isinstance(spec, Tree):
|
||||
if spec.children:
|
||||
spec = spec.children[0]
|
||||
else:
|
||||
break
|
||||
return spec
|
||||
|
||||
def _c_type_decl(self, spec, name: str) -> str:
|
||||
spec = self._unwrap_type(spec)
|
||||
if isinstance(spec, ast.TableType):
|
||||
elem = self._c_type(spec.element_type)
|
||||
count = self._table_count(spec.low, spec.high)
|
||||
return f"{elem} {name}[{count}]"
|
||||
return f"{self._c_type(spec)} {name}"
|
||||
|
||||
def _c_type(self, spec) -> str:
|
||||
if spec is None:
|
||||
return "void"
|
||||
spec = self._unwrap_type(spec)
|
||||
spec = self.types.resolve(spec)
|
||||
if isinstance(spec, ast.RangeType):
|
||||
return self._range_to_c(spec)
|
||||
if isinstance(spec, ast.BoolType):
|
||||
return "uint8_t"
|
||||
if isinstance(spec, ast.SymbolicRange):
|
||||
return "int32_t"
|
||||
if isinstance(spec, ast.DefinedType):
|
||||
return spec.name
|
||||
if isinstance(spec, ast.PtrType):
|
||||
target = self._unwrap_type(spec.target)
|
||||
if isinstance(target, ast.DefinedType):
|
||||
return f"{target.name} *"
|
||||
return f"{self._c_type(spec.target)} *"
|
||||
if isinstance(spec, ast.TableType):
|
||||
elem = self._c_type(spec.element_type)
|
||||
count = self._table_count(spec.low, spec.high)
|
||||
return f"{elem}[{count}]" # used for value contexts, not typedef names
|
||||
if isinstance(spec, ast.DescType):
|
||||
return "void * /* DESC */"
|
||||
if isinstance(spec, ast.AreaType):
|
||||
opts = " ".join(spec.options) if spec.options else "AREA"
|
||||
return f"uint8_t /* {opts} AREA({self._c_expr(spec.size_expr)}) */"
|
||||
if isinstance(spec, ast.ClassType):
|
||||
return spec.end_name
|
||||
if isinstance(spec, ast.StructType):
|
||||
return f"struct {self._struct_tag(spec)}"
|
||||
if isinstance(spec, ast.SetType):
|
||||
return "uint32_t"
|
||||
if isinstance(spec, dict) and "parms" in spec:
|
||||
ret = self._c_type(spec.get("return_type")) if spec.get("return_type") else "void"
|
||||
args = self._c_parm_list(spec.get("parms", []))
|
||||
return f"{ret} (*)({args})"
|
||||
if isinstance(spec, ast.ProcTypeSig):
|
||||
ret = self._c_type(spec.return_type) if spec.return_type else "void"
|
||||
args = self._c_parm_list(spec.parms)
|
||||
return f"{ret} (*)({args})"
|
||||
return "int32_t"
|
||||
|
||||
def _range_to_c(self, spec: ast.RangeType) -> str:
|
||||
low = self._literal_int(spec.low)
|
||||
high = self._literal_int(spec.high)
|
||||
if low is not None and high is not None:
|
||||
if low >= 0 and high <= 255:
|
||||
return "uint8_t"
|
||||
if low >= -32768 and high <= 32767:
|
||||
return "int16_t"
|
||||
if low >= 0 and high <= 65535:
|
||||
return "uint16_t"
|
||||
if low >= -2147483648 and high <= 2147483647:
|
||||
return "int32_t"
|
||||
return "int32_t"
|
||||
|
||||
def _literal_int(self, node) -> int | None:
|
||||
if isinstance(node, ast.Literal) and node.kind == "int":
|
||||
return int(node.value)
|
||||
if isinstance(node, str) and node.lstrip("-").isdigit():
|
||||
return int(node)
|
||||
return None
|
||||
|
||||
def _table_count(self, low, high) -> int:
|
||||
lo = self._literal_int(low)
|
||||
hi = self._literal_int(high)
|
||||
if lo is not None and hi is not None:
|
||||
return hi - lo + 1
|
||||
return 0
|
||||
|
||||
def _protel_string_chars(self, protel_str: str) -> list[str]:
|
||||
return list(protel_str[1:-1].replace("''", "'"))
|
||||
|
||||
def _c_char_code(self, code: int) -> str:
|
||||
if code == 0:
|
||||
return "0"
|
||||
if 32 <= code <= 126 and code not in (ord("\\"), ord("'")):
|
||||
return f"'{chr(code)}'"
|
||||
return str(code)
|
||||
|
||||
def _c_char_array_literal(self, codes: list[int]) -> str:
|
||||
items = ", ".join(self._c_char_code(code) for code in codes)
|
||||
return f"(const char[]){{ {items} }}"
|
||||
|
||||
def _flatten_char_tuple_elements(self, elements: list[Any]) -> list[int]:
|
||||
codes: list[int] = []
|
||||
for elem in elements:
|
||||
if isinstance(elem, ast.Literal) and elem.kind == "string":
|
||||
codes.extend(ord(ch) for ch in self._protel_string_chars(elem.value))
|
||||
elif isinstance(elem, ast.Literal) and elem.kind == "int":
|
||||
codes.append(int(elem.value))
|
||||
else:
|
||||
raise ValueError(
|
||||
"char tuple for C interop may only contain string literals "
|
||||
"and integer byte values (e.g. 0 for NUL)"
|
||||
)
|
||||
return codes
|
||||
|
||||
def _is_char_sequence_tuple(self, elements: list[Any]) -> bool:
|
||||
if not elements:
|
||||
return False
|
||||
return all(
|
||||
isinstance(elem, ast.Literal) and elem.kind in {"string", "int"}
|
||||
for elem in elements
|
||||
)
|
||||
|
||||
def _c_char_sequence_tuple(self, elements: list[Any]) -> str:
|
||||
return self._c_char_array_literal(self._flatten_char_tuple_elements(elements))
|
||||
|
||||
def _c_init(self, init) -> str:
|
||||
if isinstance(init, ast.TupleLit):
|
||||
if self._is_char_sequence_tuple(init.elements):
|
||||
return self._c_char_sequence_tuple(init.elements)
|
||||
items = ", ".join(self._c_expr(e) for e in init.elements)
|
||||
return f"{{ {items} }}"
|
||||
return self._c_expr(init)
|
||||
|
||||
def _c_expr(self, expr) -> str:
|
||||
if isinstance(expr, ast.Literal):
|
||||
if expr.kind == "string":
|
||||
return self._c_string(expr.value)
|
||||
if expr.kind == "int":
|
||||
return str(expr.value)
|
||||
if expr.kind == "float":
|
||||
return str(expr.value)
|
||||
if expr.kind == "true":
|
||||
return "true"
|
||||
if expr.kind == "false":
|
||||
return "false"
|
||||
if expr.kind == "NIL".lower():
|
||||
return "NULL"
|
||||
if isinstance(expr, ast.VarRef):
|
||||
if expr.is_self:
|
||||
base = self._current_self
|
||||
elif expr.is_super:
|
||||
base = f"/* SUPER */ {self._current_self}"
|
||||
else:
|
||||
base = expr.name
|
||||
for idx in expr.indices:
|
||||
if isinstance(idx, tuple):
|
||||
lo, hi = idx
|
||||
base = f"{base}[{self._c_expr(lo)} /* TO {self._c_expr(hi)} */]"
|
||||
else:
|
||||
base = f"{base}[{self._c_expr(idx)}]"
|
||||
return base
|
||||
if isinstance(expr, ast.MemberRef):
|
||||
return self._c_member_ref(expr)
|
||||
if isinstance(expr, ast.MethodCall):
|
||||
args = ", ".join(self._c_expr(a) for a in expr.args)
|
||||
class_name = self._method_class_name(expr)
|
||||
if class_name:
|
||||
return f"{class_name}_{expr.name}({self._method_call_args(expr, args)})"
|
||||
receiver = self._c_expr(expr.receiver) if expr.receiver is not None else ""
|
||||
if receiver:
|
||||
return f"{receiver}.{expr.name}({args})"
|
||||
return f"{expr.name}({args})"
|
||||
if isinstance(expr, ast.ProcCall):
|
||||
args = ", ".join(
|
||||
self._c_proc_call_arg(expr, index, arg)
|
||||
for index, arg in enumerate(expr.args)
|
||||
)
|
||||
return f"{expr.name}({args})"
|
||||
if isinstance(expr, ast.UnaryExpr):
|
||||
if expr.op == "!":
|
||||
return f"!({self._c_expr(expr.operand)})"
|
||||
if expr.op == "-":
|
||||
return f"-({self._c_expr(expr.operand)})"
|
||||
if isinstance(expr, ast.BinExpr):
|
||||
op = self._c_binop(expr.op)
|
||||
return f"({self._c_expr(expr.left)} {op} {self._c_expr(expr.right)})"
|
||||
if isinstance(expr, ast.AssignExpr):
|
||||
target = self._c_assign_target(expr.target)
|
||||
value = self._c_expr(expr.value)
|
||||
return f"({target} = {value})"
|
||||
if isinstance(expr, ast.TupleLit):
|
||||
if self._is_char_sequence_tuple(expr.elements):
|
||||
return self._c_char_sequence_tuple(expr.elements)
|
||||
items = ", ".join(self._c_expr(e) for e in expr.elements)
|
||||
return f"{{ {items} }}"
|
||||
if isinstance(expr, ast.CastExpr):
|
||||
return (
|
||||
f"/* CAST AS {self._c_type(expr.target_type)} */ "
|
||||
f"({self._c_type(expr.target_type)})({self._c_expr(expr.operand)})"
|
||||
)
|
||||
if isinstance(expr, ast.BuiltinExpr):
|
||||
operand = self._c_expr(expr.operand)
|
||||
if expr.name == "UPB":
|
||||
return f"(sizeof({operand}) / sizeof(({operand})[0]) - 1)"
|
||||
if expr.name == "TDSIZE":
|
||||
return f"(sizeof({operand}) / sizeof(({operand})[0]))"
|
||||
if expr.name in {"TYPEDESC", "VARDESC", "REFDESC"}:
|
||||
return f"/* {expr.name} */ ({operand})"
|
||||
if isinstance(expr, ast.Block):
|
||||
return "/* block expr not supported at expression position */ 0"
|
||||
return "/* unknown expr */ 0"
|
||||
|
||||
def _struct_tag(self, spec: ast.StructType) -> str:
|
||||
return "protel_struct"
|
||||
|
||||
def _emit_struct_typedef(self, name: str, spec: ast.StructType):
|
||||
self.types.declare([name], spec)
|
||||
self.emit(f"typedef struct {{")
|
||||
self.indent += 1
|
||||
for field_names, field_type in spec.fields:
|
||||
for field_name in field_names:
|
||||
self.emit(f"{self._c_type_decl(field_type, field_name)};")
|
||||
self.indent -= 1
|
||||
self.emit(f"}} {name};")
|
||||
|
||||
def _emit_symbolic_typedef(self, name: str, spec: ast.SymbolicRange):
|
||||
enum_items = ", ".join(f"{member} = {idx}" for idx, member in enumerate(spec.members))
|
||||
self.emit(f"typedef enum {{ {enum_items} }} {name};")
|
||||
|
||||
def _is_class_var_segment(self, attrs: list[str]) -> bool:
|
||||
return "PROTECTED" in attrs or "SHARED" in attrs
|
||||
|
||||
def _c_member_ref(self, expr: ast.MemberRef) -> str:
|
||||
if (
|
||||
isinstance(expr.base, ast.VarRef)
|
||||
and expr.base.is_self
|
||||
and self._current_class
|
||||
and expr.member in self._class_vars.get(self._current_class, set())
|
||||
):
|
||||
return f"{self._current_class}_{expr.member}"
|
||||
if isinstance(expr.base, ast.VarRef) and expr.base.is_self:
|
||||
return f"self->{expr.member}"
|
||||
return f"{self._c_expr(expr.base)}.{expr.member}"
|
||||
|
||||
def _emit_class_typedef(self, name: str, spec: ast.ClassType):
|
||||
self.types.declare([name], spec)
|
||||
method_map: dict[str, ast.MethodDecl] = {}
|
||||
class_vars: set[str] = set()
|
||||
self.emit(f"typedef struct {name}_t {{")
|
||||
self.indent += 1
|
||||
for part in spec.data_parts:
|
||||
if self._is_class_var_segment(part.access_attrs):
|
||||
continue
|
||||
for field_names, field_type in part.fields:
|
||||
for field_name in field_names:
|
||||
self.emit(f"{self._c_type_decl(field_type, field_name)};")
|
||||
self.indent -= 1
|
||||
self.emit(f"}} {name};")
|
||||
self.emit("")
|
||||
for part in spec.data_parts:
|
||||
if not self._is_class_var_segment(part.access_attrs):
|
||||
continue
|
||||
segment = "protected" if "PROTECTED" in part.access_attrs else "shared"
|
||||
for field_names, field_type in part.fields:
|
||||
for field_name in field_names:
|
||||
class_vars.add(field_name)
|
||||
self.emit(
|
||||
f"static {self._c_type(field_type)} {name}_{field_name}; "
|
||||
f"/* class var ({segment}) */"
|
||||
)
|
||||
self.emit("")
|
||||
self._class_vars[name] = class_vars
|
||||
for section in spec.operations:
|
||||
for method in section.methods:
|
||||
for method_name in method.names:
|
||||
method_map[method_name] = method
|
||||
self.emit(self._method_prototype(name, method_name, method) + ";")
|
||||
self.emit("")
|
||||
self._class_methods[name] = method_map
|
||||
|
||||
def _method_is_class_method(self, method: ast.MethodDecl) -> bool:
|
||||
return "CLASS" in method.attrs
|
||||
|
||||
def _method_prototype(self, class_name: str, method_name: str, method: ast.MethodDecl) -> str:
|
||||
ret = self._c_type(method.return_type) if method.return_type else "void"
|
||||
args = self._method_parm_list(class_name, method)
|
||||
return f"{ret} {class_name}_{method_name}({args})"
|
||||
|
||||
def _method_parm_list(self, class_name: str, method: ast.MethodDecl) -> str:
|
||||
parts: list[str] = []
|
||||
if not self._method_is_class_method(method):
|
||||
parts.append(f"{class_name} *{self._current_self}")
|
||||
proc_parts = self._c_parm_list(method.parms)
|
||||
if proc_parts != "void":
|
||||
parts.append(proc_parts)
|
||||
if not parts:
|
||||
return "void"
|
||||
return ", ".join(parts)
|
||||
|
||||
def _queue_class_impl(self, impl: ast.ClassImplSection):
|
||||
self.emit(f"/* IN {impl.class_name} */")
|
||||
method_map = self._class_methods.get(impl.class_name, {})
|
||||
for decl in impl.declarations:
|
||||
if isinstance(decl, ast.MethodImplDecl):
|
||||
method_decl = method_map.get(decl.name)
|
||||
self._method_impls.append((impl.class_name, decl, method_decl))
|
||||
else:
|
||||
self._emit_toplevel_decl(decl)
|
||||
for stmt in impl.statements:
|
||||
self._emit_stmt(stmt)
|
||||
self.emit("")
|
||||
|
||||
def _emit_method_impl(self, class_name: str, impl: ast.MethodImplDecl, method_decl: ast.MethodDecl | None):
|
||||
self._current_class = class_name
|
||||
is_class_method = method_decl is not None and self._method_is_class_method(method_decl)
|
||||
if method_decl is not None:
|
||||
self.emit(self._method_prototype(class_name, impl.name, method_decl))
|
||||
else:
|
||||
self.emit(f"void {class_name}_{impl.name}(void)")
|
||||
self.emit("{")
|
||||
self.indent += 1
|
||||
if not is_class_method:
|
||||
self._current_self = "self"
|
||||
else:
|
||||
self._current_self = class_name
|
||||
self._emit_block_body(impl.body)
|
||||
self.indent -= 1
|
||||
self.emit("}")
|
||||
self.emit("")
|
||||
self._current_class = None
|
||||
self._current_self = "self"
|
||||
|
||||
def _decl_type_name(self, spec) -> str | None:
|
||||
spec = self._unwrap_type(spec)
|
||||
spec = self.types.resolve(spec)
|
||||
if isinstance(spec, ast.DefinedType):
|
||||
return spec.name
|
||||
if isinstance(spec, ast.ClassType):
|
||||
return spec.end_name
|
||||
return None
|
||||
|
||||
def _method_class_name(self, call: ast.MethodCall) -> str | None:
|
||||
if call.receiver is None:
|
||||
return self._current_class
|
||||
if isinstance(call.receiver, ast.VarRef):
|
||||
if call.receiver.is_self:
|
||||
return self._current_class
|
||||
if call.receiver.name in self._var_types:
|
||||
return self._var_types[call.receiver.name]
|
||||
if call.receiver.name in self._class_methods:
|
||||
return call.receiver.name
|
||||
return self._current_class
|
||||
|
||||
def _method_call_args(self, call: ast.MethodCall, args: str) -> str:
|
||||
class_name = self._method_class_name(call)
|
||||
method_decl = None
|
||||
if class_name and class_name in self._class_methods:
|
||||
method_decl = self._class_methods[class_name].get(call.name)
|
||||
if method_decl is not None and not self._method_is_class_method(method_decl):
|
||||
receiver = self._c_expr(call.receiver) if call.receiver is not None else self._current_self
|
||||
if isinstance(call.receiver, ast.VarRef) and not call.receiver.is_self:
|
||||
receiver = f"&{receiver}"
|
||||
if args:
|
||||
return f"{receiver}, {args}"
|
||||
return receiver
|
||||
return args
|
||||
|
||||
def _emit_for(self, stmt: ast.ForStmt):
|
||||
if stmt.over_type is not None:
|
||||
members = self._symbolic_members(stmt.over_type)
|
||||
if members:
|
||||
self.emit("{")
|
||||
self.indent += 1
|
||||
self.emit(f"{self._c_type(stmt.over_type)} {stmt.var};")
|
||||
for member in members:
|
||||
self.emit(f"{stmt.var} = {member};")
|
||||
self.emit("{")
|
||||
self.indent += 1
|
||||
for s in stmt.body:
|
||||
self._emit_stmt(s)
|
||||
self.indent -= 1
|
||||
self.emit("}")
|
||||
self.indent -= 1
|
||||
self.emit("}")
|
||||
return
|
||||
from_expr = self._c_expr(stmt.from_expr) if stmt.from_expr is not None else "0"
|
||||
to_expr = self._c_expr(stmt.to_expr) if stmt.to_expr is not None else "0"
|
||||
by_expr = self._c_expr(stmt.by_expr) if stmt.by_expr is not None else "1"
|
||||
cmp = "<=" if stmt.direction != "DOWN" else ">="
|
||||
self.emit(f"for (int32_t {stmt.var} = {from_expr}; {stmt.var} {cmp} {to_expr}; {stmt.var} += {by_expr}) {{")
|
||||
self.indent += 1
|
||||
if stmt.while_expr is not None:
|
||||
self.emit(f"if (!({self._c_expr(stmt.while_expr)})) break;")
|
||||
for s in stmt.body:
|
||||
self._emit_stmt(s)
|
||||
self.indent -= 1
|
||||
self.emit("}")
|
||||
|
||||
def _emit_over(self, stmt: ast.OverStmt):
|
||||
members = self._symbolic_members(stmt.over_type)
|
||||
if not members:
|
||||
self.emit("/* OVER unsupported type */ {")
|
||||
self.indent += 1
|
||||
for s in stmt.body:
|
||||
self._emit_stmt(s)
|
||||
self.indent -= 1
|
||||
self.emit("}")
|
||||
return
|
||||
for member in members:
|
||||
self.emit("{")
|
||||
self.indent += 1
|
||||
for s in stmt.body:
|
||||
self._emit_stmt(s)
|
||||
self.indent -= 1
|
||||
self.emit("}")
|
||||
|
||||
def _symbolic_members(self, spec) -> list[str]:
|
||||
spec = self.types.resolve(self._unwrap_type(spec))
|
||||
if isinstance(spec, ast.SymbolicRange):
|
||||
return list(spec.members)
|
||||
if isinstance(spec, ast.DefinedType):
|
||||
resolved = self.types.resolve(spec)
|
||||
if isinstance(resolved, ast.SymbolicRange):
|
||||
return list(resolved.members)
|
||||
return []
|
||||
|
||||
def _emit_case(self, stmt: ast.CaseStmt):
|
||||
keyword = "SELECT" if stmt.is_select else "CASE"
|
||||
self.emit(f"/* {keyword} */ switch ({self._c_expr(stmt.selector)}) {{")
|
||||
self.indent += 1
|
||||
for arm in stmt.arms:
|
||||
labels = self._case_labels(arm.labels)
|
||||
for label in labels:
|
||||
self.emit(f"case {label}:")
|
||||
self.emit("{")
|
||||
self.indent += 1
|
||||
for s in arm.statements:
|
||||
self._emit_stmt(s)
|
||||
self.emit("break;")
|
||||
self.indent -= 1
|
||||
self.emit("}")
|
||||
if stmt.out_statements:
|
||||
self.emit("default:")
|
||||
self.emit("{")
|
||||
self.indent += 1
|
||||
for s in stmt.out_statements:
|
||||
self._emit_stmt(s)
|
||||
self.emit("break;")
|
||||
self.indent -= 1
|
||||
self.emit("}")
|
||||
self.indent -= 1
|
||||
self.emit("}")
|
||||
|
||||
def _case_labels(self, labels) -> list[str]:
|
||||
if isinstance(labels, ast.TupleLit):
|
||||
out: list[str] = []
|
||||
for elem in labels.elements:
|
||||
if isinstance(elem, ast.Literal):
|
||||
if elem.kind == "string":
|
||||
for ch in self._protel_string_chars(elem.value):
|
||||
out.append(self._c_char_code(ord(ch)))
|
||||
else:
|
||||
out.append(str(elem.value))
|
||||
else:
|
||||
out.append(self._c_expr(elem))
|
||||
return out
|
||||
if isinstance(labels, ast.Literal) and labels.kind == "string":
|
||||
return [
|
||||
self._c_char_code(ord(ch))
|
||||
for ch in self._protel_string_chars(labels.value)
|
||||
]
|
||||
return [self._c_expr(labels)]
|
||||
|
||||
def _c_proc_call_arg(self, call: ast.ProcCall, index: int, arg: Any) -> str:
|
||||
if isinstance(arg, ast.Literal) and arg.kind == "string":
|
||||
codes = [ord(ch) for ch in self._protel_string_chars(arg.value)]
|
||||
if codes and codes[-1] != 0:
|
||||
self._warn_missing_nul_terminator(call.name, arg.value)
|
||||
return self._c_char_array_literal(codes)
|
||||
if isinstance(arg, ast.TupleLit) and self._is_char_sequence_tuple(arg.elements):
|
||||
codes = self._flatten_char_tuple_elements(arg.elements)
|
||||
if not codes or codes[-1] != 0:
|
||||
self._warn_missing_nul_terminator(call.name, None)
|
||||
return self._c_char_array_literal(codes)
|
||||
return self._c_expr(arg)
|
||||
|
||||
def _warn_missing_nul_terminator(self, proc_name: str, protel_str: str | None) -> None:
|
||||
import sys
|
||||
|
||||
if protel_str is not None:
|
||||
msg = (
|
||||
f"protel: warning: call to {proc_name} uses a PROTEL string without "
|
||||
f"an explicit NUL (0) suffix; append ', 0' in a char tuple for C "
|
||||
f"interoperability"
|
||||
)
|
||||
else:
|
||||
msg = (
|
||||
f"protel: warning: call to {proc_name} uses a char tuple without "
|
||||
f"a trailing 0 byte for C interoperability"
|
||||
)
|
||||
print(msg, file=sys.stderr)
|
||||
|
||||
def _c_assign_target(self, target) -> str:
|
||||
if isinstance(target, ast.VarRef):
|
||||
return self._c_expr(target)
|
||||
return self._c_expr(target)
|
||||
|
||||
def _emit_area_typedef(self, name: str, spec: ast.AreaType) -> None:
|
||||
opts = " ".join(spec.options) if spec.options else ""
|
||||
self.emit(f"/* TYPE {name}: {opts} AREA({self._c_expr(spec.size_expr)}) */")
|
||||
self.emit("struct {")
|
||||
self.indent += 1
|
||||
for field_names, field_type in spec.fields:
|
||||
for field_name in field_names:
|
||||
self.emit(f"{self._c_type_decl(field_type, field_name)};")
|
||||
self.indent -= 1
|
||||
self.emit(f"}} {name};")
|
||||
|
||||
def _c_binop(self, op: str) -> str:
|
||||
mapping = {
|
||||
"->": "=",
|
||||
"MOD": "%",
|
||||
"^=": "!=",
|
||||
"^": "^",
|
||||
"&": "&",
|
||||
"|": "|",
|
||||
"INCL": "/* INCL */",
|
||||
"NOTINCL": "/* NOTINCL */",
|
||||
}
|
||||
return mapping.get(op, op)
|
||||
|
||||
def _c_string(self, protel_str: str) -> str:
|
||||
codes = [ord(ch) for ch in self._protel_string_chars(protel_str)]
|
||||
return self._c_char_array_literal(codes)
|
||||
|
||||
|
||||
def transpile_to_c(
|
||||
compilation_unit,
|
||||
*,
|
||||
classical: bool = False,
|
||||
source_name: str = "input.protel",
|
||||
source_path: "Path | None" = None,
|
||||
) -> str:
|
||||
from pathlib import Path
|
||||
|
||||
from .module_resolver import resolve_compilation_unit
|
||||
from .type_checker import check_types
|
||||
|
||||
if source_path is not None and not isinstance(source_path, Path):
|
||||
source_path = Path(source_path)
|
||||
compilation_unit = resolve_compilation_unit(
|
||||
compilation_unit,
|
||||
source_path=source_path,
|
||||
classical=classical,
|
||||
)
|
||||
check_types(compilation_unit, source_name=source_name)
|
||||
return CTranspiler(classical=classical, source_name=source_name).transpile(compilation_unit)
|
||||
|
||||
|
||||
def transpile_file(source: str, *, classical: bool = False, source_name: str = "input.protel") -> str:
|
||||
from .parser import parse_protel
|
||||
|
||||
tree = parse_protel(source, classical=classical)
|
||||
return transpile_to_c(tree, classical=classical, source_name=source_name)
|
||||
@@ -0,0 +1,338 @@
|
||||
"""Static type checking for PROTEL 2026 (Reference Manual §11, strong typing)."""
|
||||
|
||||
from __future__ import annotations
|
||||
|
||||
from dataclasses import dataclass
|
||||
from typing import Any
|
||||
|
||||
from . import ast_nodes as ast
|
||||
from .transpiler import TranspileError, TypeContext
|
||||
|
||||
|
||||
class TypeCheckError(TranspileError):
|
||||
"""Raised when a PROTEL construct violates type-compatibility rules."""
|
||||
|
||||
|
||||
@dataclass(frozen=True)
|
||||
class TypeInfo:
|
||||
kind: str
|
||||
name: str | None = None
|
||||
low: int | None = None
|
||||
high: int | None = None
|
||||
packed_bits: int | None = None
|
||||
pointee: TypeInfo | None = None
|
||||
|
||||
def label(self) -> str:
|
||||
if self.name:
|
||||
return self.name
|
||||
if self.kind == "bool":
|
||||
return "BOOL"
|
||||
if self.kind == "numeric" and self.low is not None and self.high is not None:
|
||||
suffix = f" PACK({self.packed_bits})" if self.packed_bits else ""
|
||||
return f"{{{self.low} TO {self.high}}}{suffix}"
|
||||
if self.kind == "ptr" and self.pointee is not None:
|
||||
return f"PTR TO {self.pointee.label()}"
|
||||
return self.kind
|
||||
|
||||
|
||||
class TypeChecker:
|
||||
def __init__(self, *, source_name: str = "input.protel"):
|
||||
self.source_name = source_name
|
||||
self.types = TypeContext()
|
||||
self._scopes: list[dict[str, TypeInfo]] = [{}]
|
||||
self._return_type: TypeInfo | None = None
|
||||
self._proc_name: str | None = None
|
||||
|
||||
def check(self, compilation_unit: list[ast.Section]) -> None:
|
||||
for section in compilation_unit:
|
||||
self._check_section(section)
|
||||
|
||||
def _fail(self, message: str) -> None:
|
||||
raise TypeCheckError(f"{message} ({self.source_name})")
|
||||
|
||||
def _literal_int(self, value: Any) -> int | None:
|
||||
if isinstance(value, ast.Literal) and value.kind == "int":
|
||||
return int(value.value)
|
||||
return None
|
||||
|
||||
def _resolve_spec(self, spec: Any) -> Any:
|
||||
from lark import Tree
|
||||
|
||||
while isinstance(spec, Tree):
|
||||
spec = spec.children[0] if spec.children else spec
|
||||
return self.types.resolve(spec)
|
||||
|
||||
def _type_info(self, spec: Any) -> TypeInfo:
|
||||
spec = self._resolve_spec(spec)
|
||||
if isinstance(spec, ast.BoolType):
|
||||
return TypeInfo(
|
||||
kind="bool",
|
||||
name="BOOL",
|
||||
packed_bits=getattr(spec, "packed", None),
|
||||
)
|
||||
if isinstance(spec, ast.RangeType):
|
||||
return TypeInfo(
|
||||
kind="numeric",
|
||||
low=self._literal_int(spec.low),
|
||||
high=self._literal_int(spec.high),
|
||||
packed_bits=getattr(spec, "packed", None),
|
||||
)
|
||||
if isinstance(spec, ast.DefinedType):
|
||||
alias = self.types.aliases.get(spec.name)
|
||||
if alias is not None:
|
||||
base = self._type_info(alias)
|
||||
return TypeInfo(
|
||||
kind=base.kind,
|
||||
name=spec.name,
|
||||
low=base.low,
|
||||
high=base.high,
|
||||
packed_bits=base.packed_bits,
|
||||
pointee=base.pointee,
|
||||
)
|
||||
return TypeInfo(kind="defined", name=spec.name)
|
||||
if isinstance(spec, ast.PtrType):
|
||||
return TypeInfo(
|
||||
kind="ptr",
|
||||
pointee=self._type_info(spec.target),
|
||||
)
|
||||
if isinstance(spec, ast.SymbolicRange):
|
||||
return TypeInfo(kind="symbolic", name="{" + ", ".join(spec.members) + "}")
|
||||
return TypeInfo(kind="unknown")
|
||||
|
||||
def _bounds(self, info: TypeInfo) -> tuple[int, int] | None:
|
||||
if info.low is not None and info.high is not None:
|
||||
return info.low, info.high
|
||||
if info.name and info.name in self.types.aliases:
|
||||
return self._bounds(self._type_info(self.types.aliases[info.name]))
|
||||
if info.name == "integer":
|
||||
return -32768, 32767
|
||||
return None
|
||||
|
||||
def _is_char_type(self, info: TypeInfo) -> bool:
|
||||
if info.name == "char":
|
||||
return True
|
||||
bounds = self._bounds(info)
|
||||
return bounds == (0, 255)
|
||||
|
||||
def _is_wide_integer(self, info: TypeInfo) -> bool:
|
||||
if info.name == "integer":
|
||||
return True
|
||||
bounds = self._bounds(info)
|
||||
if bounds is None:
|
||||
return False
|
||||
low, high = bounds
|
||||
if low == high:
|
||||
return False
|
||||
return low < 0 or high > 255 or (high - low) > 255
|
||||
|
||||
def _pointee_compatible(self, dest: TypeInfo, src: TypeInfo) -> bool:
|
||||
if dest.name and src.name:
|
||||
return dest.name == src.name
|
||||
if dest.kind == "numeric" and src.kind == "numeric":
|
||||
return dest.low == src.low and dest.high == src.high
|
||||
return dest.kind == src.kind and dest.label() == src.label()
|
||||
|
||||
def _compatible(self, dest: TypeInfo, src: TypeInfo) -> bool:
|
||||
if dest.kind == "unknown" or src.kind == "unknown":
|
||||
return True
|
||||
if dest.kind == "bool":
|
||||
return src.kind == "bool"
|
||||
if dest.kind == "ptr" and src.kind == "ptr":
|
||||
if src.pointee is not None and src.pointee.kind == "unknown":
|
||||
return True
|
||||
return (
|
||||
dest.pointee is not None
|
||||
and src.pointee is not None
|
||||
and self._pointee_compatible(dest.pointee, src.pointee)
|
||||
)
|
||||
if self._is_char_type(dest) and self._is_wide_integer(src):
|
||||
return False
|
||||
if dest.packed_bits and self._is_wide_integer(src):
|
||||
return False
|
||||
if dest.name and src.name and dest.name == src.name:
|
||||
return True
|
||||
if dest.kind == "numeric" and src.kind == "numeric":
|
||||
db = self._bounds(dest)
|
||||
sb = self._bounds(src)
|
||||
if db and sb:
|
||||
return db[0] <= sb[0] and sb[1] <= db[1]
|
||||
if dest.name and dest.name in self.types.aliases:
|
||||
return self._compatible(self._type_info(self.types.aliases[dest.name]), src)
|
||||
return False
|
||||
|
||||
def _declare_types(self, decl: ast.TypeDecl) -> None:
|
||||
self.types.declare(decl.names, decl.type_spec)
|
||||
|
||||
def _declare_vars(self, names: list[str], type_spec: Any) -> None:
|
||||
info = self._type_info(type_spec)
|
||||
for name in names:
|
||||
self._scopes[-1][name] = info
|
||||
|
||||
def _lookup(self, name: str) -> TypeInfo | None:
|
||||
for scope in reversed(self._scopes):
|
||||
if name in scope:
|
||||
return scope[name]
|
||||
return None
|
||||
|
||||
def _expr_type(self, expr: Any) -> TypeInfo:
|
||||
if isinstance(expr, ast.Literal):
|
||||
if expr.kind == "int":
|
||||
value = int(expr.value)
|
||||
return TypeInfo(kind="numeric", low=value, high=value)
|
||||
if expr.kind in {"true", "false"}:
|
||||
return TypeInfo(kind="bool", name="BOOL")
|
||||
if expr.kind == "NIL".lower():
|
||||
return TypeInfo(kind="ptr", pointee=TypeInfo(kind="unknown"))
|
||||
if isinstance(expr, ast.VarRef) and not expr.is_self and not expr.is_super:
|
||||
return self._lookup(expr.name) or TypeInfo(kind="unknown")
|
||||
if isinstance(expr, ast.BinExpr) and expr.op in {"+", "-", "*", "/", "MOD"}:
|
||||
left = self._expr_type(expr.left)
|
||||
right = self._expr_type(expr.right)
|
||||
if self._is_wide_integer(left) or self._is_wide_integer(right):
|
||||
return TypeInfo(kind="numeric", name="integer", low=-32768, high=32767)
|
||||
lb = [t.low for t in (left, right) if t.low is not None]
|
||||
hb = [t.high for t in (left, right) if t.high is not None]
|
||||
if lb and hb:
|
||||
return TypeInfo(kind="numeric", low=min(lb), high=max(hb))
|
||||
if isinstance(expr, ast.CastExpr):
|
||||
return self._type_info(expr.target_type)
|
||||
return TypeInfo(kind="unknown")
|
||||
|
||||
def _check_assignment(self, target: Any, value: Any, *, context: str) -> None:
|
||||
if not isinstance(target, ast.VarRef) or target.is_self or target.is_super:
|
||||
return
|
||||
dest = self._lookup(target.name)
|
||||
if dest is None:
|
||||
self._fail(f"unknown identifier {target.name!r} in {context}")
|
||||
src = self._expr_type(value)
|
||||
if dest.packed_bits and self._is_wide_integer(src):
|
||||
self._fail(
|
||||
f"cannot assign wide integer to packed byte-sized type "
|
||||
f"{dest.label()} in {context}"
|
||||
)
|
||||
if self._is_char_type(dest) and self._is_wide_integer(src):
|
||||
self._fail(f"cannot assign integer to char in {context}")
|
||||
if (
|
||||
dest.kind == "numeric"
|
||||
and src.kind == "numeric"
|
||||
and src.low is not None
|
||||
and src.high is not None
|
||||
and src.low == src.high
|
||||
):
|
||||
db = self._bounds(dest)
|
||||
if db and (src.low < db[0] or src.high > db[1]):
|
||||
self._fail(
|
||||
f"value {src.low}..{src.high} is out of range for "
|
||||
f"{dest.label()} in {context}"
|
||||
)
|
||||
if not self._compatible(dest, src):
|
||||
self._fail(
|
||||
f"cannot assign {src.label()} to {dest.label()} in {context}"
|
||||
)
|
||||
|
||||
def _check_return(self, value: Any | None) -> None:
|
||||
if self._return_type is None:
|
||||
if value is not None:
|
||||
self._fail(f"procedure {self._proc_name!r} cannot RETURN a value")
|
||||
return
|
||||
if value is None:
|
||||
self._fail(
|
||||
f"procedure {self._proc_name!r} must RETURN {self._return_type.label()}"
|
||||
)
|
||||
src = self._expr_type(value)
|
||||
if not self._compatible(self._return_type, src):
|
||||
self._fail(
|
||||
f"RETURN type {src.label()} is not compatible with "
|
||||
f"RETURNS {self._return_type.label()} in procedure {self._proc_name!r}"
|
||||
)
|
||||
|
||||
def _check_block(self, block: ast.Block) -> None:
|
||||
self._scopes.append({})
|
||||
for decl in block.declarations:
|
||||
if isinstance(decl, ast.TypeDecl):
|
||||
self._declare_types(decl)
|
||||
elif isinstance(decl, ast.VarDecl) and decl.names:
|
||||
self._declare_vars(decl.names, decl.type_spec)
|
||||
if decl.init is not None:
|
||||
for name in decl.names:
|
||||
self._check_assignment(
|
||||
ast.VarRef(name=name),
|
||||
decl.init,
|
||||
context=f"initialization of {name!r}",
|
||||
)
|
||||
for stmt in block.statements:
|
||||
self._check_stmt(stmt)
|
||||
self._scopes.pop()
|
||||
|
||||
def _check_stmt(self, stmt: Any) -> None:
|
||||
if isinstance(stmt, ast.Block):
|
||||
self._check_block(stmt)
|
||||
elif isinstance(stmt, ast.IfStmt):
|
||||
for part in (stmt.then_part, stmt.else_part):
|
||||
for inner in part:
|
||||
self._check_stmt(inner)
|
||||
elif isinstance(stmt, ast.LoopStmt):
|
||||
for inner in stmt.body:
|
||||
self._check_stmt(inner)
|
||||
elif isinstance(stmt, ast.ForStmt):
|
||||
for inner in stmt.body:
|
||||
self._check_stmt(inner)
|
||||
elif isinstance(stmt, ast.OverStmt):
|
||||
for inner in stmt.body:
|
||||
self._check_stmt(inner)
|
||||
elif isinstance(stmt, ast.CaseStmt):
|
||||
for arm in stmt.arms:
|
||||
for inner in arm.statements:
|
||||
self._check_stmt(inner)
|
||||
for inner in stmt.out_statements:
|
||||
self._check_stmt(inner)
|
||||
elif isinstance(stmt, ast.ReturnStmt):
|
||||
self._check_return(stmt.value)
|
||||
elif isinstance(stmt, ast.AssignExpr):
|
||||
self._check_assignment(
|
||||
stmt.target, stmt.value, context="assignment statement"
|
||||
)
|
||||
|
||||
def _check_procedure(self, proc: ast.ProcDecl) -> None:
|
||||
if proc.body is None:
|
||||
return
|
||||
self._scopes.append({})
|
||||
self._proc_name = proc.name
|
||||
self._return_type = (
|
||||
self._type_info(proc.return_type) if proc.return_type else None
|
||||
)
|
||||
for names, type_spec, _mode in proc.parms:
|
||||
self._declare_vars(names, type_spec)
|
||||
self._check_block(proc.body)
|
||||
self._return_type = None
|
||||
self._proc_name = None
|
||||
self._scopes.pop()
|
||||
|
||||
def _check_section(self, section: ast.Section) -> None:
|
||||
self._scopes.append({})
|
||||
for decl in section.declarations:
|
||||
if isinstance(decl, ast.TypeDecl):
|
||||
self._declare_types(decl)
|
||||
elif isinstance(decl, ast.VarDecl) and decl.names:
|
||||
self._declare_vars(decl.names, decl.type_spec)
|
||||
if decl.init is not None:
|
||||
for name in decl.names:
|
||||
self._check_assignment(
|
||||
ast.VarRef(name=name),
|
||||
decl.init,
|
||||
context=f"initialization of {name!r}",
|
||||
)
|
||||
elif isinstance(decl, ast.ProcDecl) and decl.body is not None:
|
||||
if not (
|
||||
decl.external or decl.export or decl.forward or decl.intrinsic
|
||||
):
|
||||
self._check_procedure(decl)
|
||||
self._scopes.pop()
|
||||
|
||||
|
||||
def check_types(
|
||||
compilation_unit: list[ast.Section],
|
||||
*,
|
||||
source_name: str = "input.protel",
|
||||
) -> None:
|
||||
TypeChecker(source_name=source_name).check(compilation_unit)
|
||||
Reference in New Issue
Block a user