How Elixir Runs Modules And Functions In Elixir Runtime — Tentamen Software Testing Blog

Image for post
Image for post
BEAM process in macOS

TL;DR

In the previous post, we presented the most powerful Elixir Feature, Macros. Today we move on to modules and functions in runtime. This post is part of the functional language series, and it is based on the remarkable book Elixir In Action by Sasa Juric.

Elixir Runtime

Elixir runtime is BEAM instance.

BEAM is the virtual machine at the core of the Erlang Open Telecom Platform (OTP).[1] BEAM is part of the Erlang Run-Time System (ERTS), which compiles Erlang and Elixir’s source code into bytecode, which is then executed on the BEAM. [source]

Let’s examine the BEAM os process on my macOS by starting. iex:

Image for post
Image for post
BEAM process in macOS

From this, it is clear that I used asdf for Erlang and Elixir installation on my macOS. It is also clear that starting iex requires several BEAM program switch (--) options.

To run Elixir Module and it’s functions, that module must be first compiled into the BEAM bytecode. Elixir Module source file with .ex the extension is compiled to the bytecode with the filename not related to the source file name. In our example, we will run the following module. To compile it, we are using elixirc the program.

Image for post
Image for post
How To Compile Elixir Source File

Remember that part of Elixir’s application deployment is moving those bytecode files to the production machine. The source is not needed. It is important to note the file name of the compiled bytecode:

Elixir.IntroToSoftwareTesting.FaultyPrograms.beam

How to run this bytecode in iex?

Image for post
Image for post
How To Load BEAM bytecode in iex

We used import statement to load module bytecode in iex shell. Note that when you run:

iex faulty_programs.ex iex automatically compiles and imports a module, but the compilation is done in memory so bytecode the file will not be generated on the filesystem.

Sometimes it is useful to know default paths where BEAM is looking for bytecode files. You can get this info with:

:code.get_path erlang function.

Output of :code.get_path

Remember

  • the filename of module compiled bytecode
  • how to compile
  • how to import
  • how to deploy
  • what does :code.get_path do

Originally published at https://blog.tentamen.eu on November 4, 2020.

Written by

Founder of Tentamen, software testing agency.

Get the Medium app

A button that says 'Download on the App Store', and if clicked it will lead you to the iOS App store
A button that says 'Get it on, Google Play', and if clicked it will lead you to the Google Play store