compile(3)
๐ธ 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/2lists:any/2lists:foreach/2lists:map/2lists:flatmap/2lists:filter/2lists:foldl/3lists:foldr/3lists:mapfoldl/3lists: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 (
.erlfile): The file is compiled usingcompile:file/2orerlc <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/2to directly pass in the term representation of the abstract format. - Write the term representation to a file with the extension
.abstrand compile that file usingcompile:file(<File>, [from_abstr])orerlc <File>.abstr.
- Call
- Core Erlang: While there is a specification for Core Erlang, certain details are left to the implementation via the
primopexpression. 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 byforms/2. ๐ซถoption()โ Seefile/2for 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 theerl_lintmodule (such as warnings for unused variables and functions) are also returned. Use optionstrong_validationto generate all warnings that the compiler would generate.strong_validationโ Similar to optionbasic_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-docattributes and places them in theDocschunk according to EEP-48. This option switches off the placement of-docattributes in theDocschunk.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 aboutbin_opt_infoin the Efficiency Guide.{compile_info, [{atom(), term()}]}โ Allows compilers built on top ofcompileto attach extra compilation metadata to thecompile_infochunk in the generated BEAM file. It is advised for compilers to remove all non-deterministic information if thedeterministicoption 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 thedebug_infochunk of your compiledbeammodule, 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 compiledbeammodule, in the form of a Backend module with custom Data. That module has to implement adebug_info/4function and it's the one responsible for generating the different code representations โ exactly like thedebug_infodescribed underbeam_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 thedebug_infooption 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 thedebug_info_keyoption's twin, except the key gets read from an.erlang.cryptfile. ๐
For the details, see beam_lib(3).
deterministicโ omits theoptionsandsourcetuples from the list thatModule: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 calledallthat 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 themakedepoption. ๐ฅ{makedep_output, Output}โ writes the generated rules to Output instead of the default<File>.Pbeam. Output can be a filename or anio_device(). Wanna write to stdout? Usestandard_io. But heads up: ifbinaryis 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 tomake(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 bothreport_errorsandreport_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 isline, then the location ErrorLocation of warnings and errors is a line number. If the value iscolumn, then ErrorLocation includes both a line number and a column number. Default iscolumn. 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 bothreturn_errorsandreturn_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 inmodule_info(compile)and in stack traces.absolute_sourceโ turns the source file name (as presented inmodule_info(compile)and stack traces) into an absolute path, which helps external tools likeperfandgdbfind 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-includeor-include_libdirective, the compiler searches for header files in these directories:".", the current working directory of the file server- The base name of the compiled file
- 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 typeatom, and Value can be any term. The default Value istrue. โจ{parse_transform,Module}โ causes the parse transformation functionModule:parse_transform/2to 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 theto_abstroption (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 functionF/Astop being auto-imported from theerlangmodule, 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 theerlangmodule 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 theerlangmodule. 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 thefrom_abstroption. 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.beamfile. 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. Peepbeam_libfor 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 anexecutable_lineinstruction 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 optionline_coverage, this module gets loaded in theline_countercoverage mode, no matter what the current coverage mode in the runtime system is. This one is used bycoverto 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_xxxform, to turn the warning on. - the
nowarn_xxxform, 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 toio:formatand similar functions.
Verbosity picks how many warnings you get:
0= no warnings at all ๐1= warnings for invalid format strings and incorrect number of arguments2= 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 theexport_alloption. Default is to emit a warning if the optionexport_allis 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 likenowarn_unused_functiondoes, 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 alsoxref(3)and the functionxref:m/1, also accessible through the function\c:xm/1.{nowarn_deprecated_function, MFAs}โ turns off warnings for calls to deprecated functions just likenowarn_deprecated_functiondoes, 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 stylecatchexpressions, the ones shaped likecatch Exprinstead of the moderntry ... catch ... end.warn_obsolete_bool_opโ turns on warnings for use of theandandorboolean 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, likepid/1andlist/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-docattribute, like it's being polite. These options turn that warning back on. Andwarn_missing_doc? That's the one-option-to-rule-them-all move โ it's literally equivalent to settingwarn_missing_doc_functions,warn_missing_doc_typesandwarn_missing_doc_callbacksall 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 withwarn_missing_docand now you're like "okay bestie that's a lot", these turn those specific warnings back off. Same deal as before:nowarn_missing_docis equivalent to settingnowarn_missing_doc_functions,nowarn_missing_doc_typesandnowarn_missing_doc_callbackstogether. ๐ซถnowarn_hidden_doc,{nowarn_hidden_doc,NAs}โ by default you do get a warning when-doc falseis set on a callback or a referenced type. Setnowarn_hidden_docto hush all of those, or{nowarn_hidden_doc, NAs}to hush just the specific callbacks or types you name. And what isNAs, 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 inTypes. AndTypeshere 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 whenbehaviour_info(callbacks)in the behaviour module returnsundefinedinstead of a list of callback functions. Use this to turn that warning off.nowarn_ill_defined_behaviour_callbacksโ by default you get a warning whenbehaviour_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 whenbehaviour_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 alsoxref(3)and the functionxref:m/1, which you can also reach throughxm/1. ๐ฅ{nowarn_unsafe_function, MFAs}โ does thenowarn_unsafe_functionthing, but only for the functions you mention. AndMFAsis 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 for1/0, but not forX/0โ because1/0is 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 (likeatom+42).nowarn_ignoredโ disable warnings for expressions whose values are ignored.nowarn_nomatchโ disable warnings for patterns that will never match (likea=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
- ubuntu stonking: erlang-doc 1:29.0.6+dfsg-1 ยท Apache-2.0
- ๐ girlified by deepseek-ai/DeepSeek-V4.1-Flash on : a language model's rewrite of the original, under its terms