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
2 changes: 1 addition & 1 deletion docs/design.md
Original file line number Diff line number Diff line change
Expand Up @@ -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.
Expand Down
2 changes: 1 addition & 1 deletion docs/design.zh.md
Original file line number Diff line number Diff line change
Expand Up @@ -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]`:它是唯一把元素类型夹在中间的写法,嵌套时要从里往外读。

刻意不进入核心的特性:

Expand Down
168 changes: 168 additions & 0 deletions examples/nested_optional.egg
Original file line number Diff line number Diff line change
@@ -0,0 +1,168 @@
// ??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
// expect: a
// expect: true false
// expect: 7 true 5
// expect: 5 -1
// expect: 5
// expect: opt ptr other
// expect: 5 6
// expect: 5 4 0
// expect: 6 7
uses io, alloc
allow unsafe

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) {
return null
}
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 deref_or(p: ?*i64) i64 {
const q = p orelse return -1
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"
}

// &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)
}

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)

if (head("abc", true)) |inner| {
if (inner) |c| {
io.print(c)
}
}
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))
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)))

// 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)
// @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
}
23 changes: 19 additions & 4 deletions lib/egg/codegen_c.rb
Original file line number Diff line number Diff line change
Expand Up @@ -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} })"
Expand Down Expand Up @@ -4521,7 +4521,22 @@ 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.
addr = "&#{lvalue(place)}"
if mode == "inout"
addr
else
# 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)
big_arg(a, later, inouts)
Expand Down Expand Up @@ -5034,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
Expand Down Expand Up @@ -5244,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};")
Expand Down
2 changes: 1 addition & 1 deletion lib/egg/own.rb
Original file line number Diff line number Diff line change
Expand Up @@ -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

Expand Down
5 changes: 3 additions & 2 deletions lib/egg/parser.rb
Original file line number Diff line number Diff line change
Expand Up @@ -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
Expand Down
Loading
Loading