Initial PROTEL 2026 toolchain import
This commit is contained in:
@@ -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)
|
||||
Reference in New Issue
Block a user