Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

unreachable code error prevents idiomatic usage of defer #2198

Closed
andrewrk opened this issue Apr 5, 2019 · 6 comments
Closed

unreachable code error prevents idiomatic usage of defer #2198

andrewrk opened this issue Apr 5, 2019 · 6 comments
Milestone

Comments

@andrewrk
Copy link
Member

andrewrk commented Apr 5, 2019

const std = @import("std");
const assert = std.debug.assert;

pub fn main() void {
    const ptr = std.debug.global_allocator.create(i32);
    defer std.debug.global_allocator.destroy(ptr);

    std.os.exit(0);
}

Expected: this compiles.

Actual:

/home/andy/dev/zig/build/test.zig:6:11: error: unreachable code
    defer std.debug.global_allocator.destroy(ptr);
          ^
@andrewrk andrewrk added this to the 0.5.0 milestone Apr 5, 2019
@tiehuis
Copy link
Member

tiehuis commented Apr 5, 2019

Existing example of this in the self-hosted compiler.

https://github.com/ziglang/zig/blob/master/src-self-hosted/main.zig#L65-L68

@andrewrk
Copy link
Member Author

andrewrk commented Apr 5, 2019

This might be solved with #283

@daurnimator
Copy link
Contributor

oooo, this is really interesting, and infact a "good thing"!
If a longjmp-ing function is defined as noreturn then we correctly catch a skipped defer at compile time.

@Rocknest
Copy link
Contributor

Rocknest commented Apr 6, 2019

So defer should run before std.os.exit()?

@daurnimator
Copy link
Contributor

So defer should run before std.os.exit()?

I'm not sure that's useful in the general case. If I have a function annotated noreturn like exit() do you even want defer statements to run?
What about if it's a sometimes-noreturn function like execve() (which can return an error if e.g. the executable is invalid)? => in that case I would probably want defer to run on failure but other times not at all.

@andrewrk
Copy link
Member Author

andrewrk commented Jan 7, 2020

This is now a duplicate of accepted proposal #2654. See the explanation there. Preferred solution to the above code is:

defer unreachable;

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
Labels
None yet
Projects
None yet
Development

No branches or pull requests

4 participants