authorgravatar for git@vexu.euVeikka Tuominen <git@vexu.eu> 2023-11-17 20:33:49+02:00
committergravatar for andrew@ziglang.orgAndrew Kelley <andrew@ziglang.org> 2024-01-22 18:08:56-08:00
logeeec34ccb6189a588b1227a57e7c7b98af849b8d
tree4e4d33e31b8cd5f89a605dc6171c73869783237b
parent9e684e8d1af39904055abe64a9afda69a3d44a59

Sema: implement comptime error return traces


4 files changed, 147 insertions(+), 22 deletions(-)

src/Module.zig+12
......@@ -3479,6 +3479,9 @@ pub fn semaFile(mod: *Module, file: *File) SemaError!void {
34793479 var comptime_mutable_decls = std.ArrayList(Decl.Index).init(gpa);
34803480 defer comptime_mutable_decls.deinit();
34813481
3482 var comptime_err_ret_trace = std.ArrayList(SrcLoc).init(gpa);
3483 defer comptime_err_ret_trace.deinit();
3484
34823485 var sema: Sema = .{
34833486 .mod = mod,
34843487 .gpa = gpa,
......@@ -3492,6 +3495,7 @@ pub fn semaFile(mod: *Module, file: *File) SemaError!void {
34923495 .fn_ret_ty_ies = null,
34933496 .owner_func_index = .none,
34943497 .comptime_mutable_decls = &comptime_mutable_decls,
3498 .comptime_err_ret_trace = &comptime_err_ret_trace,
34953499 };
34963500 defer sema.deinit();
34973501
......@@ -3600,6 +3604,9 @@ fn semaDecl(mod: *Module, decl_index: Decl.Index) !bool {
36003604 var comptime_mutable_decls = std.ArrayList(Decl.Index).init(gpa);
36013605 defer comptime_mutable_decls.deinit();
36023606
3607 var comptime_err_ret_trace = std.ArrayList(SrcLoc).init(gpa);
3608 defer comptime_err_ret_trace.deinit();
3609
36033610 var sema: Sema = .{
36043611 .mod = mod,
36053612 .gpa = gpa,
......@@ -3613,6 +3620,7 @@ fn semaDecl(mod: *Module, decl_index: Decl.Index) !bool {
36133620 .fn_ret_ty_ies = null,
36143621 .owner_func_index = .none,
36153622 .comptime_mutable_decls = &comptime_mutable_decls,
3623 .comptime_err_ret_trace = &comptime_err_ret_trace,
36163624 .builtin_type_target_index = builtin_type_target_index,
36173625 };
36183626 defer sema.deinit();
......@@ -4451,6 +4459,9 @@ pub fn analyzeFnBody(mod: *Module, func_index: InternPool.Index, arena: Allocato
44514459 var comptime_mutable_decls = std.ArrayList(Decl.Index).init(gpa);
44524460 defer comptime_mutable_decls.deinit();
44534461
4462 var comptime_err_ret_trace = std.ArrayList(SrcLoc).init(gpa);
4463 defer comptime_err_ret_trace.deinit();
4464
44544465 // In the case of a generic function instance, this is the type of the
44554466 // instance, which has comptime parameters elided. In other words, it is
44564467 // the runtime-known parameters only, not to be confused with the
......@@ -4473,6 +4484,7 @@ pub fn analyzeFnBody(mod: *Module, func_index: InternPool.Index, arena: Allocato
44734484 .owner_func_index = func_index,
44744485 .branch_quota = @max(func.branchQuota(ip).*, Sema.default_branch_quota),
44754486 .comptime_mutable_decls = &comptime_mutable_decls,
4487 .comptime_err_ret_trace = &comptime_err_ret_trace,
44764488 };
44774489 defer sema.deinit();
44784490
src/Sema.zig+113-22
......@@ -34,6 +34,7 @@ func_index: InternPool.Index,
3434func_is_naked: bool,
3535/// Used to restore the error return trace when returning a non-error from a function.
3636error_return_trace_index_on_fn_entry: Air.Inst.Ref = .none,
37comptime_err_ret_trace: *std.ArrayList(Module.SrcLoc),
3738/// When semantic analysis needs to know the return type of the function whose body
3839/// is being analyzed, this `Type` should be used instead of going through `func`.
3940/// This will correctly handle the case of a comptime/inline function call of a
......@@ -1569,7 +1570,22 @@ fn analyzeBodyInner(
15691570 const inst_data = datas[@intFromEnum(inst)].pl_node;
15701571 const extra = sema.code.extraData(Zir.Inst.Block, inst_data.payload_index);
15711572 const inline_body = sema.code.bodySlice(extra.end, extra.data.body_len);
1572 const break_data = (try sema.analyzeBodyBreak(block, inline_body)) orelse
1573
1574 // Create a temporary child block so that this loop is properly
1575 // labeled for any .restore_err_ret_index instructions
1576 var child_block = block.makeSubBlock();
1577
1578 var label: Block.Label = .{
1579 .zir_block = inst,
1580 .merges = undefined,
1581 };
1582 child_block.label = &label;
1583
1584 // Write these instructions directly into the parent block
1585 child_block.instructions = block.instructions;
1586 defer block.instructions = child_block.instructions;
1587
1588 const break_data = (try sema.analyzeBodyBreak(&child_block, inline_body)) orelse
15731589 break always_noreturn;
15741590 if (inst == break_data.block_inst) {
15751591 break :blk try sema.resolveInst(break_data.operand);
......@@ -1585,13 +1601,22 @@ fn analyzeBodyInner(
15851601 const inst_data = datas[@intFromEnum(inst)].pl_node;
15861602 const extra = sema.code.extraData(Zir.Inst.Block, inst_data.payload_index);
15871603 const inline_body = sema.code.bodySlice(extra.end, extra.data.body_len);
1588 // If this block contains a function prototype, we need to reset the
1589 // current list of parameters and restore it later.
1590 // Note: this probably needs to be resolved in a more general manner.
1591 const prev_params = block.params;
1592 block.params = .{};
1593 defer block.params = prev_params;
1594 const break_data = (try sema.analyzeBodyBreak(block, inline_body)) orelse
1604
1605 // Create a temporary child block so that this block is properly
1606 // labeled for any .restore_err_ret_index instructions
1607 var child_block = block.makeSubBlock();
1608
1609 var label: Block.Label = .{
1610 .zir_block = inst,
1611 .merges = undefined,
1612 };
1613 child_block.label = &label;
1614
1615 // Write these instructions directly into the parent block
1616 child_block.instructions = block.instructions;
1617 defer block.instructions = child_block.instructions;
1618
1619 const break_data = (try sema.analyzeBodyBreak(&child_block, inline_body)) orelse
15951620 break always_noreturn;
15961621 if (inst == break_data.block_inst) {
15971622 break :blk try sema.resolveInst(break_data.operand);
......@@ -2379,6 +2404,25 @@ fn typeSupportsFieldAccess(mod: *const Module, ty: Type, field_name: InternPool.
23792404 }
23802405}
23812406
2407fn failWithComptimeErrorRetTrace(
2408 sema: *Sema,
2409 block: *Block,
2410 src: LazySrcLoc,
2411 name: InternPool.NullTerminatedString,
2412) CompileError {
2413 const mod = sema.mod;
2414 const msg = msg: {
2415 const msg = try sema.errMsg(block, src, "caught unexpected error '{}'", .{name.fmt(&mod.intern_pool)});
2416 errdefer msg.destroy(sema.gpa);
2417
2418 for (sema.comptime_err_ret_trace.items) |src_loc| {
2419 try mod.errNoteNonLazy(src_loc, msg, "error returned here", .{});
2420 }
2421 break :msg msg;
2422 };
2423 return sema.failWithOwnedErrorMsg(block, msg);
2424}
2425
23822426/// We don't return a pointer to the new error note because the pointer
23832427/// becomes invalid when you add another one.
23842428fn errNote(
......@@ -6534,10 +6578,12 @@ pub fn analyzeSaveErrRetIndex(sema: *Sema, block: *Block) SemaError!Air.Inst.Ref
65346578 const gpa = sema.gpa;
65356579 const src = sema.src;
65366580
6537 if (!block.ownerModule().error_tracing) return .none;
6581 if (block.is_comptime or block.is_typeof) {
6582 const index_val = try mod.intValue_u64(Type.usize, sema.comptime_err_ret_trace.items.len);
6583 return Air.internedToRef(index_val.toIntern());
6584 }
65386585
6539 if (block.is_comptime)
6540 return .none;
6586 if (!block.ownerModule().error_tracing) return .none;
65416587
65426588 const stack_trace_ty = sema.getBuiltinType("StackTrace") catch |err| switch (err) {
65436589 error.NeededSourceLocation, error.GenericPoison, error.ComptimeReturn, error.ComptimeBreak => unreachable,
......@@ -7498,6 +7544,14 @@ fn analyzeCall(
74987544 try sema.ensureResultUsed(block, sema.fn_ret_ty, call_src);
74997545 }
75007546
7547 if (is_comptime_call or block.is_typeof) {
7548 // Save the error trace as our first action in the function
7549 // to match the behavior of runtime function calls.
7550 const error_return_trace_index = try sema.analyzeSaveErrRetIndex(&child_block);
7551 sema.error_return_trace_index_on_fn_entry = error_return_trace_index;
7552 child_block.error_return_trace_index = error_return_trace_index;
7553 }
7554
75017555 const result = result: {
75027556 sema.analyzeBody(&child_block, fn_info.body) catch |err| switch (err) {
75037557 error.ComptimeReturn => break :result inlining.comptime_result,
......@@ -7858,6 +7912,7 @@ fn instantiateGenericCall(
78587912 .branch_quota = sema.branch_quota,
78597913 .branch_count = sema.branch_count,
78607914 .comptime_mutable_decls = sema.comptime_mutable_decls,
7915 .comptime_err_ret_trace = sema.comptime_err_ret_trace,
78617916 };
78627917 defer child_sema.deinit();
78637918
......@@ -8783,7 +8838,7 @@ fn analyzeErrUnionPayload(
87838838 const payload_ty = err_union_ty.errorUnionPayload(mod);
87848839 if (try sema.resolveDefinedValue(block, operand_src, operand)) |val| {
87858840 if (val.getErrorName(mod).unwrap()) |name| {
8786 return sema.fail(block, src, "caught unexpected error '{}'", .{name.fmt(&mod.intern_pool)});
8841 return sema.failWithComptimeErrorRetTrace(block, src, name);
87878842 }
87888843 return Air.internedToRef(mod.intern_pool.indexToKey(val.toIntern()).error_union.val.payload);
87898844 }
......@@ -8861,7 +8916,7 @@ fn analyzeErrUnionPayloadPtr(
88618916 }
88628917 if (try sema.pointerDeref(block, src, ptr_val, operand_ty)) |val| {
88638918 if (val.getErrorName(mod).unwrap()) |name| {
8864 return sema.fail(block, src, "caught unexpected error '{}'", .{name.fmt(&mod.intern_pool)});
8919 return sema.failWithComptimeErrorRetTrace(block, src, name);
88658920 }
88668921 return Air.internedToRef((try mod.intern(.{ .ptr = .{
88678922 .ty = operand_pointer_ty.toIntern(),
......@@ -13437,7 +13492,7 @@ fn maybeErrorUnwrapComptime(sema: *Sema, block: *Block, body: []const Zir.Inst.I
1343713492
1343813493 if (try sema.resolveDefinedValue(block, src, operand)) |val| {
1343913494 if (val.getErrorName(sema.mod).unwrap()) |name| {
13440 return sema.fail(block, src, "caught unexpected error '{}'", .{name.fmt(&sema.mod.intern_pool)});
13495 return sema.failWithComptimeErrorRetTrace(block, src, name);
1344113496 }
1344213497 }
1344313498}
......@@ -19227,15 +19282,9 @@ fn zirRestoreErrRetIndex(sema: *Sema, start_block: *Block, inst: Zir.Inst.Index)
1922719282 const inst_data = sema.code.instructions.items(.data)[@intFromEnum(inst)].restore_err_ret_index;
1922819283 const src = sema.src; // TODO
1922919284
19230 // This is only relevant at runtime.
19231 if (start_block.is_comptime or start_block.is_typeof) return;
19232
1923319285 const mod = sema.mod;
1923419286 const ip = &mod.intern_pool;
1923519287
19236 if (!ip.funcAnalysis(sema.owner_func_index).calls_or_awaits_errorable_fn) return;
19237 if (!start_block.ownerModule().error_tracing) return;
19238
1923919288 const tracy = trace(@src());
1924019289 defer tracy.end();
1924119290
......@@ -19263,9 +19312,29 @@ fn zirRestoreErrRetIndex(sema: *Sema, start_block: *Block, inst: Zir.Inst.Index)
1926319312 return; // No need to restore
1926419313 };
1926519314
19315 const operand = try sema.resolveInstAllowNone(inst_data.operand);
19316
19317 if (start_block.is_comptime or start_block.is_typeof) {
19318 const is_non_error = if (operand != .none) blk: {
19319 const is_non_error_inst = try sema.analyzeIsNonErr(start_block, src, operand);
19320 const cond_val = try sema.resolveDefinedValue(start_block, src, is_non_error_inst);
19321 break :blk cond_val.?.toBool();
19322 } else true; // no operand means pop unconditionally
19323
19324 if (is_non_error) return;
19325
19326 const saved_index_val = try sema.resolveDefinedValue(start_block, src, saved_index);
19327 const saved_index_int = saved_index_val.?.toUnsignedInt(mod);
19328 assert(saved_index_int <= sema.comptime_err_ret_trace.items.len);
19329 sema.comptime_err_ret_trace.items.len = @intCast(saved_index_int);
19330 return;
19331 }
19332
19333 if (!ip.funcAnalysis(sema.owner_func_index).calls_or_awaits_errorable_fn) return;
19334 if (!start_block.ownerModule().error_tracing) return;
19335
1926619336 assert(saved_index != .none); // The .error_return_trace_index field was dropped somewhere
1926719337
19268 const operand = try sema.resolveInstAllowNone(inst_data.operand);
1926919338 return sema.popErrorReturnTrace(start_block, src, operand, saved_index);
1927019339}
1927119340
......@@ -19319,10 +19388,16 @@ fn analyzeRet(
1931919388
1932019389 if (block.inlining) |inlining| {
1932119390 if (block.is_comptime) {
19322 _ = try sema.resolveConstValue(block, src, operand, .{
19391 const ret_val = try sema.resolveConstValue(block, src, operand, .{
1932319392 .needed_comptime_reason = "value being returned at comptime must be comptime-known",
1932419393 });
1932519394 inlining.comptime_result = operand;
19395
19396 if (sema.fn_ret_ty.isError(mod) and ret_val.getErrorName(mod) != .none) {
19397 const src_decl = mod.declPtr(block.src_decl);
19398 const src_loc = src.toSrcLoc(src_decl, mod);
19399 try sema.comptime_err_ret_trace.append(src_loc);
19400 }
1932619401 return error.ComptimeReturn;
1932719402 }
1932819403 // We are inlining a function call; rewrite the `ret` as a `break`.
......@@ -35467,6 +35542,9 @@ fn semaBackingIntType(mod: *Module, struct_type: InternPool.Key.StructType) Comp
3546735542 var comptime_mutable_decls = std.ArrayList(InternPool.DeclIndex).init(gpa);
3546835543 defer comptime_mutable_decls.deinit();
3546935544
35545 var comptime_err_ret_trace = std.ArrayList(Module.SrcLoc).init(gpa);
35546 defer comptime_err_ret_trace.deinit();
35547
3547035548 var sema: Sema = .{
3547135549 .mod = mod,
3547235550 .gpa = gpa,
......@@ -35480,6 +35558,7 @@ fn semaBackingIntType(mod: *Module, struct_type: InternPool.Key.StructType) Comp
3548035558 .fn_ret_ty_ies = null,
3548135559 .owner_func_index = .none,
3548235560 .comptime_mutable_decls = &comptime_mutable_decls,
35561 .comptime_err_ret_trace = &comptime_err_ret_trace,
3548335562 };
3548435563 defer sema.deinit();
3548535564
......@@ -36289,6 +36368,9 @@ fn semaStructFields(
3628936368 var comptime_mutable_decls = std.ArrayList(InternPool.DeclIndex).init(gpa);
3629036369 defer comptime_mutable_decls.deinit();
3629136370
36371 var comptime_err_ret_trace = std.ArrayList(Module.SrcLoc).init(gpa);
36372 defer comptime_err_ret_trace.deinit();
36373
3629236374 var sema: Sema = .{
3629336375 .mod = mod,
3629436376 .gpa = gpa,
......@@ -36302,6 +36384,7 @@ fn semaStructFields(
3630236384 .fn_ret_ty_ies = null,
3630336385 .owner_func_index = .none,
3630436386 .comptime_mutable_decls = &comptime_mutable_decls,
36387 .comptime_err_ret_trace = &comptime_err_ret_trace,
3630536388 };
3630636389 defer sema.deinit();
3630736390
......@@ -36543,6 +36626,9 @@ fn semaStructFieldInits(
3654336626 var comptime_mutable_decls = std.ArrayList(InternPool.DeclIndex).init(gpa);
3654436627 defer comptime_mutable_decls.deinit();
3654536628
36629 var comptime_err_ret_trace = std.ArrayList(Module.SrcLoc).init(gpa);
36630 defer comptime_err_ret_trace.deinit();
36631
3654636632 var sema: Sema = .{
3654736633 .mod = mod,
3654836634 .gpa = gpa,
......@@ -36556,6 +36642,7 @@ fn semaStructFieldInits(
3655636642 .fn_ret_ty_ies = null,
3655736643 .owner_func_index = .none,
3655836644 .comptime_mutable_decls = &comptime_mutable_decls,
36645 .comptime_err_ret_trace = &comptime_err_ret_trace,
3655936646 };
3656036647 defer sema.deinit();
3656136648
......@@ -36727,6 +36814,9 @@ fn semaUnionFields(mod: *Module, arena: Allocator, union_type: InternPool.Key.Un
3672736814 var comptime_mutable_decls = std.ArrayList(InternPool.DeclIndex).init(gpa);
3672836815 defer comptime_mutable_decls.deinit();
3672936816
36817 var comptime_err_ret_trace = std.ArrayList(Module.SrcLoc).init(gpa);
36818 defer comptime_err_ret_trace.deinit();
36819
3673036820 var sema: Sema = .{
3673136821 .mod = mod,
3673236822 .gpa = gpa,
......@@ -36740,6 +36830,7 @@ fn semaUnionFields(mod: *Module, arena: Allocator, union_type: InternPool.Key.Un
3674036830 .fn_ret_ty_ies = null,
3674136831 .owner_func_index = .none,
3674236832 .comptime_mutable_decls = &comptime_mutable_decls,
36833 .comptime_err_ret_trace = &comptime_err_ret_trace,
3674336834 };
3674436835 defer sema.deinit();
3674536836
test/cases/compile_errors/comptime_err_ret_trace.zig created+17
......@@ -0,0 +1,17 @@
1fn inner() !void {
2 return error.SomethingBadHappened;
3}
4
5fn outer() !void {
6 return inner();
7}
8
9comptime {
10 outer() catch unreachable;
11}
12
13// error
14//
15// :10:19: error: caught unexpected error 'SomethingBadHappened'
16// :2:18: note: error returned here
17// :6:5: note: error returned here
test/cases/compile_errors/error_in_comptime_call_in_container_level_initializer.zig+5
......@@ -19,4 +19,9 @@ pub export fn entry() void {
1919// target=native
2020//
2121// :9:48: error: caught unexpected error 'InvalidVersion'
22// :?:?: note: error returned here
23// :?:?: note: error returned here
24// :?:?: note: error returned here
25// :?:?: note: error returned here
26// :?:?: note: error returned here
2227// :12:37: note: called from here