Skip to content
Open
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
77 changes: 71 additions & 6 deletions lateralus_lang/codegen/c.py
Original file line number Diff line number Diff line change
Expand Up @@ -197,6 +197,13 @@ def result(self) -> str:
"i64": "int64_t",
"usize": "size_t",
"isize": "int64_t",
# Container types. These used to fall through `_c_type`'s default branch,
# which returns the type name verbatim — so `fn f(xs: list)` emitted the C
# prototype `static int64_t f(list xs);` and gcc stopped at "unknown type
# name 'list'".
"list": "ltl_list_t*",
"List": "ltl_list_t*",
"str[]": "ltl_list_t*",
# Function type → function pointer (generic)
"fn": "void*",
"Fn": "void*",
Expand Down Expand Up @@ -569,6 +576,9 @@ def __init__(self, mode: CMode = CMode.HOSTED, *, target_arch: str = "x86_64"):
self._local_types: Dict[str, str] = {} # name → C type for current fn
self._fn_return_types: Dict[str, str] = {} # fn name → C return type
self._list_elem_types: Dict[str, str] = {} # name → elem C type (typed C arrays)
# name → primitive C type of a *boxed* list's elements, used to unbox
# `xs[i]` back to a scalar. Populated for `[x] * n` and friends.
self._box_elem_types: Dict[str, str] = {}

# ── helpers ───────────────────────────────────────────────────────────

Expand Down Expand Up @@ -667,11 +677,15 @@ def _infer_ctype_from_expr(self, node) -> str:
if isinstance(node, ListExpr):
return "ltl_list_t*"
if isinstance(node, IndexExpr):
# Typed C array? Return its element type.
# Typed C array or a boxed list whose element type we recorded:
# either way the read produces a scalar, and callers must know that
# or they will declare `ltl_value_t dx = <double>`.
if isinstance(node.obj, Ident):
nm = self._mangle(node.obj.name)
if nm in self._list_elem_types:
return self._list_elem_types[nm]
if nm in self._box_elem_types:
return self._box_elem_types[nm]
return "ltl_value_t"
if isinstance(node, Ident):
# Look up known local variable types
Expand Down Expand Up @@ -700,8 +714,18 @@ def _infer_ctype_from_expr(self, node) -> str:
if tname == "float": return "double"
if tname == "bool": return "bool"
return _c_type(node.target, "ltl_value_t")
if isinstance(node, UnaryOp):
# -1.5 is still a double; without this the boxing dispatch in
# _visit_AssignStmt sees ltl_value_t and leaves a raw double in an
# ltl_value_t slot.
return self._infer_ctype_from_expr(node.operand)
if isinstance(node, CallExpr):
if isinstance(node.callee, Ident):
# str(x) lowers to one of the ltl_*_to_str helpers, all of which
# return ltl_string_t* — say so, or `println(str(x))` picks the
# const char* overload and prints nothing.
if node.callee.name == "str" and len(node.args) == 1:
return "ltl_string_t*"
nm = self._mangle(node.callee.name)
if nm in ("ltl_int_to_str", "ltl_float_to_str",
"ltl_bool_to_str", "ltl_str_new", "ltl_str_concat"):
Expand Down Expand Up @@ -840,6 +864,7 @@ def _visit_FnDecl(self, node: FnDecl):
self._local_vars = set()
self._local_types = {}
self._list_elem_types = {}
self._box_elem_types = {}

# Register parameter types so inference can see them inside the body
for p in node.params:
Expand Down Expand Up @@ -894,10 +919,30 @@ def _visit_LetDecl(self, node: LetDecl):
return

val = self._visit_expr(node.value) if node.value else "/* uninitialized */ {0}"
# `[x] * n` stays a boxed ltl_list_t, but we still know what is inside,
# so reads can be unboxed (see _expr_IndexExpr).
boxed_elem = self._boxed_repeat_elem_type(node.value)
if boxed_elem is not None:
self._box_elem_types[name] = boxed_elem
self._w.line(f"{ctype} {name} = {val};")
self._local_types[name] = ctype
self._local_vars.add(name)

def _boxed_repeat_elem_type(self, node) -> "Optional[str]":
"""Type of the elements of a boxed list built as `[x] * n`.

The value stays an `ltl_list_t`, so elements are `ltl_value_t` and must
be unboxed on read. Mixed int/float promotes to double.
"""
if not isinstance(node, BinOp) or getattr(node, "op", None) != "*":
return None
for lit, other in ((node.left, node.right), (node.right, node.left)):
if isinstance(lit, ListExpr) and len(lit.elements) == 1:
et = self._infer_ctype_from_expr(lit.elements[0])
if et in ("int64_t", "double", "bool"):
return et
return None

