Constraints for `@generated` function

I’ve made progress on this thanks to helpful guidance from @thautwarm. Here’s my current understanding of the constraints, in case it might be helpful to others:

Like macros, a generated function requires building an AST. Most discussions of “code in generated functions” aren’t very clear about this, but there are really two kinds of code involved, with different constraints:

  • There’s the code you use the build the AST. The constraints on this are relatively loose. The big thing is, there are no guarantees regarding when it will execute, so you should avoid referencing global state. Also as I understand it, eval is disallowed here.
    Also, any reference in this code to the value passed to the function will be interpreted not as the value, but as its type (good details on this part in the docs).

  • Then there’s the code that actually ends up in the AST. Here the value passed in refers to the actual value, but you need to interpolate with $ to express it. Also, this portion is very constrained in that it does not allow closures (it’s fine to call a closure from a generated function, but not within the AST. A closure is a function that refers to values outside its scope.

2 Likes