Skip to content
Merged
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
3 changes: 2 additions & 1 deletion .cursor/skills/finding-ion-bugs/references/bug-hotspots.md
Original file line number Diff line number Diff line change
Expand Up @@ -21,7 +21,8 @@ CLI errors use `TypeCheckError` Debug form (`UseAfterMove { ... }`). LSP reforma
- Drop order and `ion_drop_*` for moved fields
- **Struct field move-out**: owned fields null after partial move on the next statement (`board.items = NULL`; deferred when the move is a call argument)
- **Vec::push lvalues**: struct variables and field paths use `&item`, not compound literal (`vec_push_struct_var_uses_address_of_lvalue`)
- **Enum emission order**: non-generic enums before structs in single-file C output. Generic enum instantiations (`Option_int`) must be complete types before tuple typedefs that store them by value (`test_tuple_option_none.ion`). `collect_generic_from_type` must walk `Type::Tuple` (and TupleLit `elem_types`); walking only nested exprs misses `Option::None` which has no payload expr. Multi-file `generate_module_source` still emits user structs before generic enum bodies (`examples/data_lib`).
- **Array typedef names**: `type_to_c` for `[T; N]` is the typedef name (`arr_int_2`), never `T[N]`. Emit `typedef T name[N]` innermost-first before Vec/Box/field uses. Nested arrays and `Box<[T;N]>` / `Vec<[T;N]>` need this (`test_nested_array.ion`, `test_box_array.ion`, `test_vec_array.ion`). C arrays are not assignable: Box/Vec copies and match payload bindings use memcpy.
- **Enum emission order**: collect generic instantiations from enum variant payloads and close generic struct/enum templates (substitute collected params into fields/payloads until fixpoint). Forward-declare non-generic structs and enums so `Option_ref_Op` can mention `Op*` (`test_vm_execute.ion`). Emit complete generic enums (`Option_int`) before non-generic enums that embed them (`Hold`). Same order in single-file `generate_c` and multi-file `generate_module_source`. Generic enums must also exist before tuple typedefs that store them by value (`test_tuple_option_none.ion`, `test_enum_option_payload_none.ion`, `test_generic_struct_option_none.ion`). Array typedefs of tuples wait until the tuple typedef exists (`test_array_of_tuples_option_none.ion`). `collect_generic_from_type` must walk `Type::Tuple` (and TupleLit `elem_types`); walking only nested exprs misses `Option::None` which has no payload expr.
- **Nested enum compound literals**: GCC rejects `(Option_int){...}` as a designated field of a tuple or struct. Emit brace-only `{ .tag = N, .data = { } }` there. Call-site and let inits stay `(Option_int){...}` (`test_option_none_call_arg.ion` cgen `take((Option_int)`).
- **Tuple mangle**: `tuple_type_name` sanitizes `*` and brackets when names include `Vec` types
- **Match scrutinee move-out**: pattern payload bindings null `match_val_N.data.variant_*` fields when ownership transfers (`statement_match_payload_move_neutralizes_scrutinee`); whole-enum binding arms clear active variant payloads via `emit_match_scrutinee_whole_enum_moved_out` (`whole_enum_binding_neutralizes_scrutinee_payloads`). IR infers `enum_type` from the scrutinee when arms use binding/wildcard only (`infer_match_enum_name`).
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -22,7 +22,7 @@ let p: Point = Point { x: 1, y: 2 };

## Enum variants

