WebAssembly / component-model

Repository for design and specification of the Component Model
Other
978 stars 82 forks source link

feature: pure function mark #321

Open oovm opened 8 months ago

oovm commented 8 months ago

I need a mechanism to mark functions as having no side effects (pure functions).

Most external interfaces come with state, so I recommend having side effects by default and adding the @pure(after https://github.com/WebAssembly/component-model/issues/58) tag if it is a pure function

Because pure functions and side-effect functions have different behaviors in dead code elimination analysis.

Pure functions such as wasi:clocks/monotonic-clock/now can be deleted directly from the control flow if they are not used.

However, functions such as wasi:random/random/get-random-u64 may change external state, so even if their return value is not used, they cannot be deleted.

lukewagner commented 8 months ago

This is an interesting idea. Since we wouldn't be able to actually enforce purity, the "pure" mark would just be advisory, which is I think what you're suggesting. But this means that someone might (for valid reasons) virtualize wasi:clocks/monotonic-clock.now to log every time now was called, and a compiler that optimized away the call to now would then be affecting the observable behavior of the program. However, if pure was considered a part of the interface contract of now, then we could say that's actually fine. But this makes me think we shouldn't be putting purity in a generic (open-ended, ignorable, extensible) syntax, but rather something that is a built-in/official part of the WIT syntax and C-M AST, so that it's just as official a part of the contract as the types (even if not semantically enforced).