Skip to content

Commit 576f1ff

Browse files
committed
Emit C function pointer declarations
1 parent e8674fa commit 576f1ff

7 files changed

Lines changed: 85 additions & 7 deletions

File tree

‎CHANGELOG.md‎

Lines changed: 3 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -40,6 +40,9 @@ and this project adheres to [Semantic Versioning](https://semver.org/spec/v2.0.0
4040
- Variable initializers using side-effectful `match` scrutinees now cache the scrutinee in a generated local before evaluating patterns.
4141
- Other side-effectful `match` expression contexts still fail closed until they have portable statement-level lowering.
4242

43+
- **C Backend Function Pointers**
44+
- Raw `fn(...)` parameter and variable declarations now emit C function-pointer declarators.
45+
4346
- **Type Checker: Slice and Index Validation**
4447
- `visit_slice_expr`: validates source is array/slice/string, checks start/end are integral, returns `SliceType`.
4548
- `visit_index_expr`: now rejects non-integer index expressions.

‎MISSING_FEATURES.md‎

Lines changed: 2 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -40,6 +40,7 @@
4040
26. C backend side-effect-free `match` expressions now lower for literal, enum, range, and wildcard patterns.
4141
27. C backend `match` statements with range patterns lower through portable `if` chains.
4242
28. C backend existing-identifier match patterns lower as comparisons in statements and expressions.
43+
29. C backend raw `fn(...)` parameter and variable declarations lower as C function pointers.
4344

4445
---
4546

@@ -67,6 +68,7 @@
6768
- Core conformance is green, but differential/backend-equivalence checks should be expanded and kept mandatory for new language features.
6869
- C `match` expressions with side-effectful scrutinees are supported in variable initializers through generated single-evaluation locals.
6970
- C `match` expressions with side-effectful scrutinees in non-declaration expression contexts still fail closed pending statement-level lowering.
71+
- Function-type aliases such as `BinaryOp :: fn(i32, i32) i32` still need semantic support before they can be relied on across backends.
7072

7173
6. **Release publishing automation**
7274
- Local package builds and artifact checks exist.

‎TODO.md‎

Lines changed: 6 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -88,9 +88,13 @@ Features that are spec'd and partially implemented, or missing from one backend.
8888
Files: `src/backends/c.py`
8989
Notes: existing identifiers in match patterns now lower as comparisons in C match statements and expressions.
9090

91-
- [ ] C backend: function-typed declarations.
91+
- [x] C backend: raw function-typed parameter and variable declarations.
9292
Files: `src/backends/c.py`
93-
Notes: function pointer type emission is blocked.
93+
Notes: raw `fn(...)` parameter and variable declarations now emit C function-pointer declarators.
94+
95+
- [ ] Function-type aliases in semantic analysis and C lowering.
96+
Files: `src/passes/type_checker.py`, `src/backends/c.py`
97+
Notes: aliases such as `BinaryOp :: fn(i32, i32) i32` still resolve as unknown in semantic analysis.
9498

9599
### Module System / Stdlib
96100

‎docs/SPEC.md‎

Lines changed: 2 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -2875,6 +2875,8 @@ Status snapshot (2026-05-07):
28752875
- Differential parity checks across backends should continue expanding for new language features.
28762876
- C lowers side-effectful `match` expression scrutinees in variable initializers by caching the scrutinee once.
28772877
- C still rejects side-effectful `match` expression scrutinees in non-declaration expression contexts.
2878+
- C lowers raw `fn(...)` parameter and variable declarations as function pointers.
2879+
- Function-type aliases still need semantic support.
28782880

28792881
6. **Release packaging hardening**
28802882
- Python packaging and installed CLI are present.

‎site/src/pages/Status.tsx‎

Lines changed: 2 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -7,7 +7,7 @@ const done = [
77
{ name: 'Semantic analysis', desc: 'Name resolution, type checking with inference, control flow and memory checks, slice/index validation.' },
88
{ name: 'Preprocessing', desc: 'Nine sub-passes: lowering, resolution, mutation, usage, shadowing, hoisting, folding.' },
99
{ name: 'Zig backend', desc: 'Full translation with type mapping, pointer handling, hoisting, annotations, labeled loops.' },
10-
{ name: 'C backend', desc: 'C11 output validated with zig cc for current examples. Labeled loops, slices, defer, range and identifier match patterns, and core match expressions are present; backend parity checks should keep expanding.' },
10+
{ name: 'C backend', desc: 'C11 output validated with zig cc for current examples. Labeled loops, slices, defer, function pointers, range and identifier match patterns, and core match expressions are present; backend parity checks should keep expanding.' },
1111
{ name: 'Release tooling', desc: 'Installed CLI entrypoint plus debug/release artifact verification for Zig and C example builds.' },
1212
]
1313

@@ -16,7 +16,7 @@ const missing = [
1616
{ name: 'Advanced match diagnostics', desc: 'Exact duplicate, wildcard-first, full bool/enum coverage, and literal range overlaps are diagnosed. Symbolic range overlap and true capture patterns remain open.' },
1717
{ name: 'Generic constraint internals', desc: 'Inline type-set constraint resolution in generics.py is still placeholder-level.' },
1818
{ name: 'Memory/lifetime model', desc: 'Only basic del reference checks. No ownership/borrow-style lifetime analysis.' },
19-
{ name: 'Backend semantic parity hardening', desc: 'Core conformance is green, but differential backend checks should expand. Side-effectful match scrutinees are supported in variable initializers; inline expression contexts remain open.' },
19+
{ name: 'Backend semantic parity hardening', desc: 'Core conformance is green, but differential backend checks should expand. Side-effectful match scrutinees are supported in variable initializers; inline expression contexts and function-type aliases remain open.' },
2020
{ name: 'Automated publishing', desc: 'Local package builds are available, but tag-based package publishing is not wired yet.' },
2121
]
2222

‎src/backends/c.py‎

Lines changed: 33 additions & 3 deletions
Original file line numberDiff line numberDiff line change
@@ -667,6 +667,10 @@ def _visit_type_alias(self, node: ASTNode) -> None:
667667
alias = self._sanitize_name(node.name or "Alias")
668668
if node.value is None:
669669
raise CodegenError("C backend: type alias missing target type", node.span)
670+
if node.value.kind == NodeKind.TYPE_FUNCTION:
671+
self._write_indent()
672+
self.output.write(f"typedef {self._emit_function_pointer_declarator(node.value, alias)};\n")
673+
return
670674
target = self._emit_type_node(node.value)
671675
self._write_indent()
672676
self.output.write(f"typedef {target} {alias};\n")
@@ -699,6 +703,16 @@ def _visit_var(self, node: ASTNode) -> None:
699703
self.output.write(f"{elem_type} {name}[{size}] = {{0}};\n")
700704
return
701705

706+
if explicit_type and explicit_type.kind == NodeKind.TYPE_FUNCTION:
707+
self._write_indent()
708+
if node.value:
709+
init = self._emit_expr(node.value)
710+
self.output.write(f"{self._emit_declarator(explicit_type, name)} = {init};\n")
711+
else:
712+
self._needs_stddef = True
713+
self.output.write(f"{self._emit_declarator(explicit_type, name)} = NULL;\n")
714+
return
715+
702716
c_type = self._infer_decl_type(explicit_type, node.value, node)
703717
if node.value:
704718
if (
@@ -1308,7 +1322,7 @@ def _emit_type_node(self, node: ASTNode) -> str:
13081322
return self._register_slice_type(node)
13091323
if kind == NodeKind.TYPE_FUNCTION:
13101324
raise CodegenError(
1311-
"C backend: function types are not yet supported in emitted declarations",
1325+
"C backend: function types require a named declarator in C",
13121326
node.span,
13131327
)
13141328
if kind == NodeKind.TYPE_STRUCT:
@@ -1480,8 +1494,10 @@ def _function_signature(self, node: ASTNode, prototype: bool) -> str:
14801494
param_parts: list[str] = []
14811495
for i, param in enumerate(node.parameters or []):
14821496
pname = self._sanitize_name(param.name or f"arg{i}")
1483-
ptype = self._emit_type_node(param.param_type) if param.param_type else "int32_t"
1484-
param_parts.append(f"{ptype} {pname}")
1497+
if param.param_type:
1498+
param_parts.append(self._emit_declarator(param.param_type, pname))
1499+
else:
1500+
param_parts.append(f"int32_t {pname}")
14851501
params = ", ".join(param_parts) if param_parts else "void"
14861502

14871503
prefix = ""
@@ -1491,6 +1507,20 @@ def _function_signature(self, node: ASTNode, prototype: bool) -> str:
14911507
prefix = "static "
14921508
return f"{prefix}{return_type} {name}({params})"
14931509

1510+
def _emit_declarator(self, type_node: ASTNode, name: str) -> str:
1511+
if type_node.kind == NodeKind.TYPE_FUNCTION:
1512+
return self._emit_function_pointer_declarator(type_node, name)
1513+
return f"{self._emit_type_node(type_node)} {name}"
1514+
1515+
def _emit_function_pointer_declarator(self, type_node: ASTNode, name: str) -> str:
1516+
return_type = self._emit_type_node(type_node.return_type) if type_node.return_type else "void"
1517+
param_types = [
1518+
self._emit_type_node(param_type)
1519+
for param_type in (type_node.parameter_types or [])
1520+
]
1521+
params = ", ".join(param_types) if param_types else "void"
1522+
return f"{return_type} (*{name})({params})"
1523+
14941524
# ------------------------------------------------------------------
14951525
# IO lowering
14961526
# ------------------------------------------------------------------

‎test/test_codegen_c.py‎

Lines changed: 37 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -350,6 +350,43 @@ def test_generated_c_supports_match_identifier_patterns(tmp_path: Path) -> None:
350350
assert result.stdout.strip() == "20 200"
351351

352352

353+
@pytest.mark.skipif(not has_zig(), reason="zig not installed")
354+
def test_generated_c_supports_function_pointer_declarations(tmp_path: Path) -> None:
355+
result = build_and_run_c(
356+
"""
357+
io :: import "std/io"
358+
359+
add :: fn(a: i32, b: i32) i32 {
360+
ret a + b
361+
}
362+
363+
double :: fn(value: i32) i32 {
364+
ret value * 2
365+
}
366+
367+
apply_unary :: fn(f: fn(i32) i32, value: i32) i32 {
368+
ret f(value)
369+
}
370+
371+
apply_binary :: fn(op: fn(i32, i32) i32, a: i32, b: i32) i32 {
372+
ret op(a, b)
373+
}
374+
375+
main :: fn() {
376+
raw: fn(i32, i32) i32 = add
377+
a := raw(2, 3)
378+
b := apply_binary(raw, 5, 8)
379+
c := apply_unary(double, 11)
380+
io.println("{} {} {}", a, b, c)
381+
}
382+
""",
383+
tmp_path,
384+
)
385+
386+
assert result.returncode == 0, result.stdout + result.stderr
387+
assert result.stdout.strip() == "5 13 22"
388+
389+
353390
@pytest.mark.skipif(not has_zig(), reason="zig not installed")
354391
def test_c_backend_match_expression_side_effectful_scrutinee_var_init(tmp_path: Path) -> None:
355392
src = tmp_path / "match_expr_call.a7"

0 commit comments

Comments
 (0)