Skip to content

Show source code in stack traces #150567

@HKalbasi

Description

@HKalbasi

Inspired by Zig, I would like to see source code snippets in the stack trace generated when panicking.

This Zig code:

fn foo(n: usize) i32 {
    const a = [3]i32{ 1, 2, 3 };
    return a[n];
}

pub fn main() void {
    _ = foo(5);
}

Generates this stack trace:

thread 224036 panic: index out of bounds: index 5, len 3
/home/hamid/zig-playground/main.zig:3:13: 0x113fac1 in foo (main.zig)
    return a[n];
            ^
/home/hamid/zig-playground/main.zig:7:12: 0x113e851 in main (main.zig)
    _ = foo(5);
           ^
/home/hamid/.local/share/mise/installs/zig/0.15.1/lib/std/start.zig:618:22: 0x113da9d in posixCallMainAndExit (std.zig)
            root.main();
                     ^

Showing the source code in the stack trace enables quickly understanding the scope and reason of the problem, without needing to lookup the line numbers in the source code. It is especially helpful when the source code has drifted and line numbers are not in sync with the current code.

This is not specific to Zig, other languages also have this feature. For example Python:

Traceback (most recent call last):
  File "/home/hamid/zig-playground/main.py", line 5, in <module>
    foo(5)
    ~~~^^^
  File "/home/hamid/zig-playground/main.py", line 3, in foo
    return a[n]
           ~^^^
IndexError: list index out of range

or Go:

panic: runtime error: index out of range [5] with length 3

goroutine 1 [running]:
main.foo(...)
        /home/hamid/zig-playground/main.go:5
main.main()
        /home/hamid/zig-playground/main.go:9 +0x18
exit status 2

What makes Zig particularly interesting to me, is that it's a low level language similar to Rust with no runtime. If Zig could afford this feature, Rust probably can as well.

Metadata

Metadata

Assignees

No one assigned

    Labels

    A-backtraceArea: BacktracesC-feature-requestCategory: A feature request, i.e: not implemented / a PR.needs-triageThis issue may need triage. Remove it if it has been sufficiently triaged.

    Type

    No type

    Projects

    No projects

    Milestone

    No milestone

    Relationships

    None yet

    Development

    No branches or pull requests

    Issue actions