# Minimal self-containing example of code transformation using generated functions?

**URL:** <https://discourse.julialang.org/t/minimal-self-containing-example-of-code-transformation-using-generated-functions/88535>\
**Category:** Internals & Design\
**Tags:** runtimegeneratedfunc\
**Created:** [October 10, 2022, 9:15pm UTC](https://discourse.julialang.org/t/minimal-self-containing-example-of-code-transformation-using-generated-functions/88535 "2022-10-10T21:15:09Z")\
**Posts on this page:** 1\
**Showing post:** 2

<div class="post-metadata">

**Author:** ![dfdx](https://sea2.discourse-cdn.com/julialang/user_avatar/discourse.julialang.org/dfdx/32/120_2.png) [@dfdx](https://discourse.julialang.org/u/dfdx)\
**Post date:** [October 10, 2022, 10:13pm UTC](https://discourse.julialang.org/t/minimal-self-containing-example-of-code-transformation-using-generated-functions/88535/2 "2022-10-10T22:13:26Z")

</div>

As always, writing down a question brings a lot of new ideas. Such as watching the Jarrett’s talk on Cassette design, especially [this moment](https://youtu.be/lyX-isPDS2M?t=1712) where he explains that generated functions can return either an expressions, or `CodeInfo` instance. So I tried this:

```julia
@generated function transform(f, args...)
    ci = @code_lowered f(args...)
    return ci
end

inc(x) = x + 1
transform(inc, 2.0)

```

which didn’t work and just returned an empty `Core.CodeInfo[]`. The problem of course was that generated functions work not on values, but on types, so `f, args` are actually `(typeof(inc), (Float64,))`. Thus we need a slightly different way of getting the `CodeInfo`:

```julia
@generated function transform(f, args...)
    ci = code_lowered(f.instance, args)[1]
    return ci
end

transform(inc, 2.0)

```

This version fails with segfault, but in this case it’s a good thing - it means that Julia accepted the new `CodeInfo` instance, just couldn’t validate it. I know that generating a valid instance of CI can be done using tools from the [JuliaCompilerPlugins](https://github.com/JuliaCompilerPlugins) org, but if somebody wants to jump in with a quick example, you are welcome!

---

_[View the full topic](https://discourse.julialang.org/t/minimal-self-containing-example-of-code-transformation-using-generated-functions/88535)._
