frontend: collect independent source diagnostics without cascades
This commit is contained in:
1 parent
2c6c7a3dcd
commit
4cda44823d
47 files changed
+697
-44
No files matched your search
@@ -38,6 +38,7 @@ pub fn checkWithModules(arena: std.mem.Allocator, file_name: []const u8, source:
|
||||
const lowered = switch (try frontend.compileWithModules(arena, file_name, source, sources)) {
|
||||
.ok => |o| o,
|
||||
.err => |d| return .{ .status = .rejected, .diagnostics = try arena.dupe(diag.Diagnostic, &.{d}) },
|
||||
.errors => |ds| return .{ .status = .rejected, .diagnostics = ds },
|
||||
.unimplemented => |what| return .{ .status = .unimplemented, .diagnostics = &.{}, .missing_stage = what },
|
||||
};
|
||||
return checkLowered(arena, file_name, lowered);
|
||||
|
||||
@@ -163,6 +163,9 @@ pub const RepairCandidate = struct {
|
||||
alternatives: []const []const u8 = &.{},
|
||||
};
|
||||
|
||||
/// Fixed source collection bound (spec 15 §10), never a semantic flag.
|
||||
pub const source_diagnostic_limit = 32;
|
||||
|
||||
/// Shared serialization for the envelope and conformance advice goldens.
|
||||
pub fn writeRepairCandidates(candidates: []const RepairCandidate, s: *std.json.Stringify) std.Io.Writer.Error!void {
|
||||
try s.beginArray();
|
||||
|
||||
+50
-12
@@ -18,8 +18,10 @@ pub const Span = ast.Span;
|
||||
pub const Compiled = union(enum) {
|
||||
/// Canonical AIR, its line map and the annotated form.
|
||||
ok: lower_mod.Output,
|
||||
/// One source diagnostic (`E7xxx`): the first problem only.
|
||||
/// 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,
|
||||
};
|
||||
|
||||
@@ -32,6 +34,7 @@ pub fn compileWithModules(arena: std.mem.Allocator, file: []const u8, 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) {
|
||||
@@ -40,25 +43,60 @@ pub fn compileWithModules(arena: std.mem.Allocator, file: []const u8, source: []
|
||||
.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| blk: {
|
||||
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) } };
|
||||
break :blk .{ .err = .{
|
||||
.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 = p.repair_candidates,
|
||||
} };
|
||||
.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").?,
|
||||
|
||||
@@ -8,7 +8,7 @@ const Allocator = std.mem.Allocator;
|
||||
const Tag = lex.Tag;
|
||||
const Token = lex.Token;
|
||||
const Error = error{ OutOfMemory, Invariant };
|
||||
pub const Result = union(enum) { ok: []const u8, err: parse.Failure };
|
||||
pub const Result = union(enum) { ok: []const u8, err: parse.Failure, errors: []const parse.Failure };
|
||||
|
||||
const Curly = enum { block, list, literal };
|
||||
const Mark = struct { angle: bool = false, prefix: bool = false, curly: Curly = .block, top: bool = false, module_end: bool = false, statement_end: bool = false, mate: usize = 0, multiline: bool = false, layout_scope: usize = 0 };
|
||||
@@ -17,6 +17,7 @@ const Node = union(enum) { block: *const ast.Block, stmt: *const ast.Stmt, expr:
|
||||
pub fn format(arena: Allocator, source: []const u8) Error!Result {
|
||||
const module = switch (try parse.parse(arena, source)) {
|
||||
.err => |f| return .{ .err = f },
|
||||
.errors => |fs| return .{ .errors = fs },
|
||||
.ok => |m| m,
|
||||
};
|
||||
const tokens = try lex.tokenize(arena, source);
|
||||
|
||||
+142
-2
@@ -175,6 +175,7 @@ pub const Result = union(enum) {
|
||||
ok: Output,
|
||||
/// A source problem (`E7xxx`).
|
||||
err: Problem,
|
||||
errors: []const Problem,
|
||||
/// A construct of a layer that is not implemented yet.
|
||||
unimplemented: struct { span: Span, construct: []const u8 },
|
||||
};
|
||||
@@ -184,7 +185,7 @@ const Error = error{ Lower, Unimplemented, OutOfMemory };
|
||||
pub fn lower(arena: Allocator, m: ast.Module) Allocator.Error!Result {
|
||||
var l: Lowerer = .{ .arena = arena, .m = m };
|
||||
l.run() catch |e| switch (e) {
|
||||
error.Lower => return .{ .err = l.problem.? },
|
||||
error.Lower => return if (l.problems.items.len > 1) .{ .errors = l.problems.items } else .{ .err = if (l.problems.items.len == 1) l.problems.items[0] else l.problem.? },
|
||||
error.Unimplemented => return .{ .unimplemented = l.unimpl.? },
|
||||
error.OutOfMemory => return error.OutOfMemory,
|
||||
};
|
||||
@@ -286,6 +287,7 @@ const Lowerer = struct {
|
||||
/// Set while a byte string is materialized: the tag for its instructions.
|
||||
in_constant: u32 = 0,
|
||||
problem: ?Problem = null,
|
||||
problems: std.ArrayList(Problem) = .empty,
|
||||
unimpl: ?@FieldType(Result, "unimplemented") = null,
|
||||
sigs: std.StringHashMapUnmanaged(FnSig) = .empty,
|
||||
/// `@Name` of each declared type.
|
||||
@@ -493,7 +495,43 @@ const Lowerer = struct {
|
||||
var type_lines: std.ArrayList(Inst) = .empty;
|
||||
for (l.m.types) |t| try type_lines.append(l.arena, .{ .text = try l.typeDeclText(t), .span = t.span });
|
||||
try l.checkRequirements();
|
||||
for (l.m.functions) |f| try l.fns.append(l.arena, try l.function(f));
|
||||
var failed_declarations: std.ArrayList(Span) = .empty;
|
||||
for (l.m.functions) |f| {
|
||||
const failed = for (failed_declarations.items) |span| {
|
||||
if (sameDeclaration(span, f.span)) break true;
|
||||
} else false;
|
||||
if (failed) continue;
|
||||
// Bodies read only validated signatures/declarations. Restore all
|
||||
// module accumulations on failure, including byte-string constants,
|
||||
// features and linearity flags; no failed FnOut is ever appended.
|
||||
const checkpoint = .{ .uses = l.uses, .linear_enabled = l.linear_enabled, .constants_len = l.constants.items.len };
|
||||
const output = l.function(f) catch |err| switch (err) {
|
||||
error.OutOfMemory => return error.OutOfMemory,
|
||||
error.Unimplemented => {
|
||||
if (l.problems.items.len == 0) return error.Unimplemented;
|
||||
l.uses = checkpoint.uses;
|
||||
l.linear_enabled = checkpoint.linear_enabled;
|
||||
l.constants.items.len = checkpoint.constants_len;
|
||||
l.in_constant = 0;
|
||||
l.unimpl = null;
|
||||
continue;
|
||||
},
|
||||
error.Lower => {
|
||||
const problem = l.problem.?;
|
||||
l.uses = checkpoint.uses;
|
||||
l.linear_enabled = checkpoint.linear_enabled;
|
||||
l.constants.items.len = checkpoint.constants_len;
|
||||
l.in_constant = 0;
|
||||
l.problem = null;
|
||||
try l.problems.append(l.arena, problem);
|
||||
try failed_declarations.append(l.arena, f.span);
|
||||
if (l.problems.items.len == @import("../diag.zig").source_diagnostic_limit) return error.Lower;
|
||||
continue;
|
||||
},
|
||||
};
|
||||
try l.fns.append(l.arena, output);
|
||||
}
|
||||
if (l.problems.items.len != 0) return error.Lower;
|
||||
|
||||
var features: std.ArrayList(u8) = .empty;
|
||||
const roots = try l.featureRoots(type_lines.items);
|
||||
@@ -809,6 +847,16 @@ const Lowerer = struct {
|
||||
l.allocs = .empty;
|
||||
l.facts = .empty;
|
||||
l.addressable = .empty;
|
||||
l.cur = null;
|
||||
l.rest = .empty;
|
||||
l.pending_loop = null;
|
||||
l.pending_bindings = .empty;
|
||||
l.pending_ends = .empty;
|
||||
l.unchecked = false;
|
||||
l.in_constant = 0;
|
||||
l.scope_binding_start = 0;
|
||||
l.problem = null;
|
||||
l.unimpl = null;
|
||||
l.counter = 0;
|
||||
l.params = f.params;
|
||||
try l.findAddressable(f.body);
|
||||
@@ -3625,6 +3673,12 @@ const Lowerer = struct {
|
||||
}
|
||||
};
|
||||
|
||||
fn sameDeclaration(a: Span, b: Span) bool {
|
||||
return a.start.line == b.start.line and a.start.col == b.start.col and
|
||||
std.mem.eql(u8, a.file orelse "", b.file orelse "") and
|
||||
std.mem.eql(u8, a.namespace orelse "", b.namespace orelse "");
|
||||
}
|
||||
|
||||
fn elemOf(t: Ty) ?Ty {
|
||||
return switch (t) {
|
||||
.array => |a| a.elem,
|
||||
@@ -4083,3 +4137,89 @@ test "cyclic source diamonds reject before property construction" {
|
||||
try std.testing.expectEqual(@as(u32, 2), l.problem.?.span.start.line);
|
||||
try std.testing.expect(l.property_module == null);
|
||||
}
|
||||
|
||||
test "failed body discards constants and features and never emits partial AIR" {
|
||||
var arena: std.heap.ArenaAllocator = .init(std.testing.allocator);
|
||||
defer arena.deinit();
|
||||
const a = arena.allocator();
|
||||
const source =
|
||||
\\module collection
|
||||
\\fn good() -> void effects [] { let text = b"good"; }
|
||||
\\fn bad() -> void effects [unsafe] { let text = b"bad"; let x = missing; }
|
||||
\\fn main() -> void effects [] {}
|
||||
;
|
||||
const m = (try parse_mod.parse(a, source)).ok;
|
||||
var l: Lowerer = .{ .arena = a, .m = m };
|
||||
try std.testing.expectError(error.Lower, l.run());
|
||||
try std.testing.expectEqual(@as(usize, 1), l.problems.items.len);
|
||||
try std.testing.expectEqualStrings("E7002", l.problems.items[0].code);
|
||||
try std.testing.expectEqual(@as(usize, 2), l.fns.items.len);
|
||||
try std.testing.expectEqual(@as(usize, 1), l.constants.items.len);
|
||||
try std.testing.expectEqualStrings("good", l.constants.items[0].bytes);
|
||||
try std.testing.expect(!l.uses.contains(.unsafe));
|
||||
try std.testing.expectEqual(@as(usize, 0), l.out.items.len);
|
||||
try std.testing.expectEqual(@as(usize, 0), l.annotated.items.len);
|
||||
try std.testing.expectEqual(@as(usize, 0), l.lines.items.len);
|
||||
try std.testing.expectEqual(@as(usize, 0), l.constant_of.items.len);
|
||||
}
|
||||
|
||||
test "later function output matches fresh lowering after failed borrow and scope bodies" {
|
||||
var arena: std.heap.ArenaAllocator = .init(std.testing.allocator);
|
||||
defer arena.deinit();
|
||||
const a = arena.allocator();
|
||||
const stable =
|
||||
\\fn stable() -> u64 effects [] {
|
||||
\\ let inferred = 7;
|
||||
\\ let text = b"ok";
|
||||
\\ var bytes: [u8; 4] = zero;
|
||||
\\ var total: u64 = inferred;
|
||||
\\ for i in 0usize..2usize { total = total + (bytes[i] as u64); }
|
||||
\\ return total + (text.len as! u64);
|
||||
\\}
|
||||
\\fn main() -> void effects [] {}
|
||||
;
|
||||
const baseline_source = try std.fmt.allocPrint(a, "module collection\n{s}", .{stable});
|
||||
const baseline_module = (try parse_mod.parse(a, baseline_source)).ok;
|
||||
var baseline: Lowerer = .{ .arena = a, .m = baseline_module };
|
||||
try baseline.run();
|
||||
var baseline_emission: Lowerer = .{ .arena = a, .m = baseline_module };
|
||||
try baseline_emission.emitFunction(baseline.fns.items[0]);
|
||||
for ([_][]const u8{
|
||||
"fn bad() -> void effects [] { let shadow = 1u64; let x = missing; }",
|
||||
"fn bad() -> void effects [] { var bytes: [u8; 4] = zero; ref unchecked view = bytes[missing]; }",
|
||||
"fn bad() -> void effects [unsafe] { scope s { let text = b\"bad\"; loop { let x = missing; } } }",
|
||||
}) |bad| {
|
||||
const source = try std.fmt.allocPrint(a, "module collection\n{s}\n{s}", .{ bad, stable });
|
||||
const m = (try parse_mod.parse(a, source)).ok;
|
||||
var recovered: Lowerer = .{ .arena = a, .m = m };
|
||||
try std.testing.expectError(error.Lower, recovered.run());
|
||||
try std.testing.expectEqual(@as(usize, 1), recovered.problems.items.len);
|
||||
try std.testing.expectEqualStrings("E7002", recovered.problems.items[0].code);
|
||||
try std.testing.expectEqual(@as(usize, 2), recovered.fns.items.len);
|
||||
try std.testing.expectEqual(@as(usize, 0), recovered.out.items.len);
|
||||
var emission: Lowerer = .{ .arena = a, .m = m };
|
||||
try emission.emitFunction(recovered.fns.items[0]);
|
||||
try std.testing.expectEqualStrings(baseline_emission.out.items, emission.out.items);
|
||||
try std.testing.expectEqualSlices(u32, baseline_emission.constant_of.items, emission.constant_of.items);
|
||||
try std.testing.expectEqual(@as(usize, 1), recovered.constants.items.len);
|
||||
try std.testing.expectEqualStrings("ok", recovered.constants.items[0].bytes);
|
||||
}
|
||||
}
|
||||
|
||||
test "defensive nonmaterializable moves retain invalid_move even in generic transfers" {
|
||||
var arena: std.heap.ArenaAllocator = .init(std.testing.allocator);
|
||||
defer arena.deinit();
|
||||
const a = arena.allocator();
|
||||
const span: Span = .{ .start = .{ .line = 2, .col = 3 }, .end = .{ .line = 2, .col = 9 } };
|
||||
// Annotation/binding checks normally reject these values earlier. Keep
|
||||
// the lower-level guard stable without inventing accepted void parameters.
|
||||
for ([_]Ty{ .void, .never }) |ty| for ([_]bool{ false, true }) |generic| {
|
||||
var l: Lowerer = .{ .arena = a, .m = .{ .name = "defensive", .types = &.{}, .functions = &.{} } };
|
||||
try l.bindings.append(a, .{ .name = "value", .value = "v", .ty = ty, .mutable = false });
|
||||
try std.testing.expectError(error.Lower, l.expr(.{ .span = span, .generic_transfer = generic, .kind = .{ .move = "value" } }, null));
|
||||
try std.testing.expectEqualStrings("E7006", l.problem.?.code);
|
||||
try std.testing.expectEqual(InvalidReason.invalid_move, l.problem.?.reason.?);
|
||||
try std.testing.expectEqual(span, l.problem.?.span);
|
||||
try std.testing.expectEqual(@as(usize, 0), l.out.items.len);
|
||||
};
|
||||
}
|
||||
+37
-12
@@ -7,7 +7,7 @@ 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 };
|
||||
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 };
|
||||
|
||||
@@ -28,7 +28,7 @@ pub fn link(arena: std.mem.Allocator, entry: ast.Module, sources: []const Source
|
||||
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 .{ .err = g.problem.? },
|
||||
error.InvalidSource => return if (g.problems.len > 1) .{ .errors = g.problems } else .{ .err = g.problem.? },
|
||||
};
|
||||
return .{ .ok = combined };
|
||||
}
|
||||
@@ -38,6 +38,22 @@ const Graph = struct {
|
||||
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()");
|
||||
@@ -117,16 +133,8 @@ const Graph = struct {
|
||||
} 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| {
|
||||
g.problem = .{
|
||||
.code = if (std.mem.startsWith(u8, source.name, "std.")) "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 (std.mem.startsWith(u8, source.name, "std.")) &.{} else failure.repair_candidates,
|
||||
};
|
||||
return error.InvalidSource;
|
||||
},
|
||||
.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;
|
||||
@@ -157,3 +165,20 @@ fn used(types: []const ast.TypeDecl, functions: []const ast.FnDecl, name: []cons
|
||||
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 = "<std.bytes>", .source = "" }, failures));
|
||||
try std.testing.expectEqual(@as(usize, 1), g.problems.len);
|
||||
try std.testing.expectEqualStrings("E7900", g.problem.?.code);
|
||||
try std.testing.expectEqualStrings("<std.bytes>", 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);
|
||||
}
|
||||
+78
-10
@@ -1,6 +1,6 @@
|
||||
//! Parser for `.aji` source 0.1 (reference/grammar.ebnf). Recursive
|
||||
//! descent. On the first error it stops with exactly one `E7001` carrying
|
||||
//! the span, what was expected and what was found: no recovery, no cascade.
|
||||
//! descent. At most one E7001 per independently bounded top-level item;
|
||||
//! malformed boundaries stop collection. No partial AST escapes on error.
|
||||
|
||||
const std = @import("std");
|
||||
const lex = @import("lex.zig");
|
||||
@@ -18,7 +18,7 @@ pub const Failure = struct {
|
||||
repair_candidates: []const diag.RepairCandidate = &.{},
|
||||
};
|
||||
|
||||
pub const Result = union(enum) { ok: ast.Module, err: Failure };
|
||||
pub const Result = union(enum) { ok: ast.Module, err: Failure, errors: []const Failure };
|
||||
|
||||
pub fn parse(arena: Allocator, src: []const u8) Allocator.Error!Result {
|
||||
return parseWithFile(arena, src, null);
|
||||
@@ -28,7 +28,7 @@ pub fn parseWithFile(arena: Allocator, src: []const u8, file: ?[]const u8) Alloc
|
||||
const tokens = try lex.tokenize(arena, src);
|
||||
var p: Parser = .{ .arena = arena, .tokens = try arena.dupe(Token, tokens), .file = file };
|
||||
const m = p.module() catch |e| switch (e) {
|
||||
error.Syntax => return .{ .err = p.failure.? },
|
||||
error.Syntax => return if (p.failures.items.len > 1) .{ .errors = p.failures.items } else .{ .err = if (p.failures.items.len == 1) p.failures.items[0] else p.failure.? },
|
||||
error.OutOfMemory => return error.OutOfMemory,
|
||||
};
|
||||
return .{ .ok = m };
|
||||
@@ -43,6 +43,7 @@ const Parser = struct {
|
||||
/// Also tracks a consumed half of `>>` while the other half stays at pos.
|
||||
last_end: ?lex.Pos = null,
|
||||
failure: ?Failure = null,
|
||||
failures: std.ArrayList(Failure) = .empty,
|
||||
file: ?[]const u8 = null,
|
||||
module_name: ?[]const u8 = null,
|
||||
/// Struct literals are not allowed where a `{` starts a block (conditions).
|
||||
@@ -234,15 +235,82 @@ const Parser = struct {
|
||||
var types: std.ArrayList(ast.TypeDecl) = .empty;
|
||||
var fns: std.ArrayList(ast.FnDecl) = .empty;
|
||||
while (p.peek().tag != .eof) {
|
||||
if (p.atWord("struct") or p.atWord("enum")) {
|
||||
try types.append(p.arena, try p.typeDecl());
|
||||
} else if (p.atWord("fn")) {
|
||||
try fns.append(p.arena, try p.fnDecl());
|
||||
} else return p.fail(p.peek(), "`struct`, `enum` or `fn`");
|
||||
const start = p.pos;
|
||||
const item = p.declaration() catch |err| switch (err) {
|
||||
error.OutOfMemory => return error.OutOfMemory,
|
||||
error.Syntax => {
|
||||
try p.failures.append(p.arena, p.failure.?);
|
||||
if (p.failures.items.len == diag.source_diagnostic_limit) return error.Syntax;
|
||||
const end = try p.recoveryEnd(start) orelse return error.Syntax;
|
||||
p.pos = end;
|
||||
p.last_end = p.tokens[end - 1].end;
|
||||
p.failure = null;
|
||||
p.no_struct = false;
|
||||
p.type_advice = null;
|
||||
p.borrow_advice = null;
|
||||
continue;
|
||||
},
|
||||
};
|
||||
switch (item) {
|
||||
.type_decl => |t| try types.append(p.arena, t),
|
||||
.function => |f| try fns.append(p.arena, f),
|
||||
}
|
||||
}
|
||||
if (p.failures.items.len != 0) return error.Syntax;
|
||||
return .{ .name = name, .imports = imports.items, .types = types.items, .functions = fns.items };
|
||||
}
|
||||
|
||||
fn declaration(p: *Parser) Error!union(enum) { type_decl: ast.TypeDecl, function: ast.FnDecl } {
|
||||
if (p.atWord("struct") or p.atWord("enum")) return .{ .type_decl = try p.typeDecl() };
|
||||
if (p.atWord("fn")) return .{ .function = try p.fnDecl() };
|
||||
return p.fail(p.peek(), "`struct`, `enum` or `fn`");
|
||||
}
|
||||
|
||||
fn itemKeyword(t: Token) bool {
|
||||
return isWord(t, "fn") or isWord(t, "struct") or isWord(t, "enum");
|
||||
}
|
||||
|
||||
/// This scan proves a delimiter boundary, not the failed item's semantics.
|
||||
/// It never trusts a keyword's column and never rewinds past a failure.
|
||||
fn recoveryEnd(p: *Parser, start: usize) Error!?usize {
|
||||
if (!itemKeyword(p.tokens[start])) return null;
|
||||
var stack: std.ArrayList(Tag) = .empty;
|
||||
var body = false;
|
||||
for (p.tokens[start..], start..) |t, i| {
|
||||
if (t.tag == .invalid and !std.mem.eql(u8, t.text, "!")) return null;
|
||||
if (!body and stack.items.len == 0 and i != start and itemKeyword(t)) {
|
||||
// Static function contracts use fn(...), selections fn path or
|
||||
// fn path::<...>; neither is a new fn Name(...) declaration.
|
||||
if (!isWord(t, "fn") or (i + 2 < p.tokens.len and p.tokens[i + 1].tag == .ident and
|
||||
(p.tokens[i + 2].tag == .l_paren or p.tokens[i + 2].tag == .lt))) return null;
|
||||
}
|
||||
switch (t.tag) {
|
||||
.l_paren, .l_bracket, .l_brace => {
|
||||
if (t.tag == .l_brace and stack.items.len == 0) body = true;
|
||||
try stack.append(p.arena, t.tag);
|
||||
},
|
||||
.r_paren, .r_bracket, .r_brace => {
|
||||
const open = stack.pop() orelse return null;
|
||||
const wanted: Tag = switch (t.tag) {
|
||||
.r_paren => .l_paren,
|
||||
.r_bracket => .l_bracket,
|
||||
else => .l_brace,
|
||||
};
|
||||
if (open != wanted) return null;
|
||||
if (body and stack.items.len == 0) {
|
||||
const end = i + 1;
|
||||
if (end <= p.pos or end >= p.tokens.len) return null;
|
||||
if (p.tokens[end].tag != .eof and !itemKeyword(p.tokens[end])) return null;
|
||||
return end;
|
||||
}
|
||||
},
|
||||
.eof => return null,
|
||||
else => {},
|
||||
}
|
||||
}
|
||||
return null;
|
||||
}
|
||||
|
||||
fn path(p: *Parser) Error![]const u8 {
|
||||
var out: std.ArrayList(u8) = .empty;
|
||||
try out.appendSlice(p.arena, try p.ident("a name"));
|
||||
@@ -359,7 +427,7 @@ const Parser = struct {
|
||||
if (t.tag != .ident) return p.fail(t, "a type");
|
||||
_ = p.next();
|
||||
const name = if (p.peek().tag == .dot) try p.pathTail(t.text) else t.text;
|
||||
if (!p.speculative and (isWord(t, "mut") or isWord(t, "ref")) and p.atWord("slice"))
|
||||
if (!p.speculative and std.mem.eql(u8, name, t.text) and (isWord(t, "mut") or isWord(t, "ref")) and p.atWord("slice"))
|
||||
p.type_advice = .{ .at = p.pos, .kind = if (isWord(t, "mut")) .slice_mut_type else .slice_ref_type };
|
||||
if (p.peek().tag != .lt) return .{ .span = p.span(start), .kind = .{ .name = name } };
|
||||
if (std.mem.eql(u8, name, "cap") or std.mem.eql(u8, name, "file")) {
|
||||
|
||||
@@ -171,6 +171,13 @@ fn run(io: std.Io, arena: std.mem.Allocator, args: []const [:0]const u8, out: *s
|
||||
try out.writeByte('\n');
|
||||
return .rejected;
|
||||
},
|
||||
.errors => |ds| {
|
||||
for (ds) |d| {
|
||||
try d.writeJson(out);
|
||||
try out.writeByte('\n');
|
||||
}
|
||||
return .rejected;
|
||||
},
|
||||
.unimplemented => |what| {
|
||||
std.debug.print("aji: not implemented yet: {s}\n", .{what});
|
||||
return .unimplemented;
|
||||
@@ -526,6 +533,13 @@ fn formatCommand(io: std.Io, arena: std.mem.Allocator, arguments: []const [:0]co
|
||||
try out.writeByte('\n');
|
||||
return .rejected;
|
||||
},
|
||||
.errors => |fs| {
|
||||
for (try aji.frontend.syntaxDiagnostics(arena, path, fs)) |d| {
|
||||
try d.writeJson(out);
|
||||
try out.writeByte('\n');
|
||||
}
|
||||
return .rejected;
|
||||
},
|
||||
.ok => |text| text,
|
||||
};
|
||||
if (mode == .stdout) {
|
||||
|
||||
Reference in new issue
Block a user