compile(3)

๐Ÿ“ฆ
version 29.0.6 ยท 3 versions
, in ubuntu stonking

๐ŸŒธ compile โ€” Erlang Compiler ๐ŸŒธ

okay so bestie, this is the manual page for compile(3) and it is long, so buckle up. It's the Erlang Compiler module. It's literally the thing that turns your beautiful little Erlang code into object code. ๐Ÿ’…


โœจ NAME โœจ

compile โ€” Erlang Compiler ๐Ÿ› ๏ธ


๐Ÿ’– DESCRIPTION ๐Ÿ’–

This module gives you an interface to the standard Erlang compiler. It can either generate a file containing the object code, or hand you back a binary that you can load directly. Choose your own adventure, bestie. ๐ŸŽ€

๐ŸŒˆ Default Compiler Options ๐ŸŒˆ

The (host operating system) environment variable ERL_COMPILER_OPTIONS can be used to give default compiler options. Its value must be a valid Erlang term. If the value is a list, it is used as is. If it is not a list, it is put into a list.

The list is appended to any options given to file/2, forms/2, and output_generated/2. Use the alternative functions noenv_file/2, noenv_forms/2, or noenv_output_generated/2 if you do not want the environment variable to be consulted โ€” for example, if you are calling the compiler recursively from inside a parse transform.

The list can be retrieved with env_compiler_options/0.

โœจ Order of Compiler Options โœจ

Options given in the compile() attribute in the source code take precedence over options given to the compiler, which in turn take precedence over options given in the environment.

A later compiler option takes precedence over an earlier one in the option list. Example:

compile:file(something, [nowarn_missing_spec,warn_missing_spec]).

Warnings will be emitted for functions without specifications, unless the source code for module something contains a compile(nowarn_missing_spec) attribute.

CHANGE: In Erlang/OTP 26 and earlier, the option order was the opposite of what is described here. Not me finding out the order used to be backwards ๐Ÿ˜ญ

๐Ÿงš Inlining ๐Ÿงš

The compiler can do function inlining within an Erlang module. Inlining means that a call to a function is replaced with the function body, with the arguments replaced with the actual values. The semantics are preserved โ€” except if exceptions are generated in the inlined code, in which case exceptions are reported as occurring in the function the body was inlined into. Also, function_clause exceptions are converted to similar case_clause exceptions. ๐Ÿ‘€

When a function is inlined, the original function is kept if it is exported (either by an explicit export or if the option export_all was given) or if not all calls to the function are inlined.

lowkey important: inlining does not necessarily improve running time. For example, inlining can increase Beam stack use, which probably is detrimental to performance for recursive functions. so don't just do it for the vibes. ๐Ÿ’€

Inlining is never default. It must be explicitly enabled with a compiler option or a -compile() attribute in the source module.

To enable inlining, either use the option inline to let the compiler decide which functions to inline, or {inline,[{Name,Arity},...]} to have the compiler inline all calls to the given functions. If the option is given inside a compile directive in an Erlang module, {Name,Arity} can be written as Name/Arity.

Example of explicit inlining:

-compile({inline,[pi/0]}).

pi() -> 3.1416.

Example of implicit inlining:

-compile(inline).

The option {inline_size,Size} controls how large functions that are allowed to be inlined. Default is 24, which keeps the size of the inlined code roughly the same as the un-inlined version (only relatively small functions are inlined).

Example:

%% Aggressive inlining - will increase code size.
-compile(inline).
-compile({inline_size,100}).

๐Ÿฆ‹ Inlining of List Functions ๐Ÿฆ‹

The compiler can also inline various list manipulation functions from the module list in STDLIB.

This feature must be explicitly enabled with a compiler option or a -compile() attribute in the source module.

To enable inlining of list functions, use option inline_list_funcs.

The following functions are inlined:

  • lists:all/2
  • lists:any/2
  • lists:foreach/2
  • lists:map/2
  • lists:flatmap/2
  • lists:filter/2
  • lists:foldl/3
  • lists:foldr/3
  • lists:mapfoldl/3
  • lists:mapfoldr/3

๐Ÿ’œ Parse Transformations ๐Ÿ’œ

Parse transformations are used when a programmer wants to use Erlang syntax but with different semantics. The original Erlang code is then transformed into other Erlang code.

See erl_id_trans for an example and an explanation of the function parse_transform_info/0.

๐Ÿ‘‘ Recommendations for Language Implementors ๐Ÿ‘‘

