Utilities for managing code compilation, code evaluation, and code loading.
This module complements Erlang's :code module
to add behavior which is specific to Elixir. For functions to
manipulate Elixir's AST (rather than evaluating it), see the
Macro module.
Working with files
This module contains three functions for compiling and evaluating files. Here is a summary of them and their behavior:
require_file/2- compiles a file and tracks its name. It does not compile the file again if it has been previously required.compile_file/2- compiles a file without tracking its name. Compiles the file multiple times when invoked multiple times.eval_file/2- evaluates the file contents without tracking its name. It returns the result of the last expression in the file, instead of the modules defined in it. Evaluated files do not trigger the compilation tracers described in the next section.
In a nutshell, the first must be used when you want to keep track of the files handled by the system, to avoid the same file from being compiled multiple times. This is common in scripts.
compile_file/2 must be used when you are interested in the modules defined in a
file, without tracking. eval_file/2 should be used when you are interested in
the result of evaluating the file rather than the modules it defines.
The functions above work with Elixir source. If you want to work
with modules compiled to bytecode, which have the .beam extension
and are typically found below the _build directory of a Mix project,
see the functions in Erlang's :code module.
Code loading on the Erlang VM
Erlang has two modes to load code: interactive and embedded.
By default, the Erlang VM runs in interactive mode, where modules are loaded as needed. In embedded mode the opposite happens, as all modules need to be loaded upfront or explicitly.
You can use ensure_loaded/1 (as well as ensure_loaded?/1 and
ensure_loaded!/1) to check if a module is loaded before using it and
act.
ensure_compiled/1 and ensure_compiled!/1
Elixir also includes ensure_compiled/1 and ensure_compiled!/1
functions that are a superset of ensure_loaded/1.
Since Elixir's compilation happens in parallel, in some situations you may need to use a module that was not yet compiled, therefore it can't even be loaded.
When invoked, ensure_compiled/1 and ensure_compiled!/1 halt the
compilation of the caller until the module becomes available. Note that
the distinction between ensure_compiled/1 and ensure_compiled!/1
is important: if you are using ensure_compiled!/1, you are
indicating to the compiler that you can only continue if said module
is available.
If you are using Code.ensure_compiled/1, you are implying you may
continue without the module and therefore Elixir may return
{:error, :unavailable} for cases where the module is not yet available
(but may be available later on).
For those reasons, developers must typically use Code.ensure_compiled!/1.
In particular, do not do this:
case Code.ensure_compiled(module) do
{:module, _} -> module
{:error, _} -> raise ...
endFinally, note you only need ensure_compiled!/1 to check for modules
being defined within the same project. It does not apply to modules from
dependencies as dependencies are always compiled upfront.
In most cases, ensure_loaded/1 is enough. ensure_compiled!/1
must be used in rare cases, usually involving macros that need to
invoke a module for callback information. The use of ensure_compiled/1
is even less likely.
Compilation tracers
Elixir supports compilation tracers, which allow modules to observe constructs
handled by the Elixir compiler when compiling files. A tracer is a module
that implements the trace/2 function. The function receives the event name
as first argument and Macro.Env as second and it must return :ok. It is
very important for a tracer to do as little work as possible synchronously
and dispatch the bulk of the work to a separate process. Slow tracers will
slow down compilation.
You can configure your list of tracers via put_compiler_option/2. The
following events are available to tracers:
:start- (since v1.11.0) invoked whenever the compiler starts to trace a new lexical context. A lexical context is started when compiling a new file or when defining a module within a function. Note evaluated code does not start a new lexical context (because they don't track unused aliases, imports, etc) but defining a module inside evaluated code will.Note this event may be emitted in parallel, where multiple files/modules invoke
:startand run at the same time. The value of thelexical_trackerof the macro environment, albeit opaque, can be used to uniquely identify the environment.:stop- (since v1.11.0) invoked whenever the compiler stops tracing a new lexical context, such as a new file.{:import, meta, module, opts}- traced whenevermoduleis imported.metais the import AST metadata andoptsare the import options.{:imported_function, meta, module, name, arity}and{:imported_macro, meta, module, name, arity}- traced whenever an imported function or macro is invoked.metais the call AST metadata,moduleis the module the import is from, followed by thenameandarityof the imported function/macro. A :remote_function/:remote_macro event may still be emitted for the imported module/name/arity.{:imported_quoted, meta, module, name, [arity]}- traced whenever an imported function or macro is processed inside aquote/2.metais the call AST metadata,moduleis the module the import is from, followed by thenameand a list ofaritiesof the imported function/macro.{:alias, meta, alias, as, opts}- traced wheneveraliasis aliased toas.metais the alias AST metadata andoptsare the alias options.{:alias_expansion, meta, as, alias}traced whenever there is an alias expansion for a previously definedalias, i.e. when the user writesaswhich is expanded toalias.metais the alias expansion AST metadata.{:alias_reference, meta, module}- traced whenever there is an alias in the code, i.e. whenever the user writesMyModule.Foo.Barin the code, regardless if it was expanded or not.{:require, meta, module, opts}- traced whenevermoduleis required.metais the require AST metadata andoptsare the require options. If themetaoption contains the:from_macro, then module was called from within a macro and therefore must be treated as a compile-time dependency.{:struct_expansion, meta, module, keys}- traced whenevermodule's struct is expanded.metais the struct AST metadata andkeysare the keys being used by expansion{:remote_function, meta, module, name, arity}and{:remote_macro, meta, module, name, arity}- traced whenever a remote function or macro is referenced.metais the call AST metadata,moduleis the invoked module, followed by thenameandarity.{:local_function, meta, name, arity}and{:local_macro, meta, name, arity}- traced whenever a local function or macro is referenced.metais the call AST metadata, followed by thenameandarity.{:compile_env, app, path, return}- traced wheneverApplication.compile_env/3orApplication.compile_env!/2are called.appis an atom,pathis a list of keys to traverse in the application environment andreturnis either{:ok, value}or:error.:defmodule- (since v1.16.2) traced as soon as the definition of a module starts. This is invoked early on in the module life cycle,Module.open?/1still returnsfalsefor such traces{:on_module, bytecode, _ignore}- (since v1.13.0) traced whenever a module is defined. This is equivalent to the@after_compilecallback and invoked after any@after_compilein the given module. The third element is currently:nonebut it may provide more metadata in the future. It is best to ignore it at the moment. Note thatModulefunctions expecting not yet compiled modules (such asModule.definitions_in/1) are still available at the time this event is emitted.
The :tracers compiler option can be combined with the :parser_options
compiler option to enrich the metadata of the traced events above.
New events may be added at any time in the future, therefore it is advised
for the trace/2 function to have a "catch-all" clause.
Below is an example tracer that prints all remote function invocations:
defmodule MyTracer do
def trace({:remote_function, _meta, module, name, arity}, env) do
IO.puts("#{env.file}:#{env.line} #{inspect(module)}.#{name}/#{arity}")
:ok
end
def trace(_event, _env) do
:ok
end
end
Summary
Types
A list with all variables and their values.
Diagnostics returned by the compiler and code evaluation.
Options for evaluation environment, accepted by env_for_eval/1.
Options for evaluation functions like eval_string/3, eval_quoted/3
and eval_quoted_with_env/4.
Options for code formatting functions.
The line. 0 indicates no line.
Options for parsing functions that convert strings to quoted expressions.
The position of the diagnostic.
Options for quoted_to_algebra/2.
Functions
Appends a path to the Erlang VM code path list.
Appends a list of paths to the Erlang VM code path list.
Returns a list with all available compiler options.
Returns true if the current process can await for module compilation.
Compiles the given file.
Compiles the quoted expression.
Compiles the given string.
Gets all compilation options from the code server.
Stores all given compilation options.
Deletes a path from the Erlang VM code path list.
Deletes a list of paths from the Erlang VM code path list.
Ensures the given modules are loaded.
Same as ensure_all_loaded/1 but raises if any of the modules cannot be loaded.
Similar to ensure_compiled!/1 but indicates you can continue without said module.
Ensures the given module is compiled and loaded.
Ensures the given module is loaded.
Same as ensure_loaded/1 but raises if the module cannot be loaded.
Ensures the given module is loaded.
Returns an environment for evaluation.
Evaluates the given file.
Evaluates the quoted contents.
Evaluates the given quoted contents with binding and env.
Evaluates the contents given by string.
Returns the docs for the given module or path to .beam file.
Formats a file.
Formats the given code string.
Returns the value of a given compiler option.
Returns true if the module is loaded.
Prepends a path to the Erlang VM code path list.
Prepends a list of paths to the Erlang VM code path list.
Prints a diagnostic into the standard error.
Purge compiler modules.
Stores a compilation option.
Converts a quoted expression to an algebra document using Elixir's formatter rules.
Requires the given file.
Lists all required files.
Converts the given string to its quoted form.
Converts the given string to its quoted form.
Converts the given string to its quoted form and a list of comments.
Converts the given string to its quoted form and a list of comments.
Removes files from the required files list.
Executes the given fun and capture all diagnostics.
Types
A list with all variables and their values.
The binding keys are usually atoms, but they may be a tuple for variables defined in a different context.
@type diagnostic(severity) :: %{ :source => Path.t() | nil, :file => Path.t() | nil, :severity => severity, :message => String.t(), :position => position(), :stacktrace => Exception.stacktrace(), :span => {line :: pos_integer(), column :: pos_integer()} | nil, optional(:details) => term(), optional(any()) => any() }
Diagnostics returned by the compiler and code evaluation.
The file and position relate to where the diagnostic should be shown. If there is a file and position, then the diagnostic is precise and you can use the given file and position for generating snippets, IDEs annotations, and so on. An optional span is available with the line and column the diagnostic ends.
Otherwise, a stacktrace may be given, which you can place your own heuristics to provide better reporting.
The source field points to the source file the compiler tracked
the error to. For example, a file lib/foo.ex may embed .eex
templates from lib/foo/bar.eex. A syntax error on the EEx template
will point to file lib/foo/bar.eex but the source is lib/foo.ex.
@type env_eval_opt() :: {:file, binary()} | {:line, pos_integer()} | {:module, module()}
Options for evaluation environment, accepted by env_for_eval/1.
Options for evaluation functions like eval_string/3, eval_quoted/3
and eval_quoted_with_env/4.
@type format_opt() :: {:file, binary()} | {:line, pos_integer()} | {:line_length, pos_integer()} | {:locals_without_parens, keyword()} | {:force_do_end_blocks, boolean()} | {:migrate, boolean()} | {:migrate_bitstring_modifiers, boolean()} | {:migrate_call_parens_on_pipe, boolean()} | {:migrate_charlists_as_sigils, boolean()} | {:migrate_unless, boolean()} | {atom(), term()}
Options for code formatting functions.