context-capabilities-initiative icon indicating copy to clipboard operation
context-capabilities-initiative copied to clipboard

How do we model globals?

Open yoshuawuyts opened this issue 2 years ago • 2 comments

Right now we don't have a design yet for how to model globals. We might expect Allocator to be a context capability, but right now that has to be set through #[global_allocator]. It'd be great if we could model that too using context capabilities.

Examples

Current

This is how to declare a global allocator today (example using wee-alloc):

// Use `wee_alloc` as the global allocator.
#[global_allocator]
static ALLOC: wee_alloc::WeeAlloc = wee_alloc::WeeAlloc::INIT;

fn main() {
    let v = vec![1, 2, 3];
}

Proposed

What I'm wondering is whether we'd be able to replace the attribute using with in global position instead:

// Use `wee_alloc` as the global allocator.
with std::alloc::Allocator = wee_alloc::WeAlloc::INIT;

fn main() {
    let v = vec![1, 2, 3];
}

This would be equivalent to doing:

fn main() {
    with std::alloc::Allocator = wee_alloc::WeAlloc::INIT {
        let v = vec![1, 2, 3];
    }
}

Open Questions

  • What should the semantics for this be?
  • What should the syntax for this be?
  • Would this be useful for other context capabilities beyond allocation?
  • What would a migration of #[global_allocator] to this look like?
  • … probably other questions too? Please comment here if there are any other questions we should figure out?

yoshuawuyts avatar Jan 11 '22 16:01 yoshuawuyts

Something I forgot to add: but I believe there is a connection between platform triples and which capabilities are exposed by default. For example wasm32-unknown-unknown will not ship with either an allocator or async runtime, but a (potential) wasm32-browser-wasi platform could be expected to provide both.

yoshuawuyts avatar Jan 11 '22 16:01 yoshuawuyts

For globals like this we may want to make them un-overridable for soundness, e.g. using the final keyword.

cc @joshtriplett

tmandry avatar Jan 11 '22 19:01 tmandry