Skip to content

resource annotations #158

@andrewrk

Description

@andrewrk

Strap your jet pack on because we're going for a pie-in-the-sky adventure.

I propose a builtin function called @resource_acquire() which returns a u64. This is an opaque identifier which is probably just random bytes. Zig code may then store this identifier somewhere, like this:

const want_resource_tracking = @compile_var("debug_safety_on");
const ResourceIdType = if (want_resource_tracking) u64 else void;
struct HeapEntry {
    debug_id: ResourceIdType,
    // ....
}
fn malloc(inline T: type, count: usize) -> %[]T {
    if (want_resource_tracking) some_heap_entry.debug_id = @resource_acquire();
}
fn free(inline T: type, mem: []T) {
    if (want_resource_tracking) @resource_release(some_heap_entry.debug_id);
}

Now, in debug mode, Zig will add safety checks to catch the following scenarios:

  • (easy) (runtime) Releasing a resource too many times.
  • (easy) (runtime) Program reaches end with unreleased resources.
  • (hard) (compile error) The compiler was able to determine that the resource couldn't possibly have been released, or that the resource will be released twice.
  • (hard) (runtime) Track the memory location where the resource id is stored and reference count it. If references drop to 0 before it gets released, runtime error, the resource leaked. The stack trace at the location the ref count drops to 0 will be very useful.

The standard library would implement these semantics for all resources, for example file streams, network connections.

If the implementation is fast enough this could even be viable for detecting failure to flush a stream, such as stdout. When anything is written, acquire a resource, unless one is already acquired. When flush is called, release the resource, unless already released.

Depending on how advanced the safety checks are, this might not even need to be a builtin function. It could just be a standard library function.

In the event of an error we would want to print the stack trace of the resource being acquired, so we might want a @get_stack_trace() builtin function. We want that anyway. Separate issue.

Metadata

Metadata

Assignees

No one assigned

    Labels

    enhancementSolving this issue will likely involve adding new logic or components to the codebase.proposalThis issue suggests modifications. If it also has the "accepted" label then it is planned.

    Type

    No type

    Projects

    No projects

    Relationships

    None yet

    Development

    No branches or pull requests

    Issue actions