cli: validate Copy content of source owning arrays

This commit is contained in:
dev committed 2026-10-08 09:01:58 +03:00
1 parent caf3b86e80
commit cfbe01a16f
42 files changed
+608 -3

No files matched your search

+13 -1
View File
@@ -3,6 +3,7 @@ const std = @import("std");
const ast = @import("ast.zig");
const lower = @import("lower.zig");
const type_positions = @import("type_positions.zig");
const type_properties = @import("type_properties.zig");
const authority = @import("../air/authority.zig");
const A = std.mem.Allocator;
const Error = error{ OutOfMemory, InvalidGeneric };
@@ -189,7 +190,18 @@ const Generator = struct {
}) };
return error.InvalidGeneric;
}
return g.headerType(t, params, depth);
try g.headerType(t, params, depth);
if (try type_properties.firstInvalid(t, g, propertyDecl, params)) |bad| {
g.problem = .{ .code = "E7005", .span = bad.span, .message = "dynamic heap arrays require Copy content", .fields = try g.arena.dupe(lower.Problem.Field, &.{
.{ .name = "constraint", .value = "Copy" },
.{ .name = "type_constructor", .value = "own_array" },
}) };
return error.InvalidGeneric;
}
}
fn propertyDecl(g: *Generator, name: []const u8, span: ast.Span) ?ast.TypeDecl {
return g.typeDecl(name, span);
}
fn headerType(g: *Generator, t: ast.Type, params: []const ast.TypeParam, depth: usize) Error!void {
+21 -1
View File
@@ -32,6 +32,7 @@ const features_mod = @import("../air/features.zig");
const air_module = @import("../air/module.zig");
const verifier_types = @import("../verifier/types.zig");
const type_positions = @import("type_positions.zig");
const type_properties = @import("type_properties.zig");
const Allocator = std.mem.Allocator;
const Span = ast.Span;
@@ -325,6 +326,8 @@ const Lowerer = struct {
fns: std.ArrayList(FnOut) = .empty,
linear_enabled: bool = false,
/// Complete declaration snapshot, with finite layouts checked before bodies.
property_module: ?air_module.Module = null,
fn probeType(l: *Lowerer, t: ast.Type) ?Ty {
const previous = l.problem;
@@ -343,6 +346,7 @@ const Lowerer = struct {
fn isLinear(l: *Lowerer, t: Ty) bool {
return l.linearAt(t, 0);
}
fn linearAt(l: *Lowerer, t: Ty, depth: usize) bool {
if (t.isLinear()) return true;
if (depth > l.m.types.len + 32) return false;
@@ -559,6 +563,7 @@ const Lowerer = struct {
const d = l.m.types[layout_context.diags.items[0].span.?.line - 1];
return l.fail("E1003", d.span, "aggregate type contains itself by value", &.{.{ .name = "type", .value = d.display_name orelse d.name }});
}
l.property_module = m;
for (l.m.requirements) |r| {
const ty = try l.typeOf(r.ty);
const t = try l.airType(ty);
@@ -682,7 +687,21 @@ const Lowerer = struct {
.{ .name = "position", .value = @tagName(bad.position) },
.{ .name = "type_constructor", .value = bad.constructor },
});
return l.resolveType(t);
const ty = try l.resolveType(t);
if (try type_properties.firstInvalid(t, l, propertyDecl, &.{})) |bad| return l.copyArrayError(bad.span);
return ty;
}
fn propertyDecl(l: *Lowerer, name: []const u8, span: Span) ?ast.TypeDecl {
const ty = l.enumOrStruct(name, span) orelse return null;
return l.m.types[ty.named];
}
fn copyArrayError(l: *Lowerer, span: Span) Error {
return l.fail("E7005", span, "dynamic heap arrays require Copy content", &.{
.{ .name = "constraint", .value = "Copy" },
.{ .name = "type_constructor", .value = "own_array" },
});
}
fn resolveType(l: *Lowerer, t: ast.Type) Error!Ty {
@@ -3242,6 +3261,7 @@ const Lowerer = struct {
const n = try l.expr(args[0], usize_ty);
try l.checkTy(args[0].span, n.ty, usize_ty);
const v = try l.consuming(args[1], null);
if (!verifier_types.isCopy(l.property_module.?, try l.airType(v.ty))) return l.copyArrayError(args[1].span);
const c = try l.expectCap(args[2], "mem.alloc");
return .{ .text = try l.fmt("own.array %{s}, %{s}, %{s}", .{ n.name, v.name, c.name }), .outcomes = try l.outs(&.{ .{ .role = "ok", .params = &.{try l.wrap(.own_array, v.ty)} }, .{ .role = "err", .params = &.{alloc_err} } }) };
}
+150
View File
@@ -0,0 +1,150 @@
//! Known structural linearity without resolving types or specializing templates.
//! Unknown parameters add no known linear leaf; iref content is phantom.
const std = @import("std");
const ast = @import("ast.zig");
const Env = struct {
params: []const ast.TypeParam,
known_linear: []const bool = &.{},
};
// Parameter states, rather than argument syntax, distinguish rotations along
// recursive generic edges. Repeated states add no new known linear leaf.
const Path = struct { name: []const u8, known_linear: []const bool, parent: ?*const Path };
const Memo = struct {
entries: std.ArrayList(struct { name: []const u8, known_linear: []const bool, value: bool, generation: usize }) = .empty,
generation: usize = 0,
};
pub fn firstInvalid(t: ast.Type, context: anytype, lookup: anytype, params: []const ast.TypeParam) std.mem.Allocator.Error!?ast.Type {
switch (t.kind) {
.wrapped => |w| {
if (std.mem.eql(u8, w.wrapper, "own_array")) {
var memo: Memo = .{};
while (true) {
const generation = memo.generation;
if (try linear(w.inner.*, context, lookup, &.{ .params = params }, null, &memo)) return w.inner.*;
if (generation == memo.generation) break;
}
}
// Graph well-formedness keeps its independently specified E2111.
for ([_][]const u8{ "island", "frozen", "arc" }) |tag| if (std.mem.eql(u8, w.wrapper, tag)) return null;
return firstInvalid(w.inner.*, context, lookup, params);
},
.array => |a| return firstInvalid(a.elem.*, context, lookup, params),
else => return null,
}
}
fn linear(t: ast.Type, context: anytype, lookup: anytype, env: *const Env, path: ?*const Path, memo: *Memo) std.mem.Allocator.Error!bool {
switch (t.kind) {
.file => return true,
.wrapped => |w| {
for ([_][]const u8{ "own", "own_array", "buffer", "task", "sender", "receiver", "mutex", "island", "frozen", "arc", "atomic" }) |tag| if (std.mem.eql(u8, w.wrapper, tag)) return true;
return false;
},
.array => |a| return linear(a.elem.*, context, lookup, env, path, memo),
.name => |name| {
for (env.params, 0..) |p, i| if (std.mem.eql(u8, p.name, name)) {
return i < env.known_linear.len and env.known_linear[i];
};
if (lookup(context, name, t.span)) |d| return declaration(d, &.{}, context, lookup, env, path, memo);
for ([_][]const u8{ "region", "stream", "listener" }) |tag| if (std.mem.eql(u8, name, tag)) return true;
return false;
},
.applied => |a| {
const d = lookup(context, a.name, t.span) orelse return false;
return declaration(d, a.args, context, lookup, env, path, memo);
},
else => return false,
}
}
fn declaration(d: ast.TypeDecl, args: []const ast.Type, context: anytype, lookup: anytype, env: *const Env, path: ?*const Path, memo: *Memo) std.mem.Allocator.Error!bool {
const generation = memo.generation;
const known = try context.arena.alloc(bool, d.generics.len);
for (known, 0..) |*flag, i| flag.* = i < args.len and try linear(args[i], context, lookup, env, path, memo);
for (memo.entries.items) |entry| if ((entry.value or entry.generation == memo.generation) and std.mem.eql(u8, entry.name, d.name) and std.mem.eql(bool, entry.known_linear, known)) return entry.value;
var previous = path;
while (previous) |p| : (previous = p.parent) {
if (std.mem.eql(u8, p.name, d.name) and std.mem.eql(bool, p.known_linear, known)) {
return false;
}
}
const next: Path = .{ .name = d.name, .known_linear = known, .parent = path };
const bound: Env = .{ .params = d.generics, .known_linear = known };
const value = switch (d.kind) {
.@"struct" => |fs| for (fs) |f| {
if (try linear(f.ty, context, lookup, &bound, &next, memo)) break true;
} else false,
.@"enum" => |vs| result: {
for (vs) |v| for (v.payload) |t| {
if (try linear(t, context, lookup, &bound, &next, memo)) break :result true;
};
break :result false;
},
};
// Positive witnesses are final. Learning one invalidates provisional
// negatives, including cycles whose back edge could reach that witness.
// A negative root is queried again until no new positive proof is learned.
if (value) memo.generation += 1;
try memo.entries.append(context.arena, .{ .name = d.name, .known_linear = known, .value = value, .generation = if (value) memo.generation else generation });
return value;
}
test "Copy-content query shares completed diamond branches" {
var arena_state = std.heap.ArenaAllocator.init(std.testing.allocator);
defer arena_state.deinit();
const arena = arena_state.allocator();
var source: std.ArrayList(u8) = .empty;
try source.appendSlice(arena, "module diamond\n");
for (0..64) |i| {
const child = if (i == 63) "u64" else try std.fmt.allocPrint(arena, "N{d}", .{i + 1});
try source.appendSlice(arena, try std.fmt.allocPrint(arena, "struct N{d} {{ a: {s}, b: {s} }}\n", .{ i, child, child }));
}
try source.appendSlice(arena, "fn unused(p: own_array<N0>) -> void effects [] { trap; }\nfn main() -> void effects [] {}\n");
const parsed = try @import("parse.zig").parse(arena, source.items);
try std.testing.expect(parsed == .ok);
const Probe = struct {
arena: std.mem.Allocator,
module: ast.Module,
lookups: usize = 0,
fn lookup(p: *@This(), name: []const u8, _: ast.Span) ?ast.TypeDecl {
p.lookups += 1;
for (p.module.types) |d| if (std.mem.eql(u8, d.name, name)) return d;
return null;
}
};
var probe: Probe = .{ .arena = arena, .module = parsed.ok };
try std.testing.expect(try firstInvalid(parsed.ok.functions[0].params[0].ty, &probe, Probe.lookup, &.{}) == null);
// An unshared walk visits 2^64 branches. Count queries, not elapsed time.
try std.testing.expect(probe.lookups <= 130);
}
test "Copy-content query shares cyclic diamond branches" {
var arena_state = std.heap.ArenaAllocator.init(std.testing.allocator);
defer arena_state.deinit();
const arena = arena_state.allocator();
var source: std.ArrayList(u8) = .empty;
try source.appendSlice(arena, "module diamond\n");
for (0..10) |i| {
const child = if (i == 9) "N0" else try std.fmt.allocPrint(arena, "N{d}", .{i + 1});
try source.appendSlice(arena, try std.fmt.allocPrint(arena, "struct N{d} {{ a: {s}, b: {s} }}\n", .{ i, child, child }));
}
try source.appendSlice(arena, "fn unused(p: own_array<N0>) -> void effects [] { trap; }\nfn main() -> void effects [] {}\n");
const parsed = try @import("parse.zig").parse(arena, source.items);
try std.testing.expect(parsed == .ok);
const Probe = struct {
arena: std.mem.Allocator,
module: ast.Module,
lookups: usize = 0,
fn lookup(p: *@This(), name: []const u8, _: ast.Span) ?ast.TypeDecl {
p.lookups += 1;
for (p.module.types) |d| if (std.mem.eql(u8, d.name, name)) return d;
return null;
}
};
var probe: Probe = .{ .arena = arena, .module = parsed.ok };
try std.testing.expect(try firstInvalid(parsed.ok.functions[0].params[0].ty, &probe, Probe.lookup, &.{}) == null);
// An unshared walk repeats every path to the same cycle. Count queries, not elapsed time.
try std.testing.expect(probe.lookups <= 22);
}