zachallaun
Note: There are a few folks I’d really love to hear from, time permitting. Pinging in case the title isn’t catchy enough
@dorgan @scohen @scottming @mhanberg @lukaszsamson @zachdaniel
Proof-of-concept on GitHub: GitHub - zachallaun/lib_elixir · GitHub
Motivation
There has been an ongoing effort in Elixir to add or improve APIs to make code analysis easier. Primarily, this has been done to support developer tools, namely language servers, allowing them to use the same mechanisms that Elixir itself uses to analyze code.
The first major fruits of this effort shipped in Elixir 1.17 in the shape of new APIs in Macro.Env, but useful improvements have been added to Code and Macro continuously, and there are a number of open issues under discussion that could lead to further improvements.
The problem, then, becomes accessing these new improvements while still supporting older versions of Elixir. Existing libraries handle this in different ways:
- Sourceror vendors in parts of
Code(and related Erlang source) related to formatting in order to support formatting in versions prior to Elixir 1.13. - Lexical vendors in
Codeand parts ofMacro(and related Erlang source) in order to parse and analyze source code in an environment that doesn’t interfere with user project dependencies. - Next LS bundles the latest version of Elixir and uses that to compile and analyze user code.
These methods have significant trade-offs. Vendoring in code is a time-consuming, manual, and potentially buggy process, as modules have to be copied in and namespaced so that they don’t conflict with the runtime. Bundling Elixir requires user code to be compiled in a different environment than that code will be run in production, which can cause spurious warnings or other subtle differences.
Ultimately, the problem is that Elixir is a shared dependency that library authors do not control.
Elixir as a library
I’ve been experimenting with a new library that allows for the Elixir standard library to be included as a dependency in a way that does not conflict with the runtime version of Elixir.
The idea is to allow library authors to replace their usage of standard library modules with namespaced ones. For the following examples, I’ll use Spitfire, which uses features of Macro.Env that were introduced in Elixir 1.17 (see here). Here’s an example of how Spitfire might use this:
defmodule Spitfire.Env do
@moduledoc """
Environment querying
"""
+ alias Spitfire.LibElixir.Macro, as: Macro
@env %{
- Macro.Env.prune_compile_info(__ENV__)
+ Macro.Env
+ |> struct(Map.from_struct(__ENV__))
+ |> Macro.Env.prune_compile_info()
| line: 0,
file: "nofile",
module: nil,
function: nil,
context_modules: []
}
defp env, do: @env
...
end
This would allow Spitfire to support versions of Elixir earlier than 1.17. (More on that below when I discuss challenges, but I think 1.15+.)
Namespacing
So, how do we compile a specific version of the Elixir standard library and then use it as in Spitfire.LibElixir.Macro.Env?
The strategy is the same one used by Lexical to ensure that its dependencies don’t conflict with user dependencies at runtime. We call it namespacing. (Hat tip @scohen, who came up with this for Lexical.)
Here’s the gist of it:
- Compile your Elixir and Erlang modules to bytecode:
.appand.beamfiles. - Read them in as Abstract Forms using
:beam_lib.chunks(path, [:abstract_code]). - Walk the abstract code, rewriting module names to their namespaced counterparts:
Code -> Spitfire.LibElixir.Code:elixir_tokenizer -> :spitfire_lib_elixir_tokenizer
- Recompile the modified abstract forms using
:compile.forms(...), writing the resulting binary out to a new.beam:Elixir.Code.beam -> Elixir.Spitfire.LibElixir.Code.beamelixir_tokenizer.beam -> spitfire_lib_elixir_tokenizer.beam
- Do something similar with the
.app:elixir.app -> spitfire_lib_elixir.app
There’s a bit more to it, but this isn’t a hypothetical:
~/dev/forks/spitfire main*
> iex -S mix run --no-compile
Erlang/OTP 25 [erts-13.2.2.10] [source] [64-bit] [smp:32:32] [ds:32:32:10] [async-threads:1] [jit:ns]
Interactive Elixir (1.15.8) - press Ctrl+C to exit (type h() ENTER for help)
iex(1)> alias Foo.Bar.Baz, as: Qux
Foo.Bar.Baz
iex(2)> env = struct(Spitfire.LibElixir.Macro.Env, Map.from_struct(__ENV__))
%Spitfire.LibElixir.Macro.Env{
aliases: [],
...
}
iex(3)> Spitfire.LibElixir.Macro.Env.expand_alias(env, [], [:Qux])
{:alias, Foo.Bar.Baz}
Challenges and open questions
At the moment, this is just a proof-of-concept and there’s a lot left to figure out.
When and how to compile?
The current proof-of-concept library is using a Mix compiler that downloads an Elixir archive from GitHub, compiles only the stdlib (make erlang app stdlib), namespaces the resulting *.beam files and app, and then sticks them in _build/dev/lib/lib_elixir/ebin.
defmodule Spitfire.MixProject do
...
def project do
[
...,
lib_elixir: [{Spitfire.LibElixir, "v1.17.2"}]
]
end
...
defp deps do
[
...,
{:lib_elixir, path: "..."}
]
end
end
This almost works, but not quite. Something’s causing protocol consolidation to fail:
14:17:49.007 [error] Task #PID<0.1890.0> started from #PID<0.94.0> terminating
** (FunctionClauseError) no function clause matching in Spitfire.LibElixir.List.Chars.Spitfire.LibElixir.Atom."-inlined-__impl__/1-"/1
Spitfire.LibElixir.List.Chars.Spitfire.LibElixir.Atom."-inlined-__impl__/1-"(:target)
(elixir 1.15.8) lib/protocol.ex:679: Protocol.each_struct_clause_for/3
(elixir 1.15.8) lib/enum.ex:1693: Enum."-map/2-lists^map/1-1-"/2
(elixir 1.15.8) lib/protocol.ex:657: Protocol.change_struct_impl_for/4
(elixir 1.15.8) lib/protocol.ex:619: Protocol.change_debug_info/3
(elixir 1.15.8) lib/protocol.ex:570: Protocol.consolidate/2
(mix 1.15.8) lib/mix/tasks/compile.protocols.ex:140: Mix.Tasks.Compile.Protocols.consolidate/4
(elixir 1.15.8) lib/task/supervised.ex:101: Task.Supervised.invoke_mfa/2
Function: #Function<9.26660727/0 in Mix.Tasks.Compile.Protocols.consolidate/6>
Args: []
I’m not yet sure why this happens. If you compile with mix compile --no-protocol-consolidation and then hop in iex with iex -S mix run --no-compile, it succeeds for Spitfire.LibElixir.List.Chars.Spitfire.LibElixir.Atom.__impl__(:for), but not for :target.
Anyways, I’m not sure whether this is necessarily the right direction and am open to suggestions.
How much to compile/include?
Right now, all of Elixir’s stdlib is being namespaced and included. An alternative might be to whitelist certain modules, like Code, Macro, Module, etc. that are likely useful to library authors.
This might solve the protocol consolidation issue above, but it could also lead to subtle or difficult-to-find bugs when a namespaced module calls into a non-namespaced module expecting certain behavior.
Version compatibility
The exact format of the data in *.beam files may change from version to version, but this strategy relies on files compiled on one version being loadable on another. I already found some incompatibility related to binaries that changed in 1.15, meaning that LibElixir 1.17.2 won’t run on any Elixir earlier than 1.15. This creates “windows of compatibility” that would need to be kept track of.
Is this even a good idea?
This is the final question. Is this generally useful and worth the effort? Are there gotchas I’m missing?
Any feedback greatly appreciated.
Trending in RFCs
Other Trending Topics
Categories:
Sub Categories:
Forums
Popular Tags
- #ecto
- #liveview
- #troubleshooting
- #learning-elixir
- #deployment
- #library
- #erlang
- #testing
- #genserver
- #mix
- #absinthe
- #remote-other
- #otp
- #plug
- #how-to-question
- #macros
- #postgres
- #channels
- #elixirconf
- #exunit
- #discussion
- #code-sync
- #javascript
- #podcasts
- #onsite
- #dialyzer
- #docker
- #authentication
- #umbrella
- #full-time-contract
- #podcasts-by-brainlid
- #ecto-query
- #elixir-ls
- #blog-post
- #phoenix_html
- #iex
- #graphql
- #ai
- #genstage
- #elixirconf-us
- #websockets
- #supervisor
- #advent-of-code
- #distillery
- #processes
- #api
- #forms
- #metaprogramming
- #security
- #hex











