zig icon indicating copy to clipboard operation
zig copied to clipboard

PROPOSAL: introduce a `final` keyword to differenciate between comptime constants and runtime "constants"

Open Lking03x opened this issue 6 months ago • 4 comments

Problems With The Current Behavior

Zig code mix comptime and runtime constructs but it's often hard to distinguish between them but with zig's emphasis on comptime constructs and manipulation it, I think, a necessity to ease this process.

const N = @import(...);
const T = @import(...).T;

const c1 = magicNumber();
var a: u8 = 120;

pub fn main() void {
	const b = getCurrentTime(); // ???
	const c2 = buildNo(); // ???
	N.doStuff(b);
	N.doStuff(c2);
	...
}

The final Proposal

const N = @import(...); // a namespace
const T = @import(...).T; // a type

const b = magicNumber(); // 'static' constant (comptime known)
var a: u8 = 120; // 'static' variable

pub fn main() void {
	final b1 = getCurrentTime();
	const b2 = buildNo(); // 'static' constant (comptime known)
	N.doStuff(b2);
	N.doStuff(b1);
	...
}
  1. All comptime known/only constructs should use const or comptime var and runtime known/only ones use var or final
  2. Mixed expressions result are resolved accordingly
    • comptime and comptime = comptime => const or comptime var
    • comptime and runtime = runtime => var or final
    • runtime and runtime = runtime => var or final
  3. Container level declarations cannot be final
  4. const also always means 'static'
fn foo(i: u32) void {
	const n = 1234;
	doStuff(n, i);
}

will always be like doing

const n = 1234;
fn foo(i: u32) void {
	doStuff(n, i);
}
  1. Runtime constants cannot be final
    • const c = expr; <=> const c = comptime expr;
    • final b = comptime expr; will be illegal
    • var a = comptime expr; remains legal

Lking03x avatar Aug 02 '24 21:08 Lking03x