Module
Provides functions to deal with modules during compilation time.
It allows a developer to dynamically add, delete and register attributes, attach documentation and so forth.
After a module is compiled, using many of the functions in this module will raise errors, since it is out of their scope to inspect runtime data. Most of the runtime data can be inspected via the __info__/1
function attached to each compiled module.
Module attributes
Each module can be decorated with one or more attributes. The following ones are currently defined by Elixir:
@after_compile
A hook that will be invoked right after the current module is compiled. Accepts a module or a {module, function_name}
. See the “Compile callbacks” section below.
@before_compile
A hook that will be invoked before the module is compiled. Accepts a module or a {module, function_or_macro_name}
tuple. See the “Compile callbacks” section below.
@behaviour
(notice the British spelling)
Behaviours can be referenced by modules to ensure they implement required specific function signatures defined by @callback
.
For example, you could specify a URI.Parser
behaviour as follows:
defmodule URI.Parser do @doc "Defines a default port" @callback default_port() :: integer @doc "Parses the given URL" @callback parse(uri_info :: URI.t) :: URI.t end
And then a module may use it as:
defmodule URI.HTTP do @behaviour URI.Parser def default_port(), do: 80 def parse(info), do: info end
If the behaviour changes or URI.HTTP
does not implement one of the callbacks, a warning will be raised.
@impl
To aid in the correct implementation of behaviours, you may optionally declare @impl
for implemented callbacks of a behaviour. This makes callbacks explicit and can help you to catch errors in your code (the compiler will warn you if you mark a function as @impl
when in fact it is not a callback, and vice versa). It also helps with maintainability by making it clear to other developers that the function’s purpose is to implement a callback.
Using @impl
the example above can be rewritten as:
defmodule URI.HTTP do @behaviour URI.parser @impl true def default_port(), do: 80 @impl true def parse(info), do: info end
You may pass either false
, true
, or a specific behaviour to @impl
.
defmodule Foo do @behaviour Bar @behaviour Baz @impl true # will warn if neither Bar nor Baz specify a callback named bar/0 def bar(), do: :ok @impl Baz # will warn if Baz does not specify a callback named baz/0 def baz(), do: :ok end
@compile
Defines options for module compilation. This is used to configure both Elixir and Erlang compilers, as any other compilation pass added by external tools. For example:
defmodule MyModule do @compile {:inline, my_fun: 1} def my_fun(arg) do to_string(arg) end end
Multiple uses of @compile
will accumulate instead of overriding previous ones. See the “Compile options” section below.
@deprecated
Provides the deprecation reason for a function. For example:
defmodule Keyword do @deprecated "Use Kernel.length/1 instead" def size(keyword) do length(keyword) end end
The mix compiler automatically looks for calls to deprecated modules and emit warnings during compilation, computed via mix xref warnings
.
We recommend using this feature with care, especially library authors. Deprecating code always pushes the burden towards library users. We also recommend for deprecated functionality to be maintained for long periods of time, even after deprecation, giving developers plenty of time to update (except for cases where keeping the deprecated API is undesired, such as in the presence of security issues).
@doc
(and @since
)
Provides documentation for the function or macro that follows the attribute.
Accepts a string (often a heredoc) or false
where @doc false
will make the function/macro invisible to documentation extraction tools like ExDoc. For example:
defmodule MyModule do @doc "Hello world" @since "1.1.0" def hello do "world" end @doc """ Sums `a` to `b`. """ def sum(a, b) do a + b end end
@since
is an optional attribute that annotates which version the function was introduced.
@dialyzer
Defines warnings to request or suppress when using a version of :dialyzer
that supports module attributes.
Accepts an atom, a tuple, or a list of atoms and tuples. For example:
defmodule MyModule do @dialyzer {:nowarn_function, my_fun: 1} def my_fun(arg) do M.not_a_function(arg) end end
For the list of supported warnings, see :dialyzer
module.
Multiple uses of @dialyzer
will accumulate instead of overriding previous ones.
@external_resource
Specifies an external resource for the current module.
Sometimes a module embeds information from an external file. This attribute allows the module to annotate which external resources have been used.
Tools like Mix may use this information to ensure the module is recompiled in case any of the external resources change.
@file
Changes the filename used in stacktraces for the function or macro that follows the attribute, such as:
defmodule MyModule do @doc "Hello world" @file "hello.ex" def hello do "world" end end
@moduledoc
Provides documentation for the current module.
defmodule MyModule do @moduledoc """ A very useful module. """ end
Accepts a string (often a heredoc) or false
where @moduledoc false
will make the module invisible to documentation extraction tools like ExDoc.
@on_definition
A hook that will be invoked when each function or macro in the current module is defined. Useful when annotating functions.
Accepts a module or a {module, function_name}
tuple. See the “Compile callbacks” section below.
@on_load
A hook that will be invoked whenever the module is loaded.
Accepts the function name (as an atom) of a function in the current module or {function_name, 0}
tuple where function_name
is the name of a function in the current module. The function must have arity 0 (no arguments) and has to return :ok
, otherwise the loading of the module will be aborted. For example:
defmodule MyModule do @on_load :load_check def load_check do if some_condition() do :ok else :abort end end def some_condition do false end end
Modules compiled with HiPE would not call this hook.
@vsn
Specify the module version. Accepts any valid Elixir value, for example:
defmodule MyModule do @vsn "1.0" end
Typespec attributes
The following attributes are part of typespecs and are also reserved by Elixir:
-
@type
- defines a type to be used in@spec
-
@typep
- defines a private type to be used in@spec
-
@opaque
- defines an opaque type to be used in@spec
-
@spec
- provides a specification for a function -
@callback
- provides a specification for a behaviour callback -
@macrocallback
- provides a specification for a macro behaviour callback -
@optional_callbacks
- specifies which behaviour callbacks and macro behaviour callbacks are optional -
@impl
- declares an implementation of a callback function or macro
Custom attributes
In addition to the built-in attributes outlined above, custom attributes may also be added. A custom attribute is any valid identifier prefixed with an @
and followed by a valid Elixir value:
defmodule MyModule do @custom_attr [some: "stuff"] end
For more advanced options available when defining custom attributes, see register_attribute/3
.
Compile callbacks
There are three callbacks that are invoked when functions are defined, as well as before and immediately after the module bytecode is generated.
@after_compile
A hook that will be invoked right after the current module is compiled.
Accepts a module or a {module, function_name}
tuple. The function must take two arguments: the module environment and its bytecode. When just a module is provided, the function is assumed to be __after_compile__/2
.
Callbacks registered first will run last.
Example
defmodule MyModule do @after_compile __MODULE__ def __after_compile__(env, _bytecode) do IO.inspect env end end
@before_compile
A hook that will be invoked before the module is compiled.
Accepts a module or a {module, function_or_macro_name}
tuple. The function/macro must take one argument: the module environment. If it’s a macro, its returned value will be injected at the end of the module definition before the compilation starts.
When just a module is provided, the function/macro is assumed to be __before_compile__/1
.
Callbacks registered first will run last. Any overridable definition will be made concrete before the first callback runs. A definition may be made overridable again in another before compile callback and it will be made concrete one last time after after all callbacks run.
Note: unlike @after_compile
, the callback function/macro must be placed in a separate module (because when the callback is invoked, the current module does not yet exist).
Example
defmodule A do defmacro __before_compile__(_env) do quote do def hello, do: "world" end end end defmodule B do @before_compile A end B.hello() #=> "world"
@on_definition
A hook that will be invoked when each function or macro in the current module is defined. Useful when annotating functions.
Accepts a module or a {module, function_name}
tuple. The function must take 6 arguments:
- the module environment
- the kind of the function/macro:
:def
,:defp
,:defmacro
, or:defmacrop
- the function/macro name
- the list of quoted arguments
- the list of quoted guards
- the quoted function body
Note the hook receives the quoted arguments and it is invoked before the function is stored in the module. So Module.defines?/2
will return false
for the first clause of every function.
If the function/macro being defined has multiple clauses, the hook will be called for each clause.
Unlike other hooks, @on_definition
will only invoke functions and never macros. This is to avoid @on_definition
callbacks from redefining functions that have just been defined in favor of more explicit approaches.
When just a module is provided, the function is assumed to be __on_definition__/6
.
Example
defmodule Hooks do def on_def(_env, kind, name, args, guards, body) do IO.puts "Defining #{kind} named #{name} with args:" IO.inspect args IO.puts "and guards" IO.inspect guards IO.puts "and body" IO.puts Macro.to_string(body) end end defmodule MyModule do @on_definition {Hooks, :on_def} def hello(arg) when is_binary(arg) or is_list(arg) do "Hello" <> to_string(arg) end def hello(_) do :ok end end
Compile options
The @compile
attribute accepts different options that are used by both Elixir and Erlang compilers. Some of the common use cases are documented below:
-
@compile :debug_info
- includes:debug_info
regardless of the corresponding setting inCode.compiler_options/1
-
@compile {:debug_info, false}
- disables:debug_info
regardless of the corresponding setting inCode.compiler_options/1
-
@compile {:inline, some_fun: 2, other_fun: 3}
- inlines the given name/arity pairs -
@compile {:autoload, false}
- disables automatic loading of modules after compilation. Instead, the module will be loaded after it is dispatched to
You can see a handful more options used by the Erlang compiler in the documentation for the :compile
module.
Summary
Functions
- __info__(kind)
-
Provides runtime information about functions and macros defined by the module, etc
- concat(list)
-
Concatenates a list of aliases and returns a new alias
- concat(left, right)
-
Concatenates two aliases and returns a new alias
- create(module, quoted, opts)
-
Creates a module with the given name and defined by the given quoted expressions
- defines?(module, tuple)
-
Checks if the module defines the given function or macro
- defines?(module, tuple, def_kind)
-
Checks if the module defines a function or macro of the given
kind
- definitions_in(module)
-
Returns all functions defined in
module
- definitions_in(module, def_kind)
-
Returns all functions defined in
module
, according to its kind - delete_attribute(module, key)
-
Deletes the module attribute that matches the given key
- eval_quoted(module_or_env, quoted, binding \\ [], opts \\ [])
-
Evaluates the quoted contents in the given module’s context
- get_attribute(module, key)
-
Gets the given attribute from a module
- make_overridable(module, tuples)
-
Makes the given functions in
module
overridable - open?(module)
-
Checks if a module is open
- overridable?(module, tuple)
-
Returns
true
iftuple
inmodule
is marked as overridable - put_attribute(module, key, value)
-
Puts a module attribute with
key
andvalue
in the givenmodule
- register_attribute(module, attribute, options)
-
Registers an attribute
- safe_concat(list)
-
Concatenates a list of aliases and returns a new alias only if the alias was already referenced
- safe_concat(left, right)
-
Concatenates two aliases and returns a new alias only if the alias was already referenced
- split(module)
-
Splits the given module name into binary parts
Functions
__info__(kind)
__info__( :attributes | :compile | :functions | :macros | :md5 | :module | :deprecated ) :: any()
Provides runtime information about functions and macros defined by the module, etc.
Each module gets an __info__/1
function when it’s compiled. The function takes one of the following atoms:
-
:functions
- keyword list of public functions along with their arities -
:macros
- keyword list of public macros along with their arities -
:module
- the module atom name -
:md5
- the MD5 of the module -
:compile
- a list with compiler metadata -
:attributes
- a list with all persisted attributes
concat(list)
concat([binary() | atom()]) :: atom()
Concatenates a list of aliases and returns a new alias.
Examples
iex> Module.concat([Foo, Bar]) Foo.Bar iex> Module.concat([Foo, "Bar"]) Foo.Bar
concat(left, right)
concat(binary() | atom(), binary() | atom()) :: atom()
Concatenates two aliases and returns a new alias.
Examples
iex> Module.concat(Foo, Bar) Foo.Bar iex> Module.concat(Foo, "Bar") Foo.Bar
create(module, quoted, opts)
create(module(), Macro.t(), Macro.Env.t() | keyword()) :: {:module, module(), binary(), term()}
Creates a module with the given name and defined by the given quoted expressions.
The line where the module is defined and its file must be passed as options.
It returns a tuple of shape {:module, module, binary, term}
where module
is the module name, binary
is the module byte code and term
is the result of the last expression in quoted
.
Similar to Kernel.defmodule/2
, the binary will only be written to disk as a .beam
file if Module.create/3
is invoked in a file that is currently being compiled.
Examples
contents = quote do def world, do: true end Module.create(Hello, contents, Macro.Env.location(__ENV__)) Hello.world #=> true
Differences from defmodule
Module.create/3
works similarly to Kernel.defmodule/2
and return the same results. While one could also use defmodule
to define modules dynamically, this function is preferred when the module body is given by a quoted expression.
Another important distinction is that Module.create/3
allows you to control the environment variables used when defining the module, while Kernel.defmodule/2
automatically uses the environment it is invoked at.
defines?(module, tuple)
defines?(module(), definition()) :: boolean()
Checks if the module defines the given function or macro.
Use defines?/3
to assert for a specific type.
This function can only be used on modules that have not yet been compiled. Use Kernel.function_exported?/3
to check compiled modules.
Examples
defmodule Example do Module.defines? __MODULE__, {:version, 0} #=> false def version, do: 1 Module.defines? __MODULE__, {:version, 0} #=> true end
defines?(module, tuple, def_kind)
defines?(module(), definition(), def_kind()) :: boolean()
Checks if the module defines a function or macro of the given kind
.
kind
can be any of :def
, :defp
, :defmacro
, or :defmacrop
.
This function can only be used on modules that have not yet been compiled. Use Kernel.function_exported?/3
to check compiled modules.
Examples
defmodule Example do Module.defines? __MODULE__, {:version, 0}, :defp #=> false def version, do: 1 Module.defines? __MODULE__, {:version, 0}, :defp #=> false end
definitions_in(module)
definitions_in(module()) :: [definition()]
Returns all functions defined in module
.
Examples
defmodule Example do def version, do: 1 Module.definitions_in __MODULE__ #=> [{:version, 0}] end
definitions_in(module, def_kind)
definitions_in(module(), def_kind()) :: [definition()]
Returns all functions defined in module
, according to its kind.
Examples
defmodule Example do def version, do: 1 Module.definitions_in __MODULE__, :def #=> [{:version, 0}] Module.definitions_in __MODULE__, :defp #=> [] end
delete_attribute(module, key)
delete_attribute(module(), atom()) :: term()
Deletes the module attribute that matches the given key.
It returns the deleted attribute value (or nil
if nothing was set).
Examples
defmodule MyModule do Module.put_attribute __MODULE__, :custom_threshold_for_lib, 10 Module.delete_attribute __MODULE__, :custom_threshold_for_lib end
eval_quoted(module_or_env, quoted, binding \\ [], opts \\ [])
eval_quoted( module() | Macro.Env.t(), Macro.t(), list(), keyword() | Macro.Env.t() ) :: term()
Evaluates the quoted contents in the given module’s context.
A list of environment options can also be given as argument. See Code.eval_string/3
for more information.
Raises an error if the module was already compiled.
Examples
defmodule Foo do contents = quote do: (def sum(a, b), do: a + b) Module.eval_quoted __MODULE__, contents end Foo.sum(1, 2) #=> 3
For convenience, you can pass any Macro.Env
struct, such as __ENV__/0
, as the first argument or as options. Both the module and all options will be automatically extracted from the environment:
defmodule Foo do contents = quote do: (def sum(a, b), do: a + b) Module.eval_quoted __ENV__, contents end Foo.sum(1, 2) #=> 3
Note that if you pass a Macro.Env
struct as first argument while also passing opts
, they will be merged with opts
having precedence.
get_attribute(module, key)
get_attribute(module(), atom()) :: term()
Gets the given attribute from a module.
If the attribute was marked with accumulate
with Module.register_attribute/3
, a list is always returned. nil
is returned if the attribute has not been marked with accumulate
and has not been set to any value.
The @
macro compiles to a call to this function. For example, the following code:
@foo
Expands to something akin to:
Module.get_attribute(__MODULE__, :foo)
Examples
defmodule Foo do Module.put_attribute __MODULE__, :value, 1 Module.get_attribute __MODULE__, :value #=> 1 Module.register_attribute __MODULE__, :value, accumulate: true Module.put_attribute __MODULE__, :value, 1 Module.get_attribute __MODULE__, :value #=> [1] end
make_overridable(module, tuples)
make_overridable(module(), module()) :: :ok
make_overridable(module(), [definition()]) :: :ok
Makes the given functions in module
overridable.
An overridable function is lazily defined, allowing a developer to customize it. See Kernel.defoverridable/1
for more information and documentation.
open?(module)
open?(module()) :: boolean()
Checks if a module is open.
A module is “open” if it is currently being defined and its attributes and functions can be modified.
overridable?(module, tuple)
overridable?(module(), definition()) :: boolean()
Returns true
if tuple
in module
is marked as overridable.
put_attribute(module, key, value)
put_attribute(module(), atom(), term()) :: :ok
Puts a module attribute with key
and value
in the given module
.
Examples
defmodule MyModule do Module.put_attribute __MODULE__, :custom_threshold_for_lib, 10 end
register_attribute(module, attribute, options)
register_attribute(module(), atom(), accumulate: boolean(), persist: boolean()) :: :ok
Registers an attribute.
By registering an attribute, a developer is able to customize how Elixir will store and accumulate the attribute values.
Options
When registering an attribute, two options can be given:
-
:accumulate
- several calls to the same attribute will accumulate instead of override the previous one. New attributes are always added to the top of the accumulated list. -
:persist
- the attribute will be persisted in the Erlang Abstract Format. Useful when interfacing with Erlang libraries.
By default, both options are false
.
Examples
defmodule MyModule do Module.register_attribute __MODULE__, :custom_threshold_for_lib, accumulate: true, persist: false @custom_threshold_for_lib 10 @custom_threshold_for_lib 20 @custom_threshold_for_lib #=> [20, 10] end
safe_concat(list)
safe_concat([binary() | atom()]) :: atom()
Concatenates a list of aliases and returns a new alias only if the alias was already referenced.
If the alias was not referenced yet, fails with ArgumentError
. It handles charlists, binaries and atoms.
Examples
iex> Module.safe_concat([Module, Unknown]) ** (ArgumentError) argument error iex> Module.safe_concat([List, Chars]) List.Chars
safe_concat(left, right)
safe_concat(binary() | atom(), binary() | atom()) :: atom()
Concatenates two aliases and returns a new alias only if the alias was already referenced.
If the alias was not referenced yet, fails with ArgumentError
. It handles charlists, binaries and atoms.
Examples
iex> Module.safe_concat(Module, Unknown) ** (ArgumentError) argument error iex> Module.safe_concat(List, Chars) List.Chars
split(module)
split(module() | String.t()) :: [String.t(), ...]
Splits the given module name into binary parts.
module
has to be an Elixir module, as split/1
won’t work with Erlang-style modules (for example, split(:lists)
raises an error).
split/1
also supports splitting the string representation of Elixir modules (that is, the result of calling Atom.to_string/1
with the module name).
Examples
iex> Module.split(Very.Long.Module.Name.And.Even.Longer) ["Very", "Long", "Module", "Name", "And", "Even", "Longer"] iex> Module.split("Elixir.String.Chars") ["String", "Chars"]
© 2012 Plataformatec
Licensed under the Apache License, Version 2.0.
https://hexdocs.pm/elixir/1.6.6/Module.html