First 10 of 23 Posts
josevalim
Very cool exploration @zachallaun!
Just some ideas (feel free to fully ignore them):
You can probably skip protocols and their implementations from
lib_elixir. All of our protocols and their implementations are public, so it is very unlikely they will change between versions in an incompatible way.Perhaps instead of allowing some modules to be removed, you could ask developers to list which modules they want to use, then you traverse their abstract code and find what they depend on, and convert these too, recursively. This means that Spitfire, which only really needs the tokenizer, gets the minimum stuff they need. You may have some corner cases, for example if we use some module conditionally, but then you can manually add those (and they should be few), such as the
string_tokenizerused by the tokenizer.zachallaun
Thank you so much for your thoughts, José! It gives me a lot more confidence knowing you’ve looked the idea over and that no hard blockers immediately came to mind.
I think skipping protocols makes sense. (It also lets me strip out some code that’s transforming debug_info.)
I like the idea of the user specifying which modules to use and walking the abstract code to find dependencies. I’ll likely work on that next.
I do have one more question that you’d probably have some insight on, José: What’s the right way to handle configuration?
Let’s say you have user project
proj, which depends onlib_aandlib_b, both of which depend onlib_elixirconfigured for different versions and modules.Right now,
lib_elixirspecifies a Mix compiler (Mix.compilers() ++ [:lib_elixir]) so that it runs after it compiles its own code, but before anything depending on it compiles, and then it uses the privateMix.ProjectStackto get configuration info. This probably isn’t a good idea.Instead, it could require that code depending on
lib_elixirspecify the compiler beforeMix.compilers()so that it runs in the context of that project (and therefore doesn’t have to use the project stack):Any thoughts?
josevalim
Can you expand a bit more on what you mean by configuration? Which configuration are you acessing and why you need Mix.ProjectStack?
zachallaun
Configuration in this case is just the Elixir module name that serves as a namespace, like
MyLib.LibElixir, and the target modules you’d like to use, like[Code, Macro, Macro.Env].josevalim
You could have that on your mix.exs and read it with Mix.Project.config (or get). Would that work?
zachallaun
Yep, that seems to work just fine.
As a quick update, here’s what it currently takes to get Spitfire using lib_elixir with all tests passing while running on Elixir 1.15 (cc @mhanberg):
zachdaniel
So, one thing to note here is that
Ignitercurrently depends onspitfire, using it to provide context aware source-code patches. This also means that packages that exposeIgniterinstallers or composable functions also depend onspitfire(i.e Ash). There are various reasons we couldn’t make this a dev-only dependency, primarily around DX/UX (DX being folks writing igniter-installers/tasks and UX being end users running them).Ultimately this means that in order for anyone to compile their Ash application they’d have to be able to download an archive, and deal w/ the associated costs of having the new dependency, which naturally is going to be problematic for our use case. We’d have to stop using spitfire if it went that route.
It may be the case that
Igniterneeds its own thing likeSpitfire. Or perhapslib_elixir'swork can be disabled in some way forcing dependencies to rely on the current elixir version instead. But then we’d be back to defensively writing code.I don’t really have an answer here unfortunately. It does seem like igniter would be the “odd man out” so-to-speak here. Unlike language servers, its depended on by applications directly and interacted with mix tasks.
josevalim
Why does Igniter need spitfire instead of the Elixir parser? Do you need error tolerance?
Also lib_elixir could extract the relevant files with an explicit step, and then check them into version control?
zachdaniel
Error tolerance was the idea, yes. It may not be strictly necessary though.
Checking the files necessary into the repo would work I think. It would need to also add in its custom compiler I think?
josevalim
I am not sure if error tolerance here is beneficial. It means that, once Igniter updates the file, you will have fixed the mistake, but you may have fixed it in a way that’s completely wrong?