Except for Erlang, there are quite a few other languages that can run on the Erlang runtime system. Generally, such compilers produce a file or binary that is fed into the Erlang compiler. There are four ways to do that using documented functionality:

  • Erlang source code (.erl file): The file is compiled using compile:file/2 or erlc <FILE>.erl. This is the most straightforward and portable way. The main disadvantage is that it is hard or impossible to map each line of Erlang code back to the corresponding line in the original source file.
  • The abstract format: This format supports mapping every Erlang source line back to its corresponding line in the original source file. To compile from the abstract format, do one following:
    • Call compile:forms/2 to directly pass in the term representation of the abstract format.
    • Write the term representation to a file with the extension .abstr and compile that file using compile:file(<File>, [from_abstr]) or erlc <File>.abstr.
  • Core Erlang: While there is a specification for Core Erlang, certain details are left to the implementation via the primop expression. Primops can be added, deleted, or changed in any major release without notice. Note that by generating Core Erlang directly, it is possible to construct code that the Core-to-BEAM backend has never encountered before, and there are no guarantees that the final BEAM code will be safe. ๐Ÿ˜ญ
  • BEAM assembly code: Strongly discouraged, as it is very hard to get right and requires continuous maintenance. New instructions are typically introduced in each major release (and sometimes old ones are removed). In particular, note that BEAM code that does not follow the correct conventions can cause the runtime system to crash (segfault). ๐Ÿ’€

Our recommendation is to use either the abstract format or Erlang source code.

๐Ÿ‘€ See Also ๐Ÿ‘€

epp, erl_expand_records, erl_id_trans, erl_lint, beam_lib


๐ŸŽ€ DATA TYPES ๐ŸŽ€

abstract_code() :: [erl_parse:abstract_form()].

bin_ret() ::
          {ok, module(), binary()} |
          {ok, module(), binary(), warnings()}.

comp_ret() :: mod_ret() | bin_ret() | err_ret().

err_ret() :: error | {error, errors(), warnings()}.

error_description() :: erl_lint:error_description().

error_info() :: erl_lint:error_info().

errors() :: [{file:filename(), [error_info()]}].

forms() :: abstract_code() | cerl:c_module().

mod_ret() ::
          {ok, module()} |
          {ok, module(), cerl:c_module()} |
          {ok, module() | [], abstract_code()} |
          {ok, module(), warnings()}.

option() :: atom() | {atom(), term()} | {d, atom(), term()}.

warnings() :: [{file:filename(), [error_info()]}].
  • forms() โ€” List of Erlang abstract or Core Erlang format representations, as used by forms/2. ๐Ÿซถ
  • option() โ€” See file/2 for detailed description.

๐Ÿ’… FUNCTIONS ๐Ÿ’…

env_compiler_options() -> [term()].

Return compiler options given via the environment variable ERL_COMPILER_OPTIONS. If the value is a list, it is returned as is. If it is not a list, it is put into a list.


file(module() | file:filename()) -> CompRet :: comp_ret().

Is the same as file(File, [verbose,report_errors,report_warnings]).


file(File :: module() | file:filename(), Options :: [option()] | option()) -> CompRet :: comp_ret().

Compiles the code in the file File, which is an Erlang source code file without the .erl extension.

Options determine the behavior of the compiler.

Returns {ok,ModuleName} if successful, or error if there are errors. An object code file is created if the compilation succeeds without errors. It is considered to be an error if the module name in the source code is not the same as the basename of the output file. ๐Ÿซ 

Available options:

  • brief โ€” Restricts error and warning messages to a single line of output. As of Erlang/OTP 24, the compiler will by default also display the part of the source code that the message refers to.
  • basic_validation โ€” This option is a fast way to test whether a module will compile successfully. This is useful for code generators that want to verify the code that they emit. No code is generated. If warnings are enabled, warnings generated by the erl_lint module (such as warnings for unused variables and functions) are also returned. Use option strong_validation to generate all warnings that the compiler would generate.
  • strong_validation โ€” Similar to option basic_validation. No code is generated, but more compiler passes are run to ensure that warnings generated by the optimization passes are generated (such as clauses that will not match, or expressions that are guaranteed to fail with an exception at runtime).
  • no_docs โ€” The compiler by default extracts documentation from -doc attributes and places them in the Docs chunk according to EEP-48. This option switches off the placement of -doc attributes in the Docs chunk.
  • binary โ€” The compiler returns the object code in a binary instead of creating an object file. If successful, the compiler returns {ok,ModuleName,Binary}.
  • bin_opt_info โ€” The compiler will emit informational warnings about binary matching optimizations (both successful and unsuccessful). For more information, see the section about bin_opt_info in the Efficiency Guide.
  • {compile_info, [{atom(), term()}]} โ€” Allows compilers built on top of compile to attach extra compilation metadata to the compile_info chunk in the generated BEAM file. It is advised for compilers to remove all non-deterministic information if the deterministic option is supported and it was supplied by the user.
  • compressed โ€” The compiler will compress the generated object code, which can be useful for embedded systems.
  • debug_info โ€” bestie, this one tucks debug info into the debug_info chunk of your compiled beam module, all in Erlang Abstract Format. Tools like Debugger, Xref, and Cover need this to work at all, so if you've ever been like "why is my tooling being weird", it's giving missing debug info ๐Ÿ’…