Tuple: `Option::Some(42)`, `Option::None`. `take(Option::None)` infers `T` from the parameter type ([tests/test_option_none_call_arg.ion](../../../../tests/test_option_none_call_arg.ion)); `send(&tx, Option::None)` infers from `Sender<T>` ([tests/test_send_option_none.ion](../../../../tests/test_send_option_none.ion)); `Box::new(Option::None)` infers from an expected `Box<Option<...>>` ([tests/test_box_new_option_none.ion](../../../../tests/test_box_new_option_none.ion)); `[Option::None]` and `(Option::None, 1)` infer from an adjacent array or tuple type ([tests/test_array_option_none.ion](../../../../tests/test_array_option_none.ion), [tests/test_tuple_option_none.ion](../../../../tests/test_tuple_option_none.ion)); unannotated `let empty = Option::None` still needs an annotation.
Tuple: `Option::Some(42)`, `Option::None`. `take(Option::None)` infers `T` from the parameter type ([tests/test_option_none_call_arg.ion](../../../../tests/test_option_none_call_arg.ion)); `send(&tx, Option::None)` infers from `Sender<T>` ([tests/test_send_option_none.ion](../../../../tests/test_send_option_none.ion)); `Box::new(Option::None)` infers from an expected `Box<Option<...>>` ([tests/test_box_new_option_none.ion](../../../../tests/test_box_new_option_none.ion)); `[Option::None]` and `(Option::None, 1)` infer from an adjacent array or tuple type ([tests/test_array_option_none.ion](../../../../tests/test_array_option_none.ion), [tests/test_tuple_option_none.ion](../../../../tests/test_tuple_option_none.ion)); `enum Hold { H(Option<int>) }` with `Hold::H(Option::None)` and `Hold::H(Option::Some(n))` emits `Option_int` ([tests/test_enum_option_payload_none.ion](../../../../tests/test_enum_option_payload_none.ion), [tests/test_enum_option_payload_some.ion](../../../../tests/test_enum_option_payload_some.ion)); unannotated `let empty = Option::None` still needs an annotation.

Struct: `Status::Ok { value: 10 }`.

