closures
This commit is contained in:
95
examples/35-closures.sx
Normal file
95
examples/35-closures.sx
Normal file
@@ -0,0 +1,95 @@
|
||||
#import "modules/std.sx";
|
||||
|
||||
// --- Closure Basics ---
|
||||
|
||||
// Factory: returns a new closure each time
|
||||
make_adder :: (n: s64) -> Closure(s64) -> s64 {
|
||||
return closure((x: s64) -> s64 => x + n);
|
||||
}
|
||||
|
||||
// Higher-order function: accepts any Closure(s64) -> s64
|
||||
apply :: (f: Closure(s64) -> s64, x: s64) -> s64 { return f(x); }
|
||||
|
||||
// Reduce: fold over a slice with a closure
|
||||
reduce :: (arr: []s64, f: Closure(s64, s64) -> s64, init: s64) -> s64 {
|
||||
acc := init;
|
||||
i : s64 = 0;
|
||||
while i < arr.len { acc = f(acc, arr[i]); i += 1; }
|
||||
return acc;
|
||||
}
|
||||
|
||||
// Auto-promoted bare function
|
||||
triple :: (x: s64) -> s64 { return x * 3; }
|
||||
|
||||
// Struct with optional closure callback
|
||||
Widget :: struct {
|
||||
name: string;
|
||||
on_update: ?Closure(s64) -> void;
|
||||
}
|
||||
|
||||
main :: () {
|
||||
// 1. Basic closure with capture
|
||||
offset := 100;
|
||||
add_offset := closure((x: s64) -> s64 => x + offset);
|
||||
print("basic: {}\n", add_offset(42));
|
||||
|
||||
// 2. Capture by value (snapshot semantics)
|
||||
n := 10;
|
||||
snap := closure((x: s64) -> s64 => x + n);
|
||||
n = 999;
|
||||
print("snapshot: {}\n", snap(5));
|
||||
|
||||
// 3. Block-body closure with control flow
|
||||
clamp := closure((x: s64) -> s64 {
|
||||
if x < 0 { return 0; }
|
||||
if x > 100 { return 100; }
|
||||
return x;
|
||||
});
|
||||
print("clamp: {} {} {}\n", clamp(50), clamp(0 - 10), clamp(200));
|
||||
|
||||
// 4. Void closure with string capture
|
||||
tag := "INFO";
|
||||
logger := closure((msg: string) {
|
||||
print("[{}] {}\n", tag, msg);
|
||||
});
|
||||
logger("system ready");
|
||||
|
||||
// 5. Factory pattern
|
||||
add5 := make_adder(5);
|
||||
add10 := make_adder(10);
|
||||
print("factory: {} {}\n", add5(100), add10(100));
|
||||
|
||||
// 6. Auto-promotion: bare fn passed where Closure expected
|
||||
print("auto-promote: {}\n", apply(triple, 7));
|
||||
|
||||
// 7. Closure passed to higher-order function
|
||||
factor := 4;
|
||||
print("hof: {}\n", apply(closure((x: s64) -> s64 => x * factor), 10));
|
||||
|
||||
// 8. Reduce with closure
|
||||
nums : []s64 = .[1, 2, 3, 4, 5];
|
||||
total := reduce(nums, closure((acc: s64, x: s64) -> s64 => acc + x), 0);
|
||||
print("reduce: {}\n", total);
|
||||
|
||||
// 9. Closure captures closure
|
||||
inner := closure((x: s64) -> s64 => x + 10);
|
||||
outer := closure((x: s64) -> s64 => inner(x) * 2);
|
||||
print("compose: {}\n", outer(5));
|
||||
|
||||
// 10. Multiple closures from same scope
|
||||
base := 100;
|
||||
cl_add := closure((x: s64) -> s64 => x + base);
|
||||
cl_mul := closure((x: s64) -> s64 => x * base);
|
||||
print("multi: {} {}\n", cl_add(5), cl_mul(5));
|
||||
|
||||
// 11. Optional closures
|
||||
w1 := Widget.{ name = "slider", on_update = closure((val: s64) {
|
||||
print("widget: {} = {}\n", "slider", val);
|
||||
}) };
|
||||
w2 := Widget.{ name = "label", on_update = null };
|
||||
|
||||
if h := w1.on_update { h(42); }
|
||||
if h := w2.on_update { h(0); } else { print("widget: no handler\n"); }
|
||||
|
||||
print("=== DONE ===\n");
|
||||
}
|
||||
@@ -1719,5 +1719,239 @@ END;
|
||||
print("guard loop: {}\n", guard_loop(3)); // guard loop: 3
|
||||
}
|
||||
|
||||
// --- block-body lambdas ---
|
||||
{
|
||||
// block-body lambda with return type
|
||||
clamp := (x: s64, lo: s64, hi: s64) -> s64 {
|
||||
if x < lo { return lo; }
|
||||
if x > hi { return hi; }
|
||||
return x;
|
||||
};
|
||||
print("block-lambda: {}\n", clamp(50, 0, 100)); // block-lambda: 50
|
||||
print("block-lambda: {}\n", clamp(-10, 0, 100)); // block-lambda: 0
|
||||
print("block-lambda: {}\n", clamp(999, 0, 100)); // block-lambda: 100
|
||||
|
||||
// block-body lambda without return type annotation
|
||||
greet := (name: string) {
|
||||
print("hello {}\n", name);
|
||||
};
|
||||
greet("block"); // hello block
|
||||
}
|
||||
|
||||
// --- named params in function types ---
|
||||
{
|
||||
// Named params are documentation only — ignored for type identity
|
||||
apply_named :: (f: (x: s32, y: s32) -> s32, a: s32, b: s32) -> s32 {
|
||||
return f(a, b);
|
||||
}
|
||||
add :: (a: s32, b: s32) -> s32 { return a + b; }
|
||||
print("named-fn-type: {}\n", apply_named(add, 3, 4)); // named-fn-type: 7
|
||||
}
|
||||
|
||||
// --- xx on function pointers ---
|
||||
{
|
||||
MyEnv :: struct { n: s32; }
|
||||
typed_fn :: (e: *MyEnv, x: s32) -> s32 {
|
||||
return x + e.n;
|
||||
}
|
||||
// xx cast: (*MyEnv, s32) -> s32 → (*void, s32) -> s32
|
||||
f : (*void, s32) -> s32 = xx typed_fn;
|
||||
env := MyEnv.{ n = 100 };
|
||||
print("xx-fnptr: {}\n", f(xx @env, 42)); // xx-fnptr: 142
|
||||
}
|
||||
|
||||
// --- closure type: construct and access fields ---
|
||||
{
|
||||
dummy_fn :: (env: *void, x: s32) -> s32 {
|
||||
return x * 2;
|
||||
}
|
||||
fn_ptr : *void = xx dummy_fn;
|
||||
null_env : *void = xx 0;
|
||||
c : Closure(s32) -> s32 = .{ fn_ptr = fn_ptr, env = null_env };
|
||||
print("closure-type: fn_ptr-nonnull={}\n", c.fn_ptr != null_env);
|
||||
print("closure-type: env-null={}\n", c.env == null_env);
|
||||
}
|
||||
|
||||
// --- closure calling convention ---
|
||||
{
|
||||
Env :: struct { n: s32; }
|
||||
impl :: (env: *void, x: s32) -> s32 {
|
||||
e : *Env = xx env;
|
||||
return x + e.n;
|
||||
}
|
||||
env := Env.{ n = 5 };
|
||||
fn_ptr : *void = xx impl;
|
||||
env_ptr : *void = xx @env;
|
||||
c : Closure(s32) -> s32 = .{ fn_ptr = fn_ptr, env = env_ptr };
|
||||
print("closure-call: {}\n", c(10));
|
||||
}
|
||||
|
||||
// --- auto-promotion: bare fn → Closure ---
|
||||
{
|
||||
double :: (x: s32) -> s32 { return x * 2; }
|
||||
apply :: (f: Closure(s32) -> s32, x: s32) -> s32 { return f(x); }
|
||||
print("auto-promote: {}\n", apply(double, 10));
|
||||
|
||||
// Named function to Closure variable
|
||||
f : Closure(s32) -> s32 = double;
|
||||
print("auto-promote-var: {}\n", f(5));
|
||||
}
|
||||
|
||||
// --- closure() intrinsic ---
|
||||
{
|
||||
// capture scalar
|
||||
n := 42;
|
||||
f := closure((x: s32) => x + n);
|
||||
print("closure-capture: {}\n", f(10));
|
||||
|
||||
// capture by value is a snapshot
|
||||
m := 5;
|
||||
g := closure((x: s32) => x + m);
|
||||
m = 100;
|
||||
print("closure-snapshot: {}\n", g(10));
|
||||
|
||||
// no captures (null env)
|
||||
h := closure((x: s32) => x * 2);
|
||||
print("closure-nocap: {}\n", h(7));
|
||||
|
||||
// multiple captures
|
||||
a := 10;
|
||||
b := 20;
|
||||
multi := closure((x: s32) => x + a + b);
|
||||
print("closure-multi: {}\n", multi(3));
|
||||
|
||||
// block-body closure with return
|
||||
offset := 50;
|
||||
clamp := closure((x: s64) -> s64 {
|
||||
if x < 0 { return 0; }
|
||||
if x > 100 { return 100; }
|
||||
return x + offset;
|
||||
});
|
||||
// Workaround: assign result with explicit type so print wraps correctly
|
||||
r1 : s64 = clamp(10);
|
||||
r2 : s64 = clamp(0 - 5);
|
||||
r3 : s64 = clamp(999);
|
||||
print("closure-block: {}\n", r1);
|
||||
print("closure-block: {}\n", r2);
|
||||
print("closure-block: {}\n", r3);
|
||||
|
||||
// void closure
|
||||
tag := "LOG";
|
||||
logger := closure((msg: string) {
|
||||
print("[{}] {}\n", tag, msg);
|
||||
});
|
||||
logger("hello");
|
||||
|
||||
// pass closure to higher-order function
|
||||
dbl :: (x: s32) -> s32 { return x * 2; }
|
||||
apply_cl :: (f2: Closure(s32) -> s32, x: s32) -> s32 { return f2(x); }
|
||||
factor : s32 = 3;
|
||||
print("closure-hof: {}\n", apply_cl(closure((x: s32) -> s32 => x * factor), 10));
|
||||
|
||||
// auto-promoted bare fn passed alongside closures
|
||||
print("closure-hof-bare: {}\n", apply_cl(dbl, 10));
|
||||
|
||||
// C5.A2: capture f32
|
||||
scale := 2.5;
|
||||
f_f32 := closure((x: f32) -> f32 => x * scale);
|
||||
print("closure-f32: {}\n", f_f32(4.0));
|
||||
|
||||
// C5.A3: capture bool
|
||||
verbose := true;
|
||||
f_bool := closure((msg: string) {
|
||||
if verbose { print("closure-bool: {}\n", msg); }
|
||||
});
|
||||
f_bool("hello");
|
||||
|
||||
// C5.B3: two params
|
||||
base : s32 = 100;
|
||||
f_2p := closure((x: s32, y: s32) -> s32 => x + y + base);
|
||||
print("closure-2p: {}\n", f_2p(3, 4));
|
||||
|
||||
// C5.B4: three params
|
||||
bias : s32 = 1;
|
||||
f_3p := closure((a: s32, b: s32, c2: s32) -> s32 => a + b + c2 + bias);
|
||||
print("closure-3p: {}\n", f_3p(10, 20, 30));
|
||||
|
||||
// C5.B5: mixed param types (string + s32)
|
||||
extra : s32 = 5;
|
||||
f_mix := closure((name: string, age: s32) {
|
||||
print("closure-mix: {} is {}\n", name, age + extra);
|
||||
});
|
||||
f_mix("Alice", 30);
|
||||
|
||||
// C5.C3: return bool
|
||||
threshold : s32 = 100;
|
||||
f_rbool := closure((x: s32) -> bool { return x > threshold; });
|
||||
print("closure-rbool: {} {}\n", f_rbool(50), f_rbool(200));
|
||||
|
||||
// C5.D3: reduce / fold
|
||||
reduce :: (arr: []s32, f3: Closure(s32, s32) -> s32, init: s32) -> s32 {
|
||||
acc := init;
|
||||
i : s64 = 0;
|
||||
while i < arr.len { acc = f3(acc, arr[i]); i += 1; }
|
||||
return acc;
|
||||
}
|
||||
r_nums : []s32 = .[1, 2, 3, 4, 5];
|
||||
r_bonus : s32 = 100;
|
||||
r_total := reduce(r_nums, closure((acc: s32, x: s32) -> s32 => acc + x), r_bonus);
|
||||
print("closure-reduce: {}\n", r_total);
|
||||
|
||||
// C5.G1: factory function
|
||||
make_adder :: (n: s32) -> Closure(s32) -> s32 {
|
||||
return closure((x: s32) -> s32 => x + n);
|
||||
}
|
||||
add5 := make_adder(5);
|
||||
add10 := make_adder(10);
|
||||
print("closure-factory: {} {}\n", add5(100), add10(100));
|
||||
|
||||
// C5.A5: capture struct
|
||||
Point :: struct { x: s32; y: s32; }
|
||||
origin := Point.{ x = 10, y = 20 };
|
||||
f_st := closure(() {
|
||||
print("closure-struct: {} {}\n", origin.x, origin.y);
|
||||
});
|
||||
f_st();
|
||||
|
||||
// C5.H1: closure captures another closure
|
||||
inner_n := 10;
|
||||
inner_cl := closure((x: s64) -> s64 => x + inner_n);
|
||||
outer_cl := closure((x: s64) -> s64 => inner_cl(x) * 2);
|
||||
print("closure-compose: {}\n", outer_cl(5));
|
||||
|
||||
// C5.M7: multiple closures from same scope capture independently
|
||||
shared : s32 = 10;
|
||||
cl_a := closure((x: s32) -> s32 => x + shared);
|
||||
cl_b := closure((x: s32) -> s32 => x * shared);
|
||||
print("closure-indep: {} {}\n", cl_a(5), cl_b(5));
|
||||
|
||||
// C6: optional closures
|
||||
f_none : ?Closure(s64) -> s64 = null;
|
||||
if h := f_none {
|
||||
print("should not print: {}\n", h(1));
|
||||
} else {
|
||||
print("opt-closure: none\n");
|
||||
}
|
||||
|
||||
opt_n := 10;
|
||||
f_some : ?Closure(s64) -> s64 = closure((x: s64) -> s64 => x + opt_n);
|
||||
if h := f_some {
|
||||
print("opt-closure: {}\n", h(5));
|
||||
} else {
|
||||
print("should not print\n");
|
||||
}
|
||||
|
||||
// Struct with optional closure callback
|
||||
Btn :: struct { label: string; on_click: ?Closure(s64) -> void; }
|
||||
btn_x := 99;
|
||||
btn_cl := closure((id: s64) {
|
||||
print("opt-closure-btn: {} {}\n", id, btn_x);
|
||||
});
|
||||
btn1 := Btn.{ label = "OK", on_click = btn_cl };
|
||||
btn2 := Btn.{ label = "Cancel", on_click = null };
|
||||
if h := btn1.on_click { h(1); }
|
||||
if h := btn2.on_click { h(2); } else { print("opt-closure-btn: null\n"); }
|
||||
}
|
||||
|
||||
print("=== DONE ===\n");
|
||||
}
|
||||
|
||||
84
specs.md
84
specs.md
@@ -1081,6 +1081,82 @@ SOME_FUNC :: () => 42; // () -> s32
|
||||
double :: (x: $T) -> T => x + x; // generic lambda with return type
|
||||
```
|
||||
|
||||
### Closures
|
||||
|
||||
A **closure** is a function bundled with captured state. It is represented as a fat pointer `{ fn_ptr, env }` (16 bytes), unlike a bare function pointer which is 8 bytes.
|
||||
|
||||
#### Closure Type
|
||||
```sx
|
||||
Closure(param_types) -> R // e.g. Closure(s32, s32) -> s32
|
||||
Closure(param_types) // void return: Closure(s64) -> void
|
||||
?Closure(s32) -> s32 // optional closure (null = none)
|
||||
```
|
||||
|
||||
#### Creating Closures — `closure()` intrinsic
|
||||
```sx
|
||||
offset := 50;
|
||||
f := closure((x: s32) -> s32 => x + offset); // expression body
|
||||
g := closure((x: s32) -> s32 { // block body
|
||||
if x < 0 { return 0; }
|
||||
return x + offset;
|
||||
});
|
||||
```
|
||||
|
||||
The `closure()` intrinsic:
|
||||
1. Analyzes the lambda body for free variables (variables from outer scope)
|
||||
2. Allocates an env struct on the heap (via `malloc`) containing captured values
|
||||
3. Generates a trampoline function with signature `(env: *void, params...) -> R`
|
||||
4. Returns a `Closure` value `{ trampoline, env_ptr }`
|
||||
|
||||
**Capture semantics**: capture by value (snapshot at creation time). Mutating the original variable after creating the closure does not affect the captured value.
|
||||
```sx
|
||||
n := 10;
|
||||
f := closure((x: s64) -> s64 => x + n);
|
||||
n = 999;
|
||||
print("{}\n", f(5)); // 15, not 1004
|
||||
```
|
||||
|
||||
#### Calling Closures
|
||||
Closures are called with normal function call syntax:
|
||||
```sx
|
||||
result := f(10);
|
||||
```
|
||||
The compiler prepends the env pointer to the argument list and does an indirect call through the fn_ptr.
|
||||
|
||||
#### Auto-Promotion
|
||||
A bare function can be implicitly promoted to a `Closure` where one is expected. The compiler generates a static thunk that ignores the env parameter, with a null env pointer.
|
||||
```sx
|
||||
double :: (x: s32) -> s32 { return x * 2; }
|
||||
apply :: (f: Closure(s32) -> s32, x: s32) -> s32 { return f(x); }
|
||||
apply(double, 10); // double auto-promoted to Closure
|
||||
```
|
||||
|
||||
#### Factory Functions
|
||||
Functions can return closures, enabling the factory pattern:
|
||||
```sx
|
||||
make_adder :: (n: s32) -> Closure(s32) -> s32 {
|
||||
return closure((x: s32) -> s32 => x + n);
|
||||
}
|
||||
add5 := make_adder(5);
|
||||
print("{}\n", add5(100)); // 105
|
||||
```
|
||||
|
||||
#### Optional Closures
|
||||
`?Closure` is supported for nullable callbacks. Uses `fn_ptr == null` as the none sentinel (zero overhead — same layout as `Closure`).
|
||||
```sx
|
||||
Button :: struct {
|
||||
label: string;
|
||||
on_click: ?Closure(s64) -> void;
|
||||
}
|
||||
btn := Button.{ label = "OK", on_click = null };
|
||||
if handler := btn.on_click {
|
||||
handler(1);
|
||||
}
|
||||
```
|
||||
|
||||
#### Memory
|
||||
Closure env is heap-allocated via `malloc`. The caller is responsible for freeing `closure.env` when the closure is no longer needed. Auto-promoted closures have a null env and require no freeing.
|
||||
|
||||
### Function Call
|
||||
```sx
|
||||
callee(args)
|
||||
@@ -1192,7 +1268,7 @@ Statements are terminated by `;`.
|
||||
The `push` statement temporarily overrides a global `context` variable for the duration of a block. The previous context is saved before the block and restored after it exits.
|
||||
|
||||
```sx
|
||||
push Context.{ arena = @arena, data = xx @logger } {
|
||||
push Context.{ allocator = arena.allocator(), data = xx @logger } {
|
||||
handle(client); // inside here, `context` has the new value
|
||||
}
|
||||
// context is restored to its previous value here
|
||||
@@ -1201,13 +1277,13 @@ push Context.{ arena = @arena, data = xx @logger } {
|
||||
**`Context` struct** — defined in `std.sx`:
|
||||
```sx
|
||||
Context :: struct {
|
||||
arena: *Arena; // pointer to active arena allocator (or null)
|
||||
data: *void; // opaque pointer for application-specific data
|
||||
allocator: Allocator; // active allocator for dynamic allocation
|
||||
data: *void; // opaque pointer for application-specific data
|
||||
}
|
||||
context : Context = ---; // global mutable variable
|
||||
```
|
||||
|
||||
Inside the pushed block, any code (including called functions) can read `context.arena` and `context.data`. The standard library's `cstring()` function checks `context.arena` and uses it for allocation when available, falling back to `malloc()` otherwise.
|
||||
Inside the pushed block, any code (including called functions) can read `context.allocator` and `context.data`. The standard library's `cstring()` and `alloc_slice()` functions use `context.allocator` for allocation when its `.ctx` is non-null, falling back to `malloc()` otherwise.
|
||||
|
||||
`push` requires a global mutable variable named `context` to be in scope (provided by `std.sx`).
|
||||
|
||||
|
||||
@@ -68,6 +68,7 @@ pub const Node = struct {
|
||||
foreign_expr: ForeignExpr,
|
||||
library_decl: LibraryDecl,
|
||||
function_type_expr: FunctionTypeExpr,
|
||||
closure_type_expr: ClosureTypeExpr,
|
||||
tuple_type_expr: TupleTypeExpr,
|
||||
tuple_literal: TupleLiteral,
|
||||
ufcs_alias: UfcsAlias,
|
||||
@@ -427,6 +428,13 @@ pub const LibraryDecl = struct {
|
||||
|
||||
pub const FunctionTypeExpr = struct {
|
||||
param_types: []const *Node,
|
||||
param_names: ?[]const ?[]const u8 = null, // optional documentation names
|
||||
return_type: ?*Node, // null = void return
|
||||
};
|
||||
|
||||
pub const ClosureTypeExpr = struct {
|
||||
param_types: []const *Node,
|
||||
param_names: ?[]const ?[]const u8 = null, // optional documentation names
|
||||
return_type: ?*Node, // null = void return
|
||||
};
|
||||
|
||||
|
||||
882
src/codegen.zig
882
src/codegen.zig
File diff suppressed because it is too large
Load Diff
104
src/parser.zig
104
src/parser.zig
@@ -390,14 +390,28 @@ pub const Parser = struct {
|
||||
}
|
||||
// Function type: (ParamTypes) -> ReturnType
|
||||
// Tuple type: (T1, T2) or (T1) — no '->' after ')'
|
||||
// Named params (documentation only): (name: Type, ...) -> ReturnType
|
||||
if (self.current.tag == .l_paren) {
|
||||
self.advance(); // skip '('
|
||||
var param_types = std.ArrayList(*Node).empty;
|
||||
var param_names = std.ArrayList(?[]const u8).empty;
|
||||
var has_names = false;
|
||||
while (self.current.tag != .r_paren and self.current.tag != .eof) {
|
||||
if (param_types.items.len > 0) {
|
||||
try self.expect(.comma);
|
||||
if (self.current.tag == .r_paren) break; // trailing comma ok
|
||||
}
|
||||
// Check for optional param name: `name: Type`
|
||||
// An identifier followed by `:` (not `::` or `:=`) is a param name
|
||||
if (self.current.tag == .identifier and self.peekNext() == .colon) {
|
||||
const pname = self.tokenSlice(self.current);
|
||||
self.advance(); // skip name
|
||||
self.advance(); // skip ':'
|
||||
try param_names.append(self.allocator, pname);
|
||||
has_names = true;
|
||||
} else {
|
||||
try param_names.append(self.allocator, null);
|
||||
}
|
||||
try param_types.append(self.allocator, try self.parseTypeExpr());
|
||||
}
|
||||
try self.expect(.r_paren);
|
||||
@@ -407,6 +421,7 @@ pub const Parser = struct {
|
||||
const return_type = try self.parseTypeExpr();
|
||||
return try self.createNode(start, .{ .function_type_expr = .{
|
||||
.param_types = try param_types.toOwnedSlice(self.allocator),
|
||||
.param_names = if (has_names) try param_names.toOwnedSlice(self.allocator) else null,
|
||||
.return_type = return_type,
|
||||
} });
|
||||
}
|
||||
@@ -439,6 +454,42 @@ pub const Parser = struct {
|
||||
}
|
||||
}
|
||||
|
||||
// Closure type: Closure(params...) -> R
|
||||
if (std.mem.eql(u8, name, "Closure") and self.current.tag == .l_paren) {
|
||||
self.advance(); // skip '('
|
||||
var param_types = std.ArrayList(*Node).empty;
|
||||
var param_names = std.ArrayList(?[]const u8).empty;
|
||||
var has_names = false;
|
||||
while (self.current.tag != .r_paren and self.current.tag != .eof) {
|
||||
if (param_types.items.len > 0) {
|
||||
try self.expect(.comma);
|
||||
if (self.current.tag == .r_paren) break; // trailing comma ok
|
||||
}
|
||||
// Check for optional param name: `name: Type`
|
||||
if (self.current.tag == .identifier and self.peekNext() == .colon) {
|
||||
const pname = self.tokenSlice(self.current);
|
||||
self.advance(); // skip name
|
||||
self.advance(); // skip ':'
|
||||
try param_names.append(self.allocator, pname);
|
||||
has_names = true;
|
||||
} else {
|
||||
try param_names.append(self.allocator, null);
|
||||
}
|
||||
try param_types.append(self.allocator, try self.parseTypeExpr());
|
||||
}
|
||||
try self.expect(.r_paren);
|
||||
var return_type: ?*Node = null;
|
||||
if (self.current.tag == .arrow) {
|
||||
self.advance();
|
||||
return_type = try self.parseTypeExpr();
|
||||
}
|
||||
return try self.createNode(start, .{ .closure_type_expr = .{
|
||||
.param_types = try param_types.toOwnedSlice(self.allocator),
|
||||
.param_names = if (has_names) try param_names.toOwnedSlice(self.allocator) else null,
|
||||
.return_type = return_type,
|
||||
} });
|
||||
}
|
||||
|
||||
// Parameterized type: Vector(N, T) or later generic struct instantiation
|
||||
if (self.current.tag == .l_paren) {
|
||||
self.advance(); // skip '('
|
||||
@@ -1889,24 +1940,56 @@ pub const Parser = struct {
|
||||
self.prev_end = saved_prev_end;
|
||||
}
|
||||
|
||||
// Use shared paren-scanning, then check for lambda patterns
|
||||
const tag = self.peekPastParens() orelse return false;
|
||||
// Check upfront if parens look like function params (for block-body disambiguation)
|
||||
const has_param_parens = blk: {
|
||||
self.advance(); // skip '('
|
||||
if (self.current.tag == .r_paren) break :blk true; // empty parens
|
||||
if (self.current.tag != .identifier) break :blk false;
|
||||
self.advance();
|
||||
break :blk self.current.tag == .colon;
|
||||
};
|
||||
|
||||
// Restore to '(' and scan past parens inline (not via peekPastParens which restores state)
|
||||
self.lexer = saved_lexer;
|
||||
self.current = saved_current;
|
||||
self.prev_end = saved_prev_end;
|
||||
self.advance(); // skip '('
|
||||
var depth: u32 = 1;
|
||||
while (depth > 0 and self.current.tag != .eof) {
|
||||
if (self.current.tag == .l_paren) depth += 1;
|
||||
if (self.current.tag == .r_paren) depth -= 1;
|
||||
if (depth > 0) self.advance();
|
||||
}
|
||||
if (self.current.tag != .r_paren) return false;
|
||||
self.advance(); // skip ')' — now positioned on token after parens
|
||||
|
||||
const tag = self.current.tag;
|
||||
// (params) => expr
|
||||
if (tag == .fat_arrow) return true;
|
||||
// (params) -> ReturnType => expr
|
||||
// (params) -> ReturnType { stmts }
|
||||
if (tag == .arrow) {
|
||||
self.advance(); // skip '->'
|
||||
// Skip past the return type tokens until we see '=>' or something unexpected
|
||||
// Skip past the return type tokens until we see '=>', '{', or something unexpected
|
||||
while (self.current.tag != .eof) {
|
||||
if (self.current.tag == .fat_arrow) return true;
|
||||
if (self.current.tag == .l_brace) return true;
|
||||
if (self.current.tag == .identifier or self.current.tag.isTypeKeyword() or
|
||||
self.current.tag == .dot or self.current.tag == .dollar or
|
||||
self.current.tag == .l_bracket or self.current.tag == .r_bracket or
|
||||
self.current.tag == .l_paren or self.current.tag == .r_paren or
|
||||
self.current.tag == .comma or self.current.tag == .int_literal)
|
||||
self.current.tag == .comma or self.current.tag == .int_literal or
|
||||
self.current.tag == .star or self.current.tag == .question)
|
||||
{
|
||||
self.advance();
|
||||
} else break;
|
||||
}
|
||||
return false;
|
||||
}
|
||||
// (params) { stmts } — block-body lambda
|
||||
// Only if contents look like function params (have `:` type annotations or is empty `()`)
|
||||
if (tag == .l_brace) {
|
||||
return has_param_parens;
|
||||
}
|
||||
return false;
|
||||
}
|
||||
@@ -1915,15 +1998,22 @@ pub const Parser = struct {
|
||||
const start = self.current.loc.start;
|
||||
const params = try self.parseParams();
|
||||
|
||||
// Optional return type: (params) -> Type => expr
|
||||
// Optional return type: (params) -> Type => expr OR (params) -> Type { stmts }
|
||||
var return_type: ?*Node = null;
|
||||
if (self.current.tag == .arrow) {
|
||||
self.advance();
|
||||
return_type = try self.parseTypeExpr();
|
||||
}
|
||||
|
||||
try self.expect(.fat_arrow);
|
||||
const body = try self.parseExpr();
|
||||
// Two body forms:
|
||||
// (params) => expr — expression lambda
|
||||
// (params) { stmts } — block-body lambda
|
||||
const body = if (self.current.tag == .l_brace)
|
||||
try self.parseBlock()
|
||||
else blk: {
|
||||
try self.expect(.fat_arrow);
|
||||
break :blk try self.parseExpr();
|
||||
};
|
||||
const type_params = try self.collectTypeParams(params);
|
||||
return try self.createNode(start, .{ .lambda = .{
|
||||
.params = params,
|
||||
|
||||
@@ -848,6 +848,7 @@ pub const Analyzer = struct {
|
||||
.foreign_expr,
|
||||
.library_decl,
|
||||
.function_type_expr,
|
||||
.closure_type_expr,
|
||||
.import_decl,
|
||||
.c_import_decl,
|
||||
.array_type_expr,
|
||||
@@ -1225,6 +1226,7 @@ pub fn findNodeAtOffset(node: *Node, offset: u32) ?*Node {
|
||||
.slice_expr,
|
||||
.tuple_type_expr,
|
||||
.ufcs_alias,
|
||||
.closure_type_expr,
|
||||
=> {},
|
||||
.tuple_literal => |tl| {
|
||||
for (tl.elements) |elem| {
|
||||
|
||||
@@ -22,6 +22,7 @@ pub const Type = union(enum) {
|
||||
many_pointer_type: ManyPointerTypeInfo,
|
||||
vector_type: VectorTypeInfo,
|
||||
function_type: FunctionTypeInfo,
|
||||
closure_type: ClosureTypeInfo,
|
||||
any_type,
|
||||
optional_type: OptionalTypeInfo,
|
||||
meta_type: MetaTypeInfo,
|
||||
@@ -44,6 +45,11 @@ pub const Type = union(enum) {
|
||||
return_type: *const Type,
|
||||
};
|
||||
|
||||
pub const ClosureTypeInfo = struct {
|
||||
param_types: []const Type,
|
||||
return_type: *const Type,
|
||||
};
|
||||
|
||||
pub const ArrayTypeInfo = struct {
|
||||
element_name: []const u8,
|
||||
length: u32,
|
||||
@@ -95,6 +101,14 @@ pub const Type = union(enum) {
|
||||
}
|
||||
return info.return_type.eql(o.return_type.*);
|
||||
},
|
||||
.closure_type => |info| {
|
||||
const o = other.closure_type;
|
||||
if (info.param_types.len != o.param_types.len) return false;
|
||||
for (info.param_types, o.param_types) |a, b| {
|
||||
if (!a.eql(b)) return false;
|
||||
}
|
||||
return info.return_type.eql(o.return_type.*);
|
||||
},
|
||||
.optional_type => |info| std.mem.eql(u8, info.child_name, other.optional_type.child_name),
|
||||
.meta_type => |info| std.mem.eql(u8, info.name, other.meta_type.name),
|
||||
.tuple_type => |info| {
|
||||
@@ -302,6 +316,21 @@ pub const Type = union(enum) {
|
||||
};
|
||||
}
|
||||
|
||||
pub fn isClosureType(self: Type) bool {
|
||||
return switch (self) {
|
||||
.closure_type => true,
|
||||
else => false,
|
||||
};
|
||||
}
|
||||
|
||||
/// Returns true for both bare function pointers and closures
|
||||
pub fn isCallable(self: Type) bool {
|
||||
return switch (self) {
|
||||
.function_type, .closure_type => true,
|
||||
else => false,
|
||||
};
|
||||
}
|
||||
|
||||
pub fn isArray(self: Type) bool {
|
||||
return switch (self) {
|
||||
.array_type => true,
|
||||
@@ -356,6 +385,7 @@ pub const Type = union(enum) {
|
||||
.f64 => 64,
|
||||
.boolean => 1,
|
||||
.pointer_type, .many_pointer_type, .function_type => 64,
|
||||
.closure_type => 128, // { ptr, ptr } = 16 bytes
|
||||
else => 0,
|
||||
};
|
||||
}
|
||||
@@ -506,6 +536,20 @@ pub const Type = union(enum) {
|
||||
}
|
||||
return try buf.toOwnedSlice(allocator);
|
||||
},
|
||||
.closure_type => |info| {
|
||||
var buf = std.ArrayList(u8).empty;
|
||||
try buf.appendSlice(allocator, "Closure(");
|
||||
for (info.param_types, 0..) |pt, i| {
|
||||
if (i > 0) try buf.appendSlice(allocator, ", ");
|
||||
try buf.appendSlice(allocator, try pt.displayName(allocator));
|
||||
}
|
||||
try buf.append(allocator, ')');
|
||||
if (!std.meta.eql(info.return_type.*, Type.void_type)) {
|
||||
try buf.appendSlice(allocator, " -> ");
|
||||
try buf.appendSlice(allocator, try info.return_type.displayName(allocator));
|
||||
}
|
||||
return try buf.toOwnedSlice(allocator);
|
||||
},
|
||||
.optional_type => |info| return fmtAlloc(allocator, "?{s}", .{info.child_name}),
|
||||
.meta_type => |info| info.name,
|
||||
.tuple_type => |info| {
|
||||
|
||||
1
tests/expected/35-closures.exit
Normal file
1
tests/expected/35-closures.exit
Normal file
@@ -0,0 +1 @@
|
||||
0
|
||||
13
tests/expected/35-closures.txt
Normal file
13
tests/expected/35-closures.txt
Normal file
@@ -0,0 +1,13 @@
|
||||
basic: 142
|
||||
snapshot: 15
|
||||
clamp: 50 0 100
|
||||
[INFO] system ready
|
||||
factory: 105 110
|
||||
auto-promote: 21
|
||||
hof: 40
|
||||
reduce: 15
|
||||
compose: 30
|
||||
multi: 105 500
|
||||
widget: slider = 42
|
||||
widget: no handler
|
||||
=== DONE ===
|
||||
@@ -426,4 +426,40 @@ or guard: 7
|
||||
or guard null: 0
|
||||
nested narrow: 10 20
|
||||
guard loop: 3
|
||||
block-lambda: 50
|
||||
block-lambda: 0
|
||||
block-lambda: 100
|
||||
hello block
|
||||
named-fn-type: 7
|
||||
xx-fnptr: 142
|
||||
closure-type: fn_ptr-nonnull=true
|
||||
closure-type: env-null=true
|
||||
closure-call: 15
|
||||
auto-promote: 20
|
||||
auto-promote-var: 10
|
||||
closure-capture: 52
|
||||
closure-snapshot: 15
|
||||
closure-nocap: 14
|
||||
closure-multi: 33
|
||||
closure-block: 60
|
||||
closure-block: 0
|
||||
closure-block: 100
|
||||
[LOG] hello
|
||||
closure-hof: 30
|
||||
closure-hof-bare: 20
|
||||
closure-f32: 10.000000
|
||||
closure-bool: hello
|
||||
closure-2p: 107
|
||||
closure-3p: 61
|
||||
closure-mix: Alice is 35
|
||||
closure-rbool: false true
|
||||
closure-reduce: 115
|
||||
closure-factory: 105 110
|
||||
closure-struct: 10 20
|
||||
closure-compose: 30
|
||||
closure-indep: 15 50
|
||||
opt-closure: none
|
||||
opt-closure: 15
|
||||
opt-closure-btn: 1 99
|
||||
opt-closure-btn: null
|
||||
=== DONE ===
|
||||
|
||||
Reference in New Issue
Block a user