Files
aji/src/frontend.zig
T

260 lines
12 KiB
Zig

//! `.aji` frontend (spec 15): source → canonical text AIR + line map.
//! Outside the trusted computing base: its output is checked by the
//! normative verifier like any other AIR.
const std = @import("std");
const diag = @import("diag.zig");
pub const lex = @import("frontend/lex.zig");
pub const ast = @import("frontend/ast.zig");
pub const parse = @import("frontend/parse.zig");
pub const lower_mod = @import("frontend/lower.zig");
pub const generics = @import("frontend/generics.zig");
pub const modules = @import("frontend/modules.zig");
pub const stdlib = @import("frontend/stdlib.zig");
pub const format = @import("frontend/format.zig");
pub const Span = ast.Span;
pub const Compiled = union(enum) {
/// Canonical AIR, its line map and the annotated form.
ok: lower_mod.Output,
/// A single source diagnostic; declaration-wide failures stop the phase.
err: diag.Diagnostic,
/// Independent source diagnostics; no partial AIR is exposed.
errors: []const diag.Diagnostic,
unimplemented: []const u8,
};
pub fn compile(arena: std.mem.Allocator, file: []const u8, source: []const u8) std.mem.Allocator.Error!Compiled {
return compileWithModules(arena, file, source, &.{});
}
pub fn compileWithModules(arena: std.mem.Allocator, file: []const u8, source: []const u8, sources: []const modules.Source) std.mem.Allocator.Error!Compiled {
const parsed = try parse.parse(arena, source);
const m = switch (parsed) {
.ok => |m| m,
.err => |f| return .{ .err = try syntaxDiagnostic(arena, file, f) },
.errors => |fs| return diagnosticResult(try syntaxDiagnostics(arena, file, fs)),
};
const linked = try modules.link(arena, m, sources);
const result = switch (linked) {
.ok => |combined| switch (try generics.specialize(arena, combined)) {
.ok => |concrete| try lower_mod.lower(arena, concrete),
.err => |p| lower_mod.Result{ .err = p },
},
.err => |p| lower_mod.Result{ .err = p },
.errors => |ps| lower_mod.Result{ .errors = ps },
};
return switch (result) {
.ok => |o| .{ .ok = o },
.err => |p| .{ .err = try problemDiagnostic(arena, file, p) },
.errors => |ps| blk: {
const ds = try arena.alloc(diag.Diagnostic, ps.len);
for (ps, ds) |p, *d| d.* = try problemDiagnostic(arena, file, p);
break :blk diagnosticResult(deduplicate(ds));
},
.unimplemented => |u| .{ .unimplemented = try std.fmt.allocPrint(arena, "{s}:{d}:{d}: {s}", .{ u.span.file orelse file, u.span.start.line, u.span.start.col, u.construct }) },
};
}
fn problemDiagnostic(arena: std.mem.Allocator, file: []const u8, p: lower_mod.Problem) std.mem.Allocator.Error!diag.Diagnostic {
const fields = try arena.alloc(diag.Field, p.fields.len + @intFromBool(p.reason != null));
for (p.fields, fields[0..p.fields.len]) |pf, *f| f.* = .{ .name = pf.name, .value = .{ .str = pf.value } };
if (p.reason) |reason| fields[p.fields.len] = .{ .name = "reason", .value = .{ .str = @tagName(reason) } };
return .{
.code = diag.lookup(p.code).?,
.span = .{ .file = p.span.file orelse file, .line = p.span.start.line, .col = p.span.start.col },
.message = p.message,
.fields = fields,
.repair_candidates = if (std.mem.eql(u8, p.code, "E7900")) &.{} else p.repair_candidates,
};
}
fn diagnosticResult(ds: []const diag.Diagnostic) Compiled {
for (ds) |d| if (std.mem.eql(u8, d.code.id, "E7900")) return .{ .err = d };
return if (ds.len == 1) .{ .err = ds[0] } else .{ .errors = ds };
}
fn deduplicate(ds: []diag.Diagnostic) []const diag.Diagnostic {
var count: usize = 0;
for (ds) |d| {
const duplicate = for (ds[0..count]) |prior| {
const a = d.span.?;
const b = prior.span.?;
if (d.code == prior.code and a.line == b.line and a.col == b.col and std.mem.eql(u8, a.file, b.file)) break true;
} else false;
if (!duplicate) {
ds[count] = d;
count += 1;
}
}
return ds[0..count];
}
pub fn syntaxDiagnostics(arena: std.mem.Allocator, file: []const u8, failures: []const parse.Failure) std.mem.Allocator.Error![]const diag.Diagnostic {
const ds = try arena.alloc(diag.Diagnostic, failures.len);
for (failures, ds) |f, *d| d.* = try syntaxDiagnostic(arena, file, f);
return deduplicate(ds);
}
pub fn syntaxDiagnostic(arena: std.mem.Allocator, file: []const u8, f: parse.Failure) std.mem.Allocator.Error!diag.Diagnostic {
return .{
.code = diag.lookup("E7001").?,
.span = .{ .file = file, .line = f.pos.line, .col = f.pos.col },
.message = try std.fmt.allocPrint(arena, "expected {s}", .{f.expected}),
.repair_candidates = f.repair_candidates,
.fields = try arena.dupe(diag.Field, &.{
.{ .name = "expected", .value = .{ .str = f.expected } },
.{ .name = "found", .value = .{ .str = f.found } },
}),
};
}
/// Moves a diagnostic on lowered AIR to its source location; the AIR
/// location stays as `air_line`/`air_col` metadata (spec 15 §10).
pub fn mapDiagnostic(arena: std.mem.Allocator, d: diag.Diagnostic, file: []const u8, lines: []const ?Span) std.mem.Allocator.Error!diag.Diagnostic {
var out = d;
if (d.related_locations.len != 0) {
const related = try arena.dupe(diag.RelatedLocation, d.related_locations);
for (related) |*r| {
const origin = r.span orelse continue;
r.air_span = origin;
const source: ?Span = if (origin.line >= 1 and origin.line <= lines.len) lines[origin.line - 1] else null;
r.span = if (source) |s| .{ .file = s.file orelse file, .line = s.start.line, .col = s.start.col } else null;
}
out.related_locations = related;
}
const sp = d.span orelse return out;
const fields = try arena.alloc(diag.Field, d.fields.len + 2);
@memcpy(fields[0..d.fields.len], d.fields);
fields[d.fields.len] = .{ .name = "air_line", .value = .{ .int = sp.line } };
fields[d.fields.len + 1] = .{ .name = "air_col", .value = .{ .int = sp.col } };
out.fields = fields;
const src: ?Span = if (sp.line >= 1 and sp.line <= lines.len) lines[sp.line - 1] else null;
out.span = .{ .file = if (src) |s| s.file orelse file else file, .line = if (src) |s| s.start.line else 1, .col = if (src) |s| s.start.col else 1 };
return out;
}
test {
_ = lex;
_ = parse;
_ = lower_mod;
_ = format;
}
test "related AIR positions map independently with no guessed source fallback" {
var a: std.heap.ArenaAllocator = .init(std.testing.allocator);
defer a.deinit();
const lines: []const ?Span = &.{
.{ .file = "entry.aji", .start = .{ .line = 8, .col = 9 }, .end = .{ .line = 8, .col = 10 } },
.{ .file = "dep.aji", .start = .{ .line = 3, .col = 5 }, .end = .{ .line = 3, .col = 6 } },
null,
};
const mapped = try mapDiagnostic(a.allocator(), .{
.code = diag.lookup("E2101").?,
.span = .{ .file = "lowered.air", .line = 1, .col = 5 },
.related_locations = &.{
.{ .role = .conflicting_borrow, .value = "%a", .span = .{ .file = "lowered.air", .line = 2, .col = 7 } },
.{ .role = .task_spawn, .value = "%b", .span = .{ .file = "lowered.air", .line = 3, .col = 5 } },
.{ .role = .task_spawn, .value = "%c", .span = .{ .file = "lowered.air", .line = 99, .col = 5 } },
},
}, "fallback.aji", lines);
try std.testing.expectEqualStrings("entry.aji", mapped.span.?.file);
try std.testing.expectEqual(@as(u32, 8), mapped.span.?.line);
const located = mapped.related_locations[0];
try std.testing.expectEqualStrings("dep.aji", located.span.?.file);
try std.testing.expectEqual(@as(u32, 3), located.span.?.line);
try std.testing.expectEqual(@as(u32, 5), located.span.?.col);
try std.testing.expectEqual(@as(u32, 2), located.air_span.?.line);
try std.testing.expectEqual(@as(u32, 7), located.air_span.?.col);
for (mapped.related_locations[1..], [_]u32{ 3, 99 }) |related, line| {
try std.testing.expect(related.span == null);
try std.testing.expectEqual(line, related.air_span.?.line);
}
}
pub const Size = struct { bytes: usize, lines: usize };
/// AIR size with every byte-string materialization (the instructions from
/// its `local.zero` to its final `borrow.end`) replaced by one notional
/// line ` const.bytes %<storage>, b"<canonical literal>"` (spec 15 §11).
/// Blank lines are not counted, as for the raw size.
pub fn normalizedSize(arena: std.mem.Allocator, o: lower_mod.Output) std.mem.Allocator.Error!Size {
var size: Size = .{ .bytes = 0, .lines = 0 };
var it = std.mem.splitScalar(u8, o.air, '\n');
var i: usize = 0;
var last: u32 = 0;
while (it.next()) |ln| : (i += 1) {
const k: u32 = if (i < o.constant_of.len) o.constant_of[i] else 0;
if (k != 0) {
if (k != last) {
const c = o.constants[k - 1];
const text = try std.fmt.allocPrint(arena, " const.bytes %{s}, {s}", .{ c.storage, try canonicalBytes(arena, c.bytes) });
size.bytes += text.len + 1;
size.lines += 1;
}
last = k;
continue;
}
last = 0;
if (std.mem.trim(u8, ln, " \t\r").len == 0) continue;
size.bytes += ln.len + 1;
size.lines += 1;
}
return size;
}
/// `b"…"` with printable ASCII as is and `\n \r \t \0 \\ \" \xNN` otherwise.
pub fn canonicalBytes(arena: std.mem.Allocator, bytes: []const u8) std.mem.Allocator.Error![]const u8 {
var out: std.ArrayList(u8) = .empty;
try out.appendSlice(arena, "b\"");
for (bytes) |c| switch (c) {
'\n' => try out.appendSlice(arena, "\\n"),
'\r' => try out.appendSlice(arena, "\\r"),
'\t' => try out.appendSlice(arena, "\\t"),
0 => try out.appendSlice(arena, "\\0"),
'\\' => try out.appendSlice(arena, "\\\\"),
'"' => try out.appendSlice(arena, "\\\""),
0x20...0x21, 0x23...0x5b, 0x5d...0x7e => try out.append(arena, c),
else => try out.print(arena, "\\x{x:0>2}", .{c}),
};
try out.append(arena, '"');
return out.items;
}
test canonicalBytes {
var a = std.heap.ArenaAllocator.init(std.testing.allocator);
defer a.deinit();
try std.testing.expectEqualStrings("b\"hi\\n\\\"\\x01\"", try canonicalBytes(a.allocator(), "hi\n\"\x01"));
}
test "unknown effect names are source errors before AIR in ordinary and template contracts" {
var arena: std.heap.ArenaAllocator = .init(std.testing.allocator);
defer arena.deinit();
const a = arena.allocator();
for ([_][]const u8{
"fn bad() -> void effects [bogus.effect] {}",
"fn bad<T>(x: T) -> T effects [bogus.effect] { return x; }",
"fn bad<F: fn(u64) -> u64 effects [bogus.effect]>() -> void effects [] {}",
"struct Bad<F: fn(u64) -> u64 effects [bogus.effect]> { value: u64 }",
}, 0..) |declaration, i| {
const source = try std.fmt.allocPrint(a, "module test.effects\n{s}\nfn main() -> u64 effects [] {{ return 42; }}", .{declaration});
const r = try compile(a, "effects.aji", source);
try std.testing.expect(r == .err);
try std.testing.expectEqualStrings("E7002", r.err.code.id);
try std.testing.expectEqualStrings("effects.aji", r.err.span.?.file);
try std.testing.expectEqual(@as(u32, 2), r.err.span.?.line);
const col: u32 = if (i == 2) 8 else if (i == 3) 12 else 1;
try std.testing.expectEqual(col, r.err.span.?.col);
try std.testing.expectEqual(@as(usize, 2), r.err.fields.len);
for (r.err.fields) |field| {
try std.testing.expect(std.mem.eql(u8, field.name, "name") or std.mem.eql(u8, field.name, "effect"));
try std.testing.expectEqualStrings("bogus.effect", field.value.str);
}
}
for (@import("air/authority.zig").effects) |effect| {
const source = try std.fmt.allocPrint(a, "module test.effects\nfn unused() -> void effects [{s}] {{}}\nfn main() -> u64 effects [] {{ return 42; }}", .{effect.name});
try std.testing.expect((try compile(a, "effects.aji", source)) == .ok);
}
}