Code (Elixir v1.20.5)

Copy Markdown View Source

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 ...
end

Finally, 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 :start and run at the same time. The value of the lexical_tracker of 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 whenever module is imported. meta is the import AST metadata and opts are 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. meta is the call AST metadata, module is the module the import is from, followed by the name and arity of 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 a quote/2. meta is the call AST metadata, module is the module the import is from, followed by the name and a list of arities of the imported function/macro.

  • {:alias, meta, alias, as, opts} - traced whenever alias is aliased to as. meta is the alias AST metadata and opts are the alias options.

  • {:alias_expansion, meta, as, alias} traced whenever there is an alias expansion for a previously defined alias, i.e. when the user writes as which is expanded to alias. meta is the alias expansion AST metadata.

  • {:alias_reference, meta, module} - traced whenever there is an alias in the code, i.e. whenever the user writes MyModule.Foo.Bar in the code, regardless if it was expanded or not.

  • {:require, meta, module, opts} - traced whenever module is required. meta is the require AST metadata and opts are the require options. If the meta option 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 whenever module's struct is expanded. meta is the struct AST metadata and keys are 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. meta is the call AST metadata, module is the invoked module, followed by the name and arity.

  • {:local_function, meta, name, arity} and {:local_macro, meta, name, arity} - traced whenever a local function or macro is referenced. meta is the call AST metadata, followed by the name and arity.

  • {:compile_env, app, path, return} - traced whenever Application.compile_env/3 or Application.compile_env!/2 are called. app is an atom, path is a list of keys to traverse in the application environment and return is 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?/1 still returns false for such traces

  • {:on_module, bytecode, _ignore} - (since v1.13.0) traced whenever a module is defined. This is equivalent to the @after_compile callback and invoked after any @after_compile in the given module. The third element is currently :none but it may provide more metadata in the future. It is best to ignore it at the moment. Note that Module functions expecting not yet compiled modules (such as Module.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.

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 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 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

binding()

@type binding() :: [{atom() | tuple(), any()}]

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.

diagnostic(severity)

@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.

env_eval_opt()

@type env_eval_opt() ::
  {:file, binary()} | {:line, pos_integer()} | {:module, module()}

Options for evaluation environment, accepted by env_for_eval/1.

eval_opt()

@type eval_opt() ::
  {:prune_binding, boolean()} | {:dbg_callback, {module(), atom(), list()}}

Options for evaluation functions like eval_string/3, eval_quoted/3 and eval_quoted_with_env/4.

format_opt()

@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.