From 57926a5a4071b534db979306fd878ec369cae454 Mon Sep 17 00:00:00 2001 From: Richard Feldman Date: Wed, 26 Nov 2025 00:31:40 -0500 Subject: [PATCH 1/8] Fix `dbg` type mismatch issue --- src/cli/test/fx_platform_test.zig | 41 +++++++++++++++++++++++++++++++ test/fx/dbg_missing_return.roc | 5 ++++ 2 files changed, 46 insertions(+) create mode 100644 test/fx/dbg_missing_return.roc diff --git a/src/cli/test/fx_platform_test.zig b/src/cli/test/fx_platform_test.zig index b45ddb53f4..c55b152b0c 100644 --- a/src/cli/test/fx_platform_test.zig +++ b/src/cli/test/fx_platform_test.zig @@ -339,3 +339,44 @@ test "fx platform match with wildcard" { }, } } + +test "fx platform dbg missing return value" { + const allocator = testing.allocator; + + try ensureRocBinary(allocator); + + // Run an app that uses dbg without providing a return value. + // This has a type error (returns Str instead of {}) which should be caught by the type checker. + // When run, it should fail gracefully with a TypeMismatch error rather than panicking. + const run_result = try std.process.Child.run(.{ + .allocator = allocator, + .argv = &[_][]const u8{ + "./zig-out/bin/roc", + "test/fx/dbg_missing_return.roc", + }, + }); + defer allocator.free(run_result.stdout); + defer allocator.free(run_result.stderr); + + // The run should fail with a non-zero exit code due to the type mismatch + switch (run_result.term) { + .Exited => |code| { + if (code == 0) { + std.debug.print("Run should have failed but succeeded\n", .{}); + return error.TestFailed; + } + }, + else => { + std.debug.print("Run terminated abnormally: {}\n", .{run_result.term}); + std.debug.print("STDOUT: {s}\n", .{run_result.stdout}); + std.debug.print("STDERR: {s}\n", .{run_result.stderr}); + return error.RunFailed; + }, + } + + // Verify that the dbg output was printed before the error + try testing.expect(std.mem.indexOf(u8, run_result.stderr, "this will break") != null); + + // Verify that it crashes with TypeMismatch error rather than a panic + try testing.expect(std.mem.indexOf(u8, run_result.stderr, "TypeMismatch") != null); +} diff --git a/test/fx/dbg_missing_return.roc b/test/fx/dbg_missing_return.roc new file mode 100644 index 0000000000..d38b2533dc --- /dev/null +++ b/test/fx/dbg_missing_return.roc @@ -0,0 +1,5 @@ +app [main!] { pf: platform "./platform/main.roc" } + +main! = || { + dbg "this will break, there return value isn't provided I think" +} From 5ffc405be97c7842bc5ad37dd661155eed708b57 Mon Sep 17 00:00:00 2001 From: Richard Feldman Date: Wed, 26 Nov 2025 10:02:04 -0500 Subject: [PATCH 2/8] Fix more `dbg` issues --- src/check/Check.zig | 9 ++- src/check/test/type_checking_integration.zig | 3 + src/cli/test/fx_platform_test.zig | 23 +++--- src/eval/interpreter.zig | 17 +++-- test/fx/dbg_missing_return.roc | 4 +- test/snapshots/fuzz_crash/fuzz_crash_023.md | 70 +++++++++++++++++- test/snapshots/fuzz_crash/fuzz_crash_027.md | 66 ++++++++++++++++- test/snapshots/fuzz_crash/fuzz_crash_028.md | Bin 56285 -> 56600 bytes test/snapshots/statement/dbg_simple_test.md | 4 +- .../statement/dbg_stmt_block_example.md | 4 +- test/snapshots/syntax_grab_bag.md | 70 +++++++++++++++++- 11 files changed, 240 insertions(+), 30 deletions(-) diff --git a/src/check/Check.zig b/src/check/Check.zig index 4d665df481..d537037dc9 100644 --- a/src/check/Check.zig +++ b/src/check/Check.zig @@ -3525,8 +3525,13 @@ fn checkExpr(self: *Self, expr_idx: CIR.Expr.Idx, env: *Env, expected: Expected) try self.unifyWith(expr_var, .{ .flex = Flex.init() }, env); }, .e_dbg => |dbg| { - does_fx = try self.checkExpr(dbg.expr, env, expected) or does_fx; - _ = try self.unify(expr_var, ModuleEnv.varFrom(dbg.expr), env); + // dbg checks the inner expression but returns {} (like expect) + // This allows dbg to be used as the last expression in a block + // without affecting the block's return type + // dbg is always effectful since it prints to stderr + _ = try self.checkExpr(dbg.expr, env, .no_expectation); + does_fx = true; + try self.unifyWith(expr_var, .{ .structure = .empty_record }, env); }, .e_expect => |expect| { does_fx = try self.checkExpr(expect.body, env, expected) or does_fx; diff --git a/src/check/test/type_checking_integration.zig b/src/check/test/type_checking_integration.zig index 5bb1901df0..dc23477031 100644 --- a/src/check/test/type_checking_integration.zig +++ b/src/check/test/type_checking_integration.zig @@ -1222,10 +1222,13 @@ test "check type - crash" { // debug // test "check type - debug" { + // debug returns {} (not the value it's debugging), so it can be used + // as a statement/side-effect without affecting the block's return type const source = \\y : U64 \\y = { \\ debug 2 + \\ 42 \\} \\ \\main = { diff --git a/src/cli/test/fx_platform_test.zig b/src/cli/test/fx_platform_test.zig index c55b152b0c..c896789650 100644 --- a/src/cli/test/fx_platform_test.zig +++ b/src/cli/test/fx_platform_test.zig @@ -345,25 +345,27 @@ test "fx platform dbg missing return value" { try ensureRocBinary(allocator); - // Run an app that uses dbg without providing a return value. - // This has a type error (returns Str instead of {}) which should be caught by the type checker. - // When run, it should fail gracefully with a TypeMismatch error rather than panicking. + // Run an app that uses dbg as the last expression in main!. + // dbg is treated as a statement (side-effect only) when it's the final + // expression in a block, so the block returns {} as expected by main!. const run_result = try std.process.Child.run(.{ .allocator = allocator, .argv = &[_][]const u8{ "./zig-out/bin/roc", + "--no-cache", "test/fx/dbg_missing_return.roc", }, }); defer allocator.free(run_result.stdout); defer allocator.free(run_result.stderr); - // The run should fail with a non-zero exit code due to the type mismatch switch (run_result.term) { .Exited => |code| { - if (code == 0) { - std.debug.print("Run should have failed but succeeded\n", .{}); - return error.TestFailed; + if (code != 0) { + std.debug.print("Run failed with exit code {}\n", .{code}); + std.debug.print("STDOUT: {s}\n", .{run_result.stdout}); + std.debug.print("STDERR: {s}\n", .{run_result.stderr}); + return error.RunFailed; } }, else => { @@ -374,9 +376,6 @@ test "fx platform dbg missing return value" { }, } - // Verify that the dbg output was printed before the error - try testing.expect(std.mem.indexOf(u8, run_result.stderr, "this will break") != null); - - // Verify that it crashes with TypeMismatch error rather than a panic - try testing.expect(std.mem.indexOf(u8, run_result.stderr, "TypeMismatch") != null); + // Verify that the dbg output was printed + try testing.expect(std.mem.indexOf(u8, run_result.stderr, "this should work now") != null); } diff --git a/src/eval/interpreter.zig b/src/eval/interpreter.zig index 7195e572ea..b2d16fe300 100644 --- a/src/eval/interpreter.zig +++ b/src/eval/interpreter.zig @@ -515,7 +515,7 @@ pub const Interpreter = struct { defer result_value.decref(&self.runtime_layout_store, roc_ops); // Only copy result if the result type is compatible with ret_ptr - if (try self.shouldCopyResult(result_value, ret_ptr)) { + if (try self.shouldCopyResult(result_value, ret_ptr, roc_ops)) { try result_value.copyToPtr(&self.runtime_layout_store, ret_ptr, roc_ops); } return; @@ -525,7 +525,7 @@ pub const Interpreter = struct { defer result.decref(&self.runtime_layout_store, roc_ops); // Only copy result if the result type is compatible with ret_ptr - if (try self.shouldCopyResult(result, ret_ptr)) { + if (try self.shouldCopyResult(result, ret_ptr, roc_ops)) { try result.copyToPtr(&self.runtime_layout_store, ret_ptr, roc_ops); } } @@ -533,7 +533,7 @@ pub const Interpreter = struct { /// Check if the result should be copied to ret_ptr based on the result's layout. /// Returns false for zero-sized types (nothing to copy). /// Validates that ret_ptr is properly aligned for the result type. - fn shouldCopyResult(self: *Interpreter, result: StackValue, ret_ptr: *anyopaque) !bool { + fn shouldCopyResult(self: *Interpreter, result: StackValue, ret_ptr: *anyopaque, _: *RocOps) !bool { const result_size = self.runtime_layout_store.layoutSize(result.layout); if (result_size == 0) { // Zero-sized types don't need copying @@ -548,7 +548,6 @@ pub const Interpreter = struct { const required_alignment = result.layout.alignment(self.runtime_layout_store.targetUsize()); const ret_addr = @intFromPtr(ret_ptr); if (ret_addr % required_alignment.toByteUnits() != 0) { - // Type mismatch detected at runtime return error.TypeMismatch; } @@ -1852,7 +1851,15 @@ pub const Interpreter = struct { const rendered = try self.renderValueRocWithType(value, inner_rt_var); defer self.allocator.free(rendered); roc_ops.dbg(rendered); - return value; + // dbg returns {} (empty record), not the inner value + // Free the inner value since we're not returning it + value.decref(&self.runtime_layout_store, roc_ops); + // Return empty record - use the same pattern as e_empty_record + // Get the compile-time type of this dbg expression (should be {}) + const ct_var = can.ModuleEnv.varFrom(expr_idx); + const rt_var = try self.translateTypeVar(self.env, ct_var); + const rec_layout = try self.getRuntimeLayout(rt_var); + return try self.pushRaw(rec_layout, 0); }, // no tag handling in minimal evaluator .e_lambda => |lam| { diff --git a/test/fx/dbg_missing_return.roc b/test/fx/dbg_missing_return.roc index d38b2533dc..c6da215ca5 100644 --- a/test/fx/dbg_missing_return.roc +++ b/test/fx/dbg_missing_return.roc @@ -1,5 +1,7 @@ app [main!] { pf: platform "./platform/main.roc" } +import pf.Stdout + main! = || { - dbg "this will break, there return value isn't provided I think" + dbg "this should work now" } diff --git a/test/snapshots/fuzz_crash/fuzz_crash_023.md b/test/snapshots/fuzz_crash/fuzz_crash_023.md index eaec4e7931..36044b80d1 100644 --- a/test/snapshots/fuzz_crash/fuzz_crash_023.md +++ b/test/snapshots/fuzz_crash/fuzz_crash_023.md @@ -281,6 +281,7 @@ UNUSED VALUE - fuzz_crash_023.md:1:1:1:1 TYPE MISMATCH - fuzz_crash_023.md:155:2:157:3 UNUSED VALUE - fuzz_crash_023.md:155:2:157:3 UNUSED VALUE - fuzz_crash_023.md:178:42:178:45 +TYPE MISMATCH - fuzz_crash_023.md:144:9:196:2 # PROBLEMS **PARSE ERROR** A parsing error occurred: `expected_expr_record_field_name` @@ -1046,6 +1047,71 @@ This expression produces a value, but it's not being used: It has the type: _[Blue]_others_ +**TYPE MISMATCH** +This expression is used in an unexpected way: +**fuzz_crash_023.md:144:9:196:2:** +```roc +main! = |_| { # Yeah I can leave a comment here + world = "World" + var number = 123 + expect blah == 1 + tag = Blue + return # Comment after return keyword + tag # Comment after return statement + + # Just a random comment! + + ... + match_time( + ..., # Single args with comment + ) + some_func( + dbg # After debug + 42, # After debug expr + ) + crash # Comment after crash keyword + "Unreachable!" # Comment after crash statement + tag_with_payload = Ok(number) + interpolated = "Hello, ${world}" + list = [ + add_one( + dbg # After dbg in list + number, # after dbg expr as arg + ), # Comment one + 456, # Comment two + 789, # Comment three + ] + for n in list { + Stdout.line!("Adding ${n} to ${number}") + number = number + n + } + record = { foo: 123, bar: "Hello", ;az: tag, qux: Ok(world), punned } + tuple = (123, "World", tag, Ok(world), (nested, tuple), [1, 2, 3]) + multiline_tuple = ( + 123, + "World", + tag1, + Ok(world), # This one has a comment + (nested, tuple), + [1, 2, 3], + ) + bin_op_result = Err(foo) ?? 12 > 5 * 5 or 13 + 2 < 5 and 10 - 1 >= 16 or 12 <= 3 / 5 + static_dispatch_style = some_fn(arg1)?.static_dispatch_method()?.next_static_dispatch_method()?.record_field? + Stdout.line!(interpolated)? + Stdout.line!( + "How about ${ # Comment after string interpolation open + Num.toStr(number) # Comment after string interpolation expr + } as a string?", + ) +} # Comment after top-level decl +``` + +It has the type: + _List(Error) => Error_ + +But the type annotation says it should have the type: + _List(Error) -> Error_ + # TOKENS ~~~zig KwApp,OpenSquare,LowerIdent,CloseSquare,OpenCurly,LowerIdent,OpColon,KwPlatform,StringStart,StringPart,StringEnd,CloseCurly, @@ -2578,7 +2644,7 @@ expect { (patt (type "Error -> U64")) (patt (type "[Red][Blue, Green][ProvidedByCompiler], _arg -> Error")) (patt (type "Error")) - (patt (type "List(Error) -> Error")) + (patt (type "Error")) (patt (type "{}")) (patt (type "Error"))) (type_decls @@ -2625,7 +2691,7 @@ expect { (expr (type "Error -> U64")) (expr (type "[Red][Blue, Green][ProvidedByCompiler], _arg -> Error")) (expr (type "Error")) - (expr (type "List(Error) -> Error")) + (expr (type "Error")) (expr (type "{}")) (expr (type "Error")))) ~~~ diff --git a/test/snapshots/fuzz_crash/fuzz_crash_027.md b/test/snapshots/fuzz_crash/fuzz_crash_027.md index 89e86c4fdd..e310cb5720 100644 --- a/test/snapshots/fuzz_crash/fuzz_crash_027.md +++ b/test/snapshots/fuzz_crash/fuzz_crash_027.md @@ -231,6 +231,7 @@ UNUSED VALUE - fuzz_crash_027.md:1:1:1:1 TYPE MISMATCH - fuzz_crash_027.md:111:2:113:3 UNUSED VALUE - fuzz_crash_027.md:111:2:113:3 TYPE MISMATCH - fuzz_crash_027.md:143:2:147:3 +TYPE MISMATCH - fuzz_crash_027.md:100:9:148:2 # PROBLEMS **LEADING ZERO** Numbers cannot have leading zeros. @@ -972,6 +973,67 @@ It has the type: But the type annotation says it should have the type: _Try(_d)_ +**TYPE MISMATCH** +This expression is used in an unexpected way: +**fuzz_crash_027.md:100:9:148:2:** +```roc +main! = |_| { # Yeah Ie + world = "World" + var number = 123 + expect blah == 1 + tag = Blue + return # Comd + tag + + # Jusnt! + + ... + match_time( + ..., # + ) + some_func( + dbg # bug + 42, # Aft expr + ) + crash "Unreachtement + tag_with = Ok(number) + ited = "Hello, ${world}" + list = [ + add_one( + dbg # Afin list +e[, # afarg + ), 456, # ee + ] + for n in list { + line!("Adding ${n} to ${number}") + number = number + n + } + record = { foo: 123, bar: "Hello", baz: tag, qux: Ok(world), punned } + tuple = (123, "World", tag, Ok(world), (nested, tuple), [1, 2, 3]) + m_tuple = ( + 123, + "World", + tag1, + Ok(world), # Thisnt + (nested, tuple), + [1, 2, 3], + ) + bsult = Err(foo) ?? 12 > 5 * 5 or 13 + 2 < 5 and 10 - 1 >= 16 or 12 <= 3 / 5 + stale = some_fn(arg1)?.statod()?.ned()?.recd? + Stdoline!( + "How about ${ # + Num.toStr(number) # on expr + } as a", + ) +} # Commenl decl +``` + +It has the type: + _List(Error) => Error_ + +But the type annotation says it should have the type: + _List(Error) -> Error_ + # TOKENS ~~~zig KwApp,OpenSquare,LowerIdent,CloseSquare,OpenCurly,LowerIdent,OpColon,KwPlatform,StringStart,StringPart,StringEnd,CloseCurly, @@ -2255,7 +2317,7 @@ expect { (patt (type "Bool -> d where [d.from_numeral : Numeral -> Try(d, [InvalidNumeral(Str)])]")) (patt (type "Error -> U64")) (patt (type "[Red, Blue][ProvidedByCompiler], _arg -> Error")) - (patt (type "List(Error) -> Error")) + (patt (type "Error")) (patt (type "{}")) (patt (type "Error"))) (type_decls @@ -2292,7 +2354,7 @@ expect { (expr (type "Bool -> d where [d.from_numeral : Numeral -> Try(d, [InvalidNumeral(Str)])]")) (expr (type "Error -> U64")) (expr (type "[Red, Blue][ProvidedByCompiler], _arg -> Error")) - (expr (type "List(Error) -> Error")) + (expr (type "Error")) (expr (type "{}")) (expr (type "Error")))) ~~~ diff --git a/test/snapshots/fuzz_crash/fuzz_crash_028.md b/test/snapshots/fuzz_crash/fuzz_crash_028.md index ffedd15fd3c51f51e3605ebd32c3aed6d664b195..57f59a7ee19c92fcf5fc74b646456b36ea0bd0fe 100644 GIT binary patch delta 230 zcmcb+oq5JC<_$rjlfR27a~PUh85#o7Wy8T(lU#ROB51|(o1tw^GXzw zQZw_?6$%oIi&Ik+O7ay-GBS%5(n|A^OEUBG6fzQvfg-62lbaBoyT*PrlBoEC^(BafN`4fLbtlez2&0b!|Ksms4qpLPBCnN_>7^YJx&u vYHA9^Xf*c#osg7j#ialQ@qVSbdZA_}n;FBdH89$4zHx0m3#0Aij@zLC Try(a, [InvalidNumeral(Str)])]"))) + (patt (type "{}"))) (expressions - (expr (type "a where [a.from_numeral : Numeral -> Try(a, [InvalidNumeral(Str)])]")))) + (expr (type "{}")))) ~~~ diff --git a/test/snapshots/statement/dbg_stmt_block_example.md b/test/snapshots/statement/dbg_stmt_block_example.md index bac8ce59a2..39cfa9420a 100644 --- a/test/snapshots/statement/dbg_stmt_block_example.md +++ b/test/snapshots/statement/dbg_stmt_block_example.md @@ -79,7 +79,7 @@ foo = |num| { ~~~clojure (inferred-types (defs - (patt (type "a -> a where [a.to_str : a -> b]"))) + (patt (type "a => {} where [a.to_str : a -> _ret]"))) (expressions - (expr (type "a -> a where [a.to_str : a -> b]")))) + (expr (type "a => {} where [a.to_str : a -> _ret]")))) ~~~ diff --git a/test/snapshots/syntax_grab_bag.md b/test/snapshots/syntax_grab_bag.md index c1f25faf45..9104c386a5 100644 --- a/test/snapshots/syntax_grab_bag.md +++ b/test/snapshots/syntax_grab_bag.md @@ -271,6 +271,7 @@ INCOMPATIBLE MATCH PATTERNS - syntax_grab_bag.md:84:2:84:2 UNUSED VALUE - syntax_grab_bag.md:1:1:1:1 TYPE MISMATCH - syntax_grab_bag.md:155:2:157:3 UNUSED VALUE - syntax_grab_bag.md:155:2:157:3 +TYPE MISMATCH - syntax_grab_bag.md:144:9:196:2 # PROBLEMS **UNDECLARED TYPE** The type _Bar_ is not declared in this scope. @@ -926,6 +927,71 @@ This expression produces a value, but it's not being used: It has the type: __d_ +**TYPE MISMATCH** +This expression is used in an unexpected way: +**syntax_grab_bag.md:144:9:196:2:** +```roc +main! = |_| { # Yeah I can leave a comment here + world = "World" + var number = 123 + expect blah == 1 + tag = Blue + return # Comment after return keyword + tag # Comment after return statement + + # Just a random comment! + + ... + match_time( + ..., # Single args with comment + ) + some_func( + dbg # After debug + 42, # After debug expr + ) + crash # Comment after crash keyword + "Unreachable!" # Comment after crash statement + tag_with_payload = Ok(number) + interpolated = "Hello, ${world}" + list = [ + add_one( + dbg # After dbg in list + number, # after dbg expr as arg + ), # Comment one + 456, # Comment two + 789, # Comment three + ] + for n in list { + Stdout.line!("Adding ${n} to ${number}") + number = number + n + } + record = { foo: 123, bar: "Hello", baz: tag, qux: Ok(world), punned } + tuple = (123, "World", tag, Ok(world), (nested, tuple), [1, 2, 3]) + multiline_tuple = ( + 123, + "World", + tag1, + Ok(world), # This one has a comment + (nested, tuple), + [1, 2, 3], + ) + bin_op_result = Err(foo) ?? 12 > 5 * 5 or 13 + 2 < 5 and 10 - 1 >= 16 or 12 <= 3 / 5 + static_dispatch_style = some_fn(arg1)?.static_dispatch_method()?.next_static_dispatch_method()?.record_field? + Stdout.line!(interpolated)? + Stdout.line!( + "How about ${ # Comment after string interpolation open + Num.toStr(number) # Comment after string interpolation expr + } as a string?", + ) +} # Comment after top-level decl +``` + +It has the type: + _List(Error) => Error_ + +But the type annotation says it should have the type: + _List(Error) -> Error_ + # TOKENS ~~~zig KwApp,OpenSquare,LowerIdent,CloseSquare,OpenCurly,LowerIdent,OpColon,KwPlatform,StringStart,StringPart,StringEnd,CloseCurly, @@ -2463,7 +2529,7 @@ expect { (patt (type "Bool -> d where [d.from_numeral : Numeral -> Try(d, [InvalidNumeral(Str)])]")) (patt (type "Error -> U64")) (patt (type "[Red][Blue, Green][ProvidedByCompiler], _arg -> Error")) - (patt (type "List(Error) -> Error")) + (patt (type "Error")) (patt (type "{}")) (patt (type "Error"))) (type_decls @@ -2509,7 +2575,7 @@ expect { (expr (type "Bool -> d where [d.from_numeral : Numeral -> Try(d, [InvalidNumeral(Str)])]")) (expr (type "Error -> U64")) (expr (type "[Red][Blue, Green][ProvidedByCompiler], _arg -> Error")) - (expr (type "List(Error) -> Error")) + (expr (type "Error")) (expr (type "{}")) (expr (type "Error")))) ~~~ From 55f04a0688bb417af6ac9bc173bd3dc4a388ea73 Mon Sep 17 00:00:00 2001 From: Richard Feldman Date: Wed, 26 Nov 2025 10:03:08 -0500 Subject: [PATCH 3/8] Add more snapshot tests --- test/snapshots/statement/dbg_as_arg.md | 84 +++++++++++++++++++ test/snapshots/statement/dbg_last_in_block.md | 63 ++++++++++++++ 2 files changed, 147 insertions(+) create mode 100644 test/snapshots/statement/dbg_as_arg.md create mode 100644 test/snapshots/statement/dbg_last_in_block.md diff --git a/test/snapshots/statement/dbg_as_arg.md b/test/snapshots/statement/dbg_as_arg.md new file mode 100644 index 0000000000..f478ce37bc --- /dev/null +++ b/test/snapshots/statement/dbg_as_arg.md @@ -0,0 +1,84 @@ +# META +~~~ini +description=Debug as function argument +type=snippet +~~~ +# SOURCE +~~~roc +foo = |f| f(dbg 42) +bar = |f| f(dbg(42)) +~~~ +# EXPECTED +NIL +# PROBLEMS +NIL +# TOKENS +~~~zig +LowerIdent,OpAssign,OpBar,LowerIdent,OpBar,LowerIdent,NoSpaceOpenRound,KwDbg,Int,CloseRound, +LowerIdent,OpAssign,OpBar,LowerIdent,OpBar,LowerIdent,NoSpaceOpenRound,KwDbg,NoSpaceOpenRound,Int,CloseRound,CloseRound, +EndOfFile, +~~~ +# PARSE +~~~clojure +(file + (type-module) + (statements + (s-decl + (p-ident (raw "foo")) + (e-lambda + (args + (p-ident (raw "f"))) + (e-apply + (e-ident (raw "f")) + (e-dbg + (e-int (raw "42")))))) + (s-decl + (p-ident (raw "bar")) + (e-lambda + (args + (p-ident (raw "f"))) + (e-apply + (e-ident (raw "f")) + (e-dbg + (e-tuple + (e-int (raw "42"))))))))) +~~~ +# FORMATTED +~~~roc +foo = |f| f(dbg 42) +bar = |f| f(dbg (42)) +~~~ +# CANONICALIZE +~~~clojure +(can-ir + (d-let + (p-assign (ident "foo")) + (e-lambda + (args + (p-assign (ident "f"))) + (e-call + (e-lookup-local + (p-assign (ident "f"))) + (e-dbg + (e-num (value "42")))))) + (d-let + (p-assign (ident "bar")) + (e-lambda + (args + (p-assign (ident "f"))) + (e-call + (e-lookup-local + (p-assign (ident "f"))) + (e-dbg + (e-num (value "42"))))))) +~~~ +# TYPES +~~~clojure +(inferred-types + (defs + (patt (type "({} -> a) => a")) + (patt (type "({} -> a) => a"))) + (expressions + (expr (type "({} -> a) => a")) + (expr (type "({} -> a) => a")))) +~~~ diff --git a/test/snapshots/statement/dbg_last_in_block.md b/test/snapshots/statement/dbg_last_in_block.md new file mode 100644 index 0000000000..f53f4e46a5 --- /dev/null +++ b/test/snapshots/statement/dbg_last_in_block.md @@ -0,0 +1,63 @@ +# META +~~~ini +description=Debug as last expression in block should return {} +type=snippet +~~~ +# SOURCE +~~~roc +main = || { + dbg "hello" +} +~~~ +# EXPECTED +NIL +# PROBLEMS +NIL +# TOKENS +~~~zig +LowerIdent,OpAssign,OpBar,OpBar,OpenCurly, +KwDbg,StringStart,StringPart,StringEnd, +CloseCurly, +EndOfFile, +~~~ +# PARSE +~~~clojure +(file + (type-module) + (statements + (s-decl + (p-ident (raw "main")) + (e-lambda + (args) + (e-block + (statements + (s-dbg + (e-string + (e-string-part (raw "hello")))))))))) +~~~ +# FORMATTED +~~~roc +main = || { + dbg "hello" +} +~~~ +# CANONICALIZE +~~~clojure +(can-ir + (d-let + (p-assign (ident "main")) + (e-lambda + (args) + (e-block + (e-dbg + (e-string + (e-literal (string "hello")))))))) +~~~ +# TYPES +~~~clojure +(inferred-types + (defs + (patt (type "({}) => {}"))) + (expressions + (expr (type "({}) => {}")))) +~~~ From d4e4b372a7e504df0464f8e7b486141a7b9e228d Mon Sep 17 00:00:00 2001 From: Richard Feldman Date: Wed, 26 Nov 2025 10:42:17 -0500 Subject: [PATCH 4/8] Fix playground --- src/check/Check.zig | 5 +---- src/eval/interpreter.zig | 12 +++++------- test/playground-integration/main.zig | 3 ++- 3 files changed, 8 insertions(+), 12 deletions(-) diff --git a/src/check/Check.zig b/src/check/Check.zig index d537037dc9..c8a86e0b86 100644 --- a/src/check/Check.zig +++ b/src/check/Check.zig @@ -3525,10 +3525,7 @@ fn checkExpr(self: *Self, expr_idx: CIR.Expr.Idx, env: *Env, expected: Expected) try self.unifyWith(expr_var, .{ .flex = Flex.init() }, env); }, .e_dbg => |dbg| { - // dbg checks the inner expression but returns {} (like expect) - // This allows dbg to be used as the last expression in a block - // without affecting the block's return type - // dbg is always effectful since it prints to stderr + // dbg evaluates its inner expression but returns {} (like expect) _ = try self.checkExpr(dbg.expr, env, .no_expectation); does_fx = true; try self.unifyWith(expr_var, .{ .structure = .empty_record }, env); diff --git a/src/eval/interpreter.zig b/src/eval/interpreter.zig index b2d16fe300..ca9e45a7e6 100644 --- a/src/eval/interpreter.zig +++ b/src/eval/interpreter.zig @@ -1845,21 +1845,19 @@ pub const Interpreter = struct { return error.Crash; }, .e_dbg => |dbg_expr| { + // Evaluate and print the inner expression const inner_ct_var = can.ModuleEnv.varFrom(dbg_expr.expr); const inner_rt_var = try self.translateTypeVar(self.env, inner_ct_var); const value = try self.evalExprMinimal(dbg_expr.expr, roc_ops, inner_rt_var); + defer value.decref(&self.runtime_layout_store, roc_ops); const rendered = try self.renderValueRocWithType(value, inner_rt_var); defer self.allocator.free(rendered); roc_ops.dbg(rendered); - // dbg returns {} (empty record), not the inner value - // Free the inner value since we're not returning it - value.decref(&self.runtime_layout_store, roc_ops); - // Return empty record - use the same pattern as e_empty_record - // Get the compile-time type of this dbg expression (should be {}) + // dbg returns {} (empty record) - use same pattern as e_expect const ct_var = can.ModuleEnv.varFrom(expr_idx); const rt_var = try self.translateTypeVar(self.env, ct_var); - const rec_layout = try self.getRuntimeLayout(rt_var); - return try self.pushRaw(rec_layout, 0); + const layout_val = try self.getRuntimeLayout(rt_var); + return try self.pushRaw(layout_val, 0); }, // no tag handling in minimal evaluator .e_lambda => |lam| { diff --git a/test/playground-integration/main.zig b/test/playground-integration/main.zig index 4f64e1b293..27c8f4031d 100644 --- a/test/playground-integration/main.zig +++ b/test/playground-integration/main.zig @@ -433,7 +433,8 @@ fn setupWasm(gpa: std.mem.Allocator, arena: std.mem.Allocator, wasm_path: []cons // Create and instantiate the module instance using the gpa allocator for the VM var module_instance = try bytebox.createModuleInstance(.Stack, module_def, gpa); errdefer module_instance.destroy(); - try module_instance.instantiate(.{}); + // Use a larger stack size (256 KB instead of default 128 KB) to accommodate complex interpreter code + try module_instance.instantiate(.{ .stack_size = 1024 * 256 }); logDebug("[INFO] WASM module instantiated successfully.\n", .{}); From ce66f8512c4e6d1e3cdfb70b4ea6b2a061b7608d Mon Sep 17 00:00:00 2001 From: Richard Feldman Date: Wed, 26 Nov 2025 11:09:51 -0500 Subject: [PATCH 5/8] Remove incorrect `debug` keyword --- src/check/test/type_checking_integration.zig | 8 ++++---- src/parse/Parser.zig | 4 ++-- src/parse/tokenize.zig | 6 ------ 3 files changed, 6 insertions(+), 12 deletions(-) diff --git a/src/check/test/type_checking_integration.zig b/src/check/test/type_checking_integration.zig index dc23477031..bf5820cfc5 100644 --- a/src/check/test/type_checking_integration.zig +++ b/src/check/test/type_checking_integration.zig @@ -1219,15 +1219,15 @@ test "check type - crash" { ); } -// debug // +// dbg // -test "check type - debug" { - // debug returns {} (not the value it's debugging), so it can be used +test "check type - dbg" { + // dbg returns {} (not the value it's debugging), so it can be used // as a statement/side-effect without affecting the block's return type const source = \\y : U64 \\y = { - \\ debug 2 + \\ dbg 2 \\ 42 \\} \\ diff --git a/src/parse/Parser.zig b/src/parse/Parser.zig index d44c48c6f5..487f7907a2 100644 --- a/src/parse/Parser.zig +++ b/src/parse/Parser.zig @@ -1111,7 +1111,7 @@ fn parseStmtByType(self: *Parser, statementType: StatementType) Error!AST.Statem } }); return statement_idx; }, - .KwDbg, .KwDebug => { + .KwDbg => { const start = self.pos; self.advance(); const expr = try self.parseExpr(); @@ -2145,7 +2145,7 @@ pub fn parseExprWithBp(self: *Parser, min_bp: u8) Error!AST.Expr.Idx { .branches = branches, } }); }, - .KwDbg, .KwDebug => { + .KwDbg => { self.advance(); const e = try self.parseExpr(); expr = try self.store.addExpr(.{ .dbg = .{ diff --git a/src/parse/tokenize.zig b/src/parse/tokenize.zig index c9b8fdd25f..779a269b6c 100644 --- a/src/parse/tokenize.zig +++ b/src/parse/tokenize.zig @@ -135,7 +135,6 @@ pub const Token = struct { KwAs, KwCrash, KwDbg, - KwDebug, KwElse, KwExpect, KwExposes, @@ -275,7 +274,6 @@ pub const Token = struct { .KwAs, .KwCrash, .KwDbg, - .KwDebug, .KwElse, .KwExpect, .KwExposes, @@ -369,7 +367,6 @@ pub const Token = struct { .{ "as", .KwAs }, .{ "crash", .KwCrash }, .{ "dbg", .KwDbg }, - .{ "debug", .KwDebug }, .{ "else", .KwElse }, .{ "expect", .KwExpect }, .{ "exposes", .KwExposes }, @@ -2210,9 +2207,6 @@ fn rebuildBufferForTesting(buf: []const u8, tokens: *TokenizedBuffer, alloc: std .KwDbg => { try buf2.appendSlice("dbg"); }, - .KwDebug => { - try buf2.appendSlice("debug"); - }, .KwElse => { try buf2.appendSlice("else"); }, From 41601b871e3b3b0cc9ba564e5485b2cd5c2de3b4 Mon Sep 17 00:00:00 2001 From: Richard Feldman Date: Wed, 26 Nov 2025 11:11:31 -0500 Subject: [PATCH 6/8] Update common misspellings --- src/reporting/common_misspellings.zig | 3 ++- 1 file changed, 2 insertions(+), 1 deletion(-) diff --git a/src/reporting/common_misspellings.zig b/src/reporting/common_misspellings.zig index 5c775bd4a3..f9cc526d7a 100644 --- a/src/reporting/common_misspellings.zig +++ b/src/reporting/common_misspellings.zig @@ -22,6 +22,7 @@ pub const CommonMisspellings = struct { .{ "case", "`case` is not a keyword in Roc. Use `match` for pattern matching." }, .{ "switch", "`switch` is not a keyword in Roc. Use `match` for pattern matching." }, .{ "when", "`when` is not a keyword in Roc. Use `match` for pattern matching." }, + .{ "debug", "`debug` is not a keyword in Roc. Use `dbg` for debug printing." }, .{ "then", "`then` is not a keyword in Roc. You can put the first branch of an `if` immediately after the condition, e.g. `if (condition) then_branch else else_branch`" }, .{ "elif", "Roc uses `else if` for chaining conditions, not `elif`." }, .{ "elseif", "Roc uses `else if` (two words) for chaining conditions." }, @@ -107,7 +108,7 @@ test "identifier misspellings lookup" { const tip = CommonMisspellings.getIdentifierTip("case"); try std.testing.expect(tip != null); try std.testing.expectEqualStrings( - "`case` is not a keyword in Roc. Use `when` for pattern matching.", + "`case` is not a keyword in Roc. Use `match` for pattern matching.", tip.?, ); } From c442c8a0888453b7b56596e0c342ae5d3cb21a8f Mon Sep 17 00:00:00 2001 From: Anton-4 <17049058+Anton-4@users.noreply.github.com> Date: Wed, 26 Nov 2025 19:38:06 +0100 Subject: [PATCH 7/8] valgrind wrapper (#8454) This was the only way I could prevent this warning being spammed thousands of times. --- .github/workflows/ci_manager.yml | 2 ++ .github/workflows/ci_zig.yml | 2 +- ci/valgind_clean.sh | 4 ++++ 3 files changed, 7 insertions(+), 1 deletion(-) create mode 100755 ci/valgind_clean.sh diff --git a/.github/workflows/ci_manager.yml b/.github/workflows/ci_manager.yml index 49a2301720..6183839cfe 100644 --- a/.github/workflows/ci_manager.yml +++ b/.github/workflows/ci_manager.yml @@ -35,6 +35,7 @@ jobs: - '.github/actions/flaky-retry/action.yml' - 'ci/zig_lints.sh' - 'ci/check_test_wiring.zig' + - 'ci/valgrind_clean.sh' - uses: dorny/paths-filter@v3 id: other_filter with: @@ -53,6 +54,7 @@ jobs: - '!.github/actions/flaky-retry/action.yml' - '!ci/zig_lints.sh' - '!ci/check_test_wiring.zig' + - '!ci/valgrind_clean.sh' # Files that ci manager workflows should not run on. - '!.gitignore' - '!.reuse' diff --git a/.github/workflows/ci_zig.yml b/.github/workflows/ci_zig.yml index f5dee1f4d6..e5798165f4 100644 --- a/.github/workflows/ci_zig.yml +++ b/.github/workflows/ci_zig.yml @@ -196,7 +196,7 @@ jobs: run: | sudo apt install -y valgrind valgrind --version - valgrind --leak-check=full --error-exitcode=1 --errors-for-leak-kinds=definite,possible ./zig-out/bin/snapshot --debug + ./ci/valgind_clean.sh --leak-check=full --error-exitcode=1 --errors-for-leak-kinds=definite,possible ./zig-out/bin/snapshot --debug - name: check if statically linked (ubuntu) if: startsWith(matrix.os, 'ubuntu') diff --git a/ci/valgind_clean.sh b/ci/valgind_clean.sh new file mode 100755 index 0000000000..393d908adc --- /dev/null +++ b/ci/valgind_clean.sh @@ -0,0 +1,4 @@ +#!/usr/bin/env bash + +valgrind "$@" 2>&1 | grep -v "Warning: DWARF2 reader: Badly formed extended line op encountered" +exit ${PIPESTATUS[0]} From 587c53210286757876478579d2c17cd59f834198 Mon Sep 17 00:00:00 2001 From: Anton-4 <17049058+Anton-4@users.noreply.github.com> Date: Wed, 26 Nov 2025 21:19:36 +0100 Subject: [PATCH 8/8] use valgrind 3.26 (#8460) try latest valgrind with snap --- .github/workflows/ci_zig.yml | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/.github/workflows/ci_zig.yml b/.github/workflows/ci_zig.yml index e5798165f4..04d37b6ee1 100644 --- a/.github/workflows/ci_zig.yml +++ b/.github/workflows/ci_zig.yml @@ -194,7 +194,7 @@ jobs: # We can re-evaluate as new version of zig/valgrind come out. if: ${{ matrix.os == 'ubuntu-22.04' }} run: | - sudo apt install -y valgrind + sudo snap install valgrind --classic valgrind --version ./ci/valgind_clean.sh --leak-check=full --error-exitcode=1 --errors-for-leak-kinds=definite,possible ./zig-out/bin/snapshot --debug