#Why does this have to be comptime marked?

1 messages · Page 1 of 1 (latest)

strange wadi
#

a pointer to an intermediate value like&.{ <comptime-known values> } will be stored in global read-only memory so long as the data is comptime-known. but if it contains even one runtime value, it will instead be stored on the stack and freed when the function returns

functions are not automatically called at comptime (unless inline), so &.{ .init(1, 2, 3) } will be considered to contain runtime values and thus stored on the stack. you need to explicit call it in a comptime expression/block for the value to be comptime-known

umbral yarrow
#

ah makes sense. What would be a runtime value? I currently only can think of user input or info gathered through files or so

#

but wait, the struct does not contain any runtime value or am I mistaken?

strange wadi
#

this is a bit of a confusing footgun and where the data will be stored can be ambiguous at times. in general, if you rely on returning references to intermediate values, it is good practice to always explicitly usecomptime &.{ ... } because then any captures of runtime values will be caught at compile time

#

by "runtime" I just mean anything that isn't pure or comptime-known

#

e.g. function arguments or global variables

umbral yarrow
#

alright, thanks

strange wadi
#

your implementation of init is pure, but the compiler doesn't know that/go far enough to analyze and learn that. for all it knows it could be implemented as return .{ some global_mutable_variable }

umbral yarrow
#

I didnt look much into comptime, is there a way to mark a function as comptime so when I use this function, I dont have to use comptime to avoid missing it and having a silent uaf tragedy?

strange wadi
#

you can implement it asts fn init(...) This { return comptime blk: { // ... break :blk ...; }; } but then the user still needs to call it in a comptime context, unless you also make it an inline fn

umbral yarrow
#

hm, idk about that. is pattern: comptime []const Pixel, a possibility?

strange wadi
#

it will have a similar effect of protecting against mistakes with compile errors, but the caller still needs to explicitly be in comptime

#

basically the only way to get the compiler to automatically always call a function at comptime is to use inline fn to evaluate the call eagerly and return comptime/make the entire body a comptime block to ensure it has no runtime side effects

umbral yarrow
#

alright, I think I like the simple comptime variable more, just less code and if it prevents me from compiling bad code, its fine

strange wadi
#

yeah, it's probably more flexible than forcing it upon the function, because maybe you want to init with values that aren't comptime known