Expand Down Expand Up @@ -302,7 +302,7 @@ struct Node {

## Arrays and slices

Fixed arrays `[T; N]` and slices `[]T` / `&[]T` support bounds-checked indexing (panic on OOB). Query length with `Slice::len` (`s.len()`); field access `s.len` is not valid. For non-panicking element access use `Slice::get_ref` (`Option<&T>`, local only), including after `&[T; N]` -> `&[]T` coercion. See [tests/test_slice_len.ion](../../../../tests/test_slice_len.ion) and [tests/test_slice_get_ref_from_array.ion](../../../../tests/test_slice_get_ref_from_array.ion).
Fixed arrays `[T; N]` and slices `[]T` / `&[]T` support bounds-checked indexing (panic on OOB). Query length with `Slice::len` (`s.len()`); field access `s.len` is not valid. For non-panicking element access use `Slice::get_ref` (`Option<&T>`, local only), including after `&[T; N]` -> `&[]T` coercion. Nested arrays, `Box<[T; N]>`, and `Vec<[T; N]>` compile ([tests/test_nested_array.ion](../../../../tests/test_nested_array.ion), [tests/test_box_array.ion](../../../../tests/test_box_array.ion), [tests/test_vec_array.ion](../../../../tests/test_vec_array.ion)). See [tests/test_slice_len.ion](../../../../tests/test_slice_len.ion) and [tests/test_slice_get_ref_from_array.ion](../../../../tests/test_slice_get_ref_from_array.ion).

```ion
let arr: [int; 3] = [1, 2, 3];
Expand Down
7 changes: 7 additions & 0 deletions CHANGELOG.md
Original file line number Diff line number Diff line change
@@ -1,5 +1,12 @@
# Changelog

## 0.1.22 - 2026-08-14

- **Codegen**: `[T; N]` lowers to a named C array typedef (`arr_int_2`) so nested arrays and `Box`/`Vec` of arrays are valid C. Functions still cannot return a C array type (pointer decay unchanged). This impacts nested `[int; N]` locals, fields, parameters, and returns, plus `Box<[T; N]>` and `Vec<[T; N]>`.
- **Codegen**: generic instantiations are collected from enum variant payloads and closed under generic struct/enum templates; `Option_int` is emitted before non-generic enums that embed it. This impacts `enum Hold { H(Option<int>) }` with `Hold::H(Option::None)` and `Hold::H(Option::Some(n))`, and `struct S<T> { x: Option<T> }` with `S { x: Option::None }`. Unannotated `let empty = Option::None` still requires an annotation.
- **Tests**: `test_nested_array.ion`, `test_nested_array_field_param_return.ion`, `test_nested_array_3d.ion`, `test_box_array.ion`, `test_vec_array.ion`, `test_enum_option_payload_none.ion`, `test_enum_option_payload_some.ion`, `test_generic_struct_option_none.ion`.
- **Docs**: ION_SPEC §4.1.1, ABI arrays, bug hotspots, verified patterns.

## 0.1.21 - 2026-08-14

- **Type checker / Codegen**: array, tuple, and `[value; N]` elements, assignment, returned compounds, and enum variant payloads now check against the adjacent expected type (same `expr_expected` helper as struct fields, call arguments, `send`, and `Box::new`). This impacts `let a: [Option<int>; 1] = [Option::None]`, `(Option::None, 1)`, `[Option::Some(4)]` (emits `Option_int`, not bare `(Option)`), `x = Option::None`, `return [Option::None]`, and `Result::Err(Option::None)` as a compound element. Unannotated `let empty = Option::None` still requires an annotation.
Expand Down
2 changes: 1 addition & 1 deletion Cargo.lock

Some generated files are not rendered by default. Learn more about how customized files appear on GitHub.

2 changes: 1 addition & 1 deletion Cargo.toml
Original file line number Diff line number Diff line change
@@ -1,6 +1,6 @@
[package]
name = "ion-compiler"
version = "0.1.21"
version = "0.1.22"
edition = "2024"

[[bin]]
Expand Down
1 change: 1 addition & 0 deletions ION_SPEC.md
Original file line number Diff line number Diff line change
Expand Up @@ -515,6 +515,7 @@ Fixed-size arrays `[T; N]` have the following safety properties:
- **Compile-time size**: Array size `N` must be a compile-time constant
- **Stack allocation**: Arrays are allocated on the stack by default
- **Index type**: The index expression may be any integer type (`int`, `i32`, `u32`, etc.).
- **C lowering**: `[T; N]` lowers to a named C array typedef (`typedef int arr_int_2[2];`, nested `typedef arr_int_2 arr_arr_int_2_3[3];`) so nested arrays and `Box<[T; N]>` / `Vec<[T; N]>` are valid C type specifiers. Indexing stays `a[i]`. Functions still cannot return a C array type; array returns decay to a pointer to the first element.

**Safe array access:**
```ion
Expand Down
11 changes: 8 additions & 3 deletions docs/ABI.md
Original file line number Diff line number Diff line change
Expand Up @@ -85,9 +85,14 @@ Stable beta expectations:

## Arrays and slices

Fixed arrays `[T; N]` are inline values. Slices `[]T` are fat views carrying a
data pointer and length. Safe indexing emits runtime bounds checks; indexing
inside `unsafe` blocks may omit those checks.
Fixed arrays `[T; N]` are inline values with C-compatible layout. Generated C
names them `arr_{elem}_{N}` (`typedef int arr_int_2[2];`). Nested arrays compose
(`typedef arr_int_2 arr_arr_int_2_3[3];`). `Box<[T; N]>` is a pointer to that
array type (`arr_int_2*`). `Vec<[T; N]>` uses the typedef as the element type
(`Vec_arr_int_2`). Functions do not return C array types; returns decay to a
pointer to the first element. Slices `[]T` are fat views carrying a data pointer
and length. Safe indexing emits runtime bounds checks; indexing inside `unsafe`
blocks may omit those checks.

- `Slice::len` returns the fat-pointer element count as `int` (empty is `0`). Method
form `s.len()` desugars to `Slice::len`. `&[T; N]` may coerce to `&[]T` for this
Expand Down
66 changes: 53 additions & 13 deletions src/cgen/builtins.rs
Original file line number Diff line number Diff line change
Expand Up @@ -24,20 +24,26 @@ impl Codegen {
.unwrap_or(&Type::Int);

let inner_c_type = self.type_to_c(inner_type);
let mut arg_code = String::new();
let old_output = std::mem::replace(&mut self.output, arg_code);
self.generate_expr_with_type(&args[0], Some(inner_type));
arg_code = std::mem::replace(&mut self.output, old_output);
let mut code = String::new();
code.push_str("({ ");
code.push_str(&format!(
"{}* ptr = ({}*)ion_box_alloc(sizeof({}));",
inner_c_type, inner_c_type, inner_c_type
));
code.push_str(" if (ptr) { *ptr = ");
// Generate the argument expression
let mut arg_code = String::new();
let old_output = std::mem::replace(&mut self.output, arg_code);
self.generate_expr_with_type(&args[0], Some(inner_type));
arg_code = std::mem::replace(&mut self.output, old_output);
code.push_str(&arg_code);
code.push_str("; } ptr; })");
// C arrays are not assignable, even behind a typedef name.
if matches!(inner_type, Type::Array { .. }) {
code.push_str(" if (ptr) { ");
code.push_str(&memcpy_from_value("ptr", &inner_c_type, &arg_code));
code.push_str("; } ptr; })");
} else {
code.push_str(" if (ptr) { *ptr = ");
code.push_str(&arg_code);
code.push_str("; } ptr; })");
}
return Some(code);
}

Expand All @@ -54,11 +60,19 @@ impl Codegen {
let old_output = std::mem::replace(&mut self.output, arg_code);
self.generate_expr(&args[0]);
arg_code = std::mem::replace(&mut self.output, old_output);
let code = format!(
"({{ {ty}* _box = {arg}; {ty} _val = *_box; ion_box_free(_box); _val; }})",
ty = inner_c_type,
arg = arg_code
);
let code = if matches!(inner_type, Type::Array { .. }) {
format!(
"({{ {ty}* _box = {arg}; static {ty} _val; memcpy(&_val, _box, sizeof(_val)); ion_box_free(_box); _val; }})",
ty = inner_c_type,
arg = arg_code
)
} else {
format!(
"({{ {ty}* _box = {arg}; {ty} _val = *_box; ion_box_free(_box); _val; }})",
ty = inner_c_type,
arg = arg_code
)
};
return Some(code);
}

Expand Down Expand Up @@ -172,6 +186,7 @@ impl Codegen {
| IREexpr::Var(_)
| IREexpr::FieldAccess { .. }
);
let elem_is_array = matches!(elem_ty, Some(Type::Array { .. }));
if value_is_lvalue {
code.push_str("ion_vec_push((ion_vec_t*)(");
code.push_str(&deref_vec);
Expand All @@ -180,6 +195,14 @@ impl Codegen {
code.push_str(", sizeof(");
code.push_str(&elem_c_type);
code.push_str("))");
} else if elem_is_array {
code.push_str("ion_vec_push((ion_vec_t*)(");
code.push_str(&deref_vec);
code.push_str("), ");
code.push_str(&compound_literal_addr(&elem_c_type, &value_code));
code.push_str(", sizeof(");
code.push_str(&elem_c_type);
code.push_str("))");
} else if matches!(args[1], IREexpr::Call { .. }) {
code.push_str("({ ");
code.push_str(&elem_c_type);
Expand Down Expand Up @@ -798,3 +821,20 @@ impl Codegen {
None
}
}

/// Address of a value for memcpy / `ion_vec_push`. Brace lists become typed compound literals.
fn compound_literal_addr(c_ty: &str, value_code: &str) -> String {
let trimmed = value_code.trim_start();
if trimmed.starts_with('{') {
format!("&(({c_ty}){trimmed})")
} else {
format!("&({value_code})")
}
}

fn memcpy_from_value(dest_ptr: &str, c_ty: &str, value_code: &str) -> String {
format!(
"memcpy({dest_ptr}, {}, sizeof({c_ty}))",
compound_literal_addr(c_ty, value_code)
)
}
Loading