โš ๏ธ Warning: you can literally reconstruct the source code from the debug information. If that's not the vibe you want, use encrypted debug info (encrypt_debug_info) to stop it. ๐Ÿซฃ

For the details, peek at beam_lib(3).

  • {debug_info, {Backend, Data}} โ€” the โœจcustomโœจ version, bestie. You get custom debug info in the compiled beam module, in the form of a Backend module with custom Data. That module has to implement a debug_info/4 function and it's the one responsible for generating the different code representations โ€” exactly like the debug_info described under beam_lib(3). ๐Ÿ‘‘
โš ๏ธ Warning: same deal, same drama โ€” source code can be reconstructed from the debug information. Use encrypted debug information (encrypt_debug_info) to prevent it. ๐Ÿ˜ญ
  • {debug_info_key,KeyString} / {debug_info_key,{Mode,KeyString}} โ€” includes debug info, but encrypts it so nobody can access it without handing over the key. (You're allowed to pass the debug_info option as well, but you don't have to, it's not necessary.) This one is lowkey iconic for always having your debug info around during testing while still protecting the source code. ๐ŸŽ€

Mode is the type of crypto algorithm used for encrypting the debug information. The default (and currently the only) type is des3_cbc.

For the details, see beam_lib(3).

  • encrypt_debug_info โ€” basically the debug_info_key option's twin, except the key gets read from an .erlang.crypt file. ๐Ÿ”

For the details, see beam_lib(3).

  • deterministic โ€” omits the options and source tuples from the list that Module:module_info(compile) returns, and shrinks the paths in stack traces down to just the module name. The whole point? Making reproducible builds actually achievable. obsessed. ๐ŸŒˆ
  • {feature, Feature, enable | disable} โ€” enables (or disables) the feature Feature during compilation. There's a special feature called all that enables (or disables) every feature at once. โœจ
๐Ÿ“Œ NOTE: this option does absolutely nothing when you use it in a -compile(..) attribute. Instead you want the -feature(..) directive (described right after this, bestie, keep reading). A feature can also be enabled (disabled) with the -feature(Feature, enable | disable). module directive โ€” but note that this directive can only live in a prefix of the file, before exports and function definitions. This is the preferred method of enabling and disabling features, since it's a local property of a module. ๐Ÿ’…
  • makedep โ€” produces a Makefile rule so you can track header dependencies. No object file gets produced, periodt.

By default the rule gets written to <File>.Pbeam. But โ€” plot twist โ€” if the binary option is set, nothing is written anywhere and the rule gets returned in Binary instead.

The output will be encoded in UTF-8. ๐ŸŒธ

For example, if you have this module right here:

-module(module).

-include_lib("eunit/include/eunit.hrl").
-include("header.hrl").

Then the Makefile rule generated by this option looks as follows:

module.beam: module.erl \
  /usr/local/lib/erlang/lib/eunit/include/eunit.hrl \
  header.hrl
  • makedep_side_effect โ€” the dependencies get created as a side effect of the normal compilation process. Which means the object file also gets produced. This option overrides the makedep option. ๐Ÿ”ฅ
  • {makedep_output, Output} โ€” writes the generated rules to Output instead of the default <File>.Pbeam. Output can be a filename or an io_device(). Wanna write to stdout? Use standard_io. But heads up: if binary is set, nothing gets written to Output and the result comes back to the caller as {ok, ModuleName, Binary}. ๐Ÿฆ‹
  • {makedep_target, Target} โ€” changes the name of the rule that gets emitted, to Target.
  • makedep_quote_target โ€” characters in Target that are special to make(1) get quoted. ๐ŸŽ€
  • makedep_add_missing โ€” treats missing headers as generated files and adds them into the dependencies. no cap.
  • makedep_phony โ€” adds a phony target for each dependency. โœจ
  • Produces a listing of the parsed code, after preprocessing and parse transforms, in the file <File>.P. No object file is produced. just vibes and a listing ๐Ÿ“„
  • Produces a listing of the code, after all source code transformations have been performed, in the file <File>.E. No object file is produced.
  • Produces a listing of the assembler code in the file <File>.S. No object file is produced. ๐Ÿ‘‘
  • recv_opt_info โ€” the compiler will emit informational warnings about selective receive optimizations, both the successful and the unsuccessful ones. For more info, see the section about selective receive optimization in the Efficiency Guide. ๐Ÿ“š
  • report_errors / report_warnings โ€” makes errors (or warnings) get printed as they occur.
  • report โ€” the short form for both report_errors and report_warnings. two for one, we love a bundle ๐Ÿ’–
  • return_errors โ€” if this flag is set, {error,ErrorList,WarningList} is returned when there are errors.
  • return_warnings โ€” if this flag is set, an extra field containing WarningList gets added to the tuples returned on success.
  • warnings_as_errors โ€” treats warnings as errors. yes bestie, the warnings are getting a glow-up they did NOT ask for ๐Ÿ˜ญ
  • {error_location,line | column} โ€” if the value of this flag is line, then the location ErrorLocation of warnings and errors is a line number. If the value is column, then ErrorLocation includes both a line number and a column number. Default is column. This option is supported since Erlang/OTP 24.0. ๐ŸŽ‰

If the value of this flag is column, then debug information includes column information.

  • return โ€” the short form for both return_errors and return_warnings.
  • verbose โ€” makes the compiler spit out more verbose information, describing what it's doing. it's the compiler narrating its own life ๐Ÿ’…
  • {source,FileName} โ€” overrides the source file name as it's presented in module_info(compile) and in stack traces.
  • absolute_source โ€” turns the source file name (as presented in module_info(compile) and stack traces) into an absolute path, which helps external tools like perf and gdb find Erlang source code. ๐Ÿ› ๏ธ
  • {outdir,Dir} โ€” sets a new directory for the object code. The current directory is used for output, except when a directory has been specified with this option.
  • export_all โ€” makes all functions in the module get exported. main character module energy, everything's invited ๐ŸŒŸ
  • {i,Dir} โ€” adds Dir to the list of directories searched when including a file. When it encounters an -include or -include_lib directive, the compiler searches for header files in these directories:
    1. ".", the current working directory of the file server
    2. The base name of the compiled file
    3. The directories specified using option i; the directory specified last is searched first
  • {d,Macro} / {d,Macro,Value} โ€” defines a macro Macro to have the value Value. Macro is of type atom, and Value can be any term. The default Value is true. โœจ
  • {parse_transform,Module} โ€” causes the parse transformation function Module:parse_transform/2 to be applied to the parsed code before the code is checked for errors. ๐Ÿ”ฎ
  • to_abstr โ€” dumps the terms representing the abstract format, after preprocessing and parse transforms, into the file <File>.abstr. No object file is produced.
  • to_exp โ€” dumps the terms representing the abstract format, after all source code transformations have been performed, to the file <File>.exp. No object file is produced. ๐ŸŽ€
  • from_abstr โ€” the input file is expected to contain Erlang terms representing forms in the abstract format, as generated by the to_abstr option (default file suffix ".abstr"). Note that the format of such terms can change between releases. ๐Ÿ˜ฌ

See also the no_lint option.

  • from_asm โ€” the input file is expected to be BEAM assembly code, as generated by the 'S' option (default file suffix ".S"). Heads up: the format of assembler files is not documented, and it can change between releases. ๐Ÿ’€
  • from_core โ€” the input file is expected to be Core Erlang code (default file suffix ".core"). Note that the exact format of Core Erlang files is not documented, and it can change between releases. same warning, same drama ๐Ÿ™ˆ
  • no_spawn_compiler_process โ€” so by default, all code is compiled in a separate process which gets terminated at the end of compilation. But some tools, like Dialyzer or compilers for other BEAM languages, may already be managing their own worker processes, and spawning an extra process can slow the compilation down. In scenarios like that, you can pass this option to stop the compiler from spawning an additional process. efficiency, we love her ๐Ÿงš
  • no_strict_record_tests โ€” this option is not recommended, bestie. ๐Ÿ’€

By default, the generated code for the operation Record#record_tag.field verifies that the tuple Record has the correct size for the record, and that the first element is the tag record_tag. Use this option to omit the verification code.

  • no_error_module_mismatch โ€” normally the compiler verifies that the module name given in the source code is the same as the base name of the output file, and refuses to generate an output file if there's a mismatch. But if you have a good reason for having a module name that's unrelated to the name of the output file, this option disables that verification (there won't even be a warning if there's a mismatch). ๐Ÿ˜Œ
  • {no_auto_import,[{F,A}, ...]} โ€” bestie, this one makes the function F/A stop being auto-imported from the erlang module, which is literally how you resolve BIF name clashes ๐Ÿ’ฅ. You must use this option to sort out name clashes with auto-imported BIFs that existed before Erlang/OTP R14A, when you're calling a local function with the same name as an auto-imported BIF and you're doing it without a module prefix.
Okay but listen: if you actually want to call the BIF, put the erlang module prefix on the call. Do not try to do it with {no_auto_import,[{F,A}, ...]}, that's not what it's for ๐Ÿ™ˆ.

If you write this option in the source code as a -compile directive, you get to use the short F/A form instead of {F,A}. For example:

-compile({no_auto_import,[error/1]}).
  • no_auto_import โ€” nope, we are not auto-importing any functions from the erlang module. Not a single one. Periodt ๐Ÿ’….
  • no_line_info โ€” dips out on line number information so the output file is a lil bit smaller. Slightly lighter, that's the whole vibe โœจ.
  • no_lint โ€” skips the pass that checks for errors and warnings ๐Ÿ˜ด. Only applicable together with the from_abstr option. This one is mainly for people implementing other languages on top of Erlang who have already done their own checks to guarantee the code is correct.
Caveat time, and it's a serious one: when this option is used, there are no guarantees that the code output by the compiler is correct and safe to use. The responsibility for correctness lies on the code or person generating the abstract format. If the code contains errors, the compiler may crash or produce unsafe code ๐Ÿ’€.
  • {extra_chunks, [{binary(), binary()}]} โ€” passes extra chunks that get stored in the .beam file. The extra chunks have to be a list of tuples with a four byte binary as the chunk name, followed by a binary with the chunk contents. Peep beam_lib for more info ๐Ÿซถ.
  • {check_ssa, Tag :: atom()} โ€” parses and checks assertions on the structure and content of the BEAM SSA code that the compiler produces. The Tag says which set of assertions to check and after which compiler pass the check happens. Heads up though: this option is internal to the compiler and can be changed or removed at any time without prior warning ๐Ÿ™ˆ.
  • line_coverage โ€” instruments the compiled code for line coverage by inserting an executable_line instruction for each executable line in the source code. By default, this instruction gets ignored when the code is loaded.

To activate those executable_line instructions, the runtime system has to be started with the option +JPcover to enable a coverage mode. Or, alternatively, code:set_coverage_mode/1 can be used to set a coverage mode before loading the code.

The coverage information gathered by the instrumented code can be retrieved by calling code:get_coverage(line, Module).

  • force_line_counters โ€” when combined with the option line_coverage, this module gets loaded in the line_counter coverage mode, no matter what the current coverage mode in the runtime system is. This one is used by cover to load cover-compiled code ๐ŸŒธ.

If warnings are turned on (that's the report_warnings option mentioned earlier ๐Ÿ‘€), the options below control what type of warnings get generated. Except for {warn_format,Verbosity}, all of the following options have two forms:

  • the warn_xxx form, to turn the warning on.
  • the nowarn_xxx form, to turn the warning off.

In the descriptions that follow, the form used to change the default value is the one listed โœจ.


  • {warn_format, Verbosity} โ€” emits warnings for malformed format strings passed as arguments to io:format and similar functions.

Verbosity picks how many warnings you get:

  • 0 = no warnings at all ๐Ÿ™…
  • 1 = warnings for invalid format strings and incorrect number of arguments
  • 2 = warnings also when the validity can't be checked, for example when the format string argument is a variable.

The default verbosity is 1. Verbosity 0 can also be selected with the option nowarn_format.

  • nowarn_bif_clash โ€” this option has been removed and it generates a fatal error if you use it ๐Ÿ’€.

To resolve BIF clashes, use explicit module names or the {no_auto_import,[F/A]} compiler directive.

  • {nowarn_bif_clash, FAs} โ€” this option has been removed too, and it also generates a fatal error if you use it ๐Ÿ’€.

To resolve BIF clashes, use explicit module names or the {no_auto_import,[F/A]} compiler directive.

  • nowarn_export_all โ€” turns off warnings for uses of the export_all option. Default is to emit a warning if the option export_all is also given.
  • warn_export_vars โ€” emits warnings for all implicitly exported variables referred to after the primitives where they were first defined. By default, the compiler only emits warnings for exported variables referred to in a pattern.
  • nowarn_shadow_vars โ€” turns off warnings for "fresh" variables in functional objects or list comprehensions that share a name with some already defined variable. Default is to emit warnings for such variables.
  • warn_keywords โ€” emits warnings when the code contains atoms that are used as keywords in some feature. When that feature is enabled, any occurrences will lead to a syntax error. To prevent that, the atom has to be renamed or quoted โš ๏ธ.
  • nowarn_unused_function โ€” turns off warnings for unused local functions. Default is to emit warnings for all local functions that aren't called directly or indirectly by an exported function. The compiler doesn't include unused local functions in the generated BEAM file, but the warning is still useful for keeping the source code cleaner ๐Ÿงน.
  • {nowarn_unused_function, FAs} โ€” turns off warnings for unused local functions just like nowarn_unused_function does, but only for the local functions you name. FAs is a tuple {Name,Arity} or a list of such tuples.
  • nowarn_deprecated_function โ€” turns off warnings for calls to deprecated functions. Default is to emit warnings for every call to a function known by the compiler to be deprecated. Quick note: the compiler does not know about the -deprecated() attribute, it uses an assembled list of deprecated functions in Erlang/OTP. If you want a more general check, the Xref tool can be used. See also xref(3) and the function xref:m/1, also accessible through the function \c:xm/1.
  • {nowarn_deprecated_function, MFAs} โ€” turns off warnings for calls to deprecated functions just like nowarn_deprecated_function does, but only for the functions you name. MFAs is a tuple {Module,Name,Arity} or a list of such tuples.
  • nowarn_deprecated_type โ€” turns off warnings for use of deprecated types. Default is to emit warnings for every use of a type known by the compiler to be deprecated.
  • nowarn_deprecated_callback โ€” turns off warnings for use of deprecated callbacks. Default is to emit warnings for every use of a callback known by the compiler to be deprecated.
  • nowarn_deprecated_catch โ€” turns off warnings for use of old style catch expressions, the ones shaped like catch Expr instead of the modern try ... catch ... end.
  • warn_obsolete_bool_op โ€” turns on warnings for use of the and and or boolean operators ๐Ÿ‘€.
  • nowarn_match_alias_pats โ€” turns off warnings for matches that unify constructors, like this one: m({a,B} = {Y,Z}) -> . . .
  • nowarn_export_var_subexpr โ€” turns off warnings for exporting variables out of subexpressions.
  • nowarn_removed โ€” turns off warnings for calls to functions that have been removed. Default is to emit warnings for every call to a function known by the compiler to have been recently removed from Erlang/OTP.
  • {nowarn_removed, ModulesOrMFAs} โ€” turns off warnings for calls to modules or functions that have been removed. Default is to emit warnings for every call to a function known by the compiler to have been recently removed from Erlang/OTP.
  • nowarn_obsolete_guard โ€” turns off warnings for calls to old type testing BIFs, like pid/1 and list/1. Peep the Erlang Reference Manual for a complete list of type testing BIFs and their old equivalents. Default is to emit warnings for calls to old type testing BIFs.
  • warn_unused_import โ€” emits warnings for unused imported functions. Default is to emit no warnings for unused imported functions.
  • nowarn_underscore_match โ€” by default, warnings get emitted when a variable that begins with an underscore is matched after being bound. Use this option to turn this kind of warning off ๐Ÿ™….
  • nowarn_unused_vars โ€” by default, warnings get emitted for unused variables, except for variables beginning with an underscore ("Prolog style warnings"). Use this option to turn this kind of warning off.
  • nowarn_unused_record โ€” turns off warnings for unused record definitions. Default is to emit warnings for unused locally defined records.
  • {nowarn_unused_record, RecordNames} โ€” turns off warnings for unused record definitions. Default is to emit warnings for unused locally defined records.
  • nowarn_unused_type โ€” turns off warnings for unused type declarations. Default is to emit warnings for unused local type declarations.
  • nowarn_nif_inline โ€” by default, warnings get emitted when inlining is enabled in a module that may load NIFs, because the compiler may inline NIF fallbacks by accident ๐Ÿ˜ญ. Use this option to turn this kind of warnings off.
  • warn_missing_doc, warn_missing_doc_functions, warn_missing_doc_types, warn_missing_doc_callbacks โ€” so by default the compiler says nothing when an exported function, a callback, or a type is missing its -doc attribute, like it's being polite. These options turn that warning back on. And warn_missing_doc? That's the one-option-to-rule-them-all move โ€” it's literally equivalent to setting warn_missing_doc_functions, warn_missing_doc_types and warn_missing_doc_callbacks all at once. โœจ
  • nowarn_missing_doc, nowarn_missing_doc_functions, nowarn_missing_doc_types, nowarn_missing_doc_callbacks โ€” and if you already flipped the warnings on with warn_missing_doc and now you're like "okay bestie that's a lot", these turn those specific warnings back off. Same deal as before: nowarn_missing_doc is equivalent to setting nowarn_missing_doc_functions, nowarn_missing_doc_types and nowarn_missing_doc_callbacks together. ๐Ÿซถ
  • nowarn_hidden_doc, {nowarn_hidden_doc,NAs} โ€” by default you do get a warning when -doc false is set on a callback or a referenced type. Set nowarn_hidden_doc to hush all of those, or {nowarn_hidden_doc, NAs} to hush just the specific callbacks or types you name. And what is NAs, you ask? It's a tuple {Name, Arity}, or a list of such tuples. โœจ
  • warn_missing_spec โ€” by default the compiler stays quiet when someone forgets to give a spec (or contract) for an exported function. This one turns that warning ON.
  • warn_missing_spec_documented โ€” by default, no warning when a spec (or contract) is missing for a documented function. This option turns that warning ON.
  • warn_missing_spec_all โ€” by default, no warning when a spec (or contract) is missing for an exported or unexported function. This option turns that warning ON. All of them, bestie. ๐Ÿ‘‘
  • nowarn_redefined_builtin_type โ€” by default you get a warning when a built-in type gets locally redefined (rude, honestly). Use this to turn that warning off.
  • {nowarn_redefined_builtin_type, Types} โ€” same vibe, but picky: turns off that same locally-redefined-built-in-type warning, but only for the types listed in Types. And Types here is a tuple {TypeName,Arity}, or a list of such tuples. ๐ŸŽ€
  • nowarn_behaviours โ€” by default, warnings get emitted for issues with behaviours. This turns all warnings of that kind off. Every last one.
  • nowarn_conflicting_behaviours โ€” by default, you get warned when a module opts into multiple behaviours that share the names of one or more callback functions. Yeah, that's a conflict. Use this to turn that warning off.
  • nowarn_undefined_behaviour_func โ€” by default, you get a warning when a module uses a behaviour but doesn't export a mandatory callback function that behaviour requires. Use this to turn that warning off.
  • nowarn_undefined_behaviour โ€” by default you get a warning when a module tries to use an unknown behaviour. Use this to turn that warning off. ๐Ÿ’…
  • nowarn_undefined_behaviour_callbacks โ€” by default you get a warning when behaviour_info(callbacks) in the behaviour module returns undefined instead of a list of callback functions. Use this to turn that warning off.
  • nowarn_ill_defined_behaviour_callbacks โ€” by default you get a warning when behaviour_info(callbacks) in the behaviour module returns a badly formed list of functions. Use this to turn that warning off.
  • nowarn_ill_defined_optional_callbacks โ€” by default you get a warning when behaviour_info(optional_callbacks) in the behaviour module returns a badly formed list of functions. Use this to turn that warning off.
  • nowarn_novalue โ€” disables warnings for creating a native record without giving values for all its fields. But heads up, bestie: this warning only shows up when the module name for the record is explicitly given as the current module. If no module name is given at all, then not initializing all fields isn't a warning โ€” it's a full-on compilation error. ๐Ÿ˜ญ
  • nowarn_undefined_field โ€” disables warnings for referencing field names that aren't present in the local native record definition. This warning fires when you're accessing, matching, or updating a native record. It can also fire when you're creating a record, if the module name for the record is explicitly given as the current module.
  • nowarn_native_record_header โ€” by default you get a warning when a native record is defined in a header file. FYI you can swap a native record definition in a header file for an -import_record() directive. Use this option to turn that warning off.
  • nowarn_unsafe_function โ€” turns off warnings for calls to unsafe functions. The default is to warn you about every single call to a function the compiler knows to be unsafe. Real talk though: the compiler doesn't know about the -unsafe() attribute โ€” it uses a pre-assembled list of unsafe functions in Erlang/OTP. So if you want a more general check, the Xref tool is right there. See also xref(3) and the function xref:m/1, which you can also reach through xm/1. ๐Ÿ”ฅ
  • {nowarn_unsafe_function, MFAs} โ€” does the nowarn_unsafe_function thing, but only for the functions you mention. And MFAs is a tuple {Module,Name,Arity}, or a list of such tuples.
  • warn_possibly_unsafe_function โ€” enables warnings for functions that are unsafe when used in a certain manner. ๐Ÿ‘€

Other kinds of warnings are opportunistic warnings. They're generated when the compiler just happens to notice potential issues while it's doing optimization and code generation. It's giving "noticed it in passing".

NOTE: the compiler does not warn for expressions it doesn't attempt to optimize. For example, it'll emit a warning for 1/0, but not for X/0 โ€” because 1/0 is a constant expression the compiler will try to evaluate. So like, the absence of warnings does NOT mean there are no remaining errors in the code. Don't let the silence gaslight you. ๐Ÿ’€

Opportunistic warnings can be disabled with these options:

  • nowarn_opportunistic โ€” disable all opportunistic warnings. All of them, gone.
  • nowarn_failed โ€” disable warnings for expressions that will always fail (like atom+42).
  • nowarn_ignored โ€” disable warnings for expressions whose values are ignored.
  • nowarn_nomatch โ€” disable warnings for patterns that will never match (like a=b) and for guards that always evaluate to false.
NOTE: all options, except the include path ({i,Dir}), can also be given in the file with the attribute -compile([Option,...]). And the -compile() attribute is allowed after the function definitions. ๐Ÿ“Œ
NOTE: before Erlang/OTP 22, the option {nowarn_deprecated_function, MFAs} was only recognized when given in the file with the -compile() attribute. (And the option {nowarn_unused_function,FAs} was incorrectly documented to only work in a file โ€” but it actually worked in the option list too.) Starting from Erlang/OTP 22, all options that can be given in the file can also be given in the option list. Glow up, honestly. โœจ

For debugging the compiler, or just out of pure curiosity, you can inspect the intermediate code generated by each compiler pass. To print a complete list of the options that produce list files, type compile:options() at the Erlang shell prompt. The options print in the order the passes are executed โ€” and if you use more than one listing option, the one representing the earliest pass is the one that takes effect. ๐ŸŒธ

Unrecognized options are ignored. (No notes, no complaints, just vibes.)

Both WarningList and ErrorList have this format:

[{FileName,[ErrorInfo]}].

The filename is included here because the compiler uses the Erlang pre-processor epp, which lets the code be included in other files. So yeah, it's genuinely important to know which file an error's or a warning's location actually refers to. ๐Ÿฆ‹

The ErrorInfo structure has this format:

{ErrorLocation, Module, ErrorDescriptor}

ErrorLocation is usually the tuple {Line, Column}. If the option {error_location,line} has been given, then ErrorLocation is only the line number. And if the error doesn't correspond to a specific location (for example, if the source file doesn't exist), then ErrorLocation is the atom none.

You grab a string describing the error with this call:

Module:format_error(ErrorDescriptor)

format_error(ErrorDescription :: error_description()) -> string().

Takes an ErrorDescriptor and returns a deep list of characters describing the error.

This function is usually called implicitly when an ErrorInfo structure gets processed โ€” so it's doing its little job behind the scenes. ๐Ÿ’…


forms(forms()) -> CompRet :: comp_ret().

Is the same as forms(Forms, [verbose,report_errors,report_warnings]). Shortcut behavior, we love her.


forms(Forms :: forms(), Options :: [option()] | option()) -> CompRet :: comp_ret().

Analogous to file/1, except it takes a list of forms as the first argument โ€” and those forms can be in either Erlang abstract or Core Erlang format representation. ๐ŸŽ€

The option binary is implicit here, meaning no object code file gets produced. And for options that normally produce a listing file โ€” like 'E' โ€” what you get back is the internal format for that compiler pass (an Erlang term, usually not a binary) instead of a binary.


noenv_file(File :: module() | file:filename(), Options :: [option()] | option()) -> comp_ret().

Works like file/2, except that the environment variable ERL_COMPILER_OPTIONS is not consulted. Lowkey the whole point.


noenv_forms(Forms :: forms(), Options :: [option()] | option()) -> comp_ret().

Works like forms/2, except that the environment variable ERL_COMPILER_OPTIONS is not consulted. Same energy as above. โœจ


noenv_output_generated(Options :: [option()]) -> boolean().

output_generated() ๐Ÿ’–

Works exactly like output_generated/1, bestie โ€” except that the environment variable ERL_COMPILER_OPTIONS is not consulted. That's it, that's the whole vibe. The env var? Not invited to this party. ๐Ÿ™…โ€โ™€๏ธ


output_generated(Options :: [option()]) -> boolean(). ๐Ÿฆ‹

output_generated(Options :: [option()]) -> boolean().

Okay so this one is the little oracle that tells you whether the compiler is gonna spit out a BEAM file when you hand it these Options. โœจ

  • true โ€” periodt ๐Ÿ’… a BEAM file is getting generated.
  • false โ€” nope, not this time. The compiler is instead generating some listing file, returning a binary, or merely checking the syntax of the source code. Which is giving "we're just here to vibe check your source, not to build anything" ๐Ÿ˜ญ
No cap: if you're out here expecting a BEAM file and you get false, that's your sign that one of those other modes got switched on. Check your options, bestie. ๐Ÿ”ฅ

and that's a wrap on compile(3), you absolute icon ๐Ÿ‘‘ this page lives in Ericsson AB's compiler docs, version 10.0.4, dated compile(3) โ€” go forth and compile something gorgeous, fr fr ๐Ÿ’–โœจ๐ŸŽ€

๐Ÿ“ฆ where this page comes from