From 2bb3f70e3528b48e7edc48582b7fff3b38d25f00 Mon Sep 17 00:00:00 2001 From: femto Date: Fri, 20 Nov 2026 15:33:12 +0800 Subject: [PATCH 1/7] Nested optionals: ??T and ?*T have two levels A generic ?V given V = ?i64 or V = *T no longer fails to instantiate: HashMap(i64, ?i64).get tells a missing key (null) from a null value. - ??T and ?*T are types: null is the outer level, a plain value is wrapped in every level, each orelse or capture unwraps one. *T is a raw pointer, so ?*T is two levels as in Rust's Option<*const T>. - ?T can be a type argument: HashMap(i64, ?i64). - An owned ?T is unwrapped where it is made, so ??Buf(u8) is E133. - ?!T stays E108. Co-Authored-By: Claude Opus 5.5 --- docs/design.md | 2 +- docs/design.zh.md | 2 +- examples/nested_optional.egg | 80 +++++++++++++++++++++++++++ lib/egg/codegen_c.rb | 2 +- lib/egg/own.rb | 2 +- lib/egg/parser.rb | 5 +- lib/egg/typecheck.rb | 24 ++++++-- spec/core.md | 9 ++- spec/diagnostics.md | 4 +- spec/grammar.ebnf | 2 +- test/errors/nested_optional_owned.egg | 11 ++++ test/errors/optional_misuse.egg | 22 +++----- test/errors/type_alias_dup.egg | 2 +- 13 files changed, 137 insertions(+), 30 deletions(-) create mode 100644 examples/nested_optional.egg create mode 100644 test/errors/nested_optional_owned.egg diff --git a/docs/design.md b/docs/design.md index eecd468..6737d04 100644 --- a/docs/design.md +++ b/docs/design.md @@ -40,7 +40,7 @@ The core follows Zig but stays smaller: it keeps only features that need no runt | `[3][4]u8` | 3 rows of 4 bytes; indexed `grid[2][3]` in the same order | | `[]u8` | slice: pointer plus runtime length | | `*[4]u8` | pointer to an array of 4 bytes | -| `?T` | a `T` or `null` (`*T` can already be null, so `?*T` is not used) | +| `?T` | a `T` or `null`; `*T` is a raw pointer and can already be null, so `?*T` and `??T` have two levels | | `!T` | a `T` or an error | Rust's `[u8; 4]` was considered and rejected: it is the only form that puts the element type in the middle, and nested arrays read inside out. diff --git a/docs/design.zh.md b/docs/design.zh.md index e6ca265..365212d 100644 --- a/docs/design.zh.md +++ b/docs/design.zh.md @@ -32,7 +32,7 @@ Egg 是一门 AI 原生的系统编程语言:核心不带任何能力,异常 | 错误 | 错误作为值(类似 `!T`)、`try` | v1 | | 编译期 | `comptime` 参数、泛型(返回 `type` 的函数);反射(`@typeInfo`) | v1;反射在 v1 之后 | -**类型语法采用前缀写法,从左往右读**(同 Go、Zig):`[4]u8` 是 4 字节数组,`[3][4]u8` 是 3 行 4 列(访问顺序 `grid[2][3]` 与类型一致),`[]u8` 是切片,`*[4]u8` 是指向数组的指针,`?T` 是 `T` 或 `null`(`*T` 本身就可以为空,所以不用 `?*T`),`!T` 是可能出错的值。不采用 Rust 的 `[u8; 4]`:它是唯一把元素类型夹在中间的写法,嵌套时要从里往外读。 +**类型语法采用前缀写法,从左往右读**(同 Go、Zig):`[4]u8` 是 4 字节数组,`[3][4]u8` 是 3 行 4 列(访问顺序 `grid[2][3]` 与类型一致),`[]u8` 是切片,`*[4]u8` 是指向数组的指针,`?T` 是 `T` 或 `null`(`*T` 是裸指针,本身就可以为空,所以 `?*T` 和 `??T` 一样有两层),`!T` 是可能出错的值。不采用 Rust 的 `[u8; 4]`:它是唯一把元素类型夹在中间的写法,嵌套时要从里往外读。 刻意不进入核心的特性: diff --git a/examples/nested_optional.egg b/examples/nested_optional.egg new file mode 100644 index 0000000..13a588e --- /dev/null +++ b/examples/nested_optional.egg @@ -0,0 +1,80 @@ +// ??T and ?*T: an optional of an optional, or of a pointer, has two +// levels. null is the outer one; a plain value is wrapped in both. They +// come up when a generic ?V is given V = ?T or V = *T, as in a map whose +// values may be null: get tells a missing key from a null value. +// expect: 3 -1 -2 +// expect: true false +// expect: 5 +// expect: -1 +// expect: -2 +// expect: found null +// expect: missing +// expect: 7 -1 +// expect: 2 +uses io, alloc +allow unsafe + +const map = @import("std/map") + +const Node = struct { value: i64 } +const MaybeInt = ?i64 + +fn first(comptime V: type, xs: []V) ?V { + if (@len(xs) == 0) { + return null + } + return xs[0] +} + +fn show(io: Io, x: ??i64) void { + io.print((x orelse -2) orelse -1) +} + +fn describe(io: Io, p: ?*Node) void { + const q = p orelse { + io.print("missing") + return + } + if (q == null) { + io.print("found null") + } else { + io.print(q.*.value) + } +} + +fn main(io: Io, a: Allocator) void { + var m = map.HashMap(i64, ?i64).init() + defer a.free(m) + m.put(a, 1, 3) + m.put(a, 2, null) + io.print((m.get(1) orelse -2) orelse -1, " ", (m.get(2) orelse -2) orelse -1, " ", (m.get(3) orelse -2) orelse -1) + const g = m.get(2) + io.print(g != null, " ", m.get(3) != null) + + const xs = [_]?i64{ 5, null } + show(io, first(?i64, xs[0..])) + show(io, first(MaybeInt, xs[1..])) + show(io, null) + + var pm = map.HashMap(i64, *Node).init() + defer a.free(pm) + pm.put(a, 1, null) + describe(io, pm.get(1)) + describe(io, pm.get(2)) + + var deep: ??i64 = 7 + if (deep) |inner| { + io.print(inner orelse 0, " ", (first(MaybeInt, xs[2..]) orelse -1) orelse 0) + } + deep = null + var levels = 0 + const one: ?i64 = null + const two: ??i64 = one + if (two != null) { + levels = levels + 1 + } + if (deep == null) { + levels = levels + 1 + } + io.print(levels) +} diff --git a/lib/egg/codegen_c.rb b/lib/egg/codegen_c.rb index 0f753e3..632e42e 100644 --- a/lib/egg/codegen_c.rb +++ b/lib/egg/codegen_c.rb @@ -4209,7 +4209,7 @@ def hoist(code, t) def coerce(code, from, to) return code if to.nil? || from == to return text_as(code, from, to) if %w[str []u8].include?(to) && text_type?(from) - return "((#{c_type(to)}){ .value = #{code}, .has = true })" if to.start_with?("?") + return "((#{c_type(to)}){ .value = #{coerce(code, from, @types[to].inner)}, .has = true })" if to.start_with?("?") return code unless to.start_with?("!") if from == "anyerror" "((#{c_type(to)}){ .err = #{code} })" diff --git a/lib/egg/own.rb b/lib/egg/own.rb index 18c2727..b544d75 100644 --- a/lib/egg/own.rb +++ b/lib/egg/own.rb @@ -369,7 +369,7 @@ def declare_slice(name, value, writable, depth = @rest.length - 1) def slice_type?(t) t = t[1..] if t.start_with?("!") - t = t[1..] if t.start_with?("?") + t = t[1..] while t.start_with?("?") t.start_with?("[]") end diff --git a/lib/egg/parser.rb b/lib/egg/parser.rb index b96f2be..f3ad581 100644 --- a/lib/egg/parser.rb +++ b/lib/egg/parser.rb @@ -847,8 +847,9 @@ def parse_primary elsif kw?("null") advance NullLit.new(t.line, t.col) - elsif op?("*") || kw?("fn") - # *T, fn(T) R as a value: a type argument such as @ptrCast(*u8, p) + elsif op?("*") || op?("?") || kw?("fn") + # *T, ?T, fn(T) R as a value: a type argument such as + # @ptrCast(*u8, p) or HashMap(i64, ?i64) TypeExpr.new(parse_type, t.line, t.col) elsif at?(:string) advance diff --git a/lib/egg/typecheck.rb b/lib/egg/typecheck.rb index 271d64e..2eaaea3 100644 --- a/lib/egg/typecheck.rb +++ b/lib/egg/typecheck.rb @@ -1064,12 +1064,16 @@ def resolve_type(t, line, col) when OptType inner = resolve_type(t.inner, line, col) return "error" if inner == "error" - unless (storable?(inner) || inner.start_with?("[]")) && !inner.start_with?("!") && !inner.start_with?("?") + # ??T and ?*T are two levels: null, or a value that is itself + # null or not, as when a ?V is instantiated with V = ?T or *T. + unless (storable?(inner) || inner.start_with?("[]")) && !inner.start_with?("!") err("E108", "?#{inner} is not a valid optional", line, col) return "error" end - unless pointee(inner).nil? - err("E108", "?#{inner} is not needed: a pointer can already be null", line, col) + # An owned ?T is unwrapped where it is made, so it is never + # wrapped again. + if owned_err?(inner) + err("E133", "?#{inner} cannot be made: a #{inner} must be unwrapped right away with orelse", line, col) return "error" end opt_type(inner) @@ -3243,7 +3247,7 @@ def pointer_slice?(e) def slice_in(t) return nil if t.nil? t = t[1..] if t.start_with?("!") - t = t[1..] if t.start_with?("?") + t = t[1..] while t.start_with?("?") t.start_with?("[]") ? t : nil end @@ -4294,9 +4298,17 @@ def fits?(want, got) inner = @types[want].inner return true if inner == got # A plain value fits a !?T, as in Zig. - return true if inner.start_with?("?") && @types[inner].inner == got + return true if opt_wraps?(inner, got) + end + opt_wraps?(want, got) + end + + # Is want an optional of got, maybe nested (i64 fits ?i64 and ??i64)? + def opt_wraps?(want, got) + while want.start_with?("?") + want = @types[want].inner + return true if want == got end - return true if want.start_with?("?") && @types[want].inner == got false end diff --git a/spec/core.md b/spec/core.md index 0d74f5f..d6e3d73 100644 --- a/spec/core.md +++ b/spec/core.md @@ -1465,7 +1465,14 @@ fn main(io: Io) void { ``` `?T` holds either a `T` or `null`, as in Zig. T may be any value type but -a pointer (which can already be null), `!U` or `?U` (E108). +`!U` (E108). T may itself be optional or a pointer, which can already be +null: a `??U` or `?*U` has two levels, null or a value that may be null. +They come from generic code: a `?V` with `V = ?i64`, so `get` on a +`HashMap(i64, ?i64)` tells a missing key (null) from a null value. +`null` is the outer level; a plain value is wrapped in every level +(`const x: ??i64 = 7`); each `orelse` or capture unwraps one. An owned +`?U` is unwrapped where it is made, so it is never wrapped again +(`??Buf(u8)` is E133). - A `T` or `null` fits where a `?T` is expected: `var best: ?i64 = null`, then `best = 7`. A function may return `!?T`, value or nothing or error: diff --git a/spec/diagnostics.md b/spec/diagnostics.md index a3d4f7c..1700e17 100644 --- a/spec/diagnostics.md +++ b/spec/diagnostics.md @@ -21,7 +21,7 @@ program imports: | E105 | checker | assigning to, or passing as inout, a `const`, a by-value parameter, or an element of a read-only slice or str; reassigning an `inout` slice parameter itself; lending a mutable slice (`&x[lo..hi]`) of a `const`, a plain parameter, a read-only slice or a str | declare it with `var`, or make the parameter `inout` (`inout xs: []T` for a slice, passed as `&x[lo..hi]`); str elements are always read-only, so copy them into a `var` array | | E106 | checker | duplicate definition (function, type, import, field, member, method) or shadowing; a type named like a built-in one (`Buf`, `i64`, ...) | rename one of them | | E107 | checker | non-void function can reach its end without returning | add a `return` on every path | -| E108 | checker | unknown type, `void` or `type` where a value type is needed, `[_]T` outside a literal; `?T` of a pointer (already nullable), `!U` or `?U` | use a value type; write `*T` for a nullable pointer | +| E108 | checker | unknown type, `void` or `type` where a value type is needed, `[_]T` outside a literal; `?T` of a `!U` | use a value type; write `!?T` for a result that may be null | | E109 | checker | missing or invalid `main` (returns something else, or takes a parameter that is not a capability value, or one twice) | `fn main(io: Io) void`, `fn main() i64` or `fn main(io: Io, a: Allocator) !void` | | E110 | checker | local variable is never used | remove it | | E111 | checker | `var` is never changed (assigned, or passed as inout), or an `inout r = &p` borrow never changes what it borrows | declare it with `const` | @@ -46,7 +46,7 @@ program imports: | E130 | capabilities | a function uses a capability (directly, or through a call) that its file does not declare | add `uses io` / `uses args` / `uses fs` / `uses net` / `uses thread` / `uses time` / `uses rand` / `uses alloc` to that file, or move the code to a file that declares it | | E131 | checker | a pointer operation (`p.*`, `@ptrAdd`, `@ptrCast`, `@intFromPtr`, `@ptrFromInt`, `@strPtr`, `@bufPtr`, `@sliceFromPtr`), an `extern fn`, a `link` or `a.str_from_c` in a file without `allow unsafe`; or `allow` with anything but `unsafe`. (`&x` outside an inout argument in such a file stays E121.) | add `allow unsafe` at the top of the file, or keep the unsafe operation in a module that has it | | E132 | checker | an invalid `extern fn`: a name that is a C keyword, `main`, declared by the C headers the generated code includes (functions, macros, types), reserved in C (`_X`, `__x`), or starts with a generated prefix; a parameter that is not an integer, float, bool, pointer to a C type, function type or extern struct, or is a function type with `inout` or `sink` parameters or with parameters or a result that are none of those, or a result that is none of those and not `void`; an `inout` parameter; or two declarations of one C function with different types | rename it, pass pointers instead of str or slices, declare the structs C sees as `extern struct` | -| E133 | checker | an owned value (a `Buf(T)`, an `owned struct`, or a struct, union or array holding one) as a pointer's target; a `!T` or `?T` of one as a field, element, local or parameter, or compared with `null`; borrowing from a temporary one or from an if with a value (`@len(make(a))`, `make_list(a).len`, or passing it to a plain parameter, `count(make(a))`), or switching on a temporary one; or `@forget` of a temporary | unwrap `!T` with `try`/`catch` and `?T` with `orelse` or `if (x) |v| { ... }`; store a temporary in a variable; borrow each variable in its own branch of an if statement | +| E133 | checker | an owned value (a `Buf(T)`, an `owned struct`, or a struct, union or array holding one) as a pointer's target; a `!T` or `?T` of one as a field, element, local or parameter, compared with `null`, or wrapped in another optional (`??Buf(u8)`); borrowing from a temporary one or from an if with a value (`@len(make(a))`, `make_list(a).len`, or passing it to a plain parameter, `count(make(a))`), or switching on a temporary one; or `@forget` of a temporary | unwrap `!T` with `try`/`catch` and `?T` with `orelse` or `if (x) |v| { ... }`; store a temporary in a variable; borrow each variable in its own branch of an if statement | | E134 | ownership | paths that join disagree on whether a buffer (or a buffer field, `v.data`) was moved (after `if`, an if with a value, `switch`, `select`, `catch`, `and`/`or`), or a loop iteration (or a `break`/`continue`, or a loop condition) changes whether one from outside the loop is owned | move or free it on every path, or on none; free and reassign it within the same iteration | | E135 | ownership | a buffer, a buffer field of a struct, or an `owned struct` not yet ended, still owned where its owner goes away (end of its block, `return`, `break`/`continue`, a `try` that returns an error), a variable or field that owns one assigned another, or an `inout` parameter that does not own all its buffers (and, for an owned struct, the struct itself) when the function returns, a `Thread` not joined or detached, or a channel end not closed | `a.free(v)` / `a.free(v.data)`, return it or pass it on; `defer a.free(v)` / `errdefer a.free(v)` right after making it; for an owned struct, its ending method (`defer db.close()`); `t.join()` or `t.detach()` for a `Thread`, `close()` for a channel end, receiving all a `Receiver` holds first | | E136 | ownership | a variable used after its buffer or owned struct was moved (passed, assigned, returned, freed or forgotten), also by a `defer` that runs after the move; a struct used whole while one of its buffer fields is moved; a field read or assigned after the whole struct was moved | use it before moving it, or give it a new buffer first (`v.data = ...`, or `v = ...` after moving all of `v`) | diff --git a/spec/grammar.ebnf b/spec/grammar.ebnf index 524f0f5..b1233ec 100644 --- a/spec/grammar.ebnf +++ b/spec/grammar.ebnf @@ -92,7 +92,7 @@ postfix = primary , { "." , IDENT , [ args ] (* field, method cal | struct_lit } ; (* after a capitalised type: Point, m.Point, Pair(i64) *) struct_lit = "{" , { NL } , { "." , IDENT , "=" , expr , [ "," ] , { NL } } , "}" ; primary = INT | FLOAT | STRING | CHAR | "true" | "false" | "null" - | "*" , type | fn_type (* a type as a value: @ptrCast( *u8, p) *) + | "*" , type | "?" , type | fn_type (* a type as a value: @ptrCast( *u8, p) *) | IDENT , [ args ] (* variable, call, type name *) | BUILTIN , args (* @len(...) ... *) | "@This" , "(" , ")" diff --git a/test/errors/nested_optional_owned.egg b/test/errors/nested_optional_owned.egg new file mode 100644 index 0000000..8255b91 --- /dev/null +++ b/test/errors/nested_optional_owned.egg @@ -0,0 +1,11 @@ +// An owned ?T is unwrapped where it is made, so it is never wrapped in +// another optional. +uses alloc + +fn make(a: Allocator) ??Buf(u8) { + return a.int_str(3) +} + +fn main() void { +} +// error: E133 @5 diff --git a/test/errors/optional_misuse.egg b/test/errors/optional_misuse.egg index 251feb3..ab7554c 100644 --- a/test/errors/optional_misuse.egg +++ b/test/errors/optional_misuse.egg @@ -1,10 +1,7 @@ // Misusing optionals and orelse. uses alloc, io -fn bad_ptr(p: ?*i64) void { -} - -fn nested(x: ??i64) void { +fn bad_err(x: ?!i64) void { } fn not_opt(io: Io) void { @@ -50,12 +47,11 @@ fn push_struct(a: Allocator) void { fn main() void { } // error: E108 @4 -// error: E108 @7 -// error: E118 @12 -// error: E103 @16 -// error: E118 @20 -// error: E133 @26 -// error: E110 @26 -// error: E113 @32 -// error: E103 @37 -// error: E103 @46 +// error: E118 @9 +// error: E103 @13 +// error: E118 @17 +// error: E133 @23 +// error: E110 @23 +// error: E113 @29 +// error: E103 @34 +// error: E103 @43 diff --git a/test/errors/type_alias_dup.egg b/test/errors/type_alias_dup.egg index 87d7752..751bb17 100644 --- a/test/errors/type_alias_dup.egg +++ b/test/errors/type_alias_dup.egg @@ -1,6 +1,6 @@ // error: E108 @3 const Self = struct { n: Next } -const Next = ?*Self +const Next = ?!i64 fn main() i64 { return 0 From 9c3306b17caf8dffb2369b89c797ecc43b818b4e Mon Sep 17 00:00:00 2001 From: femto Date: Fri, 20 Nov 2026 16:17:38 +0800 Subject: [PATCH 2/7] Nested optionals of slices: ??[]u8 borrows like ?[]u8; escape |v| in the E133 row Co-Authored-By: Claude Opus 5.5 --- examples/nested_optional.egg | 21 +++++++++++++++++++++ lib/egg/typecheck.rb | 2 +- spec/diagnostics.md | 2 +- 3 files changed, 23 insertions(+), 2 deletions(-) diff --git a/examples/nested_optional.egg b/examples/nested_optional.egg index 13a588e..003450a 100644 --- a/examples/nested_optional.egg +++ b/examples/nested_optional.egg @@ -11,6 +11,8 @@ // expect: missing // expect: 7 -1 // expect: 2 +// expect: a +// expect: true false uses io, alloc allow unsafe @@ -26,6 +28,18 @@ fn first(comptime V: type, xs: []V) ?V { return xs[0] } +// A ??[]u8 borrows like a ?[]u8: from the parameter s. +fn head(s: []u8, ok: bool) ??[]u8 { + if (!ok) { + return null + } + if (@len(s) == 0) { + const none: ?[]u8 = null + return none + } + return s[0..1] +} + fn show(io: Io, x: ??i64) void { io.print((x orelse -2) orelse -1) } @@ -77,4 +91,11 @@ fn main(io: Io, a: Allocator) void { levels = levels + 1 } io.print(levels) + + if (head("abc", true)) |inner| { + if (inner) |c| { + io.print(c) + } + } + io.print(head("", true) != null, " ", head("abc", false) != null) } diff --git a/lib/egg/typecheck.rb b/lib/egg/typecheck.rb index 2eaaea3..bb86e62 100644 --- a/lib/egg/typecheck.rb +++ b/lib/egg/typecheck.rb @@ -1066,7 +1066,7 @@ def resolve_type(t, line, col) return "error" if inner == "error" # ??T and ?*T are two levels: null, or a value that is itself # null or not, as when a ?V is instantiated with V = ?T or *T. - unless (storable?(inner) || inner.start_with?("[]")) && !inner.start_with?("!") + unless (storable?(inner) || !slice_in(inner).nil?) && !inner.start_with?("!") err("E108", "?#{inner} is not a valid optional", line, col) return "error" end diff --git a/spec/diagnostics.md b/spec/diagnostics.md index 1700e17..fa1bd56 100644 --- a/spec/diagnostics.md +++ b/spec/diagnostics.md @@ -46,7 +46,7 @@ program imports: | E130 | capabilities | a function uses a capability (directly, or through a call) that its file does not declare | add `uses io` / `uses args` / `uses fs` / `uses net` / `uses thread` / `uses time` / `uses rand` / `uses alloc` to that file, or move the code to a file that declares it | | E131 | checker | a pointer operation (`p.*`, `@ptrAdd`, `@ptrCast`, `@intFromPtr`, `@ptrFromInt`, `@strPtr`, `@bufPtr`, `@sliceFromPtr`), an `extern fn`, a `link` or `a.str_from_c` in a file without `allow unsafe`; or `allow` with anything but `unsafe`. (`&x` outside an inout argument in such a file stays E121.) | add `allow unsafe` at the top of the file, or keep the unsafe operation in a module that has it | | E132 | checker | an invalid `extern fn`: a name that is a C keyword, `main`, declared by the C headers the generated code includes (functions, macros, types), reserved in C (`_X`, `__x`), or starts with a generated prefix; a parameter that is not an integer, float, bool, pointer to a C type, function type or extern struct, or is a function type with `inout` or `sink` parameters or with parameters or a result that are none of those, or a result that is none of those and not `void`; an `inout` parameter; or two declarations of one C function with different types | rename it, pass pointers instead of str or slices, declare the structs C sees as `extern struct` | -| E133 | checker | an owned value (a `Buf(T)`, an `owned struct`, or a struct, union or array holding one) as a pointer's target; a `!T` or `?T` of one as a field, element, local or parameter, compared with `null`, or wrapped in another optional (`??Buf(u8)`); borrowing from a temporary one or from an if with a value (`@len(make(a))`, `make_list(a).len`, or passing it to a plain parameter, `count(make(a))`), or switching on a temporary one; or `@forget` of a temporary | unwrap `!T` with `try`/`catch` and `?T` with `orelse` or `if (x) |v| { ... }`; store a temporary in a variable; borrow each variable in its own branch of an if statement | +| E133 | checker | an owned value (a `Buf(T)`, an `owned struct`, or a struct, union or array holding one) as a pointer's target; a `!T` or `?T` of one as a field, element, local or parameter, compared with `null`, or wrapped in another optional (`??Buf(u8)`); borrowing from a temporary one or from an if with a value (`@len(make(a))`, `make_list(a).len`, or passing it to a plain parameter, `count(make(a))`), or switching on a temporary one; or `@forget` of a temporary | unwrap `!T` with `try`/`catch` and `?T` with `orelse` or `if (x) \|v\| { ... }`; store a temporary in a variable; borrow each variable in its own branch of an if statement | | E134 | ownership | paths that join disagree on whether a buffer (or a buffer field, `v.data`) was moved (after `if`, an if with a value, `switch`, `select`, `catch`, `and`/`or`), or a loop iteration (or a `break`/`continue`, or a loop condition) changes whether one from outside the loop is owned | move or free it on every path, or on none; free and reassign it within the same iteration | | E135 | ownership | a buffer, a buffer field of a struct, or an `owned struct` not yet ended, still owned where its owner goes away (end of its block, `return`, `break`/`continue`, a `try` that returns an error), a variable or field that owns one assigned another, or an `inout` parameter that does not own all its buffers (and, for an owned struct, the struct itself) when the function returns, a `Thread` not joined or detached, or a channel end not closed | `a.free(v)` / `a.free(v.data)`, return it or pass it on; `defer a.free(v)` / `errdefer a.free(v)` right after making it; for an owned struct, its ending method (`defer db.close()`); `t.join()` or `t.detach()` for a `Thread`, `close()` for a channel end, receiving all a `Receiver` holds first | | E136 | ownership | a variable used after its buffer or owned struct was moved (passed, assigned, returned, freed or forgotten), also by a `defer` that runs after the move; a struct used whole while one of its buffer fields is moved; a field read or assigned after the whole struct was moved | use it before moving it, or give it a new buffer first (`v.data = ...`, or `v = ...` after moving all of `v`) | From a0d1340bf7acd544a87152a18d6fafc29f970d5b Mon Sep 17 00:00:00 2001 From: femto Date: Fri, 20 Nov 2026 16:30:48 +0800 Subject: [PATCH 3/7] Nested optionals: literals, enum members and &x reach the innermost type const x: ??i8 = 7, const c: ??Color = .green, const p: ??*i64 = &x and f(&x) for a ?*i64 parameter peeled only one optional level. Co-Authored-By: Claude Opus 5.5 --- examples/nested_optional.egg | 17 +++++++++++++++++ lib/egg/codegen_c.rb | 4 +++- lib/egg/typecheck.rb | 17 +++++++++++------ 3 files changed, 31 insertions(+), 7 deletions(-) diff --git a/examples/nested_optional.egg b/examples/nested_optional.egg index 003450a..d2816ea 100644 --- a/examples/nested_optional.egg +++ b/examples/nested_optional.egg @@ -13,6 +13,8 @@ // expect: 2 // expect: a // expect: true false +// expect: 7 true 5 +// expect: 5 -1 uses io, alloc allow unsafe @@ -20,6 +22,7 @@ const map = @import("std/map") const Node = struct { value: i64 } const MaybeInt = ?i64 +const Color = enum { red, green } fn first(comptime V: type, xs: []V) ?V { if (@len(xs) == 0) { @@ -40,6 +43,11 @@ fn head(s: []u8, ok: bool) ??[]u8 { return s[0..1] } +fn deref_or(p: ?*i64) i64 { + const q = p orelse return -1 + return q.* +} + fn show(io: Io, x: ??i64) void { io.print((x orelse -2) orelse -1) } @@ -98,4 +106,13 @@ fn main(io: Io, a: Allocator) void { } } io.print(head("", true) != null, " ", head("abc", false) != null) + + // A literal, an enum member and an address take the innermost type. + const small: ??i8 = 7 + const color: ??Color = .green + var n = 5 + const pp: ??*i64 = &n + io.print((small orelse 0) orelse 1, " ", ((color orelse .red) orelse .red) == .green, " ", ((pp orelse null) orelse null).*) + io.print(deref_or(&n), " ", deref_or(null)) + n = 6 } diff --git a/lib/egg/codegen_c.rb b/lib/egg/codegen_c.rb index 632e42e..77e6eae 100644 --- a/lib/egg/codegen_c.rb +++ b/lib/egg/codegen_c.rb @@ -4521,7 +4521,9 @@ def call(c_name, args, params, receiver, ret, writes = []) later = args[(i + 1)..] codes << case a in AddrOf[expr: SliceExpr => s] then slice_expr(s) - in AddrOf[expr: place] then "&#{lvalue(place)}" + in AddrOf[expr: place] + # A pointer argument may go to a ?*T parameter. + mode == "inout" ? "&#{lvalue(place)}" : coerce("&#{lvalue(place)}", a.ty, pt) else if by_ptr?(pt, mode) && a.ty == pt && !a.is_a?(SliceExpr) big_arg(a, later, inouts) diff --git a/lib/egg/typecheck.rb b/lib/egg/typecheck.rb index bb86e62..4eac613 100644 --- a/lib/egg/typecheck.rb +++ b/lib/egg/typecheck.rb @@ -472,6 +472,12 @@ def pointee(t) info&.kind == :ptr ? info.inner : nil end + # t without its optional levels: i64 for ??i64. + def opt_base(t) + t = @types[t].inner while !t.nil? && @types[t]&.kind == :opt + t + end + # Methods are keyed apart from functions, which may be named "m.f". def method_key(owner, name) "#{owner}::#{name}" @@ -2070,8 +2076,7 @@ def check_borrow(stmt, name, type, place, writable, line, col) # is reported once: the declaration resolves it again.) def pointer_type_expr?(type, line, col) return false if type.nil? - t = resolve_type(type, line, col) - t = @types[t].inner if @types[t]&.kind == :opt + t = opt_base(resolve_type(type, line, col)) @types[t]&.kind == :ptr end @@ -2561,12 +2566,12 @@ def signed?(t) # The number type a literal should take where `expected` is wanted # (T, or the T of !T or ?T), or nil. - # The type a value has where expected wants it: T for !T, ?T and !?T. + # The type a value has where expected wants it: T for !T, ?T, ??T + # and !?T. def value_target(expected) t = expected t = @types[t].inner if !t.nil? && @types[t]&.kind == :err - t = @types[t].inner if !t.nil? && @types[t]&.kind == :opt - t + opt_base(t) end def num_target(expected) @@ -3142,7 +3147,7 @@ def check_args(sig, args, name, line, col, receivers = [], self_inout: false) elsif slice_expr?(a) at = check_slice_arg(a, pt) expect_type(pt, at, a) - elsif a.is_a?(AddrOf) && !pointee(pt).nil? + elsif a.is_a?(AddrOf) && !pointee(opt_base(pt)).nil? at = check_expr(a, pt) expect_type(pt, at, a) elsif a.is_a?(AddrOf) From 7df42c04c49025658e838313c1f802df2004eaa6 Mon Sep 17 00:00:00 2001 From: femto Date: Fri, 20 Nov 2026 17:00:34 +0800 Subject: [PATCH 4/7] Nested optionals: big &x arguments by address, exact inout types, V == ?T - f(&n) for a ??*i64 parameter (24 bytes) passes the converted value by address, like any big argument. - An inout argument must have exactly the parameter's type: an i64 variable no longer fits inout ?i64 (the callee wrote 16 bytes into 8). - A type written in place folds in a comptime comparison: V == ?i64, V == *i64, V == ?K. Co-Authored-By: Claude Opus 5.5 --- examples/nested_optional.egg | 21 +++++++++++++++++++++ lib/egg/codegen_c.rb | 7 ++++++- lib/egg/typecheck.rb | 16 +++++++++++++--- spec/core.md | 4 +++- test/errors/optional_misuse.egg | 10 ++++++++++ 5 files changed, 53 insertions(+), 5 deletions(-) diff --git a/examples/nested_optional.egg b/examples/nested_optional.egg index d2816ea..7635769 100644 --- a/examples/nested_optional.egg +++ b/examples/nested_optional.egg @@ -15,6 +15,8 @@ // expect: true false // expect: 7 true 5 // expect: 5 -1 +// expect: 5 +// expect: opt ptr other uses io, alloc allow unsafe @@ -48,6 +50,23 @@ fn deref_or(p: ?*i64) i64 { return q.* } +// ??*i64 is bigger than 16 bytes, so it goes by address. +fn deref2(p: ??*i64) i64 { + const q = (p orelse null) orelse return -1 + return q.* +} + +// A type written in place compares like a named one. +fn kind(comptime V: type) str { + if (V == ?i64) { + return "opt" + } + if (V == *i64) { + return "ptr" + } + return "other" +} + fn show(io: Io, x: ??i64) void { io.print((x orelse -2) orelse -1) } @@ -114,5 +133,7 @@ fn main(io: Io, a: Allocator) void { const pp: ??*i64 = &n io.print((small orelse 0) orelse 1, " ", ((color orelse .red) orelse .red) == .green, " ", ((pp orelse null) orelse null).*) io.print(deref_or(&n), " ", deref_or(null)) + io.print(deref2(&n)) + io.print(kind(MaybeInt), " ", kind(*i64), " ", kind(i64)) n = 6 } diff --git a/lib/egg/codegen_c.rb b/lib/egg/codegen_c.rb index 77e6eae..bfd5864 100644 --- a/lib/egg/codegen_c.rb +++ b/lib/egg/codegen_c.rb @@ -4523,7 +4523,12 @@ def call(c_name, args, params, receiver, ret, writes = []) in AddrOf[expr: SliceExpr => s] then slice_expr(s) in AddrOf[expr: place] # A pointer argument may go to a ?*T parameter. - mode == "inout" ? "&#{lvalue(place)}" : coerce("&#{lvalue(place)}", a.ty, pt) + if mode == "inout" || a.ty == pt + "&#{lvalue(place)}" + else + code = coerce("&#{lvalue(place)}", a.ty, pt) + by_ptr?(pt, mode) ? "&#{hoist(code, pt)}" : code + end else if by_ptr?(pt, mode) && a.ty == pt && !a.is_a?(SliceExpr) big_arg(a, later, inouts) diff --git a/lib/egg/typecheck.rb b/lib/egg/typecheck.rb index 4eac613..b78b78f 100644 --- a/lib/egg/typecheck.rb +++ b/lib/egg/typecheck.rb @@ -3141,7 +3141,13 @@ def check_args(sig, args, name, line, col, receivers = [], self_inout: false) t = check_lvalue(a.expr, "pass as inout") mark_root_used(a.expr) a.ty = t - expect_type(pt, t, a) + # The callee writes a pt into the place: it must be one, not a + # value that would be wrapped (an i64 for an inout ?i64). + if t != pt && t != "error" && fits?(pt, t) + err("E103", "parameter #{i + 1} of '#{name}' is an inout #{pt}: pass a #{pt} variable, found #{t}", a.line, a.col) + else + expect_type(pt, t, a) + end path = inout_path(a.expr) inout_roots << [path, a] unless path.nil? elsif slice_expr?(a) @@ -3816,13 +3822,17 @@ def comptime_type(e) end return t end + # ?T, *T, []T written in place (V == ?i64) resolve like a name. name = case e + in TypeExpr[type:] then type in Var[name:] then name in Field[obj: Var[name: m], name:] then "#{m}.#{name}" else return nil end - return @tenv[name] if @tenv.key?(name) - return nil if lookup(name) # a variable + if name.is_a?(String) + return @tenv[name] if @tenv.key?(name) + return nil if lookup(name) # a variable + end before = @diagnostics.length t = resolve_type(name, e.line, e.col) if @diagnostics.length > before || t == "error" diff --git a/spec/core.md b/spec/core.md index d6e3d73..55c93d2 100644 --- a/spec/core.md +++ b/spec/core.md @@ -339,7 +339,9 @@ fn name(p1: T1, inout p2: T2, sink p3: T3, comptime T: type) R { ... } owns nothing is E145, except in a generic instance, where T may or may not own something. - A call must pass exactly as many arguments as there are parameters (E104), - each of the declared type (E103). + each of the declared type (E103). An `inout` argument must be a place of + exactly that type: an `i64` variable does not fit an `inout ?i64`, since + the function writes a `?i64` into it. - **A non-void function must return on every path** (E107). A block returns on every path when at least one of its statements does, where: - `return` always returns; diff --git a/test/errors/optional_misuse.egg b/test/errors/optional_misuse.egg index ab7554c..cd88b22 100644 --- a/test/errors/optional_misuse.egg +++ b/test/errors/optional_misuse.egg @@ -44,6 +44,15 @@ fn push_struct(a: Allocator) void { a.free(h) } +fn clear(inout x: ?i64) void { + x = null +} + +fn wrap_inout() void { + var v: i64 = 3 + clear(&v) +} + fn main() void { } // error: E108 @4 @@ -55,3 +64,4 @@ fn main() void { // error: E113 @29 // error: E103 @34 // error: E103 @43 +// error: E103 @53 From 2b23ae931126b8f98e1d30a4b12c1a98f1d207ec Mon Sep 17 00:00:00 2001 From: femto Date: Fri, 20 Nov 2026 17:22:49 +0800 Subject: [PATCH 5/7] Pointer arguments read their place first; spawn rejects ?[]T parameters - f(&p.*, reset(&p)): the address of a pointer argument is taken before a later argument runs, so it is p's old target, not a null dereference. Both a *T and a converted ?*T argument (the *T case was on main too). - threads.spawn rejects a function taking a ?[]T or ??[]T, as it rejects []T: the thread could outlive the viewed array (on main for ?[]T). Co-Authored-By: Claude Opus 5.5 --- examples/nested_optional.egg | 16 ++++++++++++++++ lib/egg/codegen_c.rb | 16 ++++++++++++---- lib/egg/typecheck.rb | 2 +- test/errors/threads.egg | 11 +++++++---- 4 files changed, 36 insertions(+), 9 deletions(-) diff --git a/examples/nested_optional.egg b/examples/nested_optional.egg index 7635769..7151b0f 100644 --- a/examples/nested_optional.egg +++ b/examples/nested_optional.egg @@ -17,6 +17,7 @@ // expect: 5 -1 // expect: 5 // expect: opt ptr other +// expect: 5 6 uses io, alloc allow unsafe @@ -67,6 +68,17 @@ fn kind(comptime V: type) str { return "other" } +// &p.* reads p before reset sets it to null. +fn reset(inout p: *i64) i64 { + p = null + return 0 +} + +fn add(q: ?*i64, z: i64) i64 { + const r = q orelse return -1 + return r.* + z +} + fn show(io: Io, x: ??i64) void { io.print((x orelse -2) orelse -1) } @@ -135,5 +147,9 @@ fn main(io: Io, a: Allocator) void { io.print(deref_or(&n), " ", deref_or(null)) io.print(deref2(&n)) io.print(kind(MaybeInt), " ", kind(*i64), " ", kind(i64)) + var p = a.create(@as(i64, 5)) + const first_add = add(&p.*, reset(&p)) + p = a.create(@as(i64, 6)) + io.print(first_add, " ", add(&p.*, reset(&p))) n = 6 } diff --git a/lib/egg/codegen_c.rb b/lib/egg/codegen_c.rb index bfd5864..368881c 100644 --- a/lib/egg/codegen_c.rb +++ b/lib/egg/codegen_c.rb @@ -4523,11 +4523,19 @@ def call(c_name, args, params, receiver, ret, writes = []) in AddrOf[expr: SliceExpr => s] then slice_expr(s) in AddrOf[expr: place] # A pointer argument may go to a ?*T parameter. - if mode == "inout" || a.ty == pt - "&#{lvalue(place)}" + addr = "&#{lvalue(place)}" + if mode == "inout" + addr else - code = coerce("&#{lvalue(place)}", a.ty, pt) - by_ptr?(pt, mode) ? "&#{hoist(code, pt)}" : code + # A pointer argument: &p.* reads p now, before a later + # argument can change p. + addr = hoist(addr, a.ty) if later.any? { |l| writes_first?(l) } + if a.ty == pt + addr + else + code = coerce(addr, a.ty, pt) + by_ptr?(pt, mode) ? "&#{hoist(code, pt)}" : code + end end else if by_ptr?(pt, mode) && a.ty == pt && !a.is_a?(SliceExpr) diff --git a/lib/egg/typecheck.rb b/lib/egg/typecheck.rb index b78b78f..efcaba9 100644 --- a/lib/egg/typecheck.rb +++ b/lib/egg/typecheck.rb @@ -2886,7 +2886,7 @@ def check_spawn(e, args, line, col) err("E148", "a thread's function returns nothing, found #{ft.inner}: nobody could use the result yet", args[0].line, args[0].col) unless ft.inner == "void" params = fn_params(ft) params.each do |pt, mode| - lent = mode == "inout" || (mode.nil? && (owned?(pt) || pt.start_with?("[]"))) + lent = mode == "inout" || (mode.nil? && (owned?(pt) || !slice_in(pt).nil?)) next unless lent err("E148", "a thread cannot borrow a #{pt}: it may outlive the owner; take it as `sink`, or pass a copy", args[0].line, args[0].col) end diff --git a/test/errors/threads.egg b/test/errors/threads.egg index 88305d7..a41cb0d 100644 --- a/test/errors/threads.egg +++ b/test/errors/threads.egg @@ -1,13 +1,15 @@ -// error: E148 @17 -// error: E148 @18 // error: E148 @19 // error: E148 @20 -// error: E103 @21 -// error: E104 @22 +// error: E148 @21 +// error: E148 @22 +// error: E103 @23 +// error: E104 @24 +// error: E148 @25 uses alloc, thread fn borrow(b: Buf(i64)) void { _ = @len(b) } fn view(xs: []i64) void { _ = @len(xs) } +fn maybe_view(xs: ?[]i64) void { _ = xs != null } fn change(inout b: Buf(i64)) void { b[0] = 1 } fn answer() i64 { return 1 } fn take(a: Allocator, sink b: Buf(i64)) void { a.free(b) } @@ -20,5 +22,6 @@ fn main(a: Allocator, threads: Threads) void { threads.spawn(answer).join() threads.spawn(1).join() threads.spawn().join() + threads.spawn(maybe_view, b[0..]).join() a.free(b) } From 98eea9973babbb2e38c5df7b73e616e601b72996 Mon Sep 17 00:00:00 2001 From: femto Date: Fri, 20 Nov 2026 17:41:58 +0800 Subject: [PATCH 6/7] @splat and a.alloc wrap their fill into an optional element type const xs: [2]?i8 = @splat(5) and var b: Buf(?i8) = a.alloc(2, 4) failed (the first in the C compiler, the second with E103), on main too. The fill is converted to the element type, and a.alloc takes its element type from the expected buffer. Co-Authored-By: Claude Opus 5.5 --- examples/nested_optional.egg | 8 ++++++++ lib/egg/codegen_c.rb | 4 ++-- lib/egg/typecheck.rb | 3 ++- 3 files changed, 12 insertions(+), 3 deletions(-) diff --git a/examples/nested_optional.egg b/examples/nested_optional.egg index 7151b0f..d838fcb 100644 --- a/examples/nested_optional.egg +++ b/examples/nested_optional.egg @@ -18,6 +18,7 @@ // expect: 5 // expect: opt ptr other // expect: 5 6 +// expect: 5 4 0 uses io, alloc allow unsafe @@ -151,5 +152,12 @@ fn main(io: Io, a: Allocator) void { const first_add = add(&p.*, reset(&p)) p = a.create(@as(i64, 6)) io.print(first_add, " ", add(&p.*, reset(&p))) + + // A fill value is wrapped into the element type, as in a declaration. + const filled: [2]??i8 = @splat(5) + var opts: Buf(?i8) = a.alloc(2, 4) + defer a.free(opts) + a.push(&opts, null) + io.print((filled[1] orelse 0) orelse 0, " ", opts[0] orelse 0, " ", opts[2] orelse 0) n = 6 } diff --git a/lib/egg/codegen_c.rb b/lib/egg/codegen_c.rb index 368881c..0eba4a4 100644 --- a/lib/egg/codegen_c.rb +++ b/lib/egg/codegen_c.rb @@ -5049,7 +5049,7 @@ def cap_call(m, obj, args, ret) line("#{b}.len = #{codes[0]};") line("#{b}.ptr = (#{c_type(elem)} *)#{helper('egg_buf_resize')}(NULL, #{b}.len, sizeof(#{c_type(elem)}));") line("#{b}.cap = #{b}.len;") - v = hoist(codes[1], elem) + v = hoist(coerce(codes[1], args[1].ty, elem), elem) i = tmp line("for (int64_t #{i} = 0; #{i} < #{b}.len; #{i}++) #{b}.ptr[#{i}] = #{v};") b @@ -5259,7 +5259,7 @@ def builtin(e, name, args) "((void)0)" when "splat" info = @types[e.ty] - v = hoist(expr(a), info.elem) + v = hoist(coerce(expr(a), a.ty, info.elem), info.elem) out = tmp i = tmp line("#{c_type(e.ty)} #{out};") diff --git a/lib/egg/typecheck.rb b/lib/egg/typecheck.rb index efcaba9..9257135 100644 --- a/lib/egg/typecheck.rb +++ b/lib/egg/typecheck.rb @@ -3001,7 +3001,8 @@ def check_cap_method(e, obj, t, name, args, line, col, expected = nil) return value_type_error(at, "a Buf element", a.line, a.col) unless storable?(at) return owned_place_error(at, "a Buf element", a.line, a.col) if owned_err?(at) check_empty_fill(a, "a.#{name}") unless name == "push" - ret = buf_type([at], a.line, a.col) if name == "alloc" + # Buf(?i8) from a.alloc(n, 4) where one is expected. + ret = buf_type([elem.nil? ? at : elem], a.line, a.col) if name == "alloc" elsif pt == "buffer" at = check_expr(a) if at != "error" && !owned?(at) && generic_instance? && storable?(at) From 09c91f993bdb5e326a3241c4cc764b573f968af1 Mon Sep 17 00:00:00 2001 From: femto Date: Fri, 20 Nov 2026 18:32:34 +0800 Subject: [PATCH 7/7] @splat fills the array beneath ! and ? levels const xs: ?[3]i64 = @splat(4), ??[3]i64, and `return @splat(2)` in a function returning ![3]i64 were E115 (on main too for ? and !). Co-Authored-By: Claude Opus 5.5 --- examples/nested_optional.egg | 5 +++++ lib/egg/typecheck.rb | 6 ++++-- 2 files changed, 9 insertions(+), 2 deletions(-) diff --git a/examples/nested_optional.egg b/examples/nested_optional.egg index d838fcb..e0d7b1b 100644 --- a/examples/nested_optional.egg +++ b/examples/nested_optional.egg @@ -19,6 +19,7 @@ // expect: opt ptr other // expect: 5 6 // expect: 5 4 0 +// expect: 6 7 uses io, alloc allow unsafe @@ -159,5 +160,9 @@ fn main(io: Io, a: Allocator) void { defer a.free(opts) a.push(&opts, null) io.print((filled[1] orelse 0) orelse 0, " ", opts[0] orelse 0, " ", opts[2] orelse 0) + // @splat fills the array beneath the optional levels. + const arr: ?[3]i64 = @splat(6) + const arr2: ??[3]i64 = @splat(7) + io.print((arr orelse [3]i64{ 0, 0, 0 })[2], " ", ((arr2 orelse null) orelse [3]i64{ 0, 0, 0 })[1]) n = 6 } diff --git a/lib/egg/typecheck.rb b/lib/egg/typecheck.rb index 9257135..d4e8981 100644 --- a/lib/egg/typecheck.rb +++ b/lib/egg/typecheck.rb @@ -4178,7 +4178,9 @@ def check_builtin(e, name, args, expected, line, col) err("E103", "@errorName needs an anyerror (error.X, or e in catch |e|), found #{t}", a.line, a.col) unless t == "anyerror" || t == "error" "str" when "splat" - info = expected.nil? ? nil : @types[expected] + # The array beneath any ! and ? levels; the value is wrapped after. + target = value_target(expected) + info = target.nil? ? nil : @types[target] if info.nil? || info.kind != :array err("E115", "cannot infer the array type for @splat; give the variable a type such as [8]i64", line, col) unless expected == "error" check_expr(a) @@ -4187,7 +4189,7 @@ def check_builtin(e, name, args, expected, line, col) vt = check_expr(a, info.elem) expect_type(info.elem, vt, a) check_empty_fill(a, "@splat") if vt == info.elem - expected + target when "replace", "take" check_swap(name, args, line, col) when "secureZero"