//! Pure linking of explicit source inputs; no filesystem or authority. const std = @import("std"); const ast = @import("ast.zig"); const parse = @import("parse.zig"); const lower = @import("lower.zig"); const stdlib = @import("stdlib.zig"); const authority = @import("../air/authority.zig"); pub const Source = stdlib.Source; pub const Result = union(enum) { ok: ast.Module, err: lower.Problem, errors: []const lower.Problem }; const Error = error{ OutOfMemory, InvalidSource }; const Node = struct { module: ast.Module, active: bool, height: usize = 0 }; pub fn reserved(name: []const u8) bool { const first = if (std.mem.indexOfScalar(u8, name, '.')) |at| name[0..at] else name; for ([_][]const u8{ "std", "slice", "buffer", "own", "region", "cap", "task", "channel", "mutex", "island", "frozen", "arc", "atomic" }) |word| { if (std.mem.eql(u8, first, word)) return true; } for (authority.intrinsics) |intrinsic| { const at = std.mem.indexOfScalar(u8, intrinsic.name, '.').?; if (std.mem.eql(u8, first, intrinsic.name[0..at])) return true; } return false; } pub fn link(arena: std.mem.Allocator, entry: ast.Module, sources: []const Source) std.mem.Allocator.Error!Result { var g: Graph = .{ .arena = arena, .sources = sources }; const span: ast.Span = if (entry.functions.len != 0) entry.functions[0].span else .{ .start = .{ .line = 1, .col = 1 }, .end = .{ .line = 1, .col = 1 } }; const combined = g.run(entry, span) catch |err| switch (err) { error.OutOfMemory => return error.OutOfMemory, error.InvalidSource => return if (g.problems.len > 1) .{ .errors = g.problems } else .{ .err = g.problem.? }, }; return .{ .ok = combined }; } const Graph = struct { arena: std.mem.Allocator, sources: []const Source, nodes: std.ArrayList(Node) = .empty, problem: ?lower.Problem = null, problems: []const lower.Problem = &.{}, fn syntaxFailures(g: *Graph, source: Source, failures: []const parse.Failure) Error { const internal = std.mem.startsWith(u8, source.name, "std."); const problems = try g.arena.alloc(lower.Problem, if (internal) 1 else failures.len); for (failures[0..problems.len], problems) |failure, *problem| problem.* = .{ .code = if (internal) "E7900" else "E7001", .span = .{ .start = failure.pos, .end = failure.pos, .file = source.file, .namespace = source.name }, .message = try std.fmt.allocPrint(g.arena, "expected {s}", .{failure.expected}), .fields = try g.arena.dupe(lower.Problem.Field, &.{ .{ .name = "expected", .value = failure.expected }, .{ .name = "found", .value = failure.found } }), .repair_candidates = if (internal) &.{} else failure.repair_candidates, }; g.problem = problems[0]; g.problems = problems; return error.InvalidSource; } fn fail(g: *Graph, comptime code: []const u8, span: ast.Span, message: []const u8, name: []const u8) Error { if (comptime std.mem.eql(u8, code, "E7006")) @compileError("E7006 requires an explicit reason via invalid()"); g.problem = .{ .code = code, .span = span, .message = message, .fields = g.arena.dupe(lower.Problem.Field, &.{.{ .name = "name", .value = name }}) catch return error.OutOfMemory }; return error.InvalidSource; } fn invalid(g: *Graph, reason: lower.InvalidReason, span: ast.Span, message: []const u8, name: []const u8) Error { g.problem = .{ .code = "E7006", .reason = reason, .span = span, .message = message, .fields = g.arena.dupe(lower.Problem.Field, &.{.{ .name = "name", .value = name }}) catch return error.OutOfMemory }; return error.InvalidSource; } fn run(g: *Graph, entry: ast.Module, span: ast.Span) Error!ast.Module { if (g.sources.len > 1024) return g.invalid(.invalid_module_mapping, span, "more than 1024 mapped modules", entry.name); for (g.sources, 0..) |source, i| { if (reserved(source.name)) return g.invalid(.invalid_module_mapping, span, "package mapping uses a reserved namespace", source.name); for (g.sources[0..i]) |previous| if (std.mem.eql(u8, previous.name, source.name)) return g.invalid(.invalid_module_mapping, span, "module mapped twice", source.name); } try g.nodes.append(g.arena, .{ .module = entry, .active = true }); const root_height = try g.imports(entry, 0); g.nodes.items[0].height = root_height; g.nodes.items[0].active = false; std.mem.sort(Node, g.nodes.items[1..], {}, struct { fn less(_: void, a: Node, b: Node) bool { return std.mem.lessThan(u8, a.module.name, b.module.name); } }.less); var types: std.ArrayList(ast.TypeDecl) = .empty; var functions: std.ArrayList(ast.FnDecl) = .empty; var scopes: std.ArrayList(ast.ModuleScope) = .empty; try types.appendSlice(g.arena, entry.types); try functions.appendSlice(g.arena, entry.functions); for (g.nodes.items, 0..) |node, i| { const m = node.module; try scopes.append(g.arena, .{ .name = m.name, .entry = i == 0, .qualified_self = i != 0 or !reserved(m.name), .imports = m.imports }); if (i == 0) continue; for (m.types) |t| { var qualified = t; qualified.name = try std.fmt.allocPrint(g.arena, "{s}.{s}", .{ m.name, t.name }); qualified.air_name = try airName(g.arena, m.name, t.name, types.items, functions.items); try types.append(g.arena, qualified); } for (m.functions) |f| { var qualified = f; qualified.name = try std.fmt.allocPrint(g.arena, "{s}.{s}", .{ m.name, f.name }); qualified.air_name = try airName(g.arena, m.name, f.name, types.items, functions.items); try functions.append(g.arena, qualified); } } var result = entry; result.types = types.items; result.functions = functions.items; result.scopes = scopes.items; return result; } fn imports(g: *Graph, m: ast.Module, depth: usize) Error!usize { var height: usize = 0; for (m.imports, 0..) |imp, i| { for (m.imports[0..i]) |previous| if (std.mem.eql(u8, imp.path, previous.path)) return g.invalid(.duplicate_import, imp.span, "module imported twice", imp.path); height = @max(height, 1 + try g.visit(imp, depth + 1)); } return height; } fn visit(g: *Graph, imp: ast.Import, depth: usize) Error!usize { for (g.nodes.items) |node| if (std.mem.eql(u8, node.module.name, imp.path)) { if (node.active) return g.invalid(.import_cycle, imp.span, "cyclic module import", imp.path); if (depth + node.height > 256) return g.invalid(.implementation_limit, imp.span, "module import depth exceeds 256", imp.path); return node.height; }; if (depth > 256) return g.invalid(.implementation_limit, imp.span, "module import depth exceeds 256", imp.path); const source = for (stdlib.registry) |source| { if (std.mem.eql(u8, source.name, imp.path)) break source; } else for (g.sources) |source| { if (std.mem.eql(u8, source.name, imp.path)) break source; } else return g.fail("E7002", imp.span, "unknown module in explicit source mapping", imp.path); const m = switch (try parse.parseWithFile(g.arena, source.source, source.file)) { .ok => |m| m, .err => |failure| return g.syntaxFailures(source, &.{failure}), .errors => |failures| return g.syntaxFailures(source, failures), }; if (!std.mem.eql(u8, m.name, source.name)) return g.invalid(.module_header_mismatch, .{ .start = .{ .line = 1, .col = 1 }, .end = .{ .line = 1, .col = 1 }, .file = source.file, .namespace = source.name }, "module header differs from its mapped name", source.name); const index = g.nodes.items.len; try g.nodes.append(g.arena, .{ .module = m, .active = true }); const height = try g.imports(m, depth); g.nodes.items[index].height = height; g.nodes.items[index].active = false; return g.nodes.items[index].height; } }; fn airName(arena: std.mem.Allocator, module: []const u8, name: []const u8, types: []const ast.TypeDecl, functions: []const ast.FnDecl) std.mem.Allocator.Error![]const u8 { const base = try std.fmt.allocPrint(arena, "__aji_{s}_{s}", .{ module, name }); for (base) |*c| if (c.* == '.') { c.* = '_'; }; var candidate: []const u8 = base; var suffix: usize = 0; while (used(types, functions, candidate)) { suffix += 1; candidate = try std.fmt.allocPrint(arena, "{s}_{d}", .{ base, suffix }); } return candidate; } fn used(types: []const ast.TypeDecl, functions: []const ast.FnDecl, name: []const u8) bool { for (types) |t| if (std.mem.eql(u8, t.air_name orelse t.name, name)) return true; for (functions) |f| if (std.mem.eql(u8, f.air_name orelse f.name, name)) return true; return false; } test "std syntax lists become exactly one internal error without advice" { var arena: std.heap.ArenaAllocator = .init(std.testing.allocator); defer arena.deinit(); const a = arena.allocator(); const failures: []const parse.Failure = &.{ .{ .pos = .{ .line = 2, .col = 3 }, .expected = "an expression", .found = "!", .repair_candidates = @import("../diag.zig").SourceRepairKind.one(.boolean_negation) }, .{ .pos = .{ .line = 3, .col = 4 }, .expected = "an expression", .found = "!", .repair_candidates = @import("../diag.zig").SourceRepairKind.one(.boolean_negation) }, }; var g: Graph = .{ .arena = a, .sources = &.{} }; try std.testing.expectEqual(error.InvalidSource, g.syntaxFailures(.{ .name = "std.bytes", .file = "", .source = "" }, failures)); try std.testing.expectEqual(@as(usize, 1), g.problems.len); try std.testing.expectEqualStrings("E7900", g.problem.?.code); try std.testing.expectEqualStrings("", g.problem.?.span.file.?); try std.testing.expectEqual(failures[0].pos, g.problem.?.span.start); try std.testing.expectEqual(@as(usize, 0), g.problem.?.repair_candidates.len); }