def _homogeneous_list_elem_type(self, node: "ListExpr") -> "Optional[str]":
"""Return a primitive C type if every element infers to the same
primitive (int64_t / double / bool); else None. Mixed int/float is
Expand All @@ -921,7 +966,12 @@ def _homogeneous_list_elem_type(self, node: "ListExpr") -> "Optional[str]":
return None

def _visit_AssignStmt(self, node: AssignStmt):
target = self._visit_expr(node.target)
# An assignment target must stay an lvalue: `xs[i] = v`, never
# `ltl_unbox_int(xs->items[i]) = v`.
if isinstance(node.target, IndexExpr):
target = self._expr_IndexExpr(node.target, unbox=False)
else:
target = self._visit_expr(node.target)
value = self._visit_expr(node.value)
op = getattr(node, "op", "=") or "="
# If target is a list index (list->items[i]), box the RHS into ltl_value_t
Expand Down Expand Up @@ -1283,12 +1333,16 @@ def _expr_CallExpr(self, node: CallExpr) -> str:
if ctype == "ltl_string_t*":
helper = "ltl_io_println" if name == "println" else "ltl_io_print"
return f"{helper}({arg})"
# len(x): both ltl_list_t and ltl_string_t carry a `len` field.
if name == "len" and len(node.args) == 1:
arg = self._visit_expr(node.args[0])
return f"(({arg})->len)"
# Builtin type-coercion calls: int(x), float(x), bool(x), str(x).
if name in ("int", "float", "bool", "str") and len(node.args) == 1:
if name in ("int", "to_int", "float", "bool", "str") and len(node.args) == 1:
arg_node = node.args[0]
arg = self._visit_expr(arg_node)
src = self._infer_ctype_from_expr(arg_node)
if name == "int": return f"((int64_t)({arg}))"
if name in ("int", "to_int"): return f"((int64_t)({arg}))"
if name == "float": return f"((double)({arg}))"
if name == "bool": return f"((bool)({arg}))"
# str(x): dispatch on source type
Expand All @@ -1301,15 +1355,26 @@ def _expr_CallExpr(self, node: CallExpr) -> str:
args = ", ".join(self._visit_expr(a) for a in node.args)
return f"{func}({args})"

def _expr_IndexExpr(self, node: IndexExpr) -> str:
def _expr_IndexExpr(self, node: IndexExpr, unbox: bool = True) -> str:
idx = self._visit_expr(node.index)
# Typed C array? Emit native indexing.
if isinstance(node.obj, Ident):
nm = self._mangle(node.obj.name)
if nm in self._list_elem_types:
return f"{nm}[{idx}]"
obj = self._visit_expr(node.obj)
return f"{obj}->items[{idx}]"
access = f"{obj}->items[{idx}]"
# Boxed list whose element type we know → hand back a scalar, otherwise
# the caller gets an ltl_value_t where it expects an int and gcc stops.
if unbox and isinstance(node.obj, Ident):
et = self._box_elem_types.get(self._mangle(node.obj.name))
if et == "int64_t":
return f"ltl_unbox_int({access})"
if et == "double":
return f"ltl_unbox_float({access})"
if et == "bool":
return f"ltl_unbox_bool({access})"
return access

def _expr_FieldExpr(self, node: FieldExpr) -> str:
# Handle module constant access: math.PI, sys.STDOUT, etc.
Expand Down
133 changes: 133 additions & 0 deletions tests/test_c_backend.py
Original file line number Diff line number Diff line change
Expand Up @@ -746,3 +746,136 @@ def test_simple_alias(self):
c_src = check_c("type Score = int")
assert "typedef" in c_src
assert "Score" in c_src


class TestBoxedListAccess:
"""Reading an element out of a boxed list.

`ltl_list_t` stores `ltl_value_t` items, so `xs[i]` cannot be used where a
scalar is expected — gcc rejects `ltl_value_t == int`. These pin the
unboxing that makes the common `flags[i] == 1` pattern compile, and that
assignments still target the slot rather than the unboxed copy.
"""

def test_read_is_unboxed(self):
c_src = check_c("""
fn main() -> int {
let n = 10
let flags = [1] * (n + 1)
let k = 0
while k <= n {
if flags[k] == 1 { println("hit") }
k = k + 1
}
return 0
}
""")
assert "ltl_unbox_int(flags->items[k])" in c_src

def test_float_list_uses_float_unbox(self):
c_src = check_c("""
fn main() -> int {
let n = 4
let xs = [0.5] * n
let k = 0
let total = 0.0
while k < n {
total = total + xs[k]
k = k + 1
}
println(str(total))
return 0
}
""")
assert "ltl_unbox_float(xs->items[k])" in c_src

def test_assignment_target_is_not_unboxed(self):
c_src = check_c("""
fn main() -> int {
let n = 4
let flags = [0] * n
flags[1] = 7
println(str(flags[1]))
return 0
}
""")
assert "ltl_unbox_int(flags->items[1]) = " not in c_src
assert "ltl_box_int(7)" in c_src

def test_list_parameter_prototype(self):
c_src = check_c("""
fn first(xs: list) -> int {
return xs[0]
}
fn main() -> int {
let xs = [5] * 2
println(str(first(xs)))
return 0
}
""")
assert "ltl_list_t* xs" in c_src
assert "sum_list(list xs)" not in c_src

def test_len_builtin(self):
c_src = check_c("""
fn main() -> int {
let xs = [1] * 3
println(str(len(xs)))
return 0
}
""")
assert "->len" in c_src

def test_str_in_println_uses_string_helper(self):
c_src = check_c("""
fn main() -> int {
let n = 41
println(str(n + 1))
return 0
}
""")
assert "ltl_io_println(" in c_src


class TestNumericInference:
"""Element and unary types must survive into declarations.

`ltl_value_t dx = <double>` is valid C and silently wrong at runtime, so
these pin the inference rather than the emitted expression.
"""

def test_unary_minus_stays_float(self):
c_src = check_c("""
fn main() -> int {
let n = 3
let xs = [0.0] * n
xs[0] = -1.5
println(str(xs[0]))
return 0
}
""")
assert "ltl_box_float((-1.5))" in c_src

def test_index_difference_declares_double(self):
c_src = check_c("""
fn main() -> int {
let n = 3
let xs = [0.0] * n
let dx = xs[0] - xs[1]
println(str(dx))
return 0
}
""")
assert "double dx = " in c_src

def test_to_int_is_a_cast(self):
c_src = check_c("""
fn main() -> int {
let v = 2.7
let i = to_int(v)
println(str(i))
return 0
}
""")
assert "((int64_t)(v))" in c_src
assert "to_int(" not in c_src.split("int64_t ltl_main")[-1]