compiler

v9.0.4

Compiler Release Notes

This document describes the changes made to the Compiler application.

Compiler 9.0.4

Fixed Bugs and Malfunctions

For some function heads or case expressions with a huge number of clauses, the compiler could spend an inordinate amount of time compiling the code.

Own Id: OTP-19797 Aux Id: PR-10252

Passing a type for a fun as a macro argument would result in a "badly formed argument" error message from the compiler. Example:

-module(test).
-define(FOO(X), X).
-type foo() :: ?FOO(fun(() -> ok)).

Compiling this module would result in the following error message:

test.erl:3:17: badly formed argument for macro 'FOO'
%    5| -type foo() :: ?FOO(fun(() -> ok)).
%

Own Id: OTP-19821 Aux Id: GH-10280, PR-10309

In certain edge cases, the compiler could emit code that would do an unsafe destructive update of a tuple. This has been corrected.

Own Id: OTP-19879 Aux Id: GH-10367, PR-10435

Improvements and New Features

The compiler option beam_debug_stack combined with beam_debug_info will attempt to make as many variables as possible visible in the debugger. The option has no effect if given without beam_debug_info.

Own Id: OTP-19854 Aux Id: PR-10374

Compiler 9.0.3

Fixed Bugs and Malfunctions

Fixed broken type inference for lists:mapfoldl/r.

Own Id: OTP-19845 Aux Id: GH-10354, PR-10358

Compiler 9.0.2

Fixed Bugs and Malfunctions

Fixed a compiler crash caused by patch order in destructive update.

Own Id: OTP-19660 Aux Id: GH-9903, PR-9909

Fixed a compiler crash in beam_ssa_pre_codegen caused by wrong handling of multiple phi patches in the destructive update pass.

Own Id: OTP-19689 Aux Id: GH-9987, PR-9990

Fixed a crash when a zip generator contains a map pattern.

Own Id: OTP-19693 Aux Id: PR-10009, GH-10002

In rare circumstances, the compiler could crash when compiling code using bit syntax construction.

Own Id: OTP-19722 Aux Id: GH-10077, PR-10090

A few minor bugs that could affect the beam_debug_info option were fixed.

Own Id: OTP-19758 Aux Id: PR-10153

Compiler 9.0.1

Fixed Bugs and Malfunctions

Fixed a bug that could cause empty bitstring matches to always succeed, even when they should not.

Own Id: OTP-19711 Aux Id: GH-10047, PR-10048

Compiler 9.0

Fixed Bugs and Malfunctions

The compiler will now emit warnings when some map patterns cannot possibly match because a previous clauses matches the same pattern. For example:

mm_1(#{}) -> a;
mm_1(#{b := B}) -> {b,B}.

mm_2(#{a := A}) -> {a,A};
mm_2(#{a := A, b := B}) -> {b,A,B}.

The second clause of these function can never match and the compiler will now emit a warning for both of them.

Note that the compiler is not guaranteed to emit warnings for every possible map pattern that cannot match.

Own Id: OTP-19141 Aux Id: GH-8558, PR-8600

The size of an atom in the Erlang source code was limited to 255 bytes in previous releases, meaning that an atom containing only emojis could contain only 63 emojis.

While atoms are still only allowed to contain 255 characters, the number of bytes is no longer limited.

External tools that parse the AtU8 chunk of a BEAM file directly need to be updated. Tools that use beam_lib:chunks(Beam, [atoms]) to read the atom table will continue to work.

POTENTIAL INCOMPATIBILITY

Own Id: OTP-19285 Aux Id: PR-8913

The literals chunk in BEAM is no longer compressed, resulting in slightly smaller BEAM files when a BEAM file is stripped using beam_lib:strip_files/1.

This is a potential incompatibility for tools that read and interpret the contents of the literal chunk. One way to update such tools to work with the new format is to retrieve the chunk using beam_lib:chunks(Beam, [literals]).

POTENTIAL INCOMPATIBILITY

Own Id: OTP-19323 Aux Id: GH-8967, PR-8988

The final validation step in the compiler will now reject modules containing functions with more than 255 arguments. No impact is expected as the emulator has always refused to load these modules.

Own Id: OTP-19376 Aux Id: GH-9113, PR-9121

Replaced calls to deprecated crypto:start() with application:start(crypto).

Own Id: OTP-19485 Aux Id: PR-8592

Refactor code to not rely on +nowarn_shadow_vars.

Own Id: OTP-19574 Aux Id: PR-9678

Improvements and New Features

The EEP-48 doc chunk embedded into .beam files by the compiler is now compressed and deterministic.

Own Id: OTP-19096 Aux Id: PR-8494

Provided that the map argument for a maps:put/3 call is known to the compiler to be a map, the compiler will replace such calls with the corresponding update using the map syntax.

Own Id: OTP-19115 Aux Id: PR-8540

For various error types, the compiler now tries to suggest potential fixes by adding "did you mean ...?" at the end of error messages.

When a function is used with wrong arity, the compiler will try to suggest a defined function with the same name but a different arity. For example, given the following module:

-module(typos).
-export([t/0]).
bar(A) -> A.
bar(A,A,A) -> A.
bar(A,A,A,A) -> A.
t() -> bar(0, 0).

The compiler will emit the following message:

typo.erl:6:12: function bar/2 undefined, did you mean bar/1,3,4?
%   6|     t() -> bar(0, 0).
%    |            ^

For compiler errors that can easily be caused by typos, the compiler will try to suggest what the correct variable or function name, could be. For example, given the following module:

-module(typos).
-export([bar/2]).

bar(A0, B0) ->
    A + B.

the compiler will emit the following error messages:

typos.erl:5:5: variable 'A' is unbound, did you mean 'A0'?
%    5|     A + B.
%     |     ^

typos.erl:5:9: variable 'B' is unbound, did you mean 'B0'?
%    5|     A + B.
%     |         ^

Error types that now suggest correct arities: bad_inline, undefined_nif, bad_nowarn_unused_function, bad_nowarn_bif_clash, undefined_function.

Error types that now suggest correct names: bad_inline, undefined_nif, bad_nowarn_unused_function, undefined_on_load, undefined_function, undefined_record, undefined_field, unbound_var.

Using a function with wrong arity has higher precedence than having a typo in the function name. If the compiler can find a defined function with the same name but a different arity, it will not suggest a defined function with a close-enough name, regardless of arity.

Own Id: OTP-19180 Aux Id: PR-8699, PR-9094

Comprehensions have been extended with zip generators according to EEP 73.

Example:

1> [A+B || A <- [1,2,3] && B <- [4,5,6]].
[5,7,9]

Own Id: OTP-19184 Aux Id: PR-8926

Documentation chunks (EEP-48) has been updated to include the following reserved metadata fields: behaviours, group, source_path, and source_annos. The compiler has also been updated to emit this metadata. See the EEP-48 documentation for more details.

Own Id: OTP-19306 Aux Id: PR-8945, PR-8975

New strict generators have been added for comprehensions.

The currently existing generators are "relaxed": they ignore terms in the right-hand side expression that do not match the left-hand side pattern.

The new strict generators fail with exception badmatch if a pattern doesn't match.

Examples:

Using the current relaxed generator operator <-, any element not matching the pattern {_,_} will be silently discarded:

1> [T || {_,_}=T <- [{ok,1},ok,{error,2}]].
[{ok,1},{error,2}]

If the intention is that all lists processed by a list comprehension must only contain tuples of size two, using the new strict version of the operator ensures that term not matching will cause a crash:

2> [T || {_,_}=T <:- [{ok,1},ok,{error,2}]].
** exception error: no match of right hand side value ok

Using the strict generator operator to mark the intention that all list elements must match the pattern could help finding mistakes quicker if something unpexected is added to the list processed by the generator.

The strict version for bitstring generators is <:=.

Own Id: OTP-19317 Aux Id: PR-8625

New options for suppressing behaviour warnings have been added:

nowarn_conflicting_behaviours

nowarn_undefined_behaviour_func

nowarn_undefined_behaviour

nowarn_undefined_behaviour_callbacks

nowarn_ill_defined_behaviour_callbacks

nowarn_ill_defined_optional_callbacks

Own Id: OTP-19334 Aux Id: GH-8985, PR-9020

Some BIFs with side-effects are optimized in try/catch in the same way as guard BIFs in order to gain performance.

The following BIFs that are optimized in this way: binary_to_atom/1, binary_to_atom/2, binary_to_existing_atom/1, list_to_atom/1, and list_to_existing_atom/1.

Own Id: OTP-19339 Aux Id: PR-9042, PR-9122

The compiler now converts known documentation attribute metadata entries from unicode:chardata/0 to unicode:unicode_binary/0.

Own Id: OTP-19394 Aux Id: PR-9192

The warn_deprecated_catch option enables warnings for use of old-style catch expressions on the form catch Expr instead of the modern try ... catch ... end. To prevent new uses of uses of old catches to be added, this compiler option can be enabled on the project level and -compile(nowarn_deprecated_catch). added to individual files that still contain old catches.

Own Id: OTP-19425 Aux Id: PR-9154

Defining a fun in terms of an imported function is not allowed. Before this release, the compiler would not catch this kind of error if the name of the imported function happened to be a BIF. Consider this example:

-module(fun_example).
-export([foo/0, bar/0]).
-import(m, [max/2, not_a_bif/0]).

foo() ->
    fun max/2.

bar() ->
    fun not_a_bif/0.

The compiler in Erlang/OTP 27 would generate the following messages:

fun_example.erl:9:5: function not_a_bif/0 undefined
%    9|     fun not_a_bif/0.
%     |     ^

fun_example.erl:3:2: Warning: import directive overrides auto-imported BIF max/2 --
use "-compile({no_auto_import,[max/2]})." to resolve name clash
%    3| -import(m, [max/2, not_a_bif/0]).
%     |  ^

That is, there would be a (cryptic) error for fun not_a_bif/0, but only a warning for fun max/2.

When compiling with this release, both attempts to create a fun will result in error messages (as well as a warning):

fun_example.erl:6:5: creating a fun from imported name max/2 is not allowed
%    6|     fun max/2.
%     |     ^

fun_example.erl:9:5: creating a fun from imported name not_a_bif/0 is not allowed
%    9|     fun not_a_bif/0.
%     |     ^

fun_example.erl:3:2: Warning: import directive overrides auto-imported BIF max/2 --
use "-compile({no_auto_import,[max/2]})." to resolve name clash
%    3| -import(m, [max/2, not_a_bif/0]).
%     |  ^

Also, attempting to call a local function having the same name as auto-imported BIF would result in an error if the BIF was added to Erlang/OTP before R14, and a warning for newer BIFs. This has been changed to always emit a warning. For example:

-module(bif_example).
-export([bar/1]).

bar(B) ->
    is_boolean(B).

is_boolean(B) ->
        B =:= true orelse B =:= false.

will now result in the following warning instead of an error:

if_example.erl:5:5: Warning: ambiguous call of overridden auto-imported BIF is_boolean/1 --
use erlang:is_boolean/1 or "-compile({no_auto_import,[is_boolean/1]})." to resolve name clash
%    5|     is_boolean(B).
%     |     ^

Own Id: OTP-19432 Aux Id: PR-9246

The compiler’s alias analysis pass is now both faster and less conservative, allowing optimizations of records and binary construction to be applied in more cases.

Own Id: OTP-19502 Aux Id: PR-8695

BEAM files no longer include a Meta chunk if there are no features used. That slightly decreases the size of BEAM files, and it also ensures that m(Module) and beam_lib:md5(Beam) will match for preloaded modules.

Own Id: OTP-19524 Aux Id: PR-9517

The license and copyright header has changed format to include an SPDX-License-Identifier. At the same time, most files have been updated to follow a uniform standard for license headers.

Own Id: OTP-19575 Aux Id: PR-9670

An experimental API for a native debugger has been added. The main components are the following:

A new compiler option beam_debug_info for the Erlang compiler. When given, most optimizations are disabled and debug information suitable for the native debugger are added to generated BEAM files.

A new +D emulator flag. When given, the VM becomes "debuggable", which means that when modules that been compiled with the beam_debug_info option are loaded, the code is instrumented so that one can enable and disable breakpoints on executable lines.

An experimental erl_debugger module with a new debugging API. Essentially, it allows a single, local, process to be registered as the "debugger" process for the node. This process is the one that will receive messages notifying that a process hit a breakpoint. This way, the front-end implementation of a debugger (such as edb from WhatApp) can be decoupled from OTP.

The erl_debugger module also exposes new BIFs to inspect X and Y registers of a suspended process. Together with new code-information BIFs, this let's a debugger show the values of variables in scope for a suspended process.

Own Id: OTP-19609 Aux Id: PR-8670, PR-9334, PR-9604

Compiler 8.6.1.3

Fixed Bugs and Malfunctions

Fixed broken type inference for lists:mapfoldl/r.

Own Id: OTP-19845 Aux Id: GH-10354, PR-10358

Fix a compiler alias analysis bug that can generate unsafe code for repeated binary segments.

Own Id: OTP-19951 Aux Id: PR-10588

Compiler 8.6.1.2

Fixed Bugs and Malfunctions

In rare circumstances, the compiler could crash when compiling code using bit syntax construction.

Own Id: OTP-19722 Aux Id: GH-10077, PR-10090

Compiler 8.6.1.1

Fixed Bugs and Malfunctions

Fixed a bug that could cause empty bitstring matches to always succeed, even when they should not.

Own Id: OTP-19711 Aux Id: GH-10047, PR-10048

Compiler 8.6.1

Fixed Bugs and Malfunctions

Fix the compiler crash when the inner-most tuple in a nested tuple with 3 layers is updated.

Own Id: OTP-19561 Aux Id: ERIERL-1208, ERIERL-1210, PR-9650

Compiler 8.6

Improvements and New Features

The beam_validator pass in the compiler that validates generated BEAM now does stronger checks for binary syntax matching.

Own Id: OTP-19449 Aux Id: PR-9338

Compiler 8.5.5

Fixed Bugs and Malfunctions

Eliminated a bug in the alias analysis pass that could potentially cause unsafe optimizations of binary construction or record updates.

Own Id: OTP-19455 Aux Id: PR-9356

Compiler 8.5.4

Fixed Bugs and Malfunctions

Fixed a crash in the common sub-expression elimination pass.

Own Id: OTP-19243 Aux Id: GH-8818, PR-8838

Fixed a bug where bogus code was generated for consecutive calls to erlang:setelement/2, potentially crashing the runtime system.

Own Id: OTP-19270 Aux Id: GH-8783, PR-8898

When the line_coverage option was used, exceptions could show the wrong line for where the exception was raised.

Own Id: OTP-19282 Aux Id: PR-8907

The line_coverage option would be ignored if given in a compile() attribute within a module.

Own Id: OTP-19309 Aux Id: GH-8942, PR-8970

A segment matching a float in a binary generator will now skip any invalid float (such as a NaN) and continue matching the rest of the binary. Before this correction, the comprehension would stop as soon as an invalid float was encountered.

Example:

1> BadFloat = <<-1:64>>.
<<"ÿÿÿÿÿÿÿÿ">>
2> [X || <<X:64/float>> <= <<0.0/float,BadFloat/binary,42.0/float>>].
[0.0,42.0]

Own Id: OTP-19331 Aux Id: PR-8978

Compiler 8.5.3

Fixed Bugs and Malfunctions

In rare circumstances, the destructive tuple update optimization could be applied when it was unsafe.

Own Id: OTP-19340 Aux Id: GH-9014, PR-9024

In rare circumstances involving appending to multiple binaries, the compile could emit unsafe code that would crash the runtime system.

Own Id: OTP-19374 Aux Id: GH-9100, PR-9111

Compiler 8.5.2

Fixed Bugs and Malfunctions

Fixed a crash in an optimization pass relating to appending binaries.

Own Id: OTP-19168 Aux Id: GH-8630

Fixed a bug in the compiler's alias analysis pass that could make it emit unsafe code.

Own Id: OTP-19178 Aux Id: PR-8686

Compiler 8.5.1

Fixed Bugs and Malfunctions

One of the compiler's optimization passes would get very slow when compiling certain modules. The compiler will now automatically disable that pass for input that would trigger the slowdown.

Own Id: OTP-19131 Aux Id: PR-8567

Fix +deterministic to work properly with documentation attributes.

Own Id: OTP-19142 Aux Id: PR-8585, GH-8579

Compiler 8.5

Fixed Bugs and Malfunctions

Generators for binary comprehensions could be evaluated before it was known that they would be needed. That could result in a binary comprehensions failing if a generator that should not be evaluated until later failed.

As an example, consider this module:

-module(t).
-export([f/0]).

f() ->
    <<0 || _ <- [], _ <- ok, false>>.

In Erlang/OTP 26 it would fail like so:

1> t:f().
** exception error: bad generator ok
     in function  t:f/0 (t.erl, line 6)

In Erlang/OTP 27 it returns an empty binary:

1> t:f().
<<>>

Own Id: OTP-18703 Aux Id: GH-7494, PR-7538

The documentation for the preprocessor now mentions that defined(Name) can be called in the condition for an -if or -elif directive to test whether Name is the name of a defined macro. (This feature was implemented in OTP 21.)

If a function call in an -if or -elif with a name that is not the name of a guard BIF, there would not be a compilation error, but would instead cause the lines following the directive to be skipped. This has now been changed to be a compilation error.

POTENTIAL INCOMPATIBILITY

Own Id: OTP-18784 Aux Id: GH-7706, PR-7726

Improvements and New Features

The compiler now emits nicer error message for function head mismatches. For example, given:

a() -> ok;
a(_) -> error.

Erlang/OTP 26 and earlier would emit a diagnostic similar to:

t.erl:6:1: head mismatch
%    6| a(_) -> error.
%     | ^

while in Erlang/OTP 27 the diagnostic is similar to:

t.erl:6:1: head mismatch: function a with arities 0 and 1 is regarded as two distinct functions. Is the number of arguments incorrect or is the semicolon in a/0 unwanted?
%    6| a(_) -> error.
%     | ^

Own Id: OTP-18648 Aux Id: PR-7383

The compiler now optimizes creation of binaries that are known to be constant.

Consider this example:

bin() ->
    C = char(),
    <<C>>.

char() -> $*.

Essentially, the compiler rewrites the example to the slightly more efficient:

bin() ->
    _ = char(),
    <<$*>>.

char() -> $*.

Own Id: OTP-18673 Aux Id: PR-7474, ERIERL-964

The compiler will now merge consecutive updates of the same record.

As an example, the body of the following function will be combined into a single tuple creation instruction:

-record(r, {a,b,c,d}).

update(Value) ->
    R0 = #r{},
    R1 = R0#r{a=Value},
    R2 = R1#r{b=2},
    R2#r{c=3}.

Own Id: OTP-18680 Aux Id: PR-7491, PR-8086, ERIERL-967

Improved the performance of the alias analysis pass.

Own Id: OTP-18714 Aux Id: PR-7528, GH-7432

-spec attributes are now used for documentation.

Own Id: OTP-18801 Aux Id: PR-7739

Native coverage support has been implemented in the JIT. It will automatically be used by the cover tool to reduce the execution overhead when running cover-compiled code.

There are also new APIs to support native coverage without using the cover tool.

To instrument code for native coverage it must be compiled with the line_coverage option.

To enable native coverage in the runtime system, start it like so:

$ erl +JPcover true

There are also the following new functions for supporting native coverage:

code:coverage_support/0

code:get_coverage/2

code:reset_coverage/1

code:get_coverage_mode/0

code:get_coverage_mode/1

code:set_coverage_mode/1

Own Id: OTP-18856 Aux Id: PR-7856

EEP-59 - Documentation Attributes has been implemented.

Documentation attributes can be used to document functions, types, callbacks, and modules. The keyword -moduledoc "Documentation here". is used to document modules, while -doc "Documentation here". can be used on top of functions, types, and callbacks to document them, respectively.

Types, callbacks, and function documentation can be set to hidden either via -doc false or -doc hidden. When documentation attributes mark a type as hidden, they will not be part of the documentation.

The documentation from moduledoc and doc gets added by default to the binary beam file, following the format of EEP-48.

Using the compiler flag warn_missing_doc will raise a warning when -doc attributes are missing in exported functions, types, and callbacks.

Using the compiler flag warn_missing_spec_documented will raise a warning when spec attributes are missing in documented functions, types, and callbacks.

moduledocs and docs may refer to external files to be embedded, such as -doc {file, "README.md"}., which refers to the file README.md found in the current working directory.

The compiler warns about exported functions whose specs refer to hidden types. Thus, there will be warnings when a hidden type (meaning, the type is not part of the documentation) gets used in an exported function.

Own Id: OTP-18916 Aux Id: PR-7936

The documentation has been migrated to use Markdown and ExDoc.

Own Id: OTP-18955 Aux Id: PR-8026

The order in which the compiler looks up options has changed.

When there is a conflict in the compiler options given in the -compile() attribute and options given to the compiler, the options given in the -compile() attribute overrides the option given to the compiler, which in turn overrides options given in the ERL_COMPILER_OPTIONS environment variable.

Example:

If some_module.erl has the following attribute:

-compile([nowarn_missing_spec]).

and the compiler is invoked like so:

% erlc +warn_missing_spec some_module.erl

no warnings will be issued for functions that do not have any specs.

POTENTIAL INCOMPATIBILITY

Own Id: OTP-18968 Aux Id: GH-6979, PR-8093

Safe destructive update of tuples has been implemented in the compiler and runtime system. This allows the VM to update tuples in-place when it is safe to do so, thus improving performance by doing less copying but also by producing less garbage.

Example:

-record(rec, {a,b,c}).

update(#rec{a=needs_update,b=N}=R0) ->
    R = R0#rec{a=up_to_date},
    if
        N < 0 ->
            R#rec{c=negative};
        N == 0 ->
            R#rec{c=zero};
        N > 0 ->
            R#rec{c=positive}
    end.

The record updates in each of the three clauses of the if can safely be done in-place, because variable R is not used again.

Own Id: OTP-18972 Aux Id: PR-8090

Improved the match context reuse optimization slightly, allowing match contexts to be passed as-is to bit_size/1 and byte_size/1.

Own Id: OTP-18987

erl_lint (and by extension the compiler) will now warn for code using deprecated callbacks.

The only callback currenly deprecated is format_status/2 in gen_server, gen_event and gen_statem.

You can use nowarn_deprecated_callback to silence the warning.

Own Id: OTP-19010 Aux Id: PR-8205

Compiler 8.4.3.4

Fixed Bugs and Malfunctions

Fixed broken type inference for lists:mapfoldl/r.

Own Id: OTP-19845 Aux Id: GH-10354, PR-10358

Compiler 8.4.3.3

Fixed Bugs and Malfunctions

Fix a bug where unloaded nifs can crash the compiler.

Own Id: OTP-19600 Aux Id: PR-9737, GH-9715

Compiler 8.4.3.2

Fixed Bugs and Malfunctions

Fixed a bug where bogus code was generated for consecutive calls to erlang:setelement/2, potentially crashing the emulator.

Own Id: OTP-19270 Aux Id: GH-8783 PR-8898

Compiler 8.4.3.1

Fixed Bugs and Malfunctions

Fixed a crash in an optimization pass relating to appending binaries.

Own Id: OTP-19168 Aux Id: GH-8630

Fixed a bug in the compiler's alias analysis pass that could make it emit unsafe code.

Own Id: OTP-19178 Aux Id: PR-8686

Compiler 8.4.3

Fixed Bugs and Malfunctions

In rare circumstances, the compiler code generate unsafe code for a bit syntax match.

Own Id: OTP-19019

In rare circumstances, binary matches that were supposed to succeed failed.

Own Id: OTP-19035 Aux Id: GH-8280, PR-8284

Fixed a bug where a fun's environment could be overridden by an argument if all of the following conditions were met:

The fun was declared in the module that called it.

The fun's target was statically known.

The fun was called with a number of extra arguments equal to the number of environment variables.

Own Id: OTP-19045 Aux Id: GH-8316

Compiler 8.4.2

Fixed Bugs and Malfunctions

In rare circumstances, an unsafe optimization could cause the compiler to generate incorrect code for list matching.

Own Id: OTP-19003 Aux Id: GH-8187, PR-8189

Improvements and New Features

Fix the compilation server to restart if the applications in its lib dir changes inbetween erlc invokations.

Own Id: OTP-18936

Compiler 8.4.1

Fixed Bugs and Malfunctions

The compiler could become extremely slow for modules containing huge functions.

Own Id: OTP-18770 Aux Id: GH-7667, PR-7672

Compiler 8.4

Fixed Bugs and Malfunctions

The compiler could run forever when compiling a call to is_record/3 with a huge positive tuple size. The call is_record(A, a, 0) would crash the compiler when used in a function body. When used in a guard the compiler would emit incorrect code that would accept {a> as a record.

Own Id: OTP-18605 Aux Id: GH-7298, GH-7317

Fixed a bug that caused dialyzer to crash when analyzing bogus code that contained the literal atom undefined in segment sizes.

Own Id: OTP-18629 Aux Id: GH-7325

The compiler would crash when compiling some modules that contained a call to erlang:load_nif/2.

Own Id: OTP-18662 Aux Id: GH-7409, PR-7416

Fixed a bug that caused the compiler to crash on legal code.

Own Id: OTP-18678 Aux Id: GH-7488

The compiler could crash when attempting to compile a call to is_list/1 in a complex expression.

Own Id: OTP-18689 Aux Id: GH-7504, PR-7518

A complex guard expression using the or operator could succeed when it was supposed to fail.

Own Id: OTP-18692 Aux Id: GH-7517, PR-7519

Compiling nested try/catch and catch expression could result in an internal compiler error.

Own Id: OTP-18701 Aux Id: GH-7477, PR-7532

Using the bnot operator in a complex expression could cause the compiler to terminate with an internal consistency failure diagnostic.

Own Id: OTP-18719 Aux Id: GH-7468, PR-7562

Fixed a bug that caused the compiler to crash in a binary optimization pass.

Own Id: OTP-18721 Aux Id: PR-7527

The compiler could terminate with an internal error when attempting to compile a binary pattern that could not possibly match.

Own Id: OTP-18725 Aux Id: GH-7467

Improvements and New Features

Fixed various performance issues related to the alias optimization pass.

Own Id: OTP-18691 Aux Id: PR-7448

Compiler 8.3.2

Fixed Bugs and Malfunctions

Fixed a type handling bug that would cause an internal consistence failure for correct code.

Own Id: OTP-18625 Aux Id: GH-7354

Fixed a bug that could cause the stack trace of throw exceptions to be erroneously optimized out.

Own Id: OTP-18626 Aux Id: GH-7356

Complex guard expression using 'or' were not always fully evaluated, making guards that were supposed to fail succeed.

Own Id: OTP-18634 Aux Id: GH-7370

Compiler 8.3.1

Fixed Bugs and Malfunctions

Fixed a bug where a failing bsl expression in a guard threw an exception instead of causing the guard to fail.

Own Id: OTP-18576

Fixed a bug that would case the validator to reject legal code.

Own Id: OTP-18581 Aux Id: GH-7251

The compiler could re-order clauses matching binaries so that the incorrect clause would match. That could only happen for code that used the option {error_location,line} or for code without line or column number information (e.g. generated by a parse transform).

Own Id: OTP-18583 Aux Id: GH-7259

Complex guard expression using the or operator and guard BIFs that can fail could sometimes be miscompiled so that the guard would succeed even if a call to a guard BIF failed.

Own Id: OTP-18593 Aux Id: GH-7252

With optimizations disabled, a try/catch construct could return an incorrect value.

Own Id: OTP-18600 Aux Id: GH-7248

In rare circumstance, a combination of binary construction and binary_part/3 would cause the compiler to generate unsafe code that would crash the runtime system.

Own Id: OTP-18601

The compiler could be very slow when compiling guards with multiple guard tests separated with 'or' or ';'.

Own Id: OTP-18617 Aux Id: GH-7338

Complex guard expressions using 'or' and map updates could succeed even if the map update failed.

Own Id: OTP-18619 Aux Id: GH-7339

Compiler 8.3

Fixed Bugs and Malfunctions

The compiler would silently accept singleton (unbound) type variables in a union type. Starting from Erlang/OTP 26, the compiler will generate a warning for this example. The warning can be disabled using the nowarn_singleton_typevar option. In Erlang/OTP 27, the warning will become an error.

Own Id: OTP-18389 Aux Id: GH-6508, PR-6864, GH-7116

Improvements and New Features

Optimized record updates.

Own Id: OTP-18126 Aux Id: PR-6033

There are several new optimization for binary syntax in the JIT:

Creation and matching of binaries with segments of fixed sizes have been optimized.

Creation and matching of UTF-8 segments have been optimized.

Appending to binaries has been optimized.

Own Id: OTP-18137 Aux Id: PR-6259, PR-6404, PR-6576, PR-6804

The compiler and JIT now generate better code for creation of small maps where all keys are literals known at compile time.

Own Id: OTP-18185 Aux Id: GH-6139

A limitation in the binary syntax has been removed. It is now possible to match binary patterns in parallel. Example: <<A:8>> = <<B:4,C:4>> = Bin

Own Id: OTP-18297 Aux Id: GH-6348

It is documented that $\^X is the ASCII code for Control X, where X is an uppercase or lowercase letter. However, this notation would work for any character X, even then it didn't make sense.

In Erlang/OTP 26, it is now documented that the following characters are also allowed to follow the \^ characters: @, [, \, ], ^, _, and ?. Attempt to use other characters will be rejected with a compiler error.

The value for $\^? is now 127 (instead of 31 as in earlier releases).

Own Id: OTP-18337 Aux Id: GH-6477, PR-6503

The BIFs min/2 and max/2 are now allowed to be used in guards and match specs.

Own Id: OTP-18367 Aux Id: GH-6544

Map comprehensions as suggested in EEP 58 has now been implemented.

Own Id: OTP-18413 Aux Id: EEP-58, PR-6727

Improved the selective receive optimization, which can now be enabled for references returned from other functions.

This greatly improves the performance of gen_server:send_request/3, gen_server:wait_response/2, and similar functions.

Own Id: OTP-18431 Aux Id: PR-6739

Deprecates dbg:stop_clear/0 because it is simply a function alias to dbg:stop/0

Own Id: OTP-18478 Aux Id: GH-6903

The compiler will now inline calls to maps:get/3.

Own Id: OTP-18502

In Erlang/OTP 27, 0.0 will no longer be considered to be exactly equal to -0.0. See Upcoming Potential Incompatibilities.

Own Id: OTP-18574

Compiler 8.2.6.4

Fixed Bugs and Malfunctions

In rare circumstances, an unsafe optimization could cause the compiler to generate incorrect code for list matching.

Own Id: OTP-19003 Aux Id: GH-8187, PR-8189

In rare circumstances, the compiler code generate unsafe code for a bit syntax match.

Own Id: OTP-19019

Compiler 8.2.6.3

Fixed Bugs and Malfunctions

Fixed a bug that could cause the stack trace of throw exceptions to be erroneously optimized out.

Own Id: OTP-18626 Aux Id: GH-7356

Compiler 8.2.6.2

Fixed Bugs and Malfunctions

The compiler could be very slow when compiling guards with multiple guard tests separated with 'or' or ';'.

Own Id: OTP-18617 Aux Id: GH-7338

Compiler 8.2.6.1

Fixed Bugs and Malfunctions

Fixed a bug where a failing bsl expression in a guard threw an exception instead of causing the guard to fail.

Own Id: OTP-18576

Complex guard expression using the or operator and guard BIFs that can fail could sometimes be miscompiled so that the guard would succeed even if a call to a guard BIF failed.

Own Id: OTP-18593 Aux Id: GH-7252

Compiler 8.2.6

Fixed Bugs and Malfunctions

Fixed type handling bugs that could cause an internal error in the compiler for correct code.

Own Id: OTP-18565 Aux Id: GH-7147

Compiler 8.2.5

Fixed Bugs and Malfunctions

When a map update such as #{}#{key:=value} that should fail with an exception was unused, the exception would be lost.

Own Id: OTP-18497 Aux Id: GH-6960, PR-6965

Fixed bug in the validator that made it reject valid code.

Own Id: OTP-18516 Aux Id: GH-6969

Compiler 8.2.4

Fixed Bugs and Malfunctions

Fixed a bug that would cause the compiler to hang.

Own Id: OTP-18378 Aux Id: GH-6604

Fixed a crash when compiling code that contained maybe expressions.

Own Id: OTP-18381 Aux Id: GH-6601

Constructing a binary with an explicit size of all for a binary segment would crash the compiler.

Own Id: OTP-18407 Aux Id: GH-6707

The compiler would generate incorrect code for the following type of expression:

Pattern = BoundVar1 = . . . = BoundVarN = Expression

An exception should be raised if any of the bound variables have different values than Expression. The compiler would generate code that would cause the bound variables to be bound to the value of Expressionwhether the value matched or not.

Own Id: OTP-18470 Aux Id: GH-6873, PR-6877

Compiler 8.2.3

Fixed Bugs and Malfunctions

Fixed a bug that could cause legal code to fail validation.

Own Id: OTP-18365

Eliminated a rare crash in the beam_types module.

Own Id: OTP-18368

Compiler 8.2.2

Fixed Bugs and Malfunctions

Line number in compiler messages would be truncated to 4 digits for line numbers greater than 9999.

Own Id: OTP-18268 Aux Id: GH-6332

In rare circumstance, matching a binary as part of a receive clause could cause the compiler to terminate because of an internal consistency check failure.

Own Id: OTP-18273 Aux Id: GH-6341

Compiling a function with complex bit syntax matching such as f(<<X:0, _:X>>, <<Y:0, _:Y>>) -> ok. could crash the compiler.

Own Id: OTP-18308 Aux Id: GH-6426

It is not allowed to call functions from guards. The compiler failed to reject a call in a guard when done by constructing a record with a default initialization expression that called a function.

Own Id: OTP-18325 Aux Id: GH-6465, GH-6466

The compiler could crash when using a record with complex field initialization expression as a filter in a list comprehension.

Own Id: OTP-18336 Aux Id: GH-6501, PR-6502

Compiler 8.2.1

Fixed Bugs and Malfunctions

The compiler will now forbid using the empty atom '' as module name. Also forbidden are modules names containing control characters, and module names containing only spaces and soft hyphens.

Own Id: OTP-18125 Aux Id: GH-6026

The bin_opt_info and recv_opt_info options would cause the compiler to crash when attempting to compile generated code without location information.

Own Id: OTP-18162 Aux Id: PR-6102

In rare circumstances involving floating point operations, the compiler could terminate with an internal consistency check failure.

Own Id: OTP-18182 Aux Id: GH-6163

In rare circumstances when doing arithmetic instructions on non-numbers, the compiler could crash.

Own Id: OTP-18183 Aux Id: GH-6169

In rare circumstances, complex boolean expressions in nested cases could cause the compiler to crash.

Own Id: OTP-18184 Aux Id: GH-6164

Expression similar to #{assoc:=V} = #key=>self()}, V would return the empty map instead of raising an exception.

Own Id: OTP-18186

Eliminated a crash in the beam_ssa_bool pass of the compiler when compiling a complex guard expression.

Own Id: OTP-18187 Aux Id: GH-6184

In rare circumstances, the compiler could crash with an internal consistency check failure.

Own Id: OTP-18202 Aux Id: GH-6222

When compiling with the option inline_list_funcs, the compiler could produce a nonsensical warning.

Own Id: OTP-18214 Aux Id: GH-6158

When given the no_ssa_opt option, the compiler could terminate with an internal consistency failure diagnostic when compiling map matching.

Own Id: OTP-18234 Aux Id: GH-6277

Improvements and New Features

Made warnings for existing atoms being keywords in experimental features more precise, by not warning about quoted atoms.

Own Id: OTP-18050

There is a new configure option, --enable-deterministic-build, which will apply the deterministic compiler option when building Erlang/OTP. The deterministic option has been improved to eliminate more sources of non-determinism in several applications.

Own Id: OTP-18165 Aux Id: PR-5965

Compiler 8.2

Fixed Bugs and Malfunctions

A subtle bug regarding variable scoping has been corrected. Consider this example:

(A=1) + fun() -> A = 2() end

In the shell, the expression correctly evaluates to 3. In compiled code, it raised a {badmatch, 2} exception.

Own Id: OTP-17810 Aux Id: GH-5379

Fixed a rare bug that would crash the compiler during type optimization.

Own Id: OTP-17820

Starting in OTP 24, when a fun was created and immediately used, it would be inlined. An unintended consequence of the inlining was that what would be a function_clause exception without the inlining would now be a rather confusing case_clause exception. This has been corrected, so that function_clause exceptions remain function_clause exceptions in inlined code.

Own Id: OTP-17860 Aux Id: GH-5513, OTP-17226

If a default record field initialization (_ = Expr) was used even though all records fields were explicitly initialized, Expr would not be evaluated. That would not be a problem, except when Expr would bind a variable subsequently used, in which case the compiler would crash.

As an example, if record #r{} is defined to have only one field a, the following code would crash the compiler:

#r{a=[],_=V=42}, V

To fix that problem, the compiler will make sure that Expr is always evaluated at least once. The compiler will now rewrite the example to essentially:

V=42, #r{a=[]}, V

Own Id: OTP-18083

Improvements and New Features

To enable more optimizations, BEAM files compiled with OTP 21 and earlier cannot be loaded in OTP 25.

Own Id: OTP-16702

Added support for the compile attribute -nifs() to empower compiler and loader with information about which functions may be overridden as NIFs by erlang:load_nif/2. It is recommended to use this attribute in all modules that load NIF libraries.

Own Id: OTP-17151 Aux Id: ERIERL-590, PR-5479

When binary construction using the binary syntax fails, the error message printed in the shell and by erl_error:format_exception/3,4 will contain more detailed information about what went wrong.

Own Id: OTP-17504 Aux Id: GH-4971, PR-5281, PR-5752

The Erlang compiler now includes type information in BEAM files, and the JIT can now use that type information to do optimizations such as eliminating or simplifying type tests.

Own Id: OTP-17684 Aux Id: PR-5316, PR-5664

Improved the JIT's support for external tools like perf and gdb, allowing them to show line numbers and even the original Erlang source code when that can be found.

To aid them in finding the source code, the absolute_path compiler option has been added to embed the absolute file path of a module.

Own Id: OTP-17685

The maybe ... end construction proposed in EEP-49 has been implemented. It can simplify complex code where otherwise deeply nested cases would have to be used.

To enable maybe, give the option -enable-feature maybe_expr to erlc or add -feature(maybe_expr, enable). inside the module.

Own Id: OTP-17705 Aux Id: PR-5411

When a record matching or record update fails, a {badrecord,ExpectedRecordTag} exception used to be raised. In this release, the exception has been changed to {badrecord,ActualValue}, where ActualValue is the actual that was found instead of the expected record.

Own Id: OTP-17841 Aux Id: PR-5694

Improved optimization of try/catch expressions.

Own Id: OTP-17842

The beam_trim pass of the compiler could be extremely slow for huge straight-line functions. It will now compile such functions much faster (down to seconds from minutes for some huge functions).

Own Id: OTP-17885 Aux Id: GH-5140

Added support for configurable features as described in EEP-60. Features can be enabled/disabled during compilation with options (-enable-feature Feature, -disable-feature Feature and +{feature, Feature, enable|disable}) to erlc as well as with directives (-feature(Feature, enable|disable).) in the file. Similar options can be used to erl for enabling/disabling features allowed at runtime. The new maybe expression (EEP-49) is fully supported as the feature maybe_expr. The features support is documented in the reference manual.

Own Id: OTP-17988

Compiler 8.1.1.6

Fixed Bugs and Malfunctions

In rare circumstances, an unsafe optimization could cause the compiler to generate incorrect code for list matching.

Own Id: OTP-19003 Aux Id: GH-8187, PR-8189

In rare circumstances, the compiler code generate unsafe code for a bit syntax match.

Own Id: OTP-19019

Compiler 8.1.1.5

Fixed Bugs and Malfunctions

The compiler could be very slow when compiling guards with multiple guard tests separated with 'or' or ';'.

Own Id: OTP-18617 Aux Id: GH-7338

Compiler 8.1.1.4

Fixed Bugs and Malfunctions

Complex guard expression using the or operator and guard BIFs that can fail could sometimes be miscompiled so that the guard would succeed even if a call to a guard BIF failed.

Own Id: OTP-18593 Aux Id: GH-7252

Compiler 8.1.1.3

Fixed Bugs and Malfunctions

The compiler would generate incorrect code for the following type of expression:

Pattern = BoundVar1 = . . . = BoundVarN = Expression

An exception should be raised if any of the bound variables have different values than Expression. The compiler would generate code that would cause the bound variables to be bound to the value of Expressionwhether the value matched or not.

Own Id: OTP-18470 Aux Id: GH-6873, PR-6877

Compiler 8.1.1.2

Fixed Bugs and Malfunctions

It is not allowed to call functions from guards. The compiler failed to reject a call in a guard when done by constructing a record with a default initialization expression that called a function.

Own Id: OTP-18325 Aux Id: GH-6465, GH-6466

Fixed a bug that could cause legal code to fail validation.

Own Id: OTP-18365

Compiler 8.1.1.1

Fixed Bugs and Malfunctions

The bin_opt_info and recv_opt_info options would cause the compiler to crash when attempting to compile generated code without location information.

Own Id: OTP-18162 Aux Id: PR-6102

In rare circumstances involving floating point operations, the compiler could terminate with an internal consistency check failure.

Own Id: OTP-18182 Aux Id: GH-6163

Compiler 8.1.1

Fixed Bugs and Malfunctions

Fixed a performance bug in the validator that made certain files take a very long time to compile.

Own Id: OTP-18066 Aux Id: GH-5915

In rare circumstances, the compiler would mistakenly assume that a call to setelement/3 would always fail and remove all code following the call.

Own Id: OTP-18082

Compiler 8.1

Fixed Bugs and Malfunctions

The expression <<0/native-float>>=Bin would always fail to match, while <<0/float-native>>=Bin would match (provided that Bin contained the binary representation of 0.0)

Own Id: OTP-17895

Improvements and New Features

The compiler will now compile huge functions with straight-line code faster.

Own Id: OTP-17886 Aux Id: GH-5140, GH-5686

Compiler 8.0.4

Fixed Bugs and Malfunctions

When the compiler is invoked by Dialyzer, it will no longer apply an optimization of binary patterns that would turn the pattern <<"bar">> into <<6447474:24>>, which would be very confusing when printed out by Dialyzer.

Own Id: OTP-17768 Aux Id: GH-5429

The compiler would replace known failing calls (such as atom_to_list(42)) with a call to error(badarg). With the extended error information introduced in OTP 24 (EEP 54), those "optimized" calls would not have extended error information. To ensure that as much extended error information as possible is available, the compiler now keeps the original call even when it is known to fail.

Own Id: OTP-17786 Aux Id: GH-5440

Compiler 8.0.3

Fixed Bugs and Malfunctions

If a parse transform raised an exception using throw/1 or exit/1, the compiler would report that as an internal compiler error, which would be confusing. Amended to report that the parse transform failed.

Own Id: OTP-17421

The failing call io:format("~p\n") would result in a warning for line number 0 instead of the correct line and column numbers. This has been corrected, and all warnings for failing calls to io:format() has been rephrased to make it clearer exactly what the problem is.

Own Id: OTP-17430

When the options warn_missing_spec and export_all were given, there would only be warnings for missing specs for functions that had been explicitly exported using an -export attribute.

Own Id: OTP-17434 Aux Id: GH-4772

In rare circumstances, the compiler could emit an incorrect warning for a term that was constructed but never used.

Own Id: OTP-17446 Aux Id: PR-4899

Corrected bugs where builds were not reducible even when the deterministic option was given. In particular, modules with map literals with more than 32 elements could cause this problem.

As part of this fix, the term_to_binary BIF now accepts the option deterministic.

Own Id: OTP-17495 Aux Id: PR-5153

The MODULE and MODULE_STRING macros would always appear to be defined (when tested by -ifdef), even though no -module() declaration had been seen yet. Changed so that -ifdef ?MODULE. will not consider ?MODULE defined if -module() has not been previously seen.

Own Id: OTP-17505 Aux Id: GH-4995

In a guard, not (X =:= true) would incorrectly evaluate to false for non-boolean values of X.

Own Id: OTP-17510 Aux Id: GH-5007

When the deterministic option was given to the compiler, the ?FILE macro would be expanded to full path of the source file before the first include directive and to base part of the filename after include directive.

Own Id: OTP-17581 Aux Id: PR-5141

Compiler 8.0.2

Fixed Bugs and Malfunctions

A compiler optimization pass could crash when given odd but legal code using throw/1.

Own Id: OTP-17489 Aux Id: GH-4953

Compiler 8.0.1

Fixed Bugs and Malfunctions

Fixed a bug that could cause after blocks to be ignored when erlang:raise/3 was used in a catch block.

Own Id: OTP-17428 Aux Id: GH-4859

Fixed a bug in the validation pass that could cause it to reject valid code.

Own Id: OTP-17437 Aux Id: OTP-17357, GH-4774

Compiler 8.0

Fixed Bugs and Malfunctions

A floating point zero (0.0) can be both positive (+0.0) and negative (-0.0). Multiple bugs in the compiler, runtime system, and STDLIB have been fixed to ensure that the minus sign on 0.0 is not lost.

Own Id: OTP-17077 Aux Id: ERL-1431, PR-2903, PR-2905, PR-2906

A repeated stack trace variable in a try/catch was not rejected. The following example will now cause a compilation error:

try E catch _:A:A -> A
      end.

Own Id: OTP-17104 Aux Id: ERL-1380

Eliminated a Dialyzer crashed when the -MMD option is used to generate a dependency file and a BEAM file a the same time.

Own Id: OTP-17118 Aux Id: PR-2825

When the makedep option was given, the compiler would crash if the dependency output contained non-latin1 characters. The compiler will now output the dependency information encoded in UTF-8 to avoid crashing.

Own Id: OTP-17206

Improvements and New Features

Selective receive optimization will now be applied much more often.

The new recv_opt_info compile flag can be used to print diagnostics relating to this optimization.

You can read more about the selective receive optimization in the Efficiency Guide.

Own Id: OTP-10391 Aux Id: OTP-16226

erlang:throw/1 will no longer build stack traces when we can prove that they will never be inspected.

Own Id: OTP-16334

Variables bound between the keywords 'try' and 'of' can now be used in the clauses following the 'of' keyword (that is, in the success case when no exception was raised).

Own Id: OTP-16706 Aux Id: ERL-1281

Compiler warnings and errors now include column numbers in addition to line numbers.

When a compiler message is emitted, the source line is printed along with a marker (a ^ character) that indicates the column position of the issue. The option 'brief' removes the printout of the source line.

The compiler option {error_location, line | column} has been added. The default value is column. Besides adding column numbers to compilation warnings and errors, the option also determines whether column numbers are included in abstract code. If tools stop working, setting the environment variable ERL_COMPILER_OPTIONS can help (include {error_location, line}).

The compiler will now call the function PT:parse_transform_info/0 in parse transforms (if it exists). It can be used by parse transforms to signal that they can only handle line numbers in abstract code.

* POTENTIAL INCOMPATIBILITY *

Own Id: OTP-16824 Aux Id: PR-2664, PR-3006

Fixed a performance bug that made functions with lots of try/after blocks slow to compile.

Own Id: OTP-16867 Aux Id: ERL-1354

The experimental HiPE application has been removed, together with all related functionality in other applications.

* POTENTIAL INCOMPATIBILITY *

Own Id: OTP-16963

Generators in list and binary comprehensions will now raise a {bad_generator,Generator} exception if the generator has an incorrect type (instead of raising an ad-hoc badarg or badarih exception). Similarly, when a filter does not evaluate to a boolean, a {bad_filter,Filter} exception will be raised. Some minor bugs in the compilation of binary comprehensions have also been fixed.

Own Id: OTP-16964

Some compiler warnings, such as the warning for an expression whose result is ignored, could not be suppressed by assigning to a variable beginning with '_', but only by assigning to the anonymous variable ('_'). This has now been changed so that any warning that can be suppressed by assigning to the anonymous variable can also be suppressed by assigning to a variable beginning with '_'.

Own Id: OTP-16981 Aux Id: ERL-1113

The previously undocumented compiler options warn_missing_spec and warn_missing_spec_all are now documented.

Own Id: OTP-17078 Aux Id: ERL-1430, PR-2918

The compiler will now emit warnings when (previously bound) underscore-prefixed variables are matched.

Own Id: OTP-17123

Erlang source files not encoded in utf-8 will no longer be accepted by the compiler unless it contains a "coding: latin-1" comment.

Own Id: OTP-17168

New compiler options from_abstr and no_lint have been added. They are useful when implementing other languages running on the BEAM.

Own Id: OTP-17172

The bit matching and construction syntax now supports 16-bit floats (IEEE 754-2008).

Own Id: OTP-17207

The compiler will now inline funs that are used only once immediately after their definition.

Own Id: OTP-17226 Aux Id: GH-4019, PR-4545

It is now possible to disable warnings emitted from the compiler's optimization passes with the new options nowarn_opportunistic, nowarn_nomatch, nowarn_ignored, and nowarn_failed.

Own Id: OTP-17260

Introduce new types nonempty_binary/0 and nonempty_bitstring/0.

Own Id: OTP-17301 Aux Id: GH-4636

Add compiler option {nowarn_unused_record, RecordNames}. Document compiler option nowarn_unused_type.

Own Id: OTP-17330

Compiler 7.6.9.3

Fixed Bugs and Malfunctions

It is not allowed to call functions from guards. The compiler failed to reject a call in a guard when done by constructing a record with a default initialization expression that called a function.

Own Id: OTP-18325 Aux Id: GH-6465, GH-6466

Fixed a bug that could cause legal code to fail validation.

Own Id: OTP-18365

The compiler would generate incorrect code for the following type of expression:

Pattern = BoundVar1 = . . . = BoundVarN = Expression

An exception should be raised if any of the bound variables have different values than Expression. The compiler would generate code that would cause the bound variables to be bound to the value of Expressionwhether the value matched or not.

Own Id: OTP-18470 Aux Id: GH-6873, PR-6877

Compiler 7.6.9.2

Fixed Bugs and Malfunctions

In rare circumstances, the compiler would mistakenly assume that a call to setelement/3 would always fail and remove all code following the call.

Own Id: OTP-18082

Compiler 7.6.9.1

Fixed Bugs and Malfunctions

Fixed a bug in the validation pass that could cause it to reject valid code.

Own Id: OTP-17437 Aux Id: OTP-17357, GH-4774

Compiler 7.6.9

Fixed Bugs and Malfunctions

Reverted the fix for OTP-17357 as it turned out to be incomplete and made the validator reject much more legal code than before.

It will be fixed more thoroughly in a later patch.

Own Id: OTP-17386 Aux Id: ERIERL-650, OTP-17357

Compiler 7.6.8

Fixed Bugs and Malfunctions

Fixed a bug in the validator that could cause it to reject valid code.

Own Id: OTP-17357 Aux Id: GH-4774

Compiler 7.6.7

Fixed Bugs and Malfunctions

Fixed a bug in the type optimization pass that could yield incorrect values or cause the wrong clauses to be executed.

Own Id: OTP-17073

Fixed a bug in the validator that could cause it to reject valid code.

Own Id: OTP-17126 Aux Id: ERL-1471

Compiler 7.6.6

Fixed Bugs and Malfunctions

Several minor compiler bugs have been fixed:

Constructing a binary with a list as a size of a binary segment could generate a BEAM file that could not be loaded.

When matching a binary segment of type float and ignoring the matched out value, the match would always succeed, even if the size was invalid or the value of the float was NaN or some other non-numeric float value.

Attempting to construct an invalid external fun (e.g. fun m:f:bad) is supposed to raise a 'badarg' exception, but if the value was never used, no exception would be raised.

Own Id: OTP-16932

Fixed multiple bugs in the validator that could cause it to reject valid code.

Own Id: OTP-17039 Aux Id: ERL-1426

The compiler could crash when a binary comprehension had a generator that depended on another generator.

Own Id: OTP-17045 Aux Id: ERL-1427

Fixed a bug in the type optimization pass that could yield incorrect values or cause the wrong clauses to be executed.

Own Id: OTP-17072 Aux Id: ERL-1440

Compiler 7.6.5

Fixed Bugs and Malfunctions

Fixed a bug in the boolean optimization pass that caused the compiler to confuse different clauses.

Own Id: OTP-16951 Aux Id: ERL-1384

Compiler 7.6.4

Fixed Bugs and Malfunctions

Fixed a performance bug that could be triggered by tuple matching in very large functions.

Own Id: OTP-16895 Aux Id: ERL-1359

Compiler 7.6.3

Fixed Bugs and Malfunctions

If the update of a map with the 'Map#{Key := Value}' syntax failed, the line number in the stack backtrace could be incorrect.

Own Id: OTP-16701 Aux Id: ERL-1271

Fixed a performance bug that slowed down compilation of modules with deeply nested terms.

Own Id: OTP-16755 Aux Id: ERL-1297

The compiler could in rare circumstances do an an unsafe optimization that would result in a matching of a nested map pattern would fail to match.

Own Id: OTP-16820

Fixed a bug in the validator that caused it to reject valid code.

Own Id: OTP-16838 Aux Id: ERL-1340

Compiler 7.6.2

Fixed Bugs and Malfunctions

When calls to is_map_key were repeated, the compiler could terminate with an internal consistency failure.

Own Id: OTP-16708 Aux Id: ERL-1276

Fixed a bug in the type inference pass that could cause the compiler to hang.

Own Id: OTP-16745 Aux Id: ERL-1289

Compiler 7.6.1

Fixed Bugs and Malfunctions

In rare circumstances, a guard using 'not' could evaluate to the wrong boolean value.

Own Id: OTP-16652 Aux Id: ERL-1246

A guard expression that referenced a variable bound to a boolean expression could evaluate to the wrong value.

Own Id: OTP-16657 Aux Id: ERL-1253

Compiler 7.6

Fixed Bugs and Malfunctions

erlang:fun_info(fun foo/1, name/1) used to return a function name based on the name of the function that fun foo/1 was used in. The name returned is now -fun.foo/1-.

Own Id: OTP-15837

Initialization of record fields using _ is no longer allowed if the number of affected fields is zero.

Own Id: OTP-16516

Improvements and New Features

EEP-52 has been implemented.

In binary matching, the size of the segment to be matched is now allowed to be a guard expression, and similarly in map matching the keys can now be guard expressions. See the Erlang Reference Manual and Programming Examples for more details.

Language compilers or code generators that generate Core Erlang code may need to be updated to be compatible with the compiler in OTP 23. For more details, see the section Backwards Compatibility in EEP 52.

Own Id: OTP-14708

Allow underscores in numeric literals to improve readability. Examples: 123_456_789, 16#1234_ABCD.

Own Id: OTP-16007 Aux Id: PR-2324

Improved the type optimization pass' inference of types that depend on themselves, giving us more accurate types and letting us track the content types of lists.

Own Id: OTP-16214 Aux Id: PR-2460

Support message queue optimization also for references returned from the new spawn_request() BIFs.

Own Id: OTP-16367 Aux Id: OTP-15251

The compiler will now raise a warning when inlining is used in modules that load NIFs.

Own Id: OTP-16429 Aux Id: ERL-303

Refactored the internal handling of deprecated and removed functions.

Own Id: OTP-16469

Line information was sometimes incorrect for floating-point math exceptions.

Own Id: OTP-16505 Aux Id: ERL-1178

The debug_info option can now be specified in -compile() attributes.

Own Id: OTP-16523 Aux Id: ERL-1058

Reduced the resource usage of erlc in parallel builds (e.g. make -j128).

Own Id: OTP-16543 Aux Id: ERL-1186

Compiler 7.5.4.3

Improvements and New Features

Fixed a bug in the type optimization pass that could yield incorrect values or cause the wrong clauses to be executed.

Own Id: OTP-17073

Compiler 7.5.4.2

Fixed Bugs and Malfunctions

Fixed a bug in the validator that could cause it to reject valid code

Own Id: OTP-17039 Aux Id: ERL-1426

Compiler 7.5.4.1

Fixed Bugs and Malfunctions

Fixed a bug that could cause the compiler to crash on code that constructed binaries.

Own Id: OTP-16747 Aux Id: ERL-1290

Compiler 7.5.4

Fixed Bugs and Malfunctions

Fixed a bug in the validator that could cause it to reject valid code.

Own Id: OTP-16580 Aux Id: ERL-1212

Compiler 7.5.3

Fixed Bugs and Malfunctions

A 'receive' with an 'after 0' clause would prevent the optimization that can avoid scanning the entire receive queue when matching on a newly created reference.

Own Id: OTP-16350

HiPE can again handle modules with catch and try constructs.

Own Id: OTP-16418

Fixed a bug in bit-syntax optimization that could crash the compiler.

Own Id: OTP-16515

Compiler 7.5.2

Fixed Bugs and Malfunctions

Fixed a bug that could cause the compiler to reject valid code that used the is_map_key/2 BIF.

Own Id: OTP-16452 Aux Id: ERL-1161

Fixed a bug that could cause the compiler to reject valid code that matched the same map key several times.

Own Id: OTP-16456 Aux Id: ERL-1163

The compiler could crash when compiling a convoluted receive statement.

Own Id: OTP-16466 Aux Id: ERL-1170

The compiler could crash when a fun was created but never used.

The compiler could crash when compiling the expression true = 0 / X.

Own Id: OTP-16467 Aux Id: ERL-1166, ERL-1167

Compiler 7.5.1

Fixed Bugs and Malfunctions

Fixed a bug in the compiler that could cause it to reject valid code.

Own Id: OTP-16385 Aux Id: ERL-1128

Compiler 7.5

Fixed Bugs and Malfunctions

Fixed a bug in the linter where list and binary comprehensions could suppress unsafe variable errors.

Own Id: OTP-16053 Aux Id: ERL-1039

When a compilation starts from Core Erlang code, the core_lint pass will always be run and the compilation will be aborted if any errors are found.

Own Id: OTP-16181 Aux Id: ERL-1065

Improvements and New Features

The warning message that appears when the compiler detects a non-utf-8 encoded source file without an encoding string in the beginning of the file has been changed to contain information about that support for latin1 encoded source files without an encoding string will be removed in Erlang/OTP 24.

Own Id: OTP-16054 Aux Id: OTP-11791

Compiler 7.4.9

Fixed Bugs and Malfunctions

Fixed a performance bug that caused repeated matches of large records to take a very long time to compile.

Own Id: OTP-16259 Aux Id: ERIERL-436

Compiler 7.4.8

Fixed Bugs and Malfunctions

The compiler could do an unsafe optimization of receives, which would cause a receive to only scan part of the message queue.

This bug fix in the compiler fixes a bug in the socket module.

Own Id: OTP-16219 Aux Id: ERL-1076

Compiler 7.4.7

Fixed Bugs and Malfunctions

Fixed a bug where the compiler could generate incorrect code for a 'receive' statement inside a 'try'.

Own Id: OTP-16199

Compiler 7.4.6

Fixed Bugs and Malfunctions

Fixed a bug in the bit-syntax optimization pass that could crash the compiler.

Own Id: OTP-16103 Aux Id: ERL-1050

Compiler 7.4.5

Fixed Bugs and Malfunctions

Code such as the following would crash the compiler in OTP 22: [some_atom = fun some_function/1]

Own Id: OTP-15833

Compilation could get really slow (in the order of minutes instead of seconds) when compiling huge functions. (Thanks to Kostis Sagonas for reporting this bug.)

Own Id: OTP-15923

Fixed a bug in the validator that could reject valid code.

Own Id: OTP-15954 Aux Id: ERL-995

In rare circumstances, when two clauses had identical bodies and guard tests that tested a single boolean variable, the guard test for the second clause could be discarded, executing the second clause unconditionally if the first clause was not executed.

Own Id: OTP-15963

Fixed extremely slow compilation for huge functions doing predominantly pattern matching.

Own Id: OTP-15966 Aux Id: ERL-1014

The compiler could generate unsafe code (that would crash the runtime system) for map pattern matching. The code could be unsafe if the matched key was not present in the map at runtime.

Own Id: OTP-15968 Aux Id: ERL-1017

Correct code using try/after could fail to compile when using the option 'no_type_opt'.

Own Id: OTP-15969 Aux Id: ERL-997

The compiler could crash when compiling code that called 'length/1' on a binary extracted using the binary syntax.

Own Id: OTP-15970 Aux Id: ERL-1013

Fixed a bug where the compiler could fail with an internal consistency failure error when compiling receive statements.

Own Id: OTP-15982 Aux Id: ERL-1022

Fixed a problem where the compiler would crash when compiling binary matching in a function head.

Own Id: OTP-15985 Aux Id: ERL-1026

Compiler 7.4.4

Fixed Bugs and Malfunctions

Fixed a compiler crash introduced in 22.0.6 (OTP-15952).

Own Id: OTP-15953 Aux Id: ERL-999

Compiler 7.4.3

Fixed Bugs and Malfunctions

Fixed an unsafe optimization when matching tuple_size/1 outside of guards, which could crash the emulator if the argument was not a tuple.

Own Id: OTP-15945

Fixed a rare bug that could cause the wrong kind of exception to be thrown when a BIF failed in a function that matched bitstrings.

Own Id: OTP-15946

Fixed a bug where receive statements inside try/catch blocks could return incorrect results.

Own Id: OTP-15952

Compiler 7.4.2

Fixed Bugs and Malfunctions

Fixed an incorrect type determination for constructed binaries, which could cause is_binary checks to succeed when they shouldn't have.

Own Id: OTP-15872

Compiler 7.4.1

Fixed Bugs and Malfunctions

The type optimization pass of the compiler could hang or loop for a long time when analyzing a setelement/3 call with a variable position.

Own Id: OTP-15828 Aux Id: ERL-948

Certain complex receive statements would result in an internal compiler failure.

Own Id: OTP-15832 Aux Id: ERL-950

Fixed an unsafe type optimization.

Own Id: OTP-15838

Fixed a crash when optimizing compiler-generated exceptions (like badmatch) whose offending term was a constructed binary.

Own Id: OTP-15839 Aux Id: ERL-954

Fixed a bad optimization related to the ++/2 operator, where the compiler assumed that it always produced a list ([] ++ RHS returns RHS verbatim, even if it's not a list).

Own Id: OTP-15841

An is_binary/1 test followed by is_bitstring/1 (or vice versa) could fail because of an usafe optimization.

Own Id: OTP-15845

A Core Erlang module where the last clause in a case matched a map would fail to load.

Own Id: OTP-15846 Aux Id: ERL-955

Fixed a bug that could cause the compiler to crash when compiling complex nested case expressions.

Own Id: OTP-15848 Aux Id: ERL-956

Compiler 7.4

Fixed Bugs and Malfunctions

record_info/2 is a pseudo-function that requires literal arguments known at compile time. Therefore, the following usage is illegal: fun record/info/2. The compiler would crash when during compilation of that kind of code. Corrected to issue a compilation error.

Own Id: OTP-15760 Aux Id: ERL-907

Improvements and New Features

The compiler has been rewritten to internally use an intermediate representation based on Static Single Assignment (SSA). The new intermediate representation makes more optimizations possible.

Most noticeable is that the binary matching optimizations are now applicable in many more circumstances than before.

Another noticeable change is that type optimizations are now applied across local function calls, and will remove a lot more redundant type tests than before.

Own Id: OTP-14894 Aux Id: ERL-714

Funs are no longer created when they are only used locally, greatly improving the performance of named funs and "fun-wrapped" macros.

Own Id: OTP-15273 Aux Id: ERL-639

All compiler options that can be given in the source file can now also be given in the option list or from the command line for erlc.

Specifically, the option {nowarn_deprecated_function,MFAs} was only recognized when given in the file with the attribute -compile(). The option {nowarn_unused_function,FAs} was incorrectly documented to only work in a file, but it also worked when given in the option list.

Own Id: OTP-15456

Do not allow function specifications for functions residing in other modules.

* POTENTIAL INCOMPATIBILITY *

Own Id: OTP-15563 Aux Id: ERL-845, OTP-15562

Internal documentation has now been added to the Erts and Compiler applications.

The internal documents for Erts describe miscellaneous interesting implementation details. Those details can change at any time.

The internal documentation for Compiler documents the API for the Core Erlang modules. While we will not change those APIs without good reason, we don't give the same guarantees about backward compatibility as for the rest of the APIs in OTP.

Own Id: OTP-15715

There are new compiler options nowarn_removed and {nowarn_removed,Items} to suppress warnings for functions and modules that have been removed from OTP.

Own Id: OTP-15749 Aux Id: ERL-904

Compiler 7.3.2

Fixed Bugs and Malfunctions

An expression such as (A / B) band 16#ff would crash the compiler.

Own Id: OTP-15518 Aux Id: ERL-829

There could be an incorrect warning when the tuple_calls option was given. The generated code would be correct. Here is an example of code that would trigger the warning:

(list_to_atom("prefix_" ++ atom_to_list(suffix))):doit(X).

Own Id: OTP-15552 Aux Id: ERL-838

Optimize (again) Dialyzer's handling of left-associative use of andalso and orelse in guards.

Own Id: OTP-15577 Aux Id: ERL-851, PR-2141, PR-1944

Compiler 7.3.1

Fixed Bugs and Malfunctions

An optimization that avoided allocation of a stack frame for some case expressions was introduced in OTP 21. (ERL-504/OTP-14808) It turns out that in rare circumstances, this optimization is not safe. Therefore, this optimization has been disabled.

A similar optimization will be included in OTP 22 in a safe way.

Own Id: OTP-15501 Aux Id: ERL-807, ERL-514, OTP-14808

Compiler 7.3

Fixed Bugs and Malfunctions

Fixed a rare internal consistency failure caused by a bug in the beam_jump pass. (Thanks to Simon Cornish for reporting this bug.)

Own Id: OTP-15400 Aux Id: ERL-759

The compiler could fail with an internal consistency check failure when compiling code that used the is_function/2 BIF.

Own Id: OTP-15435 Aux Id: ERL-778

When an external fun was used, warnings for unused variables could be suppressed.

Own Id: OTP-15437 Aux Id: ERL-762

The compiler would crash when compiling an after block that called erlang:raise/3 like this: erlang:raise(Class, Stacktrace, Stacktrace)

Own Id: OTP-15481

Improvements and New Features

When specified, the +{source,Name} option will now override the actual file name in stack traces, instead of only affecting the return value of Mod:module_info().

The +deterministic flag will also affect stack traces now, omitting all path information except the file name, fixing a long-standing issue where deterministic builds required deterministic paths.

Own Id: OTP-15245 Aux Id: ERL-706

Compiler 7.2.7

Fixed Bugs and Malfunctions

Fixed a bug where incorrect code was generated following a binary match guard.

Own Id: OTP-15353 Aux Id: ERL-753

Compiler 7.2.6

Fixed Bugs and Malfunctions

In rare circumstances, the matched out tail of a binary could be the entire original binary. (There was partial correction to this problem in version 7.2.5 of the compiler application.)

Own Id: OTP-15335 Aux Id: ERL-689, OTP-15219

Compiler 7.2.5

Fixed Bugs and Malfunctions

Fixed a bug that prevented certain variable-sized binary comprehensions from compiling.

Own Id: OTP-15186 Aux Id: ERL-665

When compiling from Core Erlang, funs created in certain expressions that were only used for their side-effects were subtly broken.

Own Id: OTP-15188 Aux Id: ERL-658

There could be an internal consistency failure when a receive was nested in a try/catch.

Own Id: OTP-15218 Aux Id: ERL-684

In rare circumstances, the matched out tail of a binary could be the entire original binary.

Own Id: OTP-15219 Aux Id: ERL-689

When is_map_key/2 was used in a guard together with the not/1 or or/2 operators, the error behavior could be wrong when is_map_key/2 was passed a non-map as the second argument.

In rare circumstances, compiling code that uses is_map_key/2 could cause an internal consistency check failure.

Own Id: OTP-15227 Aux Id: ERL-699

The compiler could crash when compiling a function with multiple receives in multiple clauses.

Own Id: OTP-15235 Aux Id: ERL-703

Compiler 7.2.4

Fixed Bugs and Malfunctions

Fix a regression in OTP-15204 that removed .beam file metadata that some external build tools relied on.

Own Id: OTP-15292

Compiler 7.2.3

Fixed Bugs and Malfunctions

Fixed an issue where files compiled with the +deterministic option differed if they were compiled in a different directory but were otherwise identical.

Own Id: OTP-15204 Aux Id: ERL-679

Compiler 7.2.2

Fixed Bugs and Malfunctions

In rare cases involving matching of binary literal strings, the compiler could optimize away code that should be executed.

Own Id: OTP-15156 Aux Id: ERL-655

There could be an internal consistency check failure when compiling code that called map_get(Key, Map) and then updated the same map.

Own Id: OTP-15157

In rare circumstances, the compiler could crash in beam_jump when compiling a floating point operation.

Own Id: OTP-15166 Aux Id: ERL-660

Compiler 7.2.1

Fixed Bugs and Malfunctions

The could could crash when compiling a complicated function that used the binary syntax.

Own Id: OTP-15150 Aux Id: ERL-650

Compiler 7.2

Fixed Bugs and Malfunctions

Fixed an error in an optimization pass that caused impossible tuple matching.

Own Id: OTP-14855 Aux Id: ERL-549

The exception thrown when a list comprehension was given a non-list term was not always correct.

Own Id: OTP-14992 Aux Id: ERL-572

The compiler could produce incorrect code in rare circumstances when the [{inline,F/A}] option was used.

Own Id: OTP-15115 Aux Id: PR-1831

Improvements and New Features

Changed the default behaviour of .erlang loading: .erlang is no longer loaded from the current directory. c:erlangrc(PathList) can be used to search and load an .erlang file from user specified directories.

escript, erlc, dialyzer and typer no longer load an .erlang at all.

* POTENTIAL INCOMPATIBILITY *

Own Id: OTP-14439

Support for "tuple calls" have been removed from the run-time system. Tuple calls was an undocumented and unsupported feature which allowed the module argument for an apply operation to be a tuple: Var = dict:new(), Var:size(). This "feature" frequently caused confusion, especially when such call failed. The stacktrace would point out functions that don't exist in the source code.

For legacy code that need to use parameterized modules or tuple calls for some other reason, there is a new compiler option called tuple_calls. When this option is given, the compiler will generate extra code that emulates the old behavior for calls where the module is a variable.

* POTENTIAL INCOMPATIBILITY *

Own Id: OTP-14497

In code such as example({ok, Val}) -> {ok, Val}. a tuple would be built. The compiler will now automatically rewrite the code to example({ok,Val}=Tuple) -> Tuple. which will reduce code size, execution time, and remove GC pressure.

Own Id: OTP-14505

The optimization of case expression where only one of the case arms can execute successfully has been improved.

Own Id: OTP-14525

Some uses of binary matching has been slightly improved, eliminating unnecessary register shuffling.

Own Id: OTP-14594 Aux Id: ERL-444

There is a new {compile_info,Info} option for the compiler that allows BEAM-based languages such as Elixir and LFE to add their own compiler versions.

Own Id: OTP-14615 Aux Id: PR-1558

Loaded BEAM code in a 64-bit system requires less memory because of better packing of operands for instructions.

These memory savings were achieved by major improvements to the beam_makeops scripts used when building the run time system and BEAM compiler. There is also new for documentation for beam_makeops that describes how new BEAM instructions and loader transformations can be implemented. The documentation is found in here in a source directory or git repository: erts/emulator/internal_doc/beam_makeops.md. An online version can be found here: https://github.com/erlang/otp/blob/master/erts/emulator/internal_doc/beam_makeops.md

Own Id: OTP-14626

Size calculations for binary constructions has been somewhat optimized, producing smaller code.

Own Id: OTP-14654

When the value returned from a 'catch' expression is ignored, no stacktrace will be built if an exception is caught. That will save time and produce less garbage. There are also some minor optimizations of 'try/catch' both in the compiler and run-time system.

Own Id: OTP-14683

There is a new syntax in 'try/catch' for retrieving the stacktrace without calling 'erlang:get_stacktrace/0'. See the reference manual for a description of the new syntax. The 'erlang:get_stacktrace/0' BIF is now deprecated.

Own Id: OTP-14692

The following is an internal change in the compiler, that is not noticeable for normal use of the compiler: The module v3_life has been removed. Its functionality has been simplified and integrated into v3_codegen.

Own Id: OTP-14712

The optimization of binary matching that delays creation of sub binaries (see the Efficiency Guide) could be thwarted by the argument order and could be necessary to change the argument order. The compiler has now become smarter and can handle any argument order.

Own Id: OTP-14774

When the compiler was faced with complex case expressions it would unnecessarily allocate stack elements and shuffle data between x and y registers. Improved code generation to only allocate a stack frame when strictly necessary.

Own Id: OTP-14808 Aux Id: ERL-514

There is a new option 'makedep_side_effect' for the compiler and -MMD for 'erlc' that generates dependencies and continues to compile as normal.

Own Id: OTP-14830

When compiling modules with huge functions, the compiler would generate a lot of atoms for its internal, sometimes so many that the atom table would overflow. The compiler has been rewritten to generate far less internal atoms to avoid filling the atom table.

Own Id: OTP-14968 Aux Id: ERL-563

External funs with literal values for module, name, and arity (e.g. erlang:abs/1) are now treated as literals. That means more efficient code that produces less garbage on the heap.

Own Id: OTP-15003

Two new guards BIFs operating on maps have been added: map_get/2 and is_map_key/2. They do the same as maps:get/2 and maps:is_key/2, respectively, except that they are allowed to be used in guards.

Own Id: OTP-15037 Aux Id: PR-1784, PR-1802

A call or apply of a literal external fun will be replaced with a direct call.

Own Id: OTP-15044 Aux Id: ERL-614

Part of EEP-44 has been implemented.

There is a new predefined macro called OTP_RELEASE which is an integer indicating the OTP release number (its value is 21 in this release).

There are new preprocessor directives -if(Condition). and -elif(Condition).. The if/elif supports the builtin function defined(Symbol).

Own Id: OTP-15087 Aux Id: PR-1810

Compiler 7.1.5.2

Fixed Bugs and Malfunctions

Fix a regression in OTP-15204 that removed .beam file metadata that some external build tools relied on.

Own Id: OTP-15292

Compiler 7.1.5.1

Fixed Bugs and Malfunctions

Fixed an issue where files compiled with the +deterministic option differed if they were compiled in a different directory but were otherwise identical.

Own Id: OTP-15204 Aux Id: ERL-679

Compiler 7.1.5

Fixed Bugs and Malfunctions

The internal compiler pass (beam_validator) that validates the generated code has been strengthened.

When compiling from BEAM assembly code, the beam_type optimizer pass could make the code unsafe. Corrected.

Own Id: OTP-14863

Corrected optimizations of integers matched out from binaries and used in bit operations.

Own Id: OTP-14898

Compiler 7.1.4

Fixed Bugs and Malfunctions

The 'deterministic' option was not recognized when given in a -compile() attribute in the source code.

Own Id: OTP-14773 Aux Id: ERL-498

Compiler 7.1.3

Fixed Bugs and Malfunctions

The compiler could issue an incorrect internal consistency failure diagnostic for some complicated bit syntax matches.

Own Id: OTP-14640 Aux Id: ERL-490

Compiler 7.1.2

Fixed Bugs and Malfunctions

Fail labels on guard BIFs weren't taken into account during an optimization pass, and a bug in the validation pass sometimes prevented this from being noticed when a fault occurred.

Own Id: OTP-14522 Aux Id: ERIERL-48

When compiling from Core Erlang, an 'apply' with a nested apply in the function position would be treated as an invalid call. Corrected. (Thanks to Mikael Pettersson for reporting this bug.)

Own Id: OTP-14526

Fixed checking of binary matching in the beam_validator module to ensure that potential compiler bugs are found at compile-time instead as emulator crash at run-time.

Own Id: OTP-14591

There could be false warnings for erlang:get_stacktrace/0 being used outside of a try block when using multiple catch clauses.

Own Id: OTP-14600 Aux Id: ERL-478

Improvements and New Features

The Erlang code linter no longer checks that the functions mentioned in nowarn_deprecated_function options are declared in the module.

Own Id: OTP-14378

Compiler 7.1.1

Fixed Bugs and Malfunctions

Fail labels on guard BIFs weren't taken into account during an optimization pass, and a bug in the validation pass sometimes prevented this from being noticed when a fault occurred.

Own Id: OTP-14522 Aux Id: ERIERL-48

Compiler 7.1

Fixed Bugs and Malfunctions

For many releases, it has been legal to override a BIF with a local function having the same name. However, calling a local function with the same name as guard BIF as filter in a list comprehension was not allowed.

Own Id: OTP-13690

compile:forms/2 would not return the module name as documented when one of the options 'from_core', 'from_asm', or 'from_beam' was given. Also, the compiler would crash if one of those options was combined with 'native'.

Own Id: OTP-14408 Aux Id: ERL-417

Improvements and New Features

Optimized test for tuples with an atom as first element.

Own Id: OTP-12148

Compilation of modules with huge literal binary strings is now much faster.

Own Id: OTP-13794

Replaced usage of deprecated symbolic time unit representations.

Own Id: OTP-13831 Aux Id: OTP-13735

The undocumented and unsupported module sys_pre_expand has been removed. As a partial replacement for the functionality, there is a new function erl_internal:add_predefined_functions/1 and erl_expand_records will now add a module prefix to calls to BIFs and imported functions.

Own Id: OTP-13856

The internal compiler passes now start all generated variables with "@" to avoid any conflicts with variables in languages such as Elixir or LFE.

Own Id: OTP-13924

The function fmod/2 has been added to the math module.

Own Id: OTP-14000

Code generation for complicated guards have been improved.

Own Id: OTP-14042

The compiler has new warnings for repeated identical map keys.

A map expression such as,

#{'a' => 1, 'b' => 2, 'a' => 3}.

will produce a warning for the repeated key 'a'.

Own Id: OTP-14058

By default, there will now be a warning when export_all is used. The warning can be disabled using nowarn_export_all.

Own Id: OTP-14071

Optimize maps pattern matching by only examining the common keys in each clause first instead of all keys. This will reduce the number of lookups of each key in maps pattern matching.

Own Id: OTP-14072

There is a new 'deterministic' option to omit 'source' and 'options' tuples in the BEAM file.

Own Id: OTP-14087

Analyzing modules with binary construction with huge strings is now much faster. The compiler also compiles such modules slightly faster.

Own Id: OTP-14125 Aux Id: ERL-308

Atoms may now contain arbitrary Unicode characters.

Own Id: OTP-14178

compile:file/2 now accepts the option extra_chunks to include extra chunks in the BEAM file.

Own Id: OTP-14221

The format of debug information that is stored in BEAM files (when debug_info is used) has been changed. The purpose of the change is to better support other BEAM-based languages such as Elixir or LFE.

All tools included in OTP (dialyzer, debugger, cover, and so on) will handle both the new format and the previous format. Tools that retrieve the debug information using beam_lib:chunk(Beam, [abstract_code]) will continue to work with both the new and old format. Tools that call beam_lib:chunk(Beam, ["Abst"]) will not work with the new format.

For more information, see the description of debug_info in the documentation for beam_lib and the description of the {debug_info,{Backend,Data}} option in the documentation for compile.

Own Id: OTP-14369 Aux Id: PR-1367

In a future release, erlang:get_stacktrace/0 will probably only work when called from within a 'try' expression (otherwise it will return [].

To help prepare for that change, the compiler will now by default warn if 'get_stacktrace/0' is used in a way that will not work in the future. Note that the warning will not be issued if 'get_stacktrace/0' is used in a function that uses neither 'catch' nor 'try' (because that could be a legal use if the function is called from within a 'try'.

Own Id: OTP-14401

Compiler 7.0.4.1

Fixed Bugs and Malfunctions

Fail labels on guard BIFs weren't taken into account during an optimization pass, and a bug in the validation pass sometimes prevented this from being noticed when a fault occurred.

Own Id: OTP-14522 Aux Id: ERIERL-48

Compiler 7.0.4

Fixed Bugs and Malfunctions

Minor internal changes. A typo in the documentation was also fixed.

Own Id: OTP-14240

Compiler 7.0.3

Fixed Bugs and Malfunctions

Fixed a compiler crash when maps were matched.

Own Id: OTP-13931 Aux Id: ERL-266

Fixed a compiler crash having to with the delayed sub-creation optimization. (Thanks to Jose Valim for reporting this bug.)

Own Id: OTP-13947 Aux Id: ERL-268

The compiler option inline_list_funcs accidentally turned off some other optimizations.

Own Id: OTP-13985

The compiler could sometimes generate spurious warnings when inlining was enabled.

Own Id: OTP-14040 Aux Id: ERL-301

Compiler 7.0.2

Fixed Bugs and Malfunctions

If the compiler fails to write the BEAM file, it will now report the reason of the error for the write operation.

Own Id: OTP-13701

Fixed an internal compiler error. (Thanks to Svilen Ivanov for reporting this bug.)

Own Id: OTP-13780 Aux Id: ERL-202

The compiler could crash when trying to compile a complicated expression with multiple catches all on one line . (Thanks to Thomas Arts for reporting this bug.)

Own Id: OTP-13804 Aux Id: ERL-209

Eliminated a few internal compiler failures.

Own Id: OTP-13863

Compiler 7.0.1

Fixed Bugs and Malfunctions

A literal binary matching regression was introduced in 19.0 where a match could fail to resolve to the right clause. This has now been fixed.

Own Id: OTP-13738

Compiler 7.0

Fixed Bugs and Malfunctions

compile:forms/1,2 would crash when used in a working directory that had been deleted by another process.

Own Id: OTP-13430 Aux Id: ERL-113

Dialyzer no longer crashes when there is an invalid function call such as 42(7) in a module being analyzed. The compiler will now warn for invalid function calls such as X = 42, x(7).

Own Id: OTP-13552 Aux Id: ERL-138

Improvements and New Features

Optimization of tuple matching has been slightly improved.

Own Id: OTP-12951

Five deprecated and undocumented functions in the module core_lib have been removed. The functions are: get_anno/{1,2}, is_literal/1, is_literal_list/1, and literal_value. Use the appropriate functions in the cerl module instead.

Own Id: OTP-12979

The pre-processor can now expand the ?FUNCTION_NAME and ?FUNCTION_ARITY macros.

Own Id: OTP-13059

The function mapfold/4 has been added to the cerl_trees module.

Own Id: OTP-13280

Bitstring comprehensions have been generalized to allow arbitrary expressions in the construction part.

Own Id: OTP-13289

The compiler will now produce warnings for binary patterns that will never match (example: <<-1/unsigned>> = Bin).

Own Id: OTP-13374 Aux Id: ERL-44

The compiler will no longer put the compilation date and time into BEAM files. That means that two BEAM files compiled on the same computer from the same source code and compilation options will be identical.

Note: If you want to find out whether a BEAM file on disk is different from the loaded code, compared the MD5 value obtained from Mod:module_info(md5) with the MD5 value obtained from beam_lib:md5(BeamFileForMod)

.

* POTENTIAL INCOMPATIBILITY *

Own Id: OTP-13504

The function compile:env_compiler_options/0 has been added to allow tools to pick up the same default compiler options as the compiler itself.

Own Id: OTP-13654

Compiler 6.0.3.1

Fixed Bugs and Malfunctions

Fail labels on guard BIFs weren't taken into account during an optimization pass, and a bug in the validation pass sometimes prevented this from being noticed when a fault occurred.

Own Id: OTP-14522 Aux Id: ERIERL-48

Compiler 6.0.3

Fixed Bugs and Malfunctions

An complicated guard expression in a function call could crash the compiler. (Thanks to Thomas Arts for reporting this bug.)

Own Id: OTP-13208

Constructing a map in a guard in a catch could crash the compiler. (Thanks to Thomas Arts for reporting this bug.)

Own Id: OTP-13223

Updating a fun as if it were a map would cause the compiler to crash. (Thanks to Thomas Arts for reporting this bug.)

Own Id: OTP-13231

Fix pretty printing of Core Maps

Literal maps could cause Dialyzer to crash when pretty printing the results.

Own Id: OTP-13238

A complex combination of bit syntax matching operations would cause an internal consistency check failure during compilation. (Thanks to Jose Valim for reporting this bug.)

Own Id: OTP-13309

Compiler 6.0.2

Fixed Bugs and Malfunctions

Fix cerl_trees:label/2 bug with map K/V swap

Own Id: OTP-13091

Warnings produced when the 'bin_opt_info' option was given could sometimes lack filenames and line numbers. (Thanks to José Valim for reporting this bug.)

Own Id: OTP-13113

Compiler 6.0.1

Fixed Bugs and Malfunctions

Fix get_map_elements register corruption

Instruction get_map_elements might destroy target registers when the fail-label is taken. Only seen for patterns with two, and only two, target registers. Specifically if we copy one register and then jump.

Own Id: OTP-12967

Compiler 6.0

Fixed Bugs and Malfunctions

The compiler optimizes away building of terms that are never actually used. As a result, the compiler in OTP 18 may produce more warnings for terms that are built but not used than the compiler in OTP 17.

Own Id: OTP-12453

Using a map could incorrectly suppress warnings for unused variables.

Own Id: OTP-12515

The compiler now properly reports unknown parse transforms. That is, undef exceptions coming from the parse transform itself is reported differently from the absence of the parse transform.

Own Id: OTP-12723

Allow for 'creation of sub binary delayed' optimization if maps instructions are in a clause.

Own Id: OTP-12758

Improvements and New Features

The cerl and cerl_trees modules in the Compiler application are now documented.

Own Id: OTP-11978

The deprecated 'asm' option has been removed.

* POTENTIAL INCOMPATIBILITY *

Own Id: OTP-12100

Support variables as Map keys in expressions and patterns

Erlang will accept any expression as keys in Map expressions and it will accept literals or bound variables as keys in Map patterns.

Own Id: OTP-12218

Infer Map type information in beam_type compiler optimization pass.

Own Id: OTP-12253

Compiler optimizations have been improved.

Own Id: OTP-12393

Five undocumented functions in the module core_lib have been deprecated and will be removed in the next major release. The functions are: get_anno/{1,2}, is_literal/1, is_literal_list/1, and literal_value. Use the appropriate functions in the cerl module instead.

Own Id: OTP-12497

Change some internal data structures to Maps in order to speed up compilation time. Measured speed up is around 10%-15%.

Own Id: OTP-12774

Fix beam_bool pass for Maps instruction get_map_elements

Before beam_split the get_map_elements instruction is still in blocks and the helper function in beam_jump did not reflect this.

Own Id: OTP-12844 Aux Id: 17

Compiler 5.0.4

Fixed Bugs and Malfunctions

Matching out a map from a record and then updating the record could cause a 'badarg' exception at run-time. (Thanks to Dmitry Aleksandrov for reporting this bug.)

Own Id: OTP-12402

The compiler would crash when compiling some complex, nonsensical guards such as:

... when {{X}}, -X...

Own Id: OTP-12410

In rare circumstances, using binary pattern in the value part of a map pattern would cause the compiler to crash.

Own Id: OTP-12414

Case expressions where a map was wrapped in a tuple or list such as:

case {a,Map} of
{a,#{k:=_}}=Tuple -> Tuple
end.

would be unsafely "optimized" to either cause an exception at run-time or would return an empty map.

Own Id: OTP-12451

When a variable was compared to a literal map using the '==' operator, the compiler would change the operator to '=:=' since it is more efficient. However, this optimization is not safe if the map literal has numeric keys or values. The compiler will now only do the optimization if all keys and values are non-numeric.

Own Id: OTP-12456

Compiler 5.0.3

Fixed Bugs and Malfunctions

Named funs with the same name and arity could get mixed up with each other.

Own Id: OTP-12262

Coalesce map keys in dialyzer mode

This fixes a regression introduced in commit 805f9c89fc01220bc1bb0f27e1b68fd4eca688ba The problem occurred with compounded map keys compiled with dialyzer option turned on, '+dialyzer'.

Reported by: Ivan Uemlianin

Own Id: OTP-12347

Compiler 5.0.2

Fixed Bugs and Malfunctions

Corrected a bug with incorrect code generation when inlining was turned on.

Own Id: OTP-12132

Compiler 5.0.1

Fixed Bugs and Malfunctions

A Dialyzer crash involving analysis of Map types has now been fixed.

Own Id: OTP-11947

The compiler would fail to compile a file with a latin-1 character in the false branch of an -ifdef or -indef.

Own Id: OTP-11987

Compiler 5.0

Fixed Bugs and Malfunctions

Line numbers would not be correct when a binary construction such as '<<Bin/binary,...>>' fails. (Thanks to Stanislav Seletskiy for reporting this bug.)

Own Id: OTP-11572

The compiler now properly annotates the code in value in the 'after' clause for a 'try' so that Dialyzer no longer generates a false warning for an unmatched return.

Own Id: OTP-11580

Some case statements where no clause would match could cause an internal error in the compiler. (Thanks to Erik Soe Sorensen for reporting this bug.)

Own Id: OTP-11610

With --Wunmatched_returns, dialyzer will no longer warn when the value of a list comprehension is ignored, provided that the each value in the list would be an atomic value (such as integer or atoms, as opposed to tuples and lists). Example: ignoring '[io:format(...) || ...]' will not cause a warning, while ignoring '[file:close(Fd) || ...]' will.

Own Id: OTP-11626

Matching out a binary and applying the binary as if it were a fun would crash the run-time system. (Thanks to Loïc Hoguin.)

Own Id: OTP-11672

Some local implementations of removing the last element from a list are replaced by lists:droplast/1. Note that this requires at least stdlib-2.0, which is the stdlib version delivered in OTP 17.0. (Thanks to Hans Svensson)

Own Id: OTP-11678

Allow all auto imports to be suppressed at once. Introducing the no_auto_import attribute: -compile(no_auto_import). Useful for code generation tools that always use the qualified function names and want to avoid the auto imported functions clashing with local ones. (Thanks to José Valim.)

Own Id: OTP-11682

Application upgrade (appup) files are corrected for the following applications:

asn1, common_test, compiler, crypto, debugger, dialyzer, edoc, eldap, erl_docgen, et, eunit, gs, hipe, inets, observer, odbc, os_mon, otp_mibs, parsetools, percept, public_key, reltool, runtime_tools, ssh, syntax_tools, test_server, tools, typer, webtool, wx, xmerl

A new test utility for testing appup files is added to test_server. This is now used by most applications in OTP.

(Thanks to Tobias Schlager)

Own Id: OTP-11744

Adapt 'asm' deprecation message to new version scheme. (Thanks to Tuncer Ayaz)

Own Id: OTP-11751

A number of compiler errors where unusual or nonsensical code would crash the compiler have been reported by Ulf Norell and corrected by Anthony Ramine.

Own Id: OTP-11770

Improvements and New Features

Compilation times for modules with a huge number for record accesses using the dot operator has been improved.

Own Id: OTP-10652

The compiler can generate somewhat better code by moving let expressions into sequences. (Thanks to Anthony Ramine.)

Own Id: OTP-11056

Forbid unsized fields in patterns of binary generators and simplified v3_core's translation of bit string generators. (Thanks to Anthony Ramine.)

Own Id: OTP-11186

Funs can now be a given a name. Thanks to to Richard O'Keefe for the idea (EEP37) and to Anthony Ramine for the implementation.

Own Id: OTP-11537

Using the from_asm option to produce a BEAM file starting from BEAM assembly code would often fail because early optimization passes would not understand instructions that later optimization passes would introduce. (Thanks to Anthony Ramine.)

Own Id: OTP-11544

The .core and .S extensions are now documented in the erlc documentation, and the 'from_core' and 'from_asm' options are now documented in the compiler documentation. (Thanks to Tuncer Ayaz.)

Own Id: OTP-11547

Optimization of case expressions that build tuples or lists have been improved.

Own Id: OTP-11584

EEP43: New data type - Maps

With Maps you may for instance:

____ - M0 = #{ a => 1, b => 2}, % create associations

____ - M1 = M0#{ a := 10 }, % update values

____ - M2 = M1#{ "hi" => "hello"}, % add new associations

____ - #{ "hi" := V1, a := V2, b := V3} = M2. % match keys with values

For information on how to use Maps please see Map Expressions in the Reference Manual.

The current implementation is without the following features:

____ - No variable keys

____ - No single value access

____ - No map comprehensions

Note that Maps is experimental during OTP 17.0.

Own Id: OTP-11616

Some function specs are corrected or moved and some edoc comments are corrected in order to allow use of edoc. (Thanks to Pierre Fenoll)

Own Id: OTP-11702

Thanks to Anthony Ramine for several improvements to the optimizations in the BEAM compiler and for cleaning up the code the code that transforms list and binary comprehensions to Core Erlang.

Own Id: OTP-11720

The default encoding for Erlang source files is now UTF-8. As a temporary measure to ease the transition from the old default of latin-1, if the compiler encounters byte sequences that are not valid UTF-8 sequences, the compiler will re-try the compilation in latin-1 mode. This workaround will be removed in a future release.

Own Id: OTP-11791

Compiler 4.9.4

Fixed Bugs and Malfunctions

Typo fix ambigous -> ambiguous. Thanks to Leo Correa.

Own Id: OTP-11455

Improvements and New Features

Lift 'after' blocks to zeroary functions. Thanks to Anthony Ramine.

Own Id: OTP-11267

Compiler 4.9.3

Fixed Bugs and Malfunctions

Expressions such as 'B = is_integer(V), if B and B -> ok end' would crash the compiler.

Own Id: OTP-11240

compile:file2/2 with the option report_errors could return ErrorInfo tuples with only two elements, while the documentation says that the ErrorInfo tuple always has three elements. Also updated the documentation to add that the first element may be 'none' if no line number is applicable.

Own Id: OTP-11304 Aux Id: seq12412

Improvements and New Features

Fix matching of floating point middle-endian machines. Thanks to Johannes Weissl.

Own Id: OTP-11201

Restrict inlining of local fun references. Thanks to Anthony Ramine.

Own Id: OTP-11211

Silence a misleading warning with some comprehensions. Thanks to Anthony Ramine.

Own Id: OTP-11212

Forbid returning a match context in beam_validator. Thanks to Anthony Ramine.

Own Id: OTP-11247

Compiler 4.9.2

Fixed Bugs and Malfunctions

Compiling functions with complex boolean operations in guards could be very slow. (Thanks to Magnus Muller for reporting this issue.)

Own Id: OTP-10939

Certain guard expressions used in a receive statement could cause the compiler to crash.

Own Id: OTP-11119 Aux Id: seq12342

Improvements and New Features

Fix optimization of some binary comprehensions. Thanks to Anthony Ramine.

Own Id: OTP-11005

Use a set to store ref registers in beam_receive. Thanks to Anthony Ramine.

Own Id: OTP-11069

Fix renaming of bs_put_string instructions. Thanks to Anthony Ramine.

Own Id: OTP-11129

Compiler 4.9.1

Fixed Bugs and Malfunctions

The compiler would crash attempting to compile expressions such as "element(2, not_tuple)".

Own Id: OTP-10794

Forbid multiple values in Core Erlang sequence arguments. Thanks to José Valim and Anthony Ramine.

Own Id: OTP-10818

An unsafe optimization would cause the compiler to crash with an internal error for certain complex code sequences.

Own Id: OTP-10825 Aux Id: seq12247

Improvements and New Features

Integers in expression that will give a floating point result (such as "X / 2" will now be converted to floating point at compile-time. (Suggested by Richard O'Keefe.)

Identical floating points constans in a module will now be coalesced to one entry in the constant pool.

Own Id: OTP-10788

Compiler 4.9

Improvements and New Features

The compiler optimizations have been polished, so that the code quality will be slightly better in some cases.

Own Id: OTP-10193

Support for Unicode has been implemented.

Own Id: OTP-10302

Where necessary a comment stating encoding has been added to Erlang files. The comment is meant to be removed in Erlang/OTP R17B when UTF-8 becomes the default encoding.

Own Id: OTP-10630

Fix some wrong warnings triggered by the option inline_list_funcs. Thanks to Anthony Ramine.

Own Id: OTP-10690

Forbid local fun variables in Core Erlang guards. Thanks to Anthony Ramine.

Own Id: OTP-10706

Binary syntax matches could cause an internal consistency error in in the compiler. (Thanks to Viktor Sovietov for reporting this bug.)

Own Id: OTP-10724

Compiler 4.8.2

Fixed Bugs and Malfunctions

Modules with very many functions would compile very slowly.

Own Id: OTP-10123

compile:forms/2 will now use a {source,SourceFilePath} to set the source returned by module_info(compile) (Thanks to José Valim)

Own Id: OTP-10150

A process which had enabled trap_exit would receive EXIT messages after calling the compiler. (Thanks to Jeremy Heater.)

Own Id: OTP-10171

Fix messages ordering with column numbers

Own Id: OTP-10183

sys_pre_expand: Fix BASE never being set

Commit a612e99fb5aaa934fe5a8591db0f083d7fa0b20a turned module attributes from 2-tuples to 3-tuples but forgot to update get_base/1, breaking BASE for parametric modules.

Own Id: OTP-10184

The compiler will now issue a warning if literal tuple funs are used. For example, {erlang,is_tuple}(X) will now generate a warning.

Own Id: OTP-10185

The compiler will now warn for illegal sizes for segments in binary construction. For example, <<X:(2.5)>> will now cause the compiler to issue a warning.

Own Id: OTP-10197

Fix the erlc -MP flag

Because of a copy-and-paste error in erlc.c, the -MP flag had the same effect as -MG. As a workaround, you had to pass +makedep_phony to enable the MP option. This patch makes -MP work as intended.

Own Id: OTP-10211

Compiler 4.8.1

Fixed Bugs and Malfunctions

In rare circumstance, the compiler could crash when compiling a case statement. (Thanks to Hakan Mattsson.)

Own Id: OTP-9842

Calling a guard test (such as is_list/1) from the top-level in a guard, would cause a compiler crash if there was a local definition with the same name. Corrected to reject the program with an error message.

Own Id: OTP-9866

Using get/1 in a try block could in some cases cause an internal compiler error. (Thanks to Eric Merritt.)

Own Id: OTP-9867

An unexported on_load function would not get run if the module was compiled with the inline option. (Thanks to Yiannis Tsiouris.)

Own Id: OTP-9910

Fixed a discrepancy in compile_info

The BEAM disassembler used the atom 'none' to signify the absence of a compile_info chunk in a .beam file. This clashed with the type declaration of the compile_info field of a #beam_file{} record as containing a list. Now [] signifies the absence of this chunk. This simplifies the code and avoids a dialyzer warning.

Own Id: OTP-9917

Fix typo in `compile' doc: unmatched parenthesis (Thanks to Ricardo Catalinas Jiménez)

Own Id: OTP-9919

In a try...catch statement that always returned false, the compiler would remove calls to BIFs that could not cause an exception (such as put/2). Example of such code: try put(K, V), false catch _:_ -> false end.

Own Id: OTP-9982

Compiler 4.8

Fixed Bugs and Malfunctions

Add '-callback' attributes in stdlib's behaviours

Replace the behaviour_info(callbacks) export in stdlib's behaviours with -callback' attributes for all the callbacks. Update the documentation with information on the callback attribute Automatically generate 'behaviour_info' function from '-callback' attributes

'behaviour_info(callbacks)' is a special function that is defined in a module which describes a behaviour and returns a list of its callbacks.

This function is now automatically generated using the '-callback' specs. An error is returned by lint if user defines both '-callback' attributes and the behaviour_info/1 function. If no type info is needed for a callback use a generic spec for it. Add '-callback' attribute to language syntax

Behaviours may define specs for their callbacks using the familiar spec syntax, replacing the '-spec' keyword with '-callback'. Simple lint checks are performed to ensure that no callbacks are defined twice and all types referred are declared.

These attributes can be then used by tools to provide documentation to the behaviour or find discrepancies in the callback definitions in the callback module.

Add callback specs into 'application' module in kernel Add callback specs to tftp module following internet documentation Add callback specs to inets_service module following possibly deprecated comments

Own Id: OTP-9621

The calculation of the 'uniq' value for a fun (see erlang:fun_info/1) was too weak and has been strengthened. It used to be based on the only the code for the fun body, but it is now based on the MD5 of the BEAM code for the module.

Own Id: OTP-9667

Improvements and New Features

Variables are now now allowed in 'fun M:F/A' as suggested by Richard O'Keefe in EEP-23.

The representation of 'fun M:F/A' in the abstract format has been changed in an incompatible way. Tools that directly read or manipulate the abstract format (such as parse transforms) may need to be updated. The compiler can handle both the new and the old format (i.e. extracting the abstract format from a pre-R15 BEAM file and compiling it using compile:forms/1,2 will work). The syntax_tools application can also handle both formats.

* POTENTIAL INCOMPATIBILITY *

Own Id: OTP-9643

filename:find_src/1,2 will now work on stripped BEAM files (reported by Per Hedeland). The HiPE compiler will also work on stripped BEAM files. The BEAM compiler will no longer include compilation options given in the source code itself in M:module_info(compile) (because those options will be applied anyway if the module is re-compiled).

Own Id: OTP-9752

Inlining binary matching could cause an internal compiler error. (Thanks to Rene Kijewski for reporting this bug.)

Own Id: OTP-9770

Compiler 4.7.5

Fixed Bugs and Malfunctions

Compiler options given in the source code using a -compile() attribute used to be included twice in Mod:module_info(compile). They are now only included once at the beginning of the list of options.

Own Id: OTP-9534

beam_disasm: Handle stripped BEAM files

beam_disasm:file/1 would crash if asked to disassemble a stripped BEAM file without an "Attr" chunk. (Thanks to Haitao Li)

Own Id: OTP-9571

Compiler 4.7.4

Fixed Bugs and Malfunctions

If a variable is matched out in binary matching and used as the size for a binary element, it would seem to be unbound if used in a subsequent match operation. (Thanks to Bernard Duggan.)

Own Id: OTP-9134

Eliminate incorrect warning in sys_core_fold

Own Id: OTP-9152

Compiler 4.7.3

Fixed Bugs and Malfunctions

The -export_type() directive is no longer included among the attributes.

Own Id: OTP-8998

Improvements and New Features

The maximum number of allowed arguments for an Erlang function has been lowered from 256 to 255, so that the number of arguments can now fit in a byte.

Own Id: OTP-9049

Dependency generation for Makefiles has been added to the compiler and erlc. See the manual pages for compile and erlc. (Thanks to Jean-Sebastien Pedron.)

Own Id: OTP-9065

Compiler 4.7.2

Fixed Bugs and Malfunctions

Two compiler bugs (that would cause the compiler to terminate) reported by Christopher Williams have been fixed.

Own Id: OTP-8949

Improvements and New Features

The compiler would translate binary comprehensions containing tail segments in a way that would would confuse Dialyzer. For instance:

[42 || <<_:8/integer, _/bits>> <= Bits]

would produce a Dialyzer warning.

Own Id: OTP-8864

Code such as foo(A) -> <<A:0>> would crash the compiler.

Own Id: OTP-8865

The compiler could fail with an internal error when variables were exported from a receive block but the return value of the receive block were not used. (Thanks to Jim Engquist for reporting this error.)

Own Id: OTP-8888

Compiler 4.7.1

Improvements and New Features

Eliminated warnings for auto-imported BIF clashes.

Own Id: OTP-8840

Compiler 4.7

Fixed Bugs and Malfunctions

Several problems in the inliner have been fixed.

Own Id: OTP-8552

Improvements and New Features

The module binary from EEP31 (and EEP9) is implemented.

Own Id: OTP-8217

Local and imported functions now override the auto-imported BIFs when the names clash. The pre R14 behaviour was that auto-imported BIFs would override local functions. To avoid that old programs change behaviour, the following will generate an error:

Doing a call without explicit module name to a local function having a name clashing with the name of an auto-imported BIF that was present (and auto-imported) before OTP R14A

Explicitly importing a function having a name clashing with the name of an autoimported BIF that was present (and autoimported) before OTP R14A

Using any form of the old compiler directive nowarn_bif_clash

If the BIF was added or auto-imported in OTP R14A or later, overriding it with an import or a local function will only result in a warning,

To resolve clashes, you can either use the explicit module name erlang to call the BIF, or you can remove the auto-import of that specific BIF by using the new compiler directive -compile({no_auto_import,[F/A]})., which makes all calls to the local or imported function without explicit module name pass without warnings or errors.

The change makes it possible to add auto-imported BIFs without breaking or silently changing old code in the future. However some current code ingeniously utilizing the old behaviour or the nowarn_bif_clash compiler directive, might need changing to be accepted by the compiler.

* POTENTIAL INCOMPATIBILITY *

Own Id: OTP-8579

The undocumented, unsupported, and deprecated function lists:flat_length/1 has been removed.

Own Id: OTP-8584

Nested records can now be accessed without parenthesis. See the Reference Manual for examples. (Thanks to YAMASHINA Hio and Tuncer Ayaz.)

Own Id: OTP-8597

It is now possible to suppress the warning in code such as "list_to_integer(S), ok" by assigning the ignored value "" like this: "` = list_to_integer(S), ok`".

Own Id: OTP-8602

receive statements that can only read out a newly created reference are now specially optimized so that it will execute in constant time regardless of the number of messages in the receive queue for the process. That optimization will benefit calls to gen_server:call(). (See gen:do_call/4 for an example of a receive statement that will be optimized.)

Own Id: OTP-8623

The compiler optimizes record operations better.

Own Id: OTP-8668

Compiler 4.6.5

Fixed Bugs and Malfunctions

Using complex boolean expressions in ifs could cause the compiler to either crash or terminate with an internal error. (Thanks to Simon Cornish.)

Own Id: OTP-8338

Bit string comprehensions can now be used in parameterized modules. (Thanks to Jebu Ittiachen.)

Own Id: OTP-8447

Improvements and New Features

The expected return value for an on_load function has been changed. (See the section about code loading in the Reference manual.)

* POTENTIAL INCOMPATIBILITY *

Own Id: OTP-8339

In rare circumstances when using garbaging collecting guard BIFs, the validation pass (beam_validator) would signal that the code was unsafe, when it in fact was correct. (Thanks to Kiran Khaladkar.)

Own Id: OTP-8378

The -Werror option for erlc and the compiler option warnings_as_errors will cause warnings to be treated as errors. (Thanks to Christopher Faulet.)

Own Id: OTP-8382

Macros overloading has been implemented. (Thanks to Christopher Faulet.)

Own Id: OTP-8388

Compiler 4.6.4

Fixed Bugs and Malfunctions

The compiler's 'E' option now works with modules with types and specifications.

Own Id: OTP-8238 Aux Id: OTP-8150

Certain uses of binary matching in a begin-end in a list comprehension could cause the compiler to crash or generate incorrect code.

Own Id: OTP-8271

Improvements and New Features

The documentation is now built with open source tools (xsltproc and fop) that exists on most platforms. One visible change is that the frames are removed.

Own Id: OTP-8201

The compiler could crash if invalid calls to is_record/2 was used in (for example) a list comprehension. (Thanks to Tobias Lindahl.)

Own Id: OTP-8269

The -on_load() directive can be used to run a function when a module is loaded. It is documented in the section about code loading in the Reference Manual.

Own Id: OTP-8295

Compiler 4.6.3

Improvements and New Features

Corrected liveness optimization to eliminate a compiler crash that could occur when compiling bit syntax construction code. (Thanks to Mikage Sawatari.)

Calling BIFs such as length/1 in guard context in a try/catch block could cause a compiler crash. (Thanks to Paul Fisher.)

Using filter expressions containing andalso or orelse in a list comprehension could cause a compiler crash. (Thanks to Martin Engström.)

Own Id: OTP-8054

A guard with nested 'not' operators could cause the compiler to crash. (Thanks to Tuncer Ayaz.)

Own Id: OTP-8131

Compiler 4.6.2

Fixed Bugs and Malfunctions

The compiler would crash while compiling certain complex function bodies containing receive after due to a bug in the jump optimizer (a label that had only had backward references could still be removed). (Thanks to Vincent de Phily.)

Own Id: OTP-7980

Compiler 4.6.1

Fixed Bugs and Malfunctions

Miscellaneous minor bugs fixed.

Own Id: OTP-7937

Improvements and New Features

There will be more efficient code if there is a clause that matches the empty binary and no other clauses that matches non-empty binaries.

Own Id: OTP-7924

There is new option to allow a module to have a module name other than the filename. Do not use it unless you know what you are doing.

Own Id: OTP-7927

Compiler 4.6.0.1

Fixed Bugs and Malfunctions

Using andalso/orelse or record access in a try...catch could cause a compiler crash.

Some large and complex functions could require extremely long compilation times (hours or days).

Own Id: OTP-7905

Compiler 4.6

Fixed Bugs and Malfunctions

For some complex guards which used andalso/orelse, the compiler would crash. (Thanks to Hunter Morris.)

Own Id: OTP-7679

Code that (incorrectly) used the the value of nested applications of setelement/3 in bit syntax construction could crash the compiler.

Own Id: OTP-7690

Modules containing huge integers (consisting of several hundreds of thousands of digits or more) could be slow to compile. This problem has been corrected.

Own Id: OTP-7707 Aux Id: seq11129

If the generator in a list comprehension is given a non-list term, there will now be function_clause exception instead of a case_clause exception (as it was in all releases before R12B).

Own Id: OTP-7844

Improvements and New Features

The compiler could crash if the size for a binary segment in matching was a complex literal such as binary or tuple.

Own Id: OTP-7650

The compiler generates more compact and faster code for matching of complex constants (such as constant lists and tuples).

Own Id: OTP-7655

The undocumented, unsupported, and deprecated guard BIF is_constant/1 has been removed.

* INCOMPATIBILITY with R12B *

Own Id: OTP-7673

The compiler generates better code for many guard expressions, and especially for guards that use andalso/orelse or record fields.

(In technical terms, andalso/orelse in a guard would case the creation of a stack frame and saving of all x registers that could potentially be alive after the guard and restoring all x registers before leaving the guard. For certain guards, far too many x registers were saved and subsequently restored. In this version of the compiler, no stack frame is created and no x registers are saved and restored.)

Own Id: OTP-7718

The default size for the resulting binary created by a binary comprehension was 64Kb in R12B (it would grow if needed). This was often far too much. In this release, the default is changed to 256 bytes. Furthermore, for most binary comprehensions without filters, the exact size of the resulting binary can be calculated beforehand and the compiler now generates code that does that calculation.

Own Id: OTP-7737

The short-circuit operators andalso and orelse no longer guarantees that their second argument is either true or false. As a consequence, andalso/orelse are now tail-recursive.

* POTENTIAL INCOMPATIBILITY *

Own Id: OTP-7748

The compiler will refuse to a compile file where the module name in the file differs from the output file name.

When compiling using erlc, the current working directory will no be included in the code path (unless explicitly added using "-pa .").

* POTENTIAL INCOMPATIBILITY *

Own Id: OTP-7793

There will no longer be any warnings for list comprehensions without generators, as such list comprehension have turned out to be useful.

Own Id: OTP-7846

Warnings for obsolete guard tests are now turned on. (That is, writing list(L) in a guard instead of is_list(L) will generate a warning.)

The warnings can be turned off using the nowarn_obsolete_guard option.

Own Id: OTP-7850

The copyright notices have been updated.

Own Id: OTP-7851

If a module contains an exported function with the same name as an auto-imported BIF (such as length/1), any calls to the BIF must have an explicit erlang: prefix, or there will be a compilation error (such calls would only generate a warning in previous releases).

(The reason for the change is to avoid breaking code in a future major release, R14 or R15, in which we plan to make calls without a module prefix always call the local function in the same module even if there is an auto-imported BIF with the same name.)

* POTENTIAL INCOMPATIBILITY *

Own Id: OTP-7873

Compiler 4.5.5

Fixed Bugs and Malfunctions

Matching on a zero-width segment in the bit syntax would crash the compiler. (Thanks to Will.)

Own Id: OTP-7591

Improvements and New Features

In bit syntax expressions which started with a binary segment, and was followed by at least two segments of variable size, too little space could be allocated for the binary, leading to memory corruption.

Own Id: OTP-7556

In user-defined attributes, Name/Arity is now allowed and will be translated to {Name,Arity}. (An implementation of EEP-24 by Richard O'Keefe.)

The module_info/{0,1} functions automatically inserted into each compiled modules are now documented in the Modules section in the Reference Manual.

Own Id: OTP-7586

Compiler 4.5.4

Improvements and New Features

Certain complex bit syntax matching operations matching out binaries and having several clauses could give incorrect results (the matched out binaries were too short). (Thanks to Christian von Roques for bug report and correction.)

Own Id: OTP-7498

Compiler 4.5.3

Improvements and New Features

New option warn_export_all to warn for a module using export_all. (Thanks to Richard Carlsson.)

Own Id: OTP-7392

Compiler 4.5.2.1

Fixed Bugs and Malfunctions

In rare circumstances, the length/1 BIF (and a few other guard BIFs) would seem to return an incorrect value (of any type).

Own Id: OTP-7345 Aux Id: seq10962

Compiler 4.5.2

Fixed Bugs and Malfunctions

A bug in the old inliner has been fixed. Some undocumented functionality has been removed.

Own Id: OTP-7223

Matching several binary patterns in parallel using the '=' operator is not allowed (an implementation limitation), but the compiler did not reject all such attempts (depending on the patterns, the generated code might or might not work correctly). Now the compiler rejects all binary patterns joined by '='.

Own Id: OTP-7227

Complex combinations of record operations and binary matching could cause the compiler to crash. (Thanks to Vladimir Klebansky.)

Own Id: OTP-7233

In rare circumstances, mixing binary matching clauses with clauses matching other data types, the compiler could crash.

Own Id: OTP-7240 Aux Id: seq10916

Compiler 4.5.1.1

Fixed Bugs and Malfunctions

Corrected a compiler bug that could cause a complex binary matching operation to fail when it shouldn't. (Thanks to Tomas Stejskal.)

Own Id: OTP-7188

In unusual circumstances, the environment for a fun could bind wrong values.

Own Id: OTP-7202 Aux Id: seq10887

Long sequences of list comprehensions without generators joined by the '++' operator would cause a code expansion explosion, which could cause the compiler to run out of memory. To resolve this problem, in '[...||...]++Expr', Expr is now evaluated before the list comprehension. This change is backwards compatible (see the following note about evaluation order if you have doubts).

Note about evaluation order: The Reference manual says that subexpressions are evaluated in any order before the expression itself. Therefore, in an expression such as 'LeftExpr++RightExpr', you should not depend on LeftExpr being evaluated before RightExpr or vice versa. The evaluation order is only important if the expressions contains and/or depends on operations with side-effects, such as message passing or ETS operations.

Own Id: OTP-7206

Compiler 4.5.1

Fixed Bugs and Malfunctions

A match expression inside a function call could cause a false "a term is constructed but never used" warning.

Own Id: OTP-7018 Aux Id: seq10824

The compiler could crash if a binary tail was matched out, and then used in a binary append operation. (Thanks to Oleg Avdeev.)

Similarly, the compiler could crash if a binary tail was matched out, and then used (incorrectly) in binary construction in an integer field. (Thanks to Fredrik Svahn.) Or was incorrectly used in a float field. Or was used in a binary field with a given length. (Thanks to Chih - Wei Yu.)

Own Id: OTP-7022

Matching an empty binary in a record and then using the same record again could cause a compiler crash. (Thanks to Fredrik Thulin.)

Own Id: OTP-7029

In rare circumstances, constants containing floating points and integers could be confused. Example:

f(a) -> [1]; f(b) -> [1.0].

Both f(a) and f(b) would return [1].

Own Id: OTP-7073

Some bit syntax code such as

matching d(_,<$lt;$gt;$gt;) -> one; d(0,<$lt;D$gt;$gt;) ->two.

could crash the compiler. (Thanks to Simon Cornish.)

Own Id: OTP-7094

In unusual circumstances, a call to a fun could fail due to an unsafe optimization. (Thanks to Simon Cornish.)

Own Id: OTP-7102

Bit syntax matching with a guard containing two or more uses of andalso/orelse could cause the compiler to crash. (Thanks to Mateusz Berezecki.)

Own Id: OTP-7113

This was only a problem if you generated or wrote your own Core Erlang code: The Core Erlang optimizer code could move nested calls such as erlang:'$lt;'(erlang:length(L), 2) as case expression into a guard, which would change the semantics. (Thanks to Robert Virding.)

Own Id: OTP-7117

Improvements and New Features

The compiler could generate suboptimal code for record updates if the record update code consisted of multiple source code lines.

Own Id: OTP-7101

Compiler 4.5

Fixed Bugs and Malfunctions

The compiler used to allow that a binary field without size could be used in other positions than at the end in bit syntax pattern. For instance, <<B/binary,EmptyBinary/binary>> = Bin used to compile, but now the compilation will fail with an an error message.

Also, it is now longer permitted to give a literal string in a binary pattern a type or a size; for instance, <<"abc"/binary>> = Bin will no longer compile. (In previous releases, there would always be a badmatch exception at run-time.)

Own Id: OTP-6885

Improvements and New Features

Bitstrings (bit-level) binaries and binary comprehensions are now part of the language. See the Reference Manual.

Own Id: OTP-6558

The 'compressed' option for the compiler has been documented.

Own Id: OTP-6801

If the value of a list comprehension is not used, such as in '[do_something(X) || X <- List], ok', a result list will no longer be built. For more details, see the Efficiency Guide.

If the value of an expression is not used, and the expression has no side effects except for possibly throwing an exception, a warning will be generated. Examples: 'self(),ok' and '{error,Reason},ok'.

Own Id: OTP-6824

Three new functions have been added to the compile module: noenv_file/2, noenv_forms/2, and noenv_output_generated/1.

Own Id: OTP-6829

Many bit syntax operations, both construction and matching, are faster. For further information, see the Efficiency Guide.

Own Id: OTP-6838

Literal lists, tuples, and binaries are no longer constructed at run-time as they used to be, but are stored in a per-module constant pool. Literals that are used more than once are stored only once.

This is not a change to the language, only in the details of its implementation. Therefore, the implications of this change is described in the Efficiency Guide.

Example 1: In the expression element(BitNum-1, {1,2,4,8,16,32,64,128}), the tuple used to be constructed every time the expression was executed, which could be detrimental to performance in two ways if the expression was executed in a loop: the time to build the tuple itself and the time spent in garbage collections because the heap filled up with garbage faster.

Example 2: Literal strings, such as "abc", used to be stored in the compiled code compactly as a byte string and expanded to a list at run-time. Now all strings will be stored expanded to lists (such as [$a,$b,$c]) in the constant pool. That means that the string will be faster to use at run-time, but that it will require more space even when not used. If space is an issue, you might want to use binary literals (that is, <<"abc"<<) instead of string literals for infrequently used long strings (such as error messages).

Own Id: OTP-6850

Recursive calls now usually consume less stack than in R11B. See the Efficiency Guide.

Own Id: OTP-6862 Aux Id: seq10746

Two new guard BIFs have been introduced as a recommended replacement for size/1. (The size/1 BIF will be removed no earlier than in R14B.) The BIFs are tuple_size/1 to calculate the size of a tuple and byte_size/1 to calculate the number of bytes needed for the contents of the binary or bitstring (rounded up to the nearest number of bytes if necessary).

There is also a new bit_size/1 BIF that returns the exact number of bits that a binary or bitstring contains.

Own Id: OTP-6902

The two internal functions erl_bifs:is_bif/3 and erl_bifs:is_guard/3 have been removed. They were unsupported, undocumented, and unmaintained.

Own Id: OTP-6966

Compiler 4.4.5

Fixed Bugs and Malfunctions

The compiler would crash if you tried to combine to non-list literals with '++' (for instance, an_atom++"string").

Own Id: OTP-6630 Aux Id: seq10635

Improvements and New Features

Minor Makefile changes.

Own Id: OTP-6689

Compiler 4.4.4

Fixed Bugs and Malfunctions

Incorrect code could be generated for bit syntax matching if the old inliner was used with aggressive settings.

Own Id: OTP-6461

Compiler 4.4.3

Fixed Bugs and Malfunctions

The R10B compiler could generate unsafe bs_save/bs_restore instructions that could cause memory corruption. (The R11B compiler does not have that problem.) The erlang emulator will now refuse to load R10B-compiled modules that contain such unsafe bs_save/bs_restore instructions. In addition, the beam_validator module in the compiler will also reject such instructions (in case it is used to validate R10B code). (Thanks to Matthew Reilly.)

Own Id: OTP-6386

Improvements and New Features

Directives for parse transforms that have been run are now removed from the abstract code stored when the debug_info option is given, to prevent the parse transforms to be run again.

Own Id: OTP-5344

Minor improvements in code generation for some guards expression involving boolean expressions.

Own Id: OTP-6347

Compiler 4.4.2.1

Fixed Bugs and Malfunctions

The compiler could generate incorrect code for bit syntax matching consisting of several clauses.

Own Id: OTP-6392 Aux Id: seq10539

Compiler 4.4.2

Fixed Bugs and Malfunctions

Defining a fun itself containing a fun in an after block of a try would cause the compiler to crash or generate incorrect code. (Thanks to Tim Rath.)

Shorter compilation times for modules containing with an extreme number of functions (10000 functions or more).

(The compiled could generate deprecated instructions for certain bit syntax matching operations.)

Own Id: OTP-6212 Aux Id: seq10446

Fixed several bugs that would cause warnings to be shown without file name and line number.

Own Id: OTP-6260 Aux Id: seq10461

Improvements and New Features

The strict_record_tests option is now default; that is, reading a field from a record using the Record#record_tag.field syntax will fail if Record is not a record of the correct type.

If necessary, the record tests can be turned off by giving the no_strict_record_tests option. To avoid editing Makefiles, the environment variable ERL_COMPILER_OPTIONS can be set to "no_strict_record_tests".

The no_strict_record_tests option will probably be removed in the R12B release.

* POTENTIAL INCOMPATIBILITY *

Own Id: OTP-6294

Compiler 4.4.1

Fixed Bugs and Malfunctions

The compiler used to crash if a module contained code similar to 'fun(1=0) -> ok end'. (Thanks to Richard Carlsson.)

The compiler would spend really long time compiling bit syntax expressions such as '<<1:(50*1024*1024)>>' and produce a huge .beam file. Corrected.

The compiler would compile list comprehensions with many generators really, really slow. (Thanks to Thomas Raes.)

Module attributes would be stored in reverse order compared to the order in the source code. (Thus, M:module_info(attributes) would also return the attributes in reversed order.)

Defining a fun in an after block of a try would cause the compiler to crash or generate incorrect code. (Thanks to Martin Bjorklund.)

The combination of binary pattern and a guard with andalso/orelse could cause the compiler to crash.

Own Id: OTP-6121 Aux Id: seq10400

Compiler 4.4

Fixed Bugs and Malfunctions

When a .hrl file is included using -include_lib, the include path is temporarily updated to include the directory the .hrl file was found in, which will allow that .hrl file to itself include files from the same directory using -include. (Thanks to Richard Carlsson.)

Own Id: OTP-5944

Improvements and New Features

The andalso and orelse operators are now allowed to be used in guards. That also applies to match specifications.

Own Id: OTP-5894 Aux Id: OTP-5149

When given the new option strict_record_tests, the compiler will generate code that verifies the record type for R#record.field operations in guards. Code that verifies record types in bodies has already been generated since R10B, but in this release there will be a {badrecord,RecordTag} instead of a badmatch if the record verification test fails. See compile for more information.

The Erlang shell always applies strict record tests.

Own Id: OTP-5915 Aux Id: OTP-5714

The BIF is_record/3 can now be used in guards. Also, is_record/3 can now be called without an erlang: module prefix for consistency with the other is_* functions.

Own Id: OTP-5916

The compiler options ignore_try and ignore_cond, which allowed code that used unquoted try or cond as atoms or record tags, has been removed. Old code that depended on the options need to be revised to have occurrences of try or cond as atom or record tags single-quoted. (Note: Although cond is a reserved keyword, there is no cond statement. It might be introduced in a future release.)

* POTENTIAL INCOMPATIBILITY *

Own Id: OTP-6058

Compiler 4.3.12

Improvements and New Features

The following code would crash the compiler: case T of #r{s = ""} -> T #r{s = "x"} end. (Thanks to Richard Carlsson.)

The compiler could crash if binaries were constructed in certain guards involving boolean operators (including semicolon). (Thanks to Torbjorn Tornkvist.)

Own Id: OTP-5872

The compiler will now warn that the megaco:format_versions/1 function is deprecated.

Own Id: OTP-5976

Compiler 4.3.11

Improvements and New Features

The compiler would assume that some patterns with aliases ('=') would not match if they were split into several lines. (Thanks to Peter Nagy/Mats Cronqvist.)

Minor cleanups to eliminate Dialyzer warnings.

Own Id: OTP-5791 Aux Id: seq10141

Compiler 4.3.10

Fixed Bugs and Malfunctions

When given the new option strict_record_tests, the compiler will generate code that verifies the record type for R#record.field operations (in body context only, not in guards). See the documentation for the compile module for more information.

The beam validator pass of the compiler could crash given in rare circumstances when given certain combinations of catches and record operations. (Thanks to Mats Cronqvist.)

Attributes containing binaries (such as -a(<<1,2,3>>)) would crash the compiler. (Thanks to Roger Price.)

Multiple behaviours in the same module will no longer generate a warning, unless one or more callbacks for the behaviours overlap. For instance, using both the application and supervisor behaviours in the same module will NOT generate any warning, but using gen_server and gen_fsm will.

Own Id: OTP-5714 Aux Id: seq10073

The pre-processor used to complain that the macro definition -define(S(S), ??S). was circular, which it isn't. (Thanks to Richard Carlsson.)

Own Id: OTP-5777

Compiler 4.3.9

Fixed Bugs and Malfunctions

Updating at least two fields of a record with a literal string could cause the compiler to generate dangerous code that could cause a crash at run-time (e.g. R#r{a="abc",b=1}). (Thanks to Mikael Karlsson.)

Unnecessary tests (such as a 'case' with two case branches that were identical) could cause the compiler to crash. (Thanks to Fredrik Thulin.)

The validation pass of the compiler could generate an error for correct code when floating point operations were used in try/catch statements.

In bit syntax construction, any field following a binary field would always be marked as "aligned" (which may or may not be correct). That would cause the hipe native compiler to generate incorrect code if the field was in fact unaligned. (Thanks to Per Gustafsson.)

Some complex guard expressions (such as A#a.b==""; A#a.b==undefined) would crash the compiler. (Thanks to Sean Hinde.)

Compilation speed has been increased for modules with many functions and/or atoms (such as modules generated by the Asn1 application or other code generators).

Own Id: OTP-5632 Aux Id: seq10057

Compiler 4.3.8

Fixed Bugs and Malfunctions

In some circumstances, having two try/catch constructs following each in a function body, would cause an internal error to be generated (when in fact the generated code was correct). (Thanks to Fredrik Thulin.)

Incorrect calls such as M:42() would crash the compiler. The compiler now generates a warning. (Thanks to Ulf Wiger.)

Own Id: OTP-5553

Improvements and New Features

The new fun M:F/A construct creates a fun that refers to the latest version of M:F/A. This syntax is meant to replace tuple funs {M,F} which have many problems.

The new type test is_function(Fun, A) (which may be used in guards) test whether Fun is a fun that can be applied with A arguments. (Currently, Fun can also be a tuple fun.)

Own Id: OTP-5584

Compiler 4.3.7

Improvements and New Features

Further improvements of encrypted debug info: New option encrypt_debug_info for compiler.

Own Id: OTP-5541 Aux Id: seq9837

Compiler 4.3.6

Fixed Bugs and Malfunctions

Fixed a bug in the validator of the generated code (beam_validator) which caused an internal compiler error even though the generated code was indeed correct.

Own Id: OTP-5481 Aux Id: seq9798

Improvements and New Features

It is now possible to encrypt the debug information in Beam files, to help keep the source code secret. See the documentation for compile on how to provide the key for encrypting, and the documentation for beam_lib on how to provide the key for decryption so that tools such as the Debugger, Xref, or Cover can be used.

The beam_lib:chunks/2 functions now accepts an additional chunk type compile_info to retrieve the compilation information directly as a term. (Thanks to Tobias Lindahl.)

Own Id: OTP-5460 Aux Id: seq9787

Compiler 4.3.5

Fixed Bugs and Malfunctions

Complex functions could cause the internal validator in the compiler to generate an internal error even though the generated code was correct.

Own Id: OTP-5436 Aux Id: seq9781

Compiler 4.3.4

Fixed Bugs and Malfunctions

In rare circumstances, incorrect code for record or tuple access could be generated. The incorrect code would either trigger an internal error in the compiler or cause an exception at run time. (Thanks to Martin Bjorklund.)

Corrected a bug in in bit syntax matching where clauses could match in the wrong order. (Thanks to Ulf Wiger.)

Own Id: OTP-5404 Aux Id: seq9767

Compiler 4.3.3

Improvements and New Features

Given bit syntax construction in certain complex contexts involving a catch, the compiler would either crash or terminate due to failure in an internal consistency check. (Thanks to Fredrik Thulin.)

Matches such as <<103133:64/float>> = <<103133:64/float>> used to fail. Now they succeed.

Shadowing of variables in bit syntax matches in fun heads such as in L = 8, F = fun(<<L:L,B:L>>) -> B end was handled incorrectly by the compiler. The fun used to be compiled as if it was written '>fun(<<8:8,B:8>>), while it should be compiled in the same way as fun(<<L:8,B:L>>).

A bug in the validation pass has been corrected. It sometimes occurred when the compiler optimized by reusing code for causing an exception when the reused code was called from within catch or try-catch statements. Then the validator refused to approve the code and complained about fun(<<L:L,B:L>>) -> B end was handled incorrectly by the in the same way as fun(<<L:8,B:L>>).

A bug in the unknown_catch_try_state.

Corrected a bug in the optimizer that would cause the compiler to crash. (Thanks to Peter-Henry Mander.)

There are now warnings generated if a bit syntax construction will fail at run-time because of a type mismatch (e.g. <<an_atom:8>>).

Own Id: OTP-5342 Aux Id: OTP-5118, OTP-5270, OTP-5323

Binary pattern matching such as t(<<A:8>> = <<A:8>) used to silently fail at runtime (i.e. never match). The compiler now generates an error for any such patterns.

Own Id: OTP-5371

Compiler 4.3.2

Fixed Bugs and Malfunctions

In rare cases, the code compiler code generate code for a tuple match that could crash the emulator if passed a term that was not a tuple.

If a bit syntax construction failed within a catch, previously assigned variables could get the wrong value.

The compiler now runs a validation pass on the generated code and aborts before writing a Beam file if any suspect code is found. In particular, the validation pass checks for incorrect code that may cause emulator crashes or other strange symptoms in the emulator.

Some corrections to the unsupported feature parameterized modules by Richard Carlsson (HiPE).

Own Id: OTP-5247 Aux Id: OTP-5235

Compiler 4.3.1

Fixed Bugs and Malfunctions

Corrected the release note regarding try/catch below. try/catch DOES work in the initial R10B release.

A few minor issues code generation issues were corrected. Although the generated code was correct, it was slightly slower and larger than it needed to be.

A debug printout (that could be seen in rare circumstances) has been removed.

not record_test(not_a_tuple, RecordTag) and similar expressions in a guard would fail.

New options basic_validation and strong_validation to do a quick check of the code of a module.

The inline option was not recognized if it appeared in a -compile() directive inside the module.

Corrected some bugs in the undocumented feature "parameterized modules".

Own Id: OTP-5198

When the undocumented feature "parameterized modules" was used, the ?MODULE macro did not work correctly.

Own Id: OTP-5224

Invariants on the Structure and Format of BEAM SSA

Exception Handling

The translation of a try-catch expression into BEAM SSA has the following structure:

@tag = new_try_tag `try`
br @tag, ^protected_block0, ^landing_pad_block

protected_block0:
  @success0 = ... % Something that could raise an exception
  br @success0, ^protected_block1, ^landing_pad_block

...

protected_blockN:
  % The end of the protected code
  @ignored0 = kill_try_tag @tag
  br ^after_try_catch

landing_pad_block:
  @aggregate = landingpad try, @tag
  @class  = extract @aggregate, `0` % The error class
  @reason = extract @aggregate, `1` % The reason
  @stk    = extract @aggregate, `2` % The stack trace
  @ignored1 = kill_try_tag @tag
  %% Pattern matching on @class, @reason, and @stk is done here
  %% to send control to the appropriate catch clause
  br ^after_try_catch

after_try_catch:
  % Normal execution continues

The following invariants must hold for the SSA:

All code that can cause an exception in one of the protected blocks must have explicit control flow edges to the landing pad block. If there are no edges to the landing pad block except from the block containing the new_try_tag, the compiler will remove the redundant exception handler.

The extraction of the class, reason and stack trace from the result of the landingpad instruction must be done in that order. Omitting the extraction of elements which are unused is allowed.

Both the landing pad block and the final protected block must end with a kill_try_tag instruction. Trying to share the kill_try_tag epilogue between the last protected block and the landing pad is unlikely to work.

The translation of an old-style catch expression into BEAM SSA has the following structure:

@tag = new_try_tag `try`
br @tag, ^protected_block0, ^landing_pad_block

protected_block0:
  @success0 = ... % Something that could raise an exception
  br @success0, ^protected_block1, ^landing_pad_block

...

protected_blockN:
  % The end of the protected code
  @successful_result = .... % The result of a successful computation
  br ^common_end_of_catch

landing_pad_block:
   @aggregate = landingpad catch, @tag
   @catched_val = extract @ssa_agg, `0`
   br ^common_end_of_catch

common_end_of_catch:
  @tmp = phi { @catched_val, ^landing_pad_block },
             { @successful_result, ^protected_blockN }
  @result_of_catch_expr = catch_end @tag, @tmp

Just as for a try-catch expression all code that can cause an exception in one of the protected blocks must have explicit control flow edges to the landing pad block.

Exception Re-issuing

A typical user-written try-catch expression will catch a subset of all possible exception classes and reasons and leave unhandled exceptions to a handler further up the call stack. Re-issuing an exception is done with the resume instruction. The resume must come after the kill_try_tag instruction in the program flow. For example, if the example in the Exception Handling Section was to only handle user throws, the relevant blocks would look like this:

landing_pad_block:
  @aggregate = landingpad `try`, @tag
  @class  = extract @aggregate, `0` % The error class
  @reason = extract @aggregate, `1` % The reason
  @stk    = extract @aggregate, `2` % The stack trace
  @ignored1 = kill_try_tag @tag
  @is_throw = bif:'=:=' @class, `throw`
  br @is_throw ^first_block_of_throw_handler, ^reissue

first_block_of_throw_handler:
  %% Handle the user-defined throw

reissue:
  @tmp = resume @stk, @reason
  ret @tmp

Function Calls

All function calls not in a tail call position must be followed by a succeeded:body-instruction unless one of the following exceptions apply:

The function call can statically be proven to always fail.

The function call is to the erlang-module and can statically be proven to always succeed or fail.

Variable Naming

A variable name in BEAM SSA is either an atom or a non-negative integer:

atom() | non_neg_integer()

In order to generate fresh unused variable names, all compiler transforms maintain a counter, the cnt-field in the b_function and opt_st records, which is incremented each time a new variable or label is created. In the following description the value of the cnt-field is called Cnt. The Cnt value is guaranteed to never clash with a previously defined variable name. Therefore, value of Cnt can directly be used as a variable name in the SSA passes.

Note that the rules were more complicated before Erlang/OTP 27, because the Cnt value could clash with other variables.

BEAM SSA Checks

While developing optimizations operating on the BEAM SSA it is often hard to check that various transforms have the intended effect. For example, unless a transform produces crashing code, it is hard to detect that the transform is broken. Likewise missing an optimization opportunity is also hard to detect.

To simplify the creation of tests on BEAM SSA the compiler has an internal mode in which it parses and checks assertions on the structure and content of the produced BEAM SSA code. This is a short introduction to the syntax and semantics of the SSA checker functionality.

Syntax

SSA checks are embedded in the source code as comments starting with with one of %ssa%, %%ssa% or %%%ssa%. This is a short introduction the syntax, for the full syntax please refer to the ssa_check_when_clause production in erl_parse.yrl.

SSA checks can be placed inside any Erlang function, for example:

t0() ->
%ssa% () when post_ssa_opt ->
%ssa%   ret(#{}).
  #{}.

will check that t0/0 returns the literal #{}. If we want to check that a function returns its first formal parameter, we can write:

t1(A, _B) ->
%ssa% (X, _) when post_ssa_opt ->
%ssa%   ret(X).
  A.

Note how we match the first formal parameter using X. The reason for having our own formal parameters for the SSA check, is that we don't want to introduce new identifiers at the Erlang level to support SSA-level checks. Consider if t1/2 had been defined as t1([A|As], B) we would have had to introduce a new identifier for the aggregate value [A|As].

The full syntax for a SSA check clause is:

<expected-result>? (<formals>) when <pipeline-location> -> <checks> '.'

where <expected-result> can be one of pass (the check must succeed), fail and xfail (the check must fail). Omitting <expected-result> is parsed as an implicit pass.

<formals> is a comma-separated list of variables.

<pipeline-location> specifies when in the compiler pipeline to run the checks. For now the only supported value for <pipeline-location> is post_ssa_opt which runs the checks after the ssa_opt pass.

<checks> is a comma-separated list of matches against the BEAM SSA code. For non-flow-control operations the syntax is:

<variable> = <operation> ( <arguments> ) <annotation>?

where <operation> is the #b_set.op field from the internal SSA representation. BIFs are written as bif:<atom>.

<arguments> is a comma-separated list of variables or literals.

For flow control operations and labels, the syntax is as follows:

br(<bool>, <true-label>, <false-label>)

switch(<value>, <fail-label>, [{<label>,<value>},...])

ret(<value>)

label <value>

where <value> is a literal or a variable.

A check can also include an assertion on operation annotations. The assertion is written as a map-like pattern following the argument list, for example:

t0() ->
%ssa% () when post_ssa_opt ->
%ssa% _ = call(fun return_int/0) { result_type => {t_integer,{17,17}},
%ssa%                              location => {_,32} },
%ssa% _ = call(fun return_tuple/0) {
%ssa%    result_type => {t_tuple,2,true,#{1 => {t_integer,{1,1}},
%ssa%                                     2 => {t_integer,{2,2}}}}
%ssa% }.
    X = return_int(),
    Y = return_tuple(),
    {X, Y}.

Semantics

When an SSA assertion is matched against the BEAM SSA for a function, patterns are applied sequentially. If the current pattern doesn't match, the checker tries with the next instruction. If the checker reaches the end of the SSA representation without having matched all patterns, the check is considered failed otherwise the assertion is considered successful. When a pattern is matched against an SSA operation, the values of variables already bound are considered and if the patterns matches, free variables introduced in the successfully matched pattern are bound to the values they have in the matched operation.

Compiler integration

The BEAM SSA checker is enabled by the compiler option {check_ssa,post_ssa_opt}. When enabled, a failed SSA assertion will be reported using the same mechanisms as an ordinary compilation error.

Limitations

Unbound variables are not allowed in the key-part of map literals nor in annotation assertions.

compile

Erlang Compiler

This module provides an interface to the standard Erlang compiler. It can generate either a file containing the object code or return a binary that can be loaded directly.

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.

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.

Inlining does not necessarily improve running time. For example, inlining can increase Beam stack use, which probably is detrimental to performance for recursive functions.

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

Summary

Types

abstract_code()

bin_ret()

comp_ret()

err_ret()

error_description()

error_info()

errors()

forms()

List of Erlang abstract or Core Erlang format representations, as used by forms/2.

mod_ret()

option()

See file/2 for detailed description.

warnings()

Functions

env_compiler_options()

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(File)

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

file(File, Options)

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

format_error(ErrorDescription)

Uses an ErrorDescriptor and returns a deep list of characters that describes the error.

forms(Forms)

Is the same as forms(Forms, [verbose,report_errors,report_warnings]).

forms(Forms, Options)

Analogous to file/1, but takes a list of forms (in either Erlang abstract or Core Erlang format representation) as first argument.

noenv_file(File, Options)

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

noenv_forms(Forms, Options)

Works like forms/2, except that the environment variable ERL_COMPILER_OPTIONS is not consulted.

noenv_output_generated(Options)

Works like output_generated/1, except that the environment variable ERL_COMPILER_OPTIONS is not consulted.

output_generated(Options)

Determines whether the compiler generates a BEAM file with the given options.

Types

abstract_code()

(not exported)

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

bin_ret()

(not exported)

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

comp_ret()

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

err_ret()

(not exported)

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

error_description()

(not exported)

-type error_description() :: erl_lint:error_description().

error_info()

(not exported)

-type error_info() :: erl_lint:error_info().

errors()

(not exported)

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

forms()

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

List of Erlang abstract or Core Erlang format representations, as used by forms/2.

mod_ret()

(not exported)

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

option()

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

See file/2 for detailed description.

warnings()

(not exported)

-type warnings() :: [{file:filename(), [error_info()]}].

Functions

env_compiler_options()

(since OTP 19.0)

-spec 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(File)

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

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

file(File, Options)

-spec 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 - Includes debug information in the form of Erlang Abstract Format in the debug_info chunk of the compiled beam module. Tools such as Debugger, Xref, and Cover require the debug information to be included.

Warning: Source code can be reconstructed from the debug information. Use encrypted debug information (encrypt_debug_info) to prevent this.

For details, see beam_lib(3).

{debug_info, {Backend, Data}} - Includes custom debug information in the form of a Backend module with custom Data in the compiled beam module. The given module must implement a debug_info/4 function and is responsible for generating different code representations, as described in the debug_info under beam_lib(3).

Warning: Source code can be reconstructed from the debug information. Use encrypted debug information (encrypt_debug_info) to prevent this.

{debug_info_key,KeyString}

{debug_info_key,{Mode,KeyString}} - Includes debug information, but encrypts it so that it cannot be accessed without supplying the key. (To give option debug_info as well is allowed, but not necessary.) Using this option is a good way to always have the debug information available during testing, yet protecting the source code.

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

For details, see beam_lib(3).

encrypt_debug_info - Similar to the debug_info_key option, but the key is read from an .erlang.crypt file.

For details, see beam_lib(3).

deterministic - Omit the options and source tuples in the list returned by Module:module_info(compile), and reduce the paths in stack traces to the module name alone. This option will make it easier to achieve reproducible builds.

{feature, Feature, enable | disable} - Enable (disable) the feature Feature during compilation. The special feature all can be used to enable (disable) all features.

Note

This option has no effect when used in a -compile(..) attribute. Instead, the -feature(..) directive (described next) should be used.

A feature can also be enabled (disabled) using the -feature(Feature, enable | disable). module directive. Note that this directive can only be present in a prefix of the file, before exports and function definitions. This is the preferred method of enabling and disabling features, since it is a local property of a module.

makedep - Produces a Makefile rule to track headers dependencies. No object file is produced.

By default, this rule is written to <File>.Pbeam. However, if option binary is set, nothing is written and the rule is returned in Binary.

The output will be encoded in UTF-8.

For example, if you have the following module:

-module(module).

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

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 are created as a side effect to the normal compilation process. This means that the object file will also be produced. This option override the makedep option.

{makedep_output, Output} - Writes generated rules to Output instead of the default <File>.Pbeam. Output can be a filename or an io_device(). To write to stdout, use standard_io. However, if binary is set, nothing is written to Output and the result is returned to the caller with {ok, ModuleName, Binary}.

{makedep_target, Target} - Changes the name of the rule emitted to Target.

makedep_quote_target - Characters in Target special to make(1) are quoted.

makedep_add_missing - Considers missing headers as generated files and adds them to the dependencies.

makedep_phony - Adds a phony target for each dependency.

'P' - Produces a listing of the parsed code, after preprocessing and parse transforms, in the file <File>.P. No object file is produced.

'E' - Produces a listing of the code, after all source code transformations have been performed, in the file <File>.E. No object file is produced.

'S' - 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 successful and unsuccessful). For more information, see the section about selective receive optimization in the Efficiency Guide.

report_errors/report_warnings - Causes errors/warnings to be printed as they occur.

report - A short form for both report_errors and report_warnings.

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, is added to the tuples returned on success.

warnings_as_errors - Causes warnings to be treated as errors.

{error_location,line | column} - If the value of this flag is line, the location ErrorLocation of warnings and errors is a line number. If the value is column, 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, debug information includes column information.

return - A short form for both return_errors and return_warnings.

verbose - Causes more verbose information from the compiler, describing what it is doing.

{source,FileName} - Overrides the source file name as presented in module_info(compile) and 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 - Causes all functions in the module to be exported.

{i,Dir} - Adds Dir to the list of directories to be searched when including a file. When encountering an -include or -include_lib directive, the compiler searches for header files in the following 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 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, in 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"). Note that the format of assembler files is not documented, and 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 can change between releases.

no_spawn_compiler_process - By default, all code is compiled in a separate process which is terminated at the end of compilation. However, some tools, like Dialyzer or compilers for other BEAM languages, may already manage their own worker processes and spawning an extra process may slow the compilation down. In such scenarios, you can pass this option to stop the compiler from spawning an additional process.

no_strict_record_tests - This option is not recommended.

By default, the generated code for 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 is a mismatch. If there is a good reason for having a module name unrelated to the name of the output file, this option disables that verification (there will not even be a warning if there is a mismatch).

{no_auto_import,[{F,A}, ...]} - Makes the function F/A no longer being auto-imported from the erlang module, which resolves BIF name clashes. This option must be used to resolve name clashes with auto-imported BIFs that existed before Erlang/OTP R14A when calling a local function with the same name as an auto-imported BIF without module prefix.

If the BIF is to be called, use the erlang module prefix in the call, not {no_auto_import,[{F,A}, ...]}.

If this option is written in the source code, as a -compile directive, the syntax F/A can be used instead of {F,A}. For example:

-compile({no_auto_import,[error/1]}).

no_auto_import - Do not auto-import any functions from erlang module.

no_line_info - Omits line number information to produce a slightly smaller output file.

no_lint - Skips the pass that checks for errors and warnings. Only applicable together with the from_abstr option. This is mainly for implementations of other languages on top of Erlang, which have already done their own checks to guarantee correctness of the code.

Caveat: 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()}]} - Pass extra chunks to be stored in the .beam file. The extra chunks must be a list of tuples with a four byte binary as chunk name followed by a binary with the chunk contents. See beam_lib for more information.

{check_ssa, Tag :: atom()} - Parse and check assertions on the structure and content of the BEAM SSA code produced by the compiler. The Tag indicates the set of assertions to check and after which compiler pass the check is performed. This option is internal to the compiler and can be changed or removed at any time without prior warning.

line_coverage - Instrument the compiled code for line coverage by inserting an executable_line instruction for each executable line in the source code. By default, this instruction will be ignored when loading the code.

To activate the executable_line instructions, the runtime system must be started with the option +JPcover to enable a coverage mode. 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 option line_coverage, this module will be loaded in the line_counter coverage mode, regardless of the current coverage mode in the runtime system. This option is used by cover to load cover-compiled code.

If warnings are turned on (option report_warnings described earlier), the following options control what type of warnings that are generated. Except from {warn_format,Verbosity}, the following options have two forms:

A warn_xxx form, to turn on the warning.

A nowarn_xxx form, to turn off the warning.

In the descriptions that follow, the form that is used to change the default value are listed.

{warn_format, Verbosity} - Causes warnings to be emitted for malformed format strings as arguments to io:format and similar functions.

Verbosity selects the number of warnings:

0 = No warnings

1 = Warnings for invalid format strings and incorrect number of arguments

2 = Warnings also when the validity cannot be checked, for example, when the format string argument is a variable.

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

nowarn_bif_clash - This option is removed; it generates a fatal error if used.

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

{nowarn_bif_clash, FAs} - This option is removed; it generates a fatal error if used.

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 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 with the same name as 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 the feature is enabled, any occurrences will lead to a syntax error. To prevent this, 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 are not called directly or indirectly by an exported function. The compiler does not include unused local functions in the generated BEAM file, but the warning is still useful to keep the source code cleaner.

{nowarn_unused_function, FAs} - Turns off warnings for unused local functions like nowarn_unused_function does, but only for the mentioned local functions. 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. Notice that the compiler does not know about attribute -deprecated(), but uses an assembled list of deprecated functions in Erlang/OTP. To do 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 like nowarn_deprecated_function does, but only for the mentioned functions. 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 of the form catch Expr instead of the modern try ... catch ... end.

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, such as pid/1 and list/1. See 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 are emitted when a variable that begins with an underscore is matched after being bound. Use this option to turn off this kind of warning.

nowarn_unused_vars - By default, warnings are emitted for unused variables, except for variables beginning with an underscore ("Prolog style warnings"). Use this option to turn off this kind of warning.

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 are emitted when inlining is enabled in a module that may load NIFs, as the compiler may inline NIF fallbacks by accident. Use this option to turn off this kind of warnings.

warn_missing_doc | warn_missing_doc_functions | warn_missing_doc_types | warn_missing_doc_callbacks
By default, warnings are not emitted when -doc attribute for an exported function, callback or type is not given. Use these option to turn on this kind of warning. warn_missing_doc is equivalent to setting all of warn_missing_doc_functions, warn_missing_doc_types and warn_missing_doc_callbacks.

nowarn_missing_doc | nowarn_missing_doc_functions | nowarn_missing_doc_types | nowarn_missing_doc_callbacks
If warnings are enabled by warn_missing_doc, then you can use these options turn those warnings off again. nowarn_missing_doc is equivalent to setting all of nowarn_missing_doc_functions, nowarn_missing_doc_types and nowarn_missing_doc_callbacks.

nowarn_hidden_doc | {nowarn_hidden_doc,NAs}
By default, warnings are emitted when -doc false attribute is set on a callback or referenced type. You can set nowarn_hidden_doc to suppress all those warnings, or {nowarn_hidden_doc, NAs} to suppress specific callbacks or types. NAs is a tuple {Name, Arity} or a list of such tuples.

warn_missing_spec - By default, warnings are not emitted when a specification (or contract) for an exported function is not given. Use this option to turn on this kind of warning.

warn_missing_spec_documented - By default, warnings are not emitted when a specification (or contract) for a documented function is not given. Use this option to turn on this kind of warning.

warn_missing_spec_all - By default, warnings are not emitted when a specification (or contract) for an exported or unexported function is not given. Use this option to turn on this kind of warning.

nowarn_redefined_builtin_type - By default, a warning is emitted when a built-in type is locally redefined. Use this option to turn off this kind of warning.

{nowarn_redefined_builtin_type, Types} - By default, a warning is emitted when a built-in type is locally redefined. Use this option to turn off this kind of warning for the types in Types, where Types is a tuple {TypeName,Arity} or a list of such tuples.

nowarn_behaviours - By default, warnings are emitted for issues with behaviours. Use this option to turn off all warnings of this kind.

nowarn_conflicting_behaviours - By default, warnings are emitted when a module opts in to multiple behaviours that share the names of one or more callback functions. Use this option to turn off this kind of warning.

nowarn_undefined_behaviour_func - By default, a warning is emitted when a module that uses a behaviour does not export a mandatory callback function required by that behaviour. Use this option to turn off this kind of warning.

nowarn_undefined_behaviour - By default, a warning is emitted when a module attempts to us an unknown behaviour. Use this option to turn off this kind of warning.

nowarn_undefined_behaviour_callbacks - By default, a warning is emitted when behaviour_info(callbacks) in the behaviour module returns undefined instead of a list of callback functions. Use this option to turn off this kind of warning.

nowarn_ill_defined_behaviour_callbacks - By default, a warning is emitted when behaviour_info(callbacks) in the behaviour module returns a badly formed list of functions. Use this option to turn off this kind of warning.

nowarn_ill_defined_optional_callbacks - By default, a warning is emitted when behaviour_info(optional_callbacks) in the behaviour module returns a badly formed list of functions. Use this option to turn off this kind of warning.

nowarn_novalue - Disable warnings for creating a native record without giving values for all fields. Note that this kind of warning is only emitted when the module name for the record is explicitly given as the current module; when no module name is given, not initializing all fields is a compilation error.

nowarn_undefined_field - Disable warnings for referencing field names not present in the local native record definition. This warning is emitted when accessing, matching, or updating a native record. It can also be emitted when creating a record if the module name for the record is explicitly given as the current module.

Other kinds of warnings are opportunistic warnings. They are generated when the compiler happens to notice potential issues during optimization and code generation.

Note

The compiler does not warn for expressions that it does not attempt to optimize. For example, the compiler will emit a warning for 1/0 but not for X/0, because 1/0 is a constant expression that the compiler will attempt to evaluate.

The absence of warnings does not mean that there are no remaining errors in the code.

Opportunistic warnings can be disabled using the following options:

nowarn_opportunistic - Disable all opportunistic warnings.

nowarn_failed - Disable warnings for expressions that will always fail (such as atom+42).

nowarn_ignored - Disable warnings for expressions whose values are ignored.

nowarn_nomatch - Disable warnings for patterns that will never match (such as 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 attribute -compile([Option,...]). Attribute -compile() 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 attribute -compile(). (The option {nowarn_unused_function,FAs} was incorrectly documented to only work in a file, but it also worked when given in the option list.) Starting from Erlang/OTP 22, all options that can be given in the file can also be given in the option list.

For debugging of the compiler, or for pure curiosity, the intermediate code generated by each compiler pass can be inspected. To print a complete list of the options to produce list files, type compile:options() at the Erlang shell prompt. The options are printed in the order that the passes are executed. If more than one listing option is used, the one representing the earliest pass takes effect.

Unrecognized options are ignored.

Both WarningList and ErrorList have the following format:

[{FileName,[ErrorInfo]}].

The filename is included here, as the compiler uses the Erlang pre-processor epp, which allows the code to be included in other files. It is therefore important to know to which file the location of an error or a warning refers.

The ErrorInfo structure has the following format:

{ErrorLocation, Module, ErrorDescriptor}

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

A string describing the error is obtained with the following call:

Module:format_error(ErrorDescriptor)

format_error(ErrorDescription)

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

Uses an ErrorDescriptor and returns a deep list of characters that describes the error.

This function is usually called implicitly when an ErrorInfo structure is processed.

forms(Forms)

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

Is the same as forms(Forms, [verbose,report_errors,report_warnings]).

forms(Forms, Options)

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

Analogous to file/1, but takes a list of forms (in either Erlang abstract or Core Erlang format representation) as first argument.

Option binary is implicit, that is, no object code file is produced. For options that normally produce a listing file, such as 'E', the internal format for that compiler pass (an Erlang term, usually not a binary) is returned instead of a binary.

noenv_file(File, Options)

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

noenv_forms(Forms, Options)

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

Works like forms/2, except that the environment variable ERL_COMPILER_OPTIONS is not consulted.

noenv_output_generated(Options)

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

Works like output_generated/1, except that the environment variable ERL_COMPILER_OPTIONS is not consulted.

output_generated(Options)

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

Determines whether the compiler generates a BEAM file with the given options.

true means that a BEAM file is generated. false means that the compiler generates some listing file, returns a binary, or merely checks the syntax of the source code.

cerl

Core Erlang abstract syntax trees.

Note

The public interface of the Erlang compiler can be found in module compile.

This module is an internal part of the compiler. Its API is not guaranteed to remain compatible between releases.

This module defines an abstract data type for representing Core Erlang source code as syntax trees.

A recommended starting point for the first-time user is the documentation of the function type/1.

Note

This module deals with the composition and decomposition of syntactic entities (as opposed to semantic ones); its purpose is to hide all direct references to the data structures used to represent these entities. With few exceptions, the functions in this module perform no semantic interpretation of their inputs, and in general, the user is assumed to pass type-correct arguments - if this is not done, the effects are not defined.

Currently, the internal data structure used is the same as the record-based data structures used traditionally in the Beam compiler.

The internal representations of abstract syntax trees are subject to change without notice, and should not be documented outside this module. Furthermore, we do not give any guarantees on how an abstract syntax tree may or may not be represented, with the following exceptions: no syntax tree is represented by a single atom, such as none, by a list constructor [X | Y], or by the empty list []. This can be relied on when writing functions that operate on syntax trees.

Summary

Types

c_alias()

c_apply()

c_binary()

c_bitstr()

c_call()

c_case()

c_catch()

c_clause()

c_cons()

c_fun()

c_lct()

c_let()

c_letrec()

c_literal()

c_map()

c_map_pair()

c_module()

c_opaque()

c_primop()

c_receive()

c_record()

c_record_pair()

c_seq()

c_try()

c_tuple()

c_values()

c_var()

cerl()

ctype()

dtype()

map_op()

record_id()

value()

var_name()

Functions

abstract(Term)

Creates a syntax tree corresponding to an Erlang term.

add_ann(Annotations, Node)

Appends Annotations to the list of user annotations of Node.

alias_pat(Node)

Returns the pattern subtree of an abstract pattern alias.

alias_var(Node)

Returns the variable subtree of an abstract pattern alias.

ann_abstract(Annotations, Term)

See also: abstract/1.

ann_c_alias(Annotations, Variable, Pattern)

See also: c_alias/2.

ann_c_apply(Annotations, Operator, Arguments)

See also: c_apply/2.

ann_c_atom(Annotations, Name)

See also: c_atom/1.

ann_c_binary(Annotations, Segments)

See also: c_binary/1.

ann_c_bitstr(Annotations, Value, Size, Type, Flags)

Equivalent to ann_c_bitstr(As, Value, Size, abstract(1), Type, Flags).

ann_c_bitstr(Annotations, Value, Size, Unit, Type, Flags)

See also: ann_c_bitstr/5, c_bitstr/5.

ann_c_call(Annotations, Module, Name, Arguments)

See also: c_call/3.

ann_c_case(Annotations, Argument, Clauses)

See also: c_case/2.

ann_c_catch(Annotations, Body)

See also: c_catch/1.

ann_c_char(Annotations, Value)

See also: c_char/1.

ann_c_clause(Annotations, Patterns, Body)

Equivalent to ann_c_clause(As, Patterns, c_atom(true), Body).

ann_c_clause(Annotations, Patterns, Guard, Body)

See also: ann_c_clause/3, c_clause/3.

ann_c_cons(Annotations, Head, Tail)

See also: c_cons/2.

ann_c_cons_skel(Annotations, Head, Tail)

See also: c_cons_skel/2.

ann_c_float(Annotations, Value)

See also: c_float/1.

ann_c_fname(Annotations, Name, Arity)

Equivalent to ann_c_var(As, {Atom, Arity}).

ann_c_fun(Annotations, Variables, Body)

See also: c_fun/2.

ann_c_int(Annotations, Value)

See also: c_int/1.

ann_c_let(Annotations, Variables, Argument, Body)

See also: c_let/3.

ann_c_letrec(Annotations, Definitions, Body)

See also: c_letrec/2.

ann_c_map(Annotations, Pairs)

See also: c_map/1.

ann_c_map(Annotations, Argument, Pairs)

See also: c_map/2

ann_c_map_pair(Annotations, Operation, Key, Value)

See also: c_map_pair/2, c_map_pair_exact/2.

ann_c_map_pattern(Annotations, Pairs)

See also: c_map_pattern/2

ann_c_module(Annotations, Name, Exports, Definitions)

See also: ann_c_module/5, c_module/3.

ann_c_module(Annotations, Name, Exports, Attributes, Definitions)

See also: ann_c_module/4, c_module/4.

ann_c_nil(Annotations)

See also: c_nil/0.

ann_c_primop(Annotations, Name, Arguments)

See also: c_primop/2.

ann_c_receive(Annotations, Clauses)

Equivalent to ann_c_receive(As, Clauses, c_atom(infinity), c_atom(true)).

ann_c_receive(Annotations, Clauses, Timeout, Actions)

See also: ann_c_receive/2, c_receive/3.

ann_c_record(Annotations, Argument, Id, Pairs)

See also: c_record/2.

ann_c_record_pair(Annotations, Key, Value)

See also: c_record/2.

ann_c_seq(Annotations, Argument, Body)

See also: c_seq/2.

ann_c_string(Annotations, Value)

See also: c_string/1.

ann_c_try(Annotations, Argument, Variables, Body, ExceptionVars, Handler)

See also: c_try/5.

ann_c_tuple(Annotations, Elements)

See also: c_tuple/1.

ann_c_tuple_skel(Annotations, Elements)

See also: c_tuple_skel/1.

ann_c_values(Annotations, Values)

See also: c_values/1.

ann_c_var(Annotations, Name)

See also: c_var/1.

ann_make_data(Annotations, Type, Elementes)

See also: make_data/2.

ann_make_data_skel(Annotations, Type, Elements)

See also: make_data_skel/2.

ann_make_list(Annotations, List)

Equivalent to ann_make_list(As, List, none).

ann_make_list(Annotations, List, Tail)

See also: ann_make_list/2, make_list/2.

ann_make_tree(Annotations, Type, Groups)

Creates a syntax tree with the given annotations, type and subtrees.

apply_args(Node)

Returns the list of argument subtrees of an abstract function application.

apply_arity(Node)

Returns the number of argument subtrees of an abstract function application.

apply_op(Node)

Returns the operator subtree of an abstract function application.

atom_lit(Node)

Returns the literal string represented by an abstract atom. This always includes surrounding single-quote characters.

atom_name(Node)

Returns the printname of an abstract atom.

atom_val(Node)

Returns the value represented by an abstract atom.

binary_segments(Node)

Returns the list of segment subtrees of an abstract binary-template.

bitstr_bitsize(Node)

Returns the total size in bits of an abstract bit-string template.

bitstr_flags(Node)

Returns the flags subtree of an abstract bit-string template.

bitstr_size(Node)

Returns the size subtree of an abstract bit-string template.

bitstr_type(Node)

Returns the type subtree of an abstract bit-string template.

bitstr_unit(Node)

Returns the unit subtree of an abstract bit-string template.

bitstr_val(Node)

Returns the value subtree of an abstract bit-string template.

c_alias(Variable, Pattern)

Creates an abstract pattern alias.

c_apply(Operator, Arguments)

Creates an abstract function application.

c_atom(Name)

Creates an abstract atom literal.

c_binary(Segments)

Creates an abstract binary-template.

c_bitstr(Value, Type, Flags)

Equivalent to c_bitstr(Value, abstract(all), abstract(1), Type, Flags).

c_bitstr(Value, Size, Type, Flags)

Equivalent to c_bitstr(Value, Size, abstract(1), Type, Flags).

c_bitstr(Value, Size, Unit, Type, Flags)

Creates an abstract bit-string template.

c_call(Module, Name, Arguments)

Creates an abstract inter-module call.

c_case(Argument, Clauses)

Creates an abstract case-expression.

c_catch(Body)

Creates an abstract catch-expression.

c_char(Value)

Creates an abstract character literal.

c_clause(Patterns, Body)

Equivalent to c_clause(Patterns, c_atom(true), Body).

c_clause(Patterns, Guard, Body)

Creates an an abstract clause.

c_cons(Head, Tail)

Creates an abstract list constructor.

c_cons_skel(Head, Tail)

Creates an abstract list constructor skeleton.

c_float(Value)

Creates an abstract floating-point literal.

c_fname(Name, Arity)

Equivalent to c_var({Name, Arity}).

c_fun(Variables, Body)

Creates an abstract fun-expression.

c_int(Value)

Creates an abstract integer literal.

c_let(Variables, Argument, Body)

Creates an abstract let-expression.

c_letrec(Definitions, Body)

Creates an abstract letrec-expression.

c_map(Pairs)

Creates an abstract map constructor.

c_map(Argument, Pairs)

Creates an abstract map update expression.

c_map_pair(Key, Value)

Creates an abstract map pair using the assoc operator.

c_map_pair_exact(Key, Value)

Creates an abstract map pair using the exact operator.

c_map_pattern(Pairs)

Creates an abstract map pattern.

c_module(Name, Exports, Definitions)

Equivalent to c_module(Name, Exports, [], Definitions).

c_module(Name, Exports, Attributes, Definitions)

Creates an abstract module definition.

c_nil()

Creates an abstract empty list.

c_primop(Name, Arguments)

Creates an abstract primitive operation call.

c_receive(Clauses)

Equivalent to c_receive(Clauses, c_atom(infinity), c_atom(true)).

c_receive(Clauses, Timeout, Action)

Creates an abstract receive-expression.

c_record(Argument, Pairs)

Creates an abstract record constructor.

c_record_pair(Key, Value)

Creates an abstract record pair.

c_seq(Argument, Body)

Creates an abstract sequencing expression.

c_string(Value)

Creates an abstract string literal.

c_try(Argument, Variables, Body, ExceptionVars, Handler)

Creates an abstract try-expression.

c_tuple(Elements)

Creates an abstract tuple.

c_tuple_skel(Elements)

Creates an abstract tuple skeleton.

c_values(Elements)

Creates an abstract value list.

c_var(Name)

Creates an abstract variable.

call_args(Node)

Returns the list of argument subtrees of an abstract inter-module call.

call_arity(Node)

Returns the number of argument subtrees of an abstract inter-module call.

call_module(Node)

Returns the module subtree of an abstract inter-module call.

call_name(Node)

Returns the name subtree of an abstract inter-module call.

case_arg(Node)

Returns the argument subtree of an abstract case-expression.

case_arity(Node)

Equivalent to clause_arity(hd(case_clauses(Node))), but potentially more efficient.

case_clauses(Node)

Returns the list of clause subtrees of an abstract case-expression.

catch_body(Node)

Returns the body subtree of an abstract catch-expression.

char_lit(Node)

Returns the literal string represented by an abstract character. This includes a leading $ character.

char_val(Node)

Returns the value represented by an abstract character literal.

clause_arity(Node)

Returns the number of pattern subtrees of an abstract clause.

clause_body(Node)

Returns the body subtree of an abstract clause.

clause_guard(Node)

Returns the guard subtree of an abstract clause.

clause_pats(Node)

Returns the list of pattern subtrees of an abstract clause.

clause_vars(Node)

Returns the list of all abstract variables in the patterns of an abstract clause.

concrete(Node)

Returns the Erlang term represented by a syntax tree.

cons_hd(Node)

Returns the head subtree of an abstract list constructor.

cons_tl(Node)

Returns the tail subtree of an abstract list constructor.

copy_ann(Source, Target)

Copies the list of user annotations from Source to Target.

data_arity(Node)

Returns the number of subtrees of a data constructor node.

data_es(Node)

Returns the list of subtrees of a data constructor node.

data_type(Node)

Returns a type descriptor for a data constructor node. (Cf. is_data/1.)

float_lit(Node)

Returns the numeral string represented by a floating-point literal node.

float_val(Node)

Returns the value represented by a floating-point literal node.

fname_arity(Node)

Returns the arity part of an abstract function name variable.

fname_id(Node)

Returns the identifier part of an abstract function name variable.

fold_literal(Node)

Ensures that literals have a compact representation.

from_records(Node)

Translates an explicit record representation to a corresponding abstract syntax tree.

fun_arity(Node)

Returns the number of parameter subtrees of an abstract fun-expression.

fun_body(Node)

Returns the body subtree of an abstract fun-expression.

fun_vars(Node)

Returns the list of parameter subtrees of an abstract fun-expression.

get_ann(Node)

Returns the list of user annotations associated with a syntax tree node.

int_lit(Node)

Returns the numeral string represented by an integer literal node.

int_val(Node)

Returns the value represented by an integer literal node.

is_c_alias(Node)

Returns true if Node is an abstract pattern alias, otherwise false.

is_c_apply(Node)

Returns true if Node is an abstract function application, otherwise false.

is_c_atom(Node)

Returns true if Node represents an atom literal, otherwise false.

is_c_binary(Node)

Returns true if Node is an abstract binary-template, otherwise false.

is_c_bitstr(Node)

Returns true if Node is an abstract bit-string template, otherwise false.

is_c_call(Node)

Returns true if Node is an abstract inter-module call expression, otherwise false.

is_c_case(Node)

Returns true if Node is an abstract case-expression, otherwise false.

is_c_catch(Node)

Returns true if Node is an abstract catch-expression, otherwise false.

is_c_char(Node)

Returns true if Node may represent a character literal, otherwise false.

is_c_clause(Node)

Returns true if Node is an abstract clause, otherwise false.

is_c_cons(Node)

Returns true if Node is an abstract list constructor, otherwise false.

is_c_float(Node)

Returns true if Node represents a floating-point literal, otherwise false.

is_c_fname(Node)

Returns true if Node is an abstract function name variable, otherwise false.

is_c_fun(Node)

Returns true if Node is an abstract fun-expression, otherwise false.

is_c_int(Node)

Returns true if Node represents an integer literal, otherwise false.

is_c_let(Node)

Returns true if Node is an abstract let-expression, otherwise false.

is_c_letrec(Node)

Returns true if Node is an abstract letrec-expression, otherwise false.

is_c_list(Node)

Returns true if Node represents a proper list, otherwise false.

is_c_map(Node)

Returns true if Node is any kind of abstract map (for constructing, updating or matching), otherwise false.

is_c_map_empty(Node)

Returns true if Node represents an empty abstract map, otherwise false.

is_c_map_pattern(Node)

Returns true if Node is an abstract map pattern, otherwise false.

is_c_module(Node)

Returns true if Node is an abstract module definition, otherwise false.

is_c_nil(Node)

Returns true if Node is an abstract empty list, otherwise false.

is_c_primop(Node)

Returns true if Node is an abstract primitive operation call, otherwise false.

is_c_receive(Node)

Returns true if Node is an abstract receive-expression, otherwise false.

is_c_record(Node)

Returns true if Node is an abstract record, otherwise false.

is_c_seq(Node)

Returns true if Node is an abstract sequencing expression, otherwise false.

is_c_string(Node)

Returns true if Node may represent a string literal, otherwise false.

is_c_try(Node)

Returns true if Node is an abstract try-expression, otherwise false.

is_c_tuple(Node)

Returns true if Node is an abstract tuple, otherwise false.

is_c_values(Node)

Returns true if Node is an abstract value list, otherwise false.

is_c_var(Node)

Returns true if Node is an abstract variable, otherwise false.

is_data(Node)

Returns true if Node represents a data constructor, otherwise false.

is_leaf(Node)

Returns true if Node is a leaf node, otherwise false.

is_literal(Node)

Returns true if Node represents a literal term, otherwise false.

is_literal_term(Term)

Returns true if Term can be represented as a literal, otherwise false.

is_print_char(Node)

Returns true if Node may represent a "printing" character, otherwise false. (Cf. is_c_char/1.)

is_print_string(Node)

Returns true if Node may represent a string literal containing only "printing" characters, otherwise false.

let_arg(Node)

Returns the argument subtree of an abstract let-expression.

let_arity(Node)

Returns the number of left-hand side variables of an abstract let-expression.

let_body(Node)

Returns the body subtree of an abstract let-expression.

let_vars(Node)

Returns the list of left-hand side variables of an abstract let-expression.

letrec_body(Node)

Returns the body subtree of an abstract letrec-expression.

letrec_defs(Node)

Returns the list of definitions of an abstract letrec-expression.

letrec_vars(Node)

Returns the list of left-hand side function variable subtrees of a letrec-expression.

list_elements(Node)

Returns the list of element subtrees of an abstract list.

list_length(Node)

Returns the number of element subtrees of an abstract list.

make_data(Type, Elements)

Creates a data constructor node with the specified type and subtrees. (Cf. data_type/1.)

make_data_skel(Type, Elements)

Like make_data/2, but analogous to c_tuple_skel/1 and c_cons_skel/2.

make_list(List)

Equivalent to make_list(List, none).

make_list(List, Tail)

Creates an abstract list from the elements in List and the optional Tail.

make_tree(Type, Groups)

Creates a syntax tree with the given type and subtrees.

map_arg(Node)

Returns the argument subtree of an abstract map.

map_es(Node)

Returns the list of map pair subtrees of an abstract map.

map_pair_key(Node)

Returns the key subtree of an abstract map pair.

map_pair_op(Node)

Returns the operation subtree of an abstract map pair.

map_pair_val(Node)

Returns the value subtree of an abstract map pair.

meta(Tree)

Creates a meta-representation of a syntax tree.

module_attrs(Node)

Returns the list of pairs of attribute key/value subtrees of an abstract module definition.

module_defs(Node)

Returns the list of function definitions of an abstract module definition.

module_exports(Node)

Returns the list of exports subtrees of an abstract module definition.

module_name(Node)

Returns the name subtree of an abstract module definition.

module_vars(Node)

Returns the list of left-hand side function variable subtrees of an abstract module definition.

pat_list_vars(Patterns)

Returns the list of all abstract variables in the given patterns.

pat_vars(Node)

Returns the list of all abstract variables in a pattern.

primop_args(Node)

Returns the list of argument subtrees of an abstract primitive operation call.

primop_arity(Node)

Returns the number of argument subtrees of an abstract primitive operation call.

primop_name(Node)

Returns the name subtree of an abstract primitive operation call.

receive_action(Node)

Returns the action subtree of an abstract receive-expression.

receive_clauses(Node)

Returns the list of clause subtrees of an abstract receive-expression.

receive_timeout(Node)

Returns the timeout subtree of an abstract receive-expression.

record_arg(Node)

Returns the argument subtree of an abstract record.

record_es(Node)

Returns the list of native record pair subtrees of an abstract record.

record_id(Node)

Returns the identifier of of an abstract record.

record_pair_key(Node)

Returns the key subtree of an abstract record pair.

record_pair_val(Node)

Returns the value subtree of an abstract record pair.

seq_arg(Node)

Returns the argument subtree of an abstract sequencing expression.

seq_body(Node)

Returns the body subtree of an abstract sequencing expression.

set_ann(Node, Annotations)

Sets the list of user annotations of Node to Annotations.

string_lit(Node)

Returns the literal string represented by an abstract string. This includes surrounding double-quote characters "...".

string_val(Node)

Returns the value represented by an abstract string literal.

subtrees(Node)

Returns the grouped list of all subtrees of a node.

to_records(Node)

Translates an abstract syntax tree to a corresponding explicit record representation.

try_arg(Node)

Returns the expression subtree of an abstract try-expression.

try_body(Node)

Returns the success body subtree of an abstract try-expression.

try_evars(Node)

Returns the list of exception variable subtrees of an abstract try-expression.

try_handler(Node)

Returns the exception body subtree of an abstract try-expression.

try_vars(Node)

Returns the list of success variable subtrees of an abstract try-expression.

tuple_arity(Node)

Returns the number of element subtrees of an abstract tuple.

tuple_es(Node)

Returns the list of element subtrees of an abstract tuple.

type(Node)

Returns the type tag of Node.

unfold_literal(Node)

Ensures that literals have a fully expanded representation.

update_c_alias(Node, Variable, Pattern)

See also: c_alias/2.

update_c_apply(Node, Operator, Arguments)

See also: c_apply/2.

update_c_binary(Node, Segments)

See also: c_binary/1.

update_c_bitstr(Node, Value, Size, Type, Flags)

Equivalent to update_c_bitstr(Node, Value, Size, abstract(1), Type, Flags).

update_c_bitstr(Node, Value, Size, Unit, Type, Flags)

See also: c_bitstr/5, update_c_bitstr/5.

update_c_call(Node, Module, Name, Arguments)

See also: c_call/3.

update_c_case(Node, Argument, Clauses)

See also: c_case/2.

update_c_catch(Node, Body)

See also: c_catch/1.

update_c_clause(Node, Patterns, Guard, Body)

See also: c_clause/3.

update_c_cons(Node, Head, Tail)

See also: c_cons/2.

update_c_cons_skel(Node, Head, Tail)

See also: c_cons_skel/2.

update_c_fname(Node, Name)

Like update_c_fname/3, but takes the arity from Node.

update_c_fname(Node, Name, Arity)

Equivalent to update_c_var(Old, {Atom, Arity}).

update_c_fun(Node, Variables, Body)

See also: c_fun/2.

update_c_let(Node, Variables, Argument, Body)

See also: c_let/3.

update_c_letrec(Node, Definitions, Body)

See also: c_letrec/2.

update_c_map(Node, Map, Pairs)

See also: c_map/1, c_map_pattern/1.

update_c_map_pair(Node, Operation, Key, Value)

See also: c_map_pair/2, c_map_pair_exact/2.

update_c_module(Node, Name, Exports, Attributes, Definitions)

See also: c_module/4.

update_c_primop(Node, Name, Arguments)

See also: c_primop/2.

update_c_receive(Node, Clauses, Timeout, Action)

See also: c_receive/3.

update_c_record(Node, Arg, Id, Pairs)

See also: c_record/2.

update_c_record_pair(Node, Key, Value)

See also: c_record_pair/2.

update_c_seq(Node, Argument, Body)

See also: c_seq/2.

update_c_try(Node, Argument, Variables, Body, ExceptionVars, Handler)

See also: c_try/5.

update_c_tuple(Node, Elements)

See also: c_tuple/1.

update_c_tuple_skel(Node, Elements)

See also: c_tuple_skel/1.

update_c_values(Node, Elements)

See also: c_values/1.

update_c_var(Node, Name)

See also: c_var/1.

update_data(Node, Type, Elements)

See also: make_data/2.

update_data_skel(Node, Type, Elements)

See also: make_data_skel/2.

update_list(Node, List)

Equivalent to update_list(Old, List, none).

update_list(Node, List, Tail)

See also: make_list/2, update_list/2.

update_tree(Node, Groups)

Creates a syntax tree with the given subtrees, and the same type and annotations as the node Node.

update_tree(Node, Type, Groups)

Creates a syntax tree with the given type and subtrees, and the same annotations as the node Node.

values_arity(Node)

Returns the number of element subtrees of an abstract value list.

values_es(Node)

Returns the list of element subtrees of an abstract value list.

var_name(Node)

Returns the name of an abstract variable.

Types

c_alias()

(not exported)

-type c_alias() :: #c_alias{anno :: list(), var :: cerl:cerl(), pat :: cerl:cerl()}.

c_apply()

(not exported)

-type c_apply() :: #c_apply{anno :: list(), op :: cerl:cerl(), args :: [cerl:cerl()]}.

c_binary()

-type c_binary() :: #c_binary{anno :: list(), segments :: [cerl:c_bitstr()]}.

c_bitstr()

-type c_bitstr() ::
          #c_bitstr{anno :: list(),
                    val :: cerl:cerl(),
                    size :: cerl:cerl(),
                    unit :: cerl:cerl(),
                    type :: cerl:cerl(),
                    flags :: cerl:cerl()}.

c_call()

-type c_call() ::
          #c_call{anno :: list(), module :: cerl:cerl(), name :: cerl:cerl(), args :: [cerl:cerl()]}.

c_case()

(not exported)

-type c_case() :: #c_case{anno :: list(), arg :: cerl:cerl(), clauses :: [cerl:cerl()]}.

c_catch()

(not exported)

-type c_catch() :: #c_catch{anno :: list(), body :: cerl:cerl()}.

c_clause()

-type c_clause() ::
          #c_clause{anno :: list(),
                    pats :: [cerl:cerl()],
                    guard :: cerl:cerl(),
                    body :: cerl:cerl() | any()}.

c_cons()

-type c_cons() :: #c_cons{anno :: list(), hd :: cerl:cerl(), tl :: cerl:cerl()}.

c_fun()

-type c_fun() :: #c_fun{anno :: list(), vars :: [cerl:cerl()], body :: cerl:cerl()}.

c_lct()

(not exported)

-type c_lct() :: c_literal() | c_cons() | c_tuple().

c_let()

-type c_let() :: #c_let{anno :: list(), vars :: [cerl:cerl()], arg :: cerl:cerl(), body :: cerl:cerl()}.

c_letrec()

(not exported)

-type c_letrec() :: #c_letrec{anno :: list(), defs :: [{cerl:cerl(), cerl:cerl()}], body :: cerl:cerl()}.

c_literal()

-type c_literal() :: #c_literal{anno :: list(), val :: any()}.

c_map()

-type c_map() ::
          #c_map{anno :: list(),
                 arg :: cerl:c_var() | cerl:c_literal(),
                 es :: [cerl:c_map_pair()],
                 is_pat :: boolean()}.

c_map_pair()

-type c_map_pair() ::
          #c_map_pair{anno :: list(),
                      op ::
                          #c_literal{val :: assoc, anno :: list()} |
                          #c_literal{val :: exact, anno :: list()},
                      key :: any(),
                      val :: any()}.

c_module()

-type c_module() ::
          #c_module{anno :: list(),
                    name :: cerl:cerl(),
                    exports :: [cerl:cerl()],
                    attrs :: [{cerl:cerl(), cerl:cerl()}],
                    defs :: [{cerl:cerl(), cerl:cerl()}]}.

c_opaque()

(not exported)

-type c_opaque() :: #c_opaque{anno :: list(), val :: any()}.

c_primop()

(not exported)

-type c_primop() :: #c_primop{anno :: list(), name :: cerl:cerl(), args :: [cerl:cerl()]}.

c_receive()

(not exported)

-type c_receive() ::
          #c_receive{anno :: list(),
                     clauses :: [cerl:cerl()],
                     timeout :: cerl:cerl(),
                     action :: cerl:cerl()}.

c_record()

-type c_record() ::
          #c_record{anno :: list(),
                    arg :: cerl:c_var() | cerl:c_literal(),
                    id :: cerl:c_literal(),
                    es :: [cerl:c_record_pair()]}.

c_record_pair()

-type c_record_pair() :: #c_record_pair{anno :: list(), key :: cerl:c_literal(), val :: cerl:cerl()}.

c_seq()

(not exported)

-type c_seq() :: #c_seq{anno :: list(), arg :: cerl:cerl() | any(), body :: cerl:cerl()}.

c_try()

(not exported)

-type c_try() ::
          #c_try{anno :: list(),
                 arg :: cerl:cerl(),
                 vars :: [cerl:cerl()],
                 body :: cerl:cerl(),
                 evars :: [cerl:cerl()],
                 handler :: cerl:cerl()}.

c_tuple()

-type c_tuple() :: #c_tuple{anno :: list(), es :: [cerl:cerl()]}.

c_values()

-type c_values() :: #c_values{anno :: list(), es :: [cerl:cerl()]}.

c_var()

-type c_var() :: #c_var{anno :: list(), name :: cerl:var_name()}.

cerl()

-type cerl() ::
          c_alias() |
          c_apply() |
          c_binary() |
          c_bitstr() |
          c_call() |
          c_case() |
          c_catch() |
          c_clause() |
          c_cons() |
          c_fun() |
          c_let() |
          c_letrec() |
          c_literal() |
          c_map() |
          c_map_pair() |
          c_record() |
          c_record_pair() |
          c_module() |
          c_opaque() |
          c_primop() |
          c_receive() |
          c_seq() |
          c_try() |
          c_tuple() |
          c_values() |
          c_var().

ctype()

(not exported)

-type ctype() ::
          alias | apply | binary | bitstr | call | 'case' | 'catch' | clause | cons | 'fun' | 'let' |
          letrec | literal | map | map_pair | module | opaque | primop | 'receive' | seq | record |
          record_pair | 'try' | tuple | values | var.

dtype()

(not exported)

-type dtype() :: cons | tuple | {atomic, value()}.

map_op()

(not exported)

-type map_op() :: #c_literal{val :: assoc, anno :: list()} | #c_literal{val :: exact, anno :: list()}.

record_id()

(not exported)

-type record_id() :: c_literal().

value()

(not exported)

-type value() :: integer() | float() | atom() | [].

var_name()

-type var_name() :: integer() | atom() | {atom(), integer()}.

Functions

abstract(Term)

-spec abstract(Term :: term()) -> c_literal().

Creates a syntax tree corresponding to an Erlang term.

Term must be a literal term, that is, one that can be represented as a source code literal. Thus, it may not contain a process identifier, port, reference, binary or function value as a subterm.

Note: This is a constant time operation.

See also: ann_abstract/2, concrete/1, is_literal/1, is_literal_term/1.

add_ann(Annotations, Node)

-spec add_ann(Annotations :: [term()], Node :: cerl()) -> cerl().

Appends Annotations to the list of user annotations of Node.

Note: this is equivalent to set_ann(Node, Annotations ++ get_ann(Node)), but potentially more efficient.

See also: get_ann/1, set_ann/2.

alias_pat(Node)

-spec alias_pat(Node :: c_alias()) -> cerl().

Returns the pattern subtree of an abstract pattern alias.

See also: c_alias/2.

alias_var(Node)

-spec alias_var(Node :: c_alias()) -> c_var().

Returns the variable subtree of an abstract pattern alias.

See also: c_alias/2.

ann_abstract(Annotations, Term)

-spec ann_abstract(Annotations :: [term()], Term :: term()) -> c_literal().

See also: abstract/1.

ann_c_alias(Annotations, Variable, Pattern)

-spec ann_c_alias(Annotations :: [term()], Variable :: c_var(), Pattern :: cerl()) -> c_alias().

See also: c_alias/2.

ann_c_apply(Annotations, Operator, Arguments)

-spec ann_c_apply(Annotations :: [term()], Operator :: cerl(), Arguments :: [cerl()]) -> c_apply().

See also: c_apply/2.

ann_c_atom(Annotations, Name)

-spec ann_c_atom(Annotations :: [term()], Name :: atom() | string()) -> c_literal().

See also: c_atom/1.

ann_c_binary(Annotations, Segments)

-spec ann_c_binary(Annotations :: [term()], Segments :: [cerl()]) -> c_binary().

See also: c_binary/1.

ann_c_bitstr(Annotations, Value, Size, Type, Flags)

-spec ann_c_bitstr(Annotations :: [term()],
                   Value :: cerl(),
                   Size :: cerl(),
                   Type :: cerl(),
                   Flags :: cerl()) ->
                      c_bitstr().

Equivalent to ann_c_bitstr(As, Value, Size, abstract(1), Type, Flags).

ann_c_bitstr(Annotations, Value, Size, Unit, Type, Flags)

-spec ann_c_bitstr(Annotations :: [term()],
                   Value :: cerl(),
                   Size :: cerl(),
                   Unit :: cerl(),
                   Type :: cerl(),
                   Flags :: cerl()) ->
                      c_bitstr().

See also: ann_c_bitstr/5, c_bitstr/5.

ann_c_call(Annotations, Module, Name, Arguments)

-spec ann_c_call(Annotations :: [term()], Module :: cerl(), Name :: cerl(), Arguments :: [cerl()]) ->
                    c_call().

See also: c_call/3.

ann_c_case(Annotations, Argument, Clauses)

-spec ann_c_case(Annotations :: [term()], Argument :: cerl(), Clauses :: [cerl()]) -> c_case().

See also: c_case/2.

ann_c_catch(Annotations, Body)

-spec ann_c_catch(Annotations :: [term()], Body :: cerl()) -> c_catch().

See also: c_catch/1.

ann_c_char(Annotations, Value)

-spec ann_c_char(Annotations :: [term()], Value :: char()) -> c_literal().

See also: c_char/1.

ann_c_clause(Annotations, Patterns, Body)

-spec ann_c_clause(Annotations :: [term()], Patterns :: [cerl()], Body :: cerl()) -> c_clause().

Equivalent to ann_c_clause(As, Patterns, c_atom(true), Body).

See also: c_clause/3.

ann_c_clause(Annotations, Patterns, Guard, Body)

-spec ann_c_clause(Annotations :: [term()], Patterns :: [cerl()], Guard :: cerl(), Body :: cerl()) ->
                      c_clause().

See also: ann_c_clause/3, c_clause/3.

ann_c_cons(Annotations, Head, Tail)

-spec ann_c_cons(Annotations :: [term()], Head :: cerl(), Tail :: cerl()) -> c_literal() | c_cons().

See also: c_cons/2.

ann_c_cons_skel(Annotations, Head, Tail)

-spec ann_c_cons_skel(Annotations :: [term()], Head :: cerl(), Tail :: cerl()) -> c_cons().

See also: c_cons_skel/2.

ann_c_float(Annotations, Value)

-spec ann_c_float(Annotations :: [term()], Value :: float()) -> c_literal().

See also: c_float/1.

ann_c_fname(Annotations, Name, Arity)

-spec ann_c_fname(Annotations :: [term()], Name :: atom(), Arity :: arity()) -> c_var().

Equivalent to ann_c_var(As, {Atom, Arity}).

See also: c_fname/2.

ann_c_fun(Annotations, Variables, Body)

-spec ann_c_fun(Annotations :: [term()], Variables :: [cerl()], Body :: cerl()) -> c_fun().

See also: c_fun/2.

ann_c_int(Annotations, Value)

-spec ann_c_int(Annotations :: [term()], Value :: integer()) -> c_literal().

See also: c_int/1.

ann_c_let(Annotations, Variables, Argument, Body)

-spec ann_c_let(Annotations :: [term()], Variables :: [cerl()], Argument :: cerl(), Body :: cerl()) ->
                   c_let().

See also: c_let/3.

ann_c_letrec(Annotations, Definitions, Body)

-spec ann_c_letrec(Annotations :: [term()], Definitions :: [{cerl(), cerl()}], Body :: cerl()) ->
                      c_letrec().

See also: c_letrec/2.

ann_c_map(Annotations, Pairs)

(since OTP 17.0)

-spec ann_c_map(Annotations :: [term()], Pairs :: [c_map_pair()]) -> c_map() | c_literal().

See also: c_map/1.

ann_c_map(Annotations, Argument, Pairs)

(since OTP 17.0)

-spec ann_c_map(Annotations :: [term()], Argument :: c_map() | c_literal(), Pairs :: [c_map_pair()]) ->
                   c_map() | c_literal().

See also: c_map/2

ann_c_map_pair(Annotations, Operation, Key, Value)

(since OTP 17.0)

-spec ann_c_map_pair(Annotations :: [term()], Operation :: cerl(), Key :: cerl(), Value :: cerl()) ->
                        c_map_pair().

See also: c_map_pair/2, c_map_pair_exact/2.

ann_c_map_pattern(Annotations, Pairs)

(since OTP 17.0)

-spec ann_c_map_pattern(Annotations :: [term()], Pairs :: [c_map_pair()]) -> c_map().

See also: c_map_pattern/2

ann_c_module(Annotations, Name, Exports, Definitions)

-spec ann_c_module(Annotations :: [term()],
                   Name :: cerl(),
                   Exports :: [cerl()],
                   Definitions :: [{cerl(), cerl()}]) ->
                      c_module().

See also: ann_c_module/5, c_module/3.

ann_c_module(Annotations, Name, Exports, Attributes, Definitions)

-spec ann_c_module(Annotations :: [term()],
                   Name :: cerl(),
                   Exports :: [cerl()],
                   Attributes :: [{cerl(), cerl()}],
                   Definitions :: [{cerl(), cerl()}]) ->
                      c_module().

See also: ann_c_module/4, c_module/4.

ann_c_nil(Annotations)

-spec ann_c_nil(Annotations :: [term()]) -> c_literal().

See also: c_nil/0.

ann_c_primop(Annotations, Name, Arguments)

-spec ann_c_primop(Annotations :: [term()], Name :: cerl(), Arguments :: [cerl()]) -> c_primop().

See also: c_primop/2.

ann_c_receive(Annotations, Clauses)

-spec ann_c_receive(Annotations :: [term()], Clauses :: [cerl()]) -> c_receive().

Equivalent to ann_c_receive(As, Clauses, c_atom(infinity), c_atom(true)).

See also: c_atom/1, c_receive/3.

ann_c_receive(Annotations, Clauses, Timeout, Actions)

-spec ann_c_receive(Annotations :: [term()], Clauses :: [cerl()], Timeout :: cerl(), Actions :: cerl()) ->
                       c_receive().

See also: ann_c_receive/2, c_receive/3.

ann_c_record(Annotations, Argument, Id, Pairs)

(since OTP @OTP-19785@)

-spec ann_c_record(Annotations :: [term()],
                   Argument :: c_var() | c_record() | c_literal(),
                   Id :: term(),
                   Pairs :: [c_record_pair()]) ->
                      #c_record{anno :: list(),
                                arg :: cerl:c_var() | cerl:c_literal(),
                                id :: cerl:c_literal(),
                                es :: [cerl:c_record_pair()]}.

See also: c_record/2.

ann_c_record_pair(Annotations, Key, Value)

(since OTP @OTP-19785@)

-spec ann_c_record_pair(Annotations :: [term()], Key :: cerl(), Value :: cerl()) -> c_record_pair().

See also: c_record/2.

ann_c_seq(Annotations, Argument, Body)

-spec ann_c_seq(Annotations :: [term()], Argument :: cerl(), Body :: cerl()) -> c_seq().

See also: c_seq/2.

ann_c_string(Annotations, Value)

-spec ann_c_string(Annotations :: [term()], Value :: string()) -> c_literal().

See also: c_string/1.

ann_c_try(Annotations, Argument, Variables, Body, ExceptionVars, Handler)

-spec ann_c_try(Annotations :: [term()],
                Argument :: cerl(),
                Variables :: [cerl()],
                Body :: cerl(),
                ExceptionVars :: [cerl()],
                Handler :: cerl()) ->
                   c_try().

See also: c_try/5.

ann_c_tuple(Annotations, Elements)

-spec ann_c_tuple(Annotations :: [term()], Elements :: [cerl()]) -> c_tuple() | c_literal().

See also: c_tuple/1.

ann_c_tuple_skel(Annotations, Elements)

-spec ann_c_tuple_skel(Annotations :: [term()], Elements :: [cerl()]) -> c_tuple().

See also: c_tuple_skel/1.

ann_c_values(Annotations, Values)

-spec ann_c_values(Annotations :: [term()], Values :: [cerl()]) -> c_values().

See also: c_values/1.

ann_c_var(Annotations, Name)

-spec ann_c_var(Annotations :: [term()], Name :: var_name()) -> c_var().

See also: c_var/1.

ann_make_data(Annotations, Type, Elementes)

-spec ann_make_data(Annotations :: [term()], Type :: dtype(), Elementes :: [cerl()]) -> c_lct().

See also: make_data/2.

ann_make_data_skel(Annotations, Type, Elements)

-spec ann_make_data_skel(Annotations :: [term()], Type :: dtype(), Elements :: [cerl()]) -> c_lct().

See also: make_data_skel/2.

ann_make_list(Annotations, List)

-spec ann_make_list(Annotations :: [term()], List :: [cerl()]) -> cerl().

Equivalent to ann_make_list(As, List, none).

ann_make_list(Annotations, List, Tail)

-spec ann_make_list(Annotations :: [term()], List :: [cerl()], Tail :: cerl() | none) -> cerl().

See also: ann_make_list/2, make_list/2.

ann_make_tree(Annotations, Type, Groups)

-spec ann_make_tree(Annotations :: [term()], Type :: ctype(), Groups :: [[cerl()], ...]) -> cerl().

Creates a syntax tree with the given annotations, type and subtrees.

See make_tree/2 for details.

See also: make_tree/2.

apply_args(Node)

-spec apply_args(Node :: c_apply()) -> [cerl()].

Returns the list of argument subtrees of an abstract function application.

See also: apply_arity/1, c_apply/2.

apply_arity(Node)

-spec apply_arity(Node :: c_apply()) -> arity().

Returns the number of argument subtrees of an abstract function application.

Note: this is equivalent to length(apply_args(Node)), but potentially more efficient.

See also: apply_args/1, c_apply/2.

apply_op(Node)

-spec apply_op(Node :: c_apply()) -> cerl().

Returns the operator subtree of an abstract function application.

See also: c_apply/2.

atom_lit(Node)

-spec atom_lit(Node :: cerl()) -> nonempty_string().

Returns the literal string represented by an abstract atom. This always includes surrounding single-quote characters.

Note that an abstract atom may have several literal representations, and that the representation yielded by this function is not fixed; for example, atom_lit(c_atom("a\012b")) could yield the string "\'a\\nb\'".

See also: c_atom/1.

atom_name(Node)

-spec atom_name(Node :: c_literal()) -> string().

Returns the printname of an abstract atom.

See also: c_atom/1.

atom_val(Node)

-spec atom_val(Node :: c_literal()) -> atom().

Returns the value represented by an abstract atom.

See also: c_atom/1.

binary_segments(Node)

-spec binary_segments(Node :: c_binary()) -> [cerl()].

Returns the list of segment subtrees of an abstract binary-template.

See also: c_binary/1, c_bitstr/5.

bitstr_bitsize(Node)

-spec bitstr_bitsize(Node :: c_bitstr()) -> all | any | utf | non_neg_integer().

Returns the total size in bits of an abstract bit-string template.

If the size field is an integer literal, the result is the product of the size and unit values; if the size field is the atom literal all, the atom all is returned. If the size is not a literal, the atom any is returned. If the type of the bit-string segment is one of utf8, utf16 or utf32, the atom utf is returned.

See also: c_bitstr/5.

bitstr_flags(Node)

-spec bitstr_flags(Node :: c_bitstr()) -> cerl().

Returns the flags subtree of an abstract bit-string template.

See also: c_bitstr/5.

bitstr_size(Node)

-spec bitstr_size(Node :: c_bitstr()) -> cerl().

Returns the size subtree of an abstract bit-string template.

See also: c_bitstr/5.

bitstr_type(Node)

-spec bitstr_type(Node :: c_bitstr()) -> cerl().

Returns the type subtree of an abstract bit-string template.

See also: c_bitstr/5.

bitstr_unit(Node)

-spec bitstr_unit(Node :: c_bitstr()) -> cerl().

Returns the unit subtree of an abstract bit-string template.

See also: c_bitstr/5.

bitstr_val(Node)

-spec bitstr_val(Node :: c_bitstr()) -> cerl().

Returns the value subtree of an abstract bit-string template.

See also: c_bitstr/5.

c_alias(Variable, Pattern)

-spec c_alias(Variable :: c_var(), Pattern :: cerl()) -> c_alias().

Creates an abstract pattern alias.

The result represents "Variable = Pattern".

See also: alias_pat/1, alias_var/1, ann_c_alias/3, c_clause/3, is_c_alias/1, update_c_alias/3.

c_apply(Operator, Arguments)

-spec c_apply(Operator :: cerl(), Arguments :: [cerl()]) -> c_apply().

Creates an abstract function application.

If Arguments is [A1, ..., An], the result represents "apply Operator(A1, ..., An)".

See also: ann_c_apply/3, apply_args/1, apply_arity/1, apply_op/1, c_call/3, c_primop/2, is_c_apply/1, update_c_apply/3.

c_atom(Name)

-spec c_atom(Name :: atom() | string()) -> c_literal().

Creates an abstract atom literal.

The print name of the atom is the character sequence represented by Name.

Note: passing a string as argument to this function causes a corresponding atom to be created for the internal representation.

See also: ann_c_atom/2, atom_lit/1, atom_name/1, atom_val/1, is_c_atom/1.

c_binary(Segments)

-spec c_binary(Segments :: [cerl()]) -> c_binary().

Creates an abstract binary-template.

A binary object is in this context is a sequence of an arbitrary number of bits. (The number of bits used to be evenly divisible by 8, but after the introduction of bit strings in the Erlang language, the choice was made to use the binary template for all bit strings.) It is specified by zero or more bit-string template segments of arbitrary lengths (in number of bits).

If Segments is [S1, ..., Sn], the result represents "#{S1, ..., Sn}#". All the Si must have type bitstr.

See also: ann_c_binary/2, binary_segments/1, c_bitstr/5, is_c_binary/1, update_c_binary/2.

c_bitstr(Value, Type, Flags)

-spec c_bitstr(Value :: cerl(), Type :: cerl(), Flags :: cerl()) -> c_bitstr().

Equivalent to c_bitstr(Value, abstract(all), abstract(1), Type, Flags).

c_bitstr(Value, Size, Type, Flags)

-spec c_bitstr(Value :: cerl(), Size :: cerl(), Type :: cerl(), Flags :: cerl()) -> c_bitstr().

Equivalent to c_bitstr(Value, Size, abstract(1), Type, Flags).

c_bitstr(Value, Size, Unit, Type, Flags)

-spec c_bitstr(Value :: cerl(), Size :: cerl(), Unit :: cerl(), Type :: cerl(), Flags :: cerl()) ->
                  c_bitstr().

Creates an abstract bit-string template.

These can only occur as components of an abstract binary-template (see c_binary/1). The result represents "#<Value>(Size, Unit, Type, Flags)", where Unit must represent a positive integer constant, Type must represent a constant atom (one of 'integer', 'float', 'binary', 'utf8', 'utf16' or 'utf32'), and Flags must represent a constant list "[F1, ..., Fn]" where all the Fi are atoms.

See also: ann_c_bitstr/6, bitstr_flags/1, bitstr_size/1, bitstr_type/1, bitstr_unit/1, bitstr_val/1, c_binary/1, is_c_bitstr/1, update_c_bitstr/6.

c_call(Module, Name, Arguments)

-spec c_call(Module :: cerl(), Name :: cerl(), Arguments :: [cerl()]) -> c_call().

Creates an abstract inter-module call.

If Arguments is [A1, ..., An], the result represents "call Module:Name(A1, ..., An)".

See also: ann_c_call/4, c_apply/2, c_primop/2, call_args/1, call_arity/1, call_module/1, call_name/1, is_c_call/1, update_c_call/4.

c_case(Argument, Clauses)

-spec c_case(Argument :: cerl(), Clauses :: [cerl()]) -> c_case().

Creates an abstract case-expression.

If Clauses is [C1, ..., Cn], the result represents "case Argument of C1 ... Cn end". Clauses must not be empty.

See also: ann_c_case/3, c_clause/3, case_arg/1, case_arity/1, case_clauses/1, is_c_case/1, update_c_case/3.

c_catch(Body)

-spec c_catch(Body :: cerl()) -> c_catch().

Creates an abstract catch-expression.

The result represents "catch Body".

Note: catch-expressions can be rewritten as try-expressions, and will eventually be removed from Core Erlang.

See also: ann_c_catch/2, c_try/5, catch_body/1, is_c_catch/1, update_c_catch/2.

c_char(Value)

-spec c_char(Value :: non_neg_integer()) -> c_literal().

Creates an abstract character literal.

If the local implementation of Erlang defines char/0 as a subset of integer/0, this function is equivalent to c_int/1. Otherwise, if the given value is an integer, it will be converted to the character with the corresponding code. The lexical representation of a character is "$Char", where Char is a single printing character or an escape sequence.

See also: ann_c_char/2, c_int/1, c_string/1, char_lit/1, char_val/1, is_c_char/1, is_print_char/1.

c_clause(Patterns, Body)

-spec c_clause(Patterns :: [cerl()], Body :: cerl()) -> c_clause().

Equivalent to c_clause(Patterns, c_atom(true), Body).

See also: c_atom/1.

c_clause(Patterns, Guard, Body)

-spec c_clause(Patterns :: [cerl()], Guard :: cerl(), Body :: cerl()) -> c_clause().

Creates an an abstract clause.

If Patterns is [P1, ..., Pn], the result represents "<P1, ..., Pn> when Guard -> Body".

See also: ann_c_clause/4, c_case/2, c_clause/2, c_receive/3, clause_arity/1, clause_body/1, clause_guard/1, clause_pats/1, clause_vars/1, is_c_clause/1, update_c_clause/4.

c_cons(Head, Tail)

-spec c_cons(Head :: cerl(), Tail :: cerl()) -> c_literal() | c_cons().

Creates an abstract list constructor.

The result represents "[Head | Tail]". Note that if both Head and Tail have type literal, then the result will also have type literal, and annotations on Head and Tail are lost.

Recall that in Erlang, the tail element of a list constructor is not necessarily a list.

See also: ann_c_cons/3, c_cons_skel/2, c_nil/0, cons_hd/1, cons_tl/1, is_c_cons/1, is_c_list/1, list_elements/1, list_length/1, make_list/2, update_c_cons/3.

c_cons_skel(Head, Tail)

-spec c_cons_skel(Head :: cerl(), Tail :: cerl()) -> c_cons().

Creates an abstract list constructor skeleton.

Does not fold constant literals, that is, the result always has type cons, representing "[Head | Tail]".

This function is occasionally useful when it is necessary to have annotations on the subnodes of a list constructor node, even when the subnodes are constant literals. However, note that is_literal/1 will yield false and concrete/1 will fail if passed the result from this function.

fold_literal/1 can be used to revert a node to the normal-form representation.

See also: ann_c_cons_skel/3, c_cons/2, c_nil/0, concrete/1, fold_literal/1, is_c_cons/1, is_c_list/1, is_literal/1, update_c_cons_skel/3.

c_float(Value)

-spec c_float(Value :: float()) -> c_literal().

Creates an abstract floating-point literal.

The lexical representation is the decimal floating-point numeral of Value.

See also: ann_c_float/2, float_lit/1, float_val/1, is_c_float/1.

c_fname(Name, Arity)

-spec c_fname(Name :: atom(), Arity :: arity()) -> c_var().

Equivalent to c_var({Name, Arity}).

See also: ann_c_fname/3, fname_arity/1, fname_id/1, is_c_fname/1, update_c_fname/3.

c_fun(Variables, Body)

-spec c_fun(Variables :: [cerl()], Body :: cerl()) -> c_fun().

Creates an abstract fun-expression.

If Variables is [V1, ..., Vn], the result represents "fun (V1, ..., Vn) -> Body". All the Vi must have type var.

See also: ann_c_fun/3, fun_arity/1, fun_body/1, fun_vars/1, is_c_fun/1, update_c_fun/3.

c_int(Value)

-spec c_int(Value :: integer()) -> c_literal().

Creates an abstract integer literal.

The lexical representation is the canonical decimal numeral of Value.

See also: ann_c_int/2, c_char/1, int_lit/1, int_val/1, is_c_int/1.

c_let(Variables, Argument, Body)

-spec c_let(Variables :: [cerl()], Argument :: cerl(), Body :: cerl()) -> c_let().

Creates an abstract let-expression.

If Variables is [V1, ..., Vn], the result represents "let <V1, ..., Vn> = Argument in Body". All the Vi must have type var.

See also: ann_c_let/4, is_c_let/1, let_arg/1, let_arity/1, let_body/1, let_vars/1, update_c_let/4.

c_letrec(Definitions, Body)

-spec c_letrec(Definitions :: [{cerl(), cerl()}], Body :: cerl()) -> c_letrec().

Creates an abstract letrec-expression.

If Definitions is [{V1, F1}, ..., {Vn, Fn}], the result represents "letrec V1 = F1 ... Vn = Fn in Body". All the Vi must have type var and represent function names. All the Fi must have type 'fun'.

See also: ann_c_letrec/3, is_c_letrec/1, letrec_body/1, letrec_defs/1, letrec_vars/1, update_c_letrec/3.

c_map(Pairs)

(since OTP 17.0)

-spec c_map(Pairs :: [c_map_pair()]) -> c_map().

Creates an abstract map constructor.

If Pairs is [E1, ..., EN], the result represents "~{E1, ..., EN}~" (creating a new map). Note that if all pairs in Pairs have type literal for both the key and the value, or if Pairs is empty, then the result will also have type literal and annotations on nodes in Pairs are lost.

All Ei must be abstract pairs constructed by c_map_pair/2.

See also: ann_c_map/2, is_c_map/1, is_c_map_empty/1, is_c_map_pattern/1, map_es/1, c_map_pair/2, c_map_pair_exact/2.

c_map(Argument, Pairs)

(since OTP 27.0)

-spec c_map(Argument :: cerl(), Pairs :: [c_map_pair()]) -> c_map().

Creates an abstract map update expression.

If Pairs is [E1, ..., EN], the result represents "~{E1, ..., EN | Argument}~" (updating an existing map). Note that if Argument is a literal and all pairs in Pairs have type literal for both the key and the value, or if Pairs is empty, then the result will also have type literal and annotations on nodes in Pairs are lost.

All Ei must be abstract pairs constructed by either c_map_pair/2 or c_map_pair_exact/2.

See also: ann_c_map/2, is_c_map/1, is_c_map_empty/1, is_c_map_pattern/1, map_es/1, c_map_pair/2, c_map_pair_exact/2.

c_map_pair(Key, Value)

(since OTP 17.0)

-spec c_map_pair(Key :: cerl(), Value :: cerl()) -> c_map_pair().

Creates an abstract map pair using the assoc operator.

These can only occur as components of an abstract map creation expression or an abstract update expression (see c_map/1 and c_map/2).

The result represents "Key => Value".

See also: map_pair_key/1, map_pair_op/1, map_pair_val/1.

c_map_pair_exact(Key, Value)

(since OTP 17.0)

-spec c_map_pair_exact(Key :: cerl(), Value :: cerl()) -> c_map_pair().

Creates an abstract map pair using the exact operator.

These can only occur as components of an abstract map update expression or an abstract map pattern (see c_map/1 and c_map_pattern/1).

The result represents "Key := Value".

See also: map_pair_key/1, map_pair_op/1, map_pair_val/1.

c_map_pattern(Pairs)

(since OTP 17.0)

-spec c_map_pattern(Pairs :: [c_map_pair()]) -> c_map().

Creates an abstract map pattern.

If Pairs is [E1, ..., EN], the result represents "~{E1, ..., EN}~".

All Ei must be abstract pairs constructed by c_map_pair_exact/2.

See also: ann_c_map/2, is_c_map/1, is_c_map_empty/1, is_c_map_pattern/1, map_es/1, c_map_pair_exact/2.

c_module(Name, Exports, Definitions)

-spec c_module(Name :: cerl(), Exports :: [cerl()], Definitions :: [{cerl(), cerl()}]) -> c_module().

Equivalent to c_module(Name, Exports, [], Definitions).

c_module(Name, Exports, Attributes, Definitions)

-spec c_module(Name :: cerl(),
               Exports :: [cerl()],
               Attributes :: [{cerl(), cerl()}],
               Definitions :: [{cerl(), cerl()}]) ->
                  c_module().

Creates an abstract module definition.

The result represents

    module Name [E1, ..., Ek]
      attributes [K1 = T1, ...,
                  Km = Tm]
      V1 = F1
      ...
      Vn = Fn
    end

if Exports = [E1, ..., Ek], Attributes = [{K1, T1}, ..., {Km, Tm}], and Definitions = [{V1, F1}, ..., {Vn, Fn}].

Name and all the Ki must be atom literals, and all the Ti must be constant literals. All the Vi and Ei must have type var and represent function names. All the Fi must have type 'fun'.

See also: ann_c_module/4, ann_c_module/5, c_atom/1, c_fun/2, c_module/3, c_var/1, is_literal/1, module_attrs/1, module_defs/1, module_exports/1, module_name/1, module_vars/1, update_c_module/5.

c_nil()

-spec c_nil() -> c_literal().

Creates an abstract empty list.

The result represents "[]". The empty list is traditionally called "nil".

See also: ann_c_nil/1, c_cons/2, is_c_list/1.

c_primop(Name, Arguments)

-spec c_primop(Name :: cerl(), Arguments :: [cerl()]) -> c_primop().

Creates an abstract primitive operation call.

If Arguments is [A1, ..., An], the result represents "primop Name(A1, ..., An)". Name must be an atom literal.

See also: ann_c_primop/3, c_apply/2, c_call/3, is_c_primop/1, primop_args/1, primop_arity/1, primop_name/1, update_c_primop/3.

c_receive(Clauses)

-spec c_receive(Clauses :: [cerl()]) -> c_receive().

Equivalent to c_receive(Clauses, c_atom(infinity), c_atom(true)).

See also: c_atom/1.

c_receive(Clauses, Timeout, Action)

-spec c_receive(Clauses :: [cerl()], Timeout :: cerl(), Action :: cerl()) -> c_receive().

Creates an abstract receive-expression.

If Clauses is [C1, ..., Cn], the result represents "receive C1 ... Cn after Timeout -> Action end".

See also: ann_c_receive/4, c_receive/1, is_c_receive/1, receive_action/1, receive_clauses/1, receive_timeout/1, update_c_receive/4.

c_record(Argument, Pairs)

(since OTP @OTP-19785@)

-spec c_record(Argument :: record_id(), Pairs :: [c_record_pair()]) ->
                  #c_record{anno :: list(),
                            arg :: cerl:c_var() | cerl:c_literal(),
                            id :: cerl:c_literal(),
                            es :: [cerl:c_record_pair()]}.

Creates an abstract record constructor.

See also: ann_c_record/3, is_c_record/1, record_id/1, record_es/1, c_record_pair/2, update_c_record/4.

c_record_pair(Key, Value)

(since OTP @OTP-19785@)

-spec c_record_pair(Key :: c_literal(), Value :: cerl()) -> c_record_pair().

Creates an abstract record pair.

These can only occur as components of an abstract record creation expression or an abstract update expression (see c_record/2).

The result represents "Key = Value".

See also: ann_c_record_pair/3, record_pair_key/1, record_pair_val/1.

c_seq(Argument, Body)

-spec c_seq(Argument :: cerl(), Body :: cerl()) -> c_seq().

Creates an abstract sequencing expression.

The result represents "do Argument Body".

See also: ann_c_seq/3, is_c_seq/1, seq_arg/1, seq_body/1, update_c_seq/3.

c_string(Value)

-spec c_string(Value :: string()) -> c_literal().

Creates an abstract string literal.

Equivalent to creating an abstract list of the corresponding character literals (cf. is_c_string/1), but is typically more efficient. The lexical representation of a string is ""Chars"", where Chars is a sequence of printing characters or spaces.

See also: ann_c_string/2, c_char/1, is_c_string/1, is_print_string/1, string_lit/1, string_val/1.

c_try(Argument, Variables, Body, ExceptionVars, Handler)

-spec c_try(Argument :: cerl(),
            Variables :: [cerl()],
            Body :: cerl(),
            ExceptionVars :: [cerl()],
            Handler :: cerl()) ->
               c_try().

Creates an abstract try-expression.

If Variables is [V1, ..., Vn] and ExceptionVars is [X1, ..., Xm], the result represents "try Argument of <V1, ..., Vn> -> Body catch <X1, ..., Xm> -> Handler". All the Vi and Xi must have type var.

See also: ann_c_try/6, c_catch/1, is_c_try/1, try_arg/1, try_body/1, try_vars/1, update_c_try/6.

c_tuple(Elements)

-spec c_tuple(Elements :: [cerl()]) -> c_tuple() | c_literal().

Creates an abstract tuple.

If Elements is [E1, ..., En], the result represents "{E1, ..., En}". Note that if all nodes in Elements have type literal, or if Elements is empty, then the result will also have type literal and annotations on nodes in Elements are lost.

Recall that Erlang has distinct 1-tuples, that is, {X} is always distinct from X itself.

See also: ann_c_tuple/2, c_tuple_skel/1, is_c_tuple/1, tuple_arity/1, tuple_es/1, update_c_tuple/2.

c_tuple_skel(Elements)

-spec c_tuple_skel(Elements :: [cerl()]) -> c_tuple().

Creates an abstract tuple skeleton.

Does not fold constant literals, that is, the result always has type tuple, representing "{E1, ..., En}", if Elements is [E1, ..., En].

This function is occasionally useful when it is necessary to have annotations on the subnodes of a tuple node, even when all the subnodes are constant literals. However, note that is_literal/1 will yield false and concrete/1 will fail if passed the result from this function.

fold_literal/1 can be used to revert a node to the normal-form representation.

See also: ann_c_tuple_skel/2, c_tuple/1, concrete/1, fold_literal/1, is_c_tuple/1, is_literal/1, tuple_es/1, update_c_tuple_skel/2.

c_values(Elements)

-spec c_values(Elements :: [cerl()]) -> c_values().

Creates an abstract value list.

If Elements is [E1, ..., En], the result represents "<E1, ..., En>".

See also: ann_c_values/2, is_c_values/1, update_c_values/2, values_arity/1, values_es/1.

c_var(Name)

-spec c_var(Name :: var_name()) -> c_var().

Creates an abstract variable.

A variable is identified by its name, given by the Name parameter.

If a name is given by a single atom, it should either be a "simple" atom which does not need to be single-quoted in Erlang, or otherwise its print name should correspond to a proper Erlang variable, that is, begin with an uppercase character or an underscore. Names of the form {A, N} represent function name variables "A/N"; these are special variables which may be bound only in the function definitions of a module or a letrec. They may not be bound in let expressions and cannot occur in clause patterns. The atom A in a function name may be any atom; the integer N must be nonnegative. The functions c_fname/2 etc. are utilities for handling function name variables.

When printing variable names, they must have the form of proper Core Erlang variables and function names. E.g., a name represented by an integer such as 42 could be formatted as "_42", an atom 'Xxx' simply as "Xxx", and an atom foo as "_foo". However, one must assure that any two valid distinct names are never mapped to the same strings. Tuples such as {foo, 2} representing function names can simply by formatted as "'foo'/2", with no risk of conflicts.

See also: ann_c_var/2, c_fname/2, c_letrec/2, c_module/4, is_c_var/1, update_c_var/2, var_name/1.

call_args(Node)

-spec call_args(Node :: c_call()) -> [cerl()].

Returns the list of argument subtrees of an abstract inter-module call.

See also: c_call/3, call_arity/1.

call_arity(Node)

-spec call_arity(Node :: c_call()) -> arity().

Returns the number of argument subtrees of an abstract inter-module call.

Note: this is equivalent to length(call_args(Node)), but potentially more efficient.

See also: c_call/3, call_args/1.

call_module(Node)

-spec call_module(Node :: c_call()) -> cerl().

Returns the module subtree of an abstract inter-module call.

See also: c_call/3.

call_name(Node)

-spec call_name(Node :: c_call()) -> cerl().

Returns the name subtree of an abstract inter-module call.

See also: c_call/3.

case_arg(Node)

-spec case_arg(Node :: c_case()) -> cerl().

Returns the argument subtree of an abstract case-expression.

See also: c_case/2.

case_arity(Node)

-spec case_arity(Node :: c_case()) -> non_neg_integer().

Equivalent to clause_arity(hd(case_clauses(Node))), but potentially more efficient.

See also: c_case/2, case_clauses/1, clause_arity/1.

case_clauses(Node)

-spec case_clauses(Node :: c_case()) -> [cerl()].

Returns the list of clause subtrees of an abstract case-expression.

See also: c_case/2, case_arity/1.

catch_body(Node)

-spec catch_body(Node :: c_catch()) -> cerl().

Returns the body subtree of an abstract catch-expression.

See also: c_catch/1.

char_lit(Node)

-spec char_lit(Node :: c_literal()) -> nonempty_string().

Returns the literal string represented by an abstract character. This includes a leading $ character.

Currently, all characters that are not in the set of ISO 8859-1 (Latin-1) "printing" characters will be escaped.

See also: c_char/1.

char_val(Node)

-spec char_val(Node :: c_literal()) -> char().

Returns the value represented by an abstract character literal.

See also: c_char/1.

clause_arity(Node)

-spec clause_arity(Node :: c_clause()) -> non_neg_integer().

Returns the number of pattern subtrees of an abstract clause.

Note: this is equivalent to length(clause_pats(Node)), but potentially more efficient.

See also: c_clause/3, clause_pats/1.

clause_body(Node)

-spec clause_body(Node :: c_clause()) -> cerl().

Returns the body subtree of an abstract clause.

See also: c_clause/3.

clause_guard(Node)

-spec clause_guard(Node :: c_clause()) -> cerl().

Returns the guard subtree of an abstract clause.

See also: c_clause/3.

clause_pats(Node)

-spec clause_pats(Node :: c_clause()) -> [cerl()].

Returns the list of pattern subtrees of an abstract clause.

See also: c_clause/3, clause_arity/1.

clause_vars(Node)

-spec clause_vars(Node :: c_clause()) -> [cerl()].

Returns the list of all abstract variables in the patterns of an abstract clause.

The order of listing is not defined.

See also: c_clause/3, pat_list_vars/1.

concrete(Node)

-spec concrete(Node :: c_literal()) -> term().

Returns the Erlang term represented by a syntax tree.

An exception is thrown if Node does not represent a literal term.

Note: This is a constant time operation.

See also: abstract/1, is_literal/1.

cons_hd(Node)

-spec cons_hd(Node :: c_cons() | c_literal()) -> cerl().

Returns the head subtree of an abstract list constructor.

See also: c_cons/2.

cons_tl(Node)

-spec cons_tl(Node :: c_cons() | c_literal()) -> cerl().

Returns the tail subtree of an abstract list constructor.

Recall that the tail does not necessarily represent a proper list.

See also: c_cons/2.

copy_ann(Source, Target)

-spec copy_ann(Source :: cerl(), Target :: cerl()) -> cerl().

Copies the list of user annotations from Source to Target.

Note: this is equivalent to set_ann(Target, get_ann(Source)), but potentially more efficient.

See also: get_ann/1, set_ann/2.

data_arity(Node)

-spec data_arity(Node :: c_lct()) -> non_neg_integer().

Returns the number of subtrees of a data constructor node.

This is equivalent to length(data_es(Node)), but potentially more efficient.

See also: data_es/1, is_data/1.

data_es(Node)

-spec data_es(Node :: c_lct()) -> [cerl()].

Returns the list of subtrees of a data constructor node.

If the arity of the constructor is zero, the result is the empty list.

Note: if data_type(Node) is cons, the number of subtrees is exactly two. If data_type(Node) is {atomic, Value}, the number of subtrees is zero.

See also: data_arity/1, data_type/1, is_data/1, make_data/2.

data_type(Node)

-spec data_type(Node :: c_lct()) -> dtype().

Returns a type descriptor for a data constructor node. (Cf. is_data/1.)

This is mainly useful for comparing types and for constructing new nodes of the same type (cf. make_data/2). If Node represents an integer, floating-point number, atom or empty list, the result is {atomic, Value}, where Value is the value of concrete(Node), otherwise the result is either cons or tuple.

Type descriptors can be compared for equality or order (in the Erlang term order), but remember that floating-point values should in general never be tested for equality.

See also: concrete/1, is_data/1, make_data/2, type/1.

float_lit(Node)

-spec float_lit(Node :: c_literal()) -> string().

Returns the numeral string represented by a floating-point literal node.

See also: c_float/1.

float_val(Node)

-spec float_val(Node :: c_literal()) -> float().

Returns the value represented by a floating-point literal node.

See also: c_float/1.

fname_arity(Node)

-spec fname_arity(Node :: c_var()) -> arity().

Returns the arity part of an abstract function name variable.

See also: c_fname/2, fname_id/1.

fname_id(Node)

-spec fname_id(Node :: c_var()) -> atom().

Returns the identifier part of an abstract function name variable.

See also: c_fname/2, fname_arity/1.

fold_literal(Node)

-spec fold_literal(Node :: cerl()) -> cerl().

Ensures that literals have a compact representation.

This is occasionally useful if c_cons_skel/2, c_tuple_skel/1 or unfold_literal/1 were used in the construction of Node, and you want to revert to the normal "folded" representation of literals. If Node represents a tuple or list constructor, its elements are rewritten recursively, and the node is reconstructed using c_cons/2 or c_tuple/1, respectively; otherwise, Node is not changed.

See also: c_cons/2, c_cons_skel/2, c_tuple/1, c_tuple_skel/1, is_literal/1, unfold_literal/1.

from_records(Node)

-spec from_records(Node :: cerl()) -> cerl().

Translates an explicit record representation to a corresponding abstract syntax tree.

The records are defined in the file "core_parse.hrl".

See also: to_records/1, type/1.

fun_arity(Node)

-spec fun_arity(Node :: c_fun()) -> arity().

Returns the number of parameter subtrees of an abstract fun-expression.

Note: this is equivalent to length(fun_vars(Node)), but potentially more efficient.

See also: c_fun/2, fun_vars/1.

fun_body(Node)

-spec fun_body(Node :: c_fun()) -> cerl().

Returns the body subtree of an abstract fun-expression.

See also: c_fun/2.

fun_vars(Node)

-spec fun_vars(Node :: c_fun()) -> [cerl()].

Returns the list of parameter subtrees of an abstract fun-expression.

See also: c_fun/2, fun_arity/1.

get_ann(Node)

-spec get_ann(Node :: cerl()) -> [term()].

Returns the list of user annotations associated with a syntax tree node.

For a newly created node, this is the empty list. The annotations may be any terms.

See also: set_ann/2.

int_lit(Node)

-spec int_lit(Node :: c_literal()) -> string().

Returns the numeral string represented by an integer literal node.

See also: c_int/1.

int_val(Node)

-spec int_val(Node :: c_literal()) -> integer().

Returns the value represented by an integer literal node.

See also: c_int/1.

is_c_alias(Node)

-spec is_c_alias(Node :: cerl()) -> boolean().

Returns true if Node is an abstract pattern alias, otherwise false.

See also: c_alias/2.

is_c_apply(Node)

-spec is_c_apply(Node :: cerl()) -> boolean().

Returns true if Node is an abstract function application, otherwise false.

See also: c_apply/2.

is_c_atom(Node)

-spec is_c_atom(Node :: cerl()) -> boolean().

Returns true if Node represents an atom literal, otherwise false.

See also: c_atom/1.

is_c_binary(Node)

-spec is_c_binary(Node :: cerl()) -> boolean().

Returns true if Node is an abstract binary-template, otherwise false.

See also: c_binary/1.

is_c_bitstr(Node)

-spec is_c_bitstr(Node :: cerl()) -> boolean().

Returns true if Node is an abstract bit-string template, otherwise false.

See also: c_bitstr/5.

is_c_call(Node)

-spec is_c_call(Node :: cerl()) -> boolean().

Returns true if Node is an abstract inter-module call expression, otherwise false.

See also: c_call/3.

is_c_case(Node)

-spec is_c_case(Node :: cerl()) -> boolean().

Returns true if Node is an abstract case-expression, otherwise false.

See also: c_case/2.

is_c_catch(Node)

-spec is_c_catch(Node :: cerl()) -> boolean().

Returns true if Node is an abstract catch-expression, otherwise false.

See also: c_catch/1.

is_c_char(Node)

-spec is_c_char(Node :: c_literal()) -> boolean().

Returns true if Node may represent a character literal, otherwise false.

If the local implementation of Erlang defines char/0 as a subset of integer/0, then is_c_int(Node) will also yield true.

See also: c_char/1, is_print_char/1.

is_c_clause(Node)

-spec is_c_clause(Node :: cerl()) -> boolean().

Returns true if Node is an abstract clause, otherwise false.

See also: c_clause/3.

is_c_cons(Node)

-spec is_c_cons(Node :: cerl()) -> boolean().

Returns true if Node is an abstract list constructor, otherwise false.

is_c_float(Node)

-spec is_c_float(Node :: cerl()) -> boolean().

Returns true if Node represents a floating-point literal, otherwise false.

See also: c_float/1.

is_c_fname(Node)

-spec is_c_fname(Node :: cerl()) -> boolean().

Returns true if Node is an abstract function name variable, otherwise false.

See also: c_fname/2, c_var/1, var_name/1.

is_c_fun(Node)

-spec is_c_fun(Node :: cerl()) -> boolean().

Returns true if Node is an abstract fun-expression, otherwise false.

See also: c_fun/2.

is_c_int(Node)

-spec is_c_int(Node :: cerl()) -> boolean().

Returns true if Node represents an integer literal, otherwise false.

See also: c_int/1.

is_c_let(Node)

-spec is_c_let(Node :: cerl()) -> boolean().

Returns true if Node is an abstract let-expression, otherwise false.

See also: c_let/3.

is_c_letrec(Node)

-spec is_c_letrec(Node :: cerl()) -> boolean().

Returns true if Node is an abstract letrec-expression, otherwise false.

See also: c_letrec/2.

is_c_list(Node)

-spec is_c_list(Node :: cerl()) -> boolean().

Returns true if Node represents a proper list, otherwise false.

A proper list is either the empty list [], or a cons cell [Head | Tail], where recursively Tail is a proper list.

Note: Because Node is a syntax tree, the actual run-time values corresponding to its subtrees may often be partially or completely unknown. Thus, if Node represents for example "[... | Ns]" (where Ns is a variable), then the function will return false, because it is not known whether Ns will be bound to a list at run-time. If Node instead represents for example "[1, 2, 3]" or "[A | []]", then the function will return true.

See also: c_cons/2, c_nil/0, list_elements/1, list_length/1.

is_c_map(Node)

(since OTP 17.0)

-spec is_c_map(Node :: cerl()) -> boolean().

Returns true if Node is any kind of abstract map (for constructing, updating or matching), otherwise false.

See also: ann_c_map/3, c_map/1, c_map_pattern/1.

is_c_map_empty(Node)

(since OTP 17.0)

-spec is_c_map_empty(Node :: c_map() | c_literal()) -> boolean().

Returns true if Node represents an empty abstract map, otherwise false.

See also: c_map/1, c_map_pattern/1.

is_c_map_pattern(Node)

(since OTP 17.0)

-spec is_c_map_pattern(Node :: c_map()) -> boolean().

Returns true if Node is an abstract map pattern, otherwise false.

See also: c_map/1, c_map_pattern/1.

is_c_module(Node)

-spec is_c_module(Node :: cerl()) -> boolean().

Returns true if Node is an abstract module definition, otherwise false.

See also: type/1.

is_c_nil(Node)

-spec is_c_nil(Node :: cerl()) -> boolean().

Returns true if Node is an abstract empty list, otherwise false.

is_c_primop(Node)

-spec is_c_primop(Node :: cerl()) -> boolean().

Returns true if Node is an abstract primitive operation call, otherwise false.

See also: c_primop/2.

is_c_receive(Node)

-spec is_c_receive(Node :: cerl()) -> boolean().

Returns true if Node is an abstract receive-expression, otherwise false.

See also: c_receive/3.

is_c_record(Node)

(since OTP @OTP-19785@)

-spec is_c_record(Node :: cerl()) -> boolean().

Returns true if Node is an abstract record, otherwise false.

See also: c_record/2.

is_c_seq(Node)

-spec is_c_seq(Node :: cerl()) -> boolean().

Returns true if Node is an abstract sequencing expression, otherwise false.

See also: c_seq/2.

is_c_string(Node)

-spec is_c_string(Node :: cerl()) -> boolean().

Returns true if Node may represent a string literal, otherwise false.

Strings are defined as lists of characters; see is_c_char/1 for details.

See also: c_string/1, is_c_char/1, is_print_string/1.

is_c_try(Node)

-spec is_c_try(Node :: cerl()) -> boolean().

Returns true if Node is an abstract try-expression, otherwise false.

See also: c_try/5.

is_c_tuple(Node)

-spec is_c_tuple(Node :: cerl()) -> boolean().

Returns true if Node is an abstract tuple, otherwise false.

See also: c_tuple/1.

is_c_values(Node)

-spec is_c_values(Node :: cerl()) -> boolean().

Returns true if Node is an abstract value list, otherwise false.

See also: c_values/1.

is_c_var(Node)

-spec is_c_var(Node :: cerl()) -> boolean().

Returns true if Node is an abstract variable, otherwise false.

See also: c_var/1.

is_data(Node)

-spec is_data(Node :: cerl()) -> boolean().

Returns true if Node represents a data constructor, otherwise false.

Data constructors are cons cells, tuples, and atomic literals.

See also: data_arity/1, data_es/1, data_type/1.

is_leaf(Node)

-spec is_leaf(Node :: cerl()) -> boolean().

Returns true if Node is a leaf node, otherwise false.

The current leaf node types are literal and var.

Note: all literals (cf. is_literal/1) are leaf nodes, even if they represent structured (constant) values such as {foo, [bar, baz]}. Also note that variables are leaf nodes but not literals.

See also: is_literal/1, type/1.

is_literal(Node)

-spec is_literal(Node :: cerl()) -> boolean().

Returns true if Node represents a literal term, otherwise false.

This function returns true if and only if the value of concrete(Node) is defined.

Note: This is a constant time operation.

See also: abstract/1, concrete/1, fold_literal/1.

is_literal_term(Term)

-spec is_literal_term(Term :: term()) -> boolean().

Returns true if Term can be represented as a literal, otherwise false.

This function takes time proportional to the size of Term.

See also: abstract/1.

is_print_char(Node)

-spec is_print_char(Node :: cerl()) -> boolean().

Returns true if Node may represent a "printing" character, otherwise false. (Cf. is_c_char/1.)

A "printing" character has either a given graphical representation, or a "named" escape sequence such as "\n". Currently, only ISO 8859-1 (Latin-1) character values are recognized.

See also: c_char/1, is_c_char/1.

is_print_string(Node)

-spec is_print_string(Node :: cerl()) -> boolean().

Returns true if Node may represent a string literal containing only "printing" characters, otherwise false.

See is_c_string/1 and is_print_char/1 for details. Currently, only ISO 8859-1 (Latin-1) character values are recognized.

See also: c_string/1, is_c_string/1, is_print_char/1.

let_arg(Node)

-spec let_arg(Node :: c_let()) -> cerl().

Returns the argument subtree of an abstract let-expression.

See also: c_let/3.

let_arity(Node)

-spec let_arity(Node :: c_let()) -> non_neg_integer().

Returns the number of left-hand side variables of an abstract let-expression.

Note: this is equivalent to length(let_vars(Node)), but potentially more efficient.

See also: c_let/3, let_vars/1.

let_body(Node)

-spec let_body(Node :: c_let()) -> cerl().

Returns the body subtree of an abstract let-expression.

See also: c_let/3.

let_vars(Node)

-spec let_vars(Node :: c_let()) -> [cerl()].

Returns the list of left-hand side variables of an abstract let-expression.

See also: c_let/3, let_arity/1.

letrec_body(Node)

-spec letrec_body(Node :: c_letrec()) -> cerl().

Returns the body subtree of an abstract letrec-expression.

See also: c_letrec/2.

letrec_defs(Node)

-spec letrec_defs(Node :: c_letrec()) -> [{cerl(), cerl()}].

Returns the list of definitions of an abstract letrec-expression.

If Node represents "letrec V1 = F1 ... Vn = Fn in Body", the returned value is [{V1, F1}, ..., {Vn, Fn}].

See also: c_letrec/2.

letrec_vars(Node)

-spec letrec_vars(Node :: c_letrec()) -> [cerl()].

Returns the list of left-hand side function variable subtrees of a letrec-expression.

If Node represents§ "letrec V1 = F1 ... Vn = Fn in Body", the returned value is [V1, ..., Vn].

See also: c_letrec/2.

list_elements(Node)

-spec list_elements(Node :: c_cons() | c_literal()) -> [cerl()].

Returns the list of element subtrees of an abstract list.

Node must represent a proper list. For example, if Node represents "[X1, X2 | [X3, X4 | []]", then list_elements(Node) yields the list [X1, X2, X3, X4].

See also: c_cons/2, c_nil/0, is_c_list/1, list_length/1, make_list/2.

list_length(Node)

-spec list_length(Node :: c_cons() | c_literal()) -> non_neg_integer().

Returns the number of element subtrees of an abstract list.

Node must represent a proper list. For example, if Node represents "[X1 | [X2, X3 | [X4, X5, X6]]]", then list_length(Node) returns the integer 6.

Note: this is equivalent to length(list_elements(Node)), but potentially more efficient.

See also: c_cons/2, c_nil/0, is_c_list/1, list_elements/1.

make_data(Type, Elements)

-spec make_data(Type :: dtype(), Elements :: [cerl()]) -> c_lct().

Creates a data constructor node with the specified type and subtrees. (Cf. data_type/1.)

An exception is thrown if the length of Elements is invalid for the given Type; see data_es/1 for arity constraints on constructor types.

See also: ann_make_data/3, data_es/1, data_type/1, make_data_skel/2, update_data/3.

make_data_skel(Type, Elements)

-spec make_data_skel(Type :: dtype(), Elements :: [cerl()]) -> c_lct().

Like make_data/2, but analogous to c_tuple_skel/1 and c_cons_skel/2.

See also: ann_make_data_skel/3, c_cons_skel/2, c_tuple_skel/1, make_data/2, update_data_skel/3.

make_list(List)

-spec make_list(List :: [cerl()]) -> cerl().

Equivalent to make_list(List, none).

make_list(List, Tail)

-spec make_list(List :: [cerl()], Tail :: cerl() | none) -> cerl().

Creates an abstract list from the elements in List and the optional Tail.

If Tail is none, the result will represent a nil-terminated list, otherwise it represents "[... | Tail]".

See also: ann_make_list/3, c_cons/2, c_nil/0, list_elements/1, update_list/3.

make_tree(Type, Groups)

-spec make_tree(Type :: ctype(), Groups :: [[cerl()], ...]) -> cerl().

Creates a syntax tree with the given type and subtrees.

Type must be a node type name (cf. type/1) that does not denote a leaf node type (cf. is_leaf/1).

Groups must be a nonempty list of groups of syntax trees, representing the subtrees of a node of the given type, in left-to-right order as they would occur in the printed program text, grouped by category as done by subtrees/1.

The result of ann_make_tree(get_ann(Node), type(Node), subtrees(Node)) (cf. update_tree/2) represents the same source code text as the original Node, assuming that subtrees(Node) yields a nonempty list. However, it does not necessarily have the exact same data representation as Node.

See also: ann_make_tree/3, is_leaf/1, subtrees/1, type/1, update_tree/2.

map_arg(Node)

(since OTP 17.0)

-spec map_arg(Node :: c_map() | c_literal()) -> c_map() | c_literal().

Returns the argument subtree of an abstract map.

See also: c_map/2.

map_es(Node)

(since OTP 17.0)

-spec map_es(Node :: c_map() | c_literal()) -> [c_map_pair()].

Returns the list of map pair subtrees of an abstract map.

See also: c_map/1.

map_pair_key(Node)

(since OTP 17.0)

-spec map_pair_key(Node :: c_map_pair()) -> cerl().

Returns the key subtree of an abstract map pair.

See also: c_map_pair/2, c_map_pair_exact/2.

map_pair_op(Node)

(since OTP 17.0)

-spec map_pair_op(Node :: c_map_pair()) -> map_op().

Returns the operation subtree of an abstract map pair.

See also: c_map_pair/2, c_map_pair_exact/2.

map_pair_val(Node)

(since OTP 17.0)

-spec map_pair_val(Node :: c_map_pair()) -> cerl().

Returns the value subtree of an abstract map pair.

See also: c_map_pair/2, c_map_pair_exact/2.

meta(Tree)

-spec meta(Tree :: cerl()) -> cerl().

Creates a meta-representation of a syntax tree.

The result represents an Erlang expression "MetaTree" which, if evaluated, will yield a new syntax tree representing the same source code text as Tree (although the actual data representation may be different). The expression represented by MetaTree is implementation independent with regard to the data structures used by the abstract syntax tree implementation.

Any node in Tree whose node type is var (cf. type/1), and whose list of annotations (cf. get_ann/1) contains the atom meta_var, will remain unchanged in the resulting tree, except that exactly one occurrence of meta_var is removed from its annotation list.

The main use of the function meta/1 is to transform a data structure Tree, which represents a piece of program code, into a form that is representation independent when printed. E.g., suppose Tree represents a variable named "V". Then (assuming a function print/1 for printing syntax trees), evaluating print(abstract(Tree)) - simply using abstract/1 to map the actual data structure onto a syntax tree representation - would output a string that might look something like "{var, ..., 'V'}", which is obviously dependent on the implementation of the abstract syntax trees. This could, for example, be useful for caching a syntax tree in a file. However, in some situations like in a program generator generator (with two "generator"), it may be unacceptable. Using print(meta(Tree)) instead would output a representation independent syntax tree generating expression; in the above case, something like "cerl:c_var('V')".

The implementation tries to generate compact code with respect to literals and lists.

See also: abstract/1, get_ann/1, type/1.

module_attrs(Node)

-spec module_attrs(Node :: c_module()) -> [{cerl(), cerl()}].

Returns the list of pairs of attribute key/value subtrees of an abstract module definition.

See also: c_module/4.

module_defs(Node)

-spec module_defs(Node :: c_module()) -> [{cerl(), cerl()}].

Returns the list of function definitions of an abstract module definition.

See also: c_module/4.

module_exports(Node)

-spec module_exports(Node :: c_module()) -> [cerl()].

Returns the list of exports subtrees of an abstract module definition.

See also: c_module/4.

module_name(Node)

-spec module_name(Node :: c_module()) -> cerl().

Returns the name subtree of an abstract module definition.

See also: c_module/4.

module_vars(Node)

-spec module_vars(Node :: c_module()) -> [cerl()].

Returns the list of left-hand side function variable subtrees of an abstract module definition.

See also: c_module/4.

pat_list_vars(Patterns)

-spec pat_list_vars(Patterns :: [cerl()]) -> [cerl()].

Returns the list of all abstract variables in the given patterns.

An exception is thrown if some element in Patterns does not represent a well-formed Core Erlang clause pattern. The order of listing is not defined.

See also: clause_vars/1, pat_vars/1.

pat_vars(Node)

-spec pat_vars(Node :: cerl()) -> [cerl()].

Returns the list of all abstract variables in a pattern.

An exception is thrown if Node does not represent a well-formed Core Erlang clause pattern. The order of listing is not defined.

See also: clause_vars/1, pat_list_vars/1.

primop_args(Node)

-spec primop_args(Node :: c_primop()) -> [cerl()].

Returns the list of argument subtrees of an abstract primitive operation call.

See also: c_primop/2, primop_arity/1.

primop_arity(Node)

-spec primop_arity(Node :: c_primop()) -> arity().

Returns the number of argument subtrees of an abstract primitive operation call.

Note: this is equivalent to length(primop_args(Node)), but potentially more efficient.

See also: c_primop/2, primop_args/1.

primop_name(Node)

-spec primop_name(Node :: c_primop()) -> cerl().

Returns the name subtree of an abstract primitive operation call.

See also: c_primop/2.

receive_action(Node)

-spec receive_action(Node :: c_receive()) -> cerl().

Returns the action subtree of an abstract receive-expression.

See also: c_receive/3.

receive_clauses(Node)

-spec receive_clauses(Node :: c_receive()) -> [cerl()].

Returns the list of clause subtrees of an abstract receive-expression.

See also: c_receive/3.

receive_timeout(Node)

-spec receive_timeout(Node :: c_receive()) -> cerl().

Returns the timeout subtree of an abstract receive-expression.

See also: c_receive/3.

record_arg(Node)

(since OTP @OTP-19785@)

-spec record_arg(Node :: c_record()) -> c_record() | c_literal().

Returns the argument subtree of an abstract record.

See also: c_record/2.

record_es(Node)

(since OTP @OTP-19785@)

-spec record_es(Node :: c_record()) -> [c_record_pair()].

Returns the list of native record pair subtrees of an abstract record.

See also: c_record/2.

record_id(Node)

(since OTP @OTP-19785@)

-spec record_id(Node :: c_record()) -> record_id().

Returns the identifier of of an abstract record.

See also: c_record/2.

record_pair_key(Node)

(since OTP @OTP-19785@)

-spec record_pair_key(Node :: c_record_pair()) -> c_literal().

Returns the key subtree of an abstract record pair.

See also: c_record_pair/2.

record_pair_val(Node)

(since OTP @OTP-19785@)

-spec record_pair_val(Node :: c_record_pair()) -> cerl().

Returns the value subtree of an abstract record pair.

See also: c_record_pair/2.

seq_arg(Node)

-spec seq_arg(Node :: c_seq()) -> cerl().

Returns the argument subtree of an abstract sequencing expression.

See also: c_seq/2.

seq_body(Node)

-spec seq_body(Node :: c_seq()) -> cerl().

Returns the body subtree of an abstract sequencing expression.

See also: c_seq/2.

set_ann(Node, Annotations)

-spec set_ann(Node :: cerl(), Annotations :: [term()]) -> cerl().

Sets the list of user annotations of Node to Annotations.

See also: add_ann/2, copy_ann/2, get_ann/1.

string_lit(Node)

-spec string_lit(Node :: c_literal()) -> nonempty_string().

Returns the literal string represented by an abstract string. This includes surrounding double-quote characters "...".

Currently, characters that are not in the set of ISO 8859-1 (Latin-1) "printing" characters will be escaped, except for spaces.

See also: c_string/1.

string_val(Node)

-spec string_val(Node :: c_literal()) -> string().

Returns the value represented by an abstract string literal.

See also: c_string/1.

subtrees(Node)

-spec subtrees(Node :: cerl()) -> [[cerl()]].

Returns the grouped list of all subtrees of a node.

If Node is a leaf node (cf. is_leaf/1), this is the empty list, otherwise the result is always a nonempty list, containing the lists of subtrees of Node, in left-to-right order as they occur in the printed program text, and grouped by category. Often, each group contains only a single subtree.

Depending on the type of Node, the size of some groups may be variable (for example, the group consisting of all the elements of a tuple), while others always contain the same number of elements - usually exactly one (for example, the group containing the argument expression of a case-expression). Note, however, that the exact structure of the returned list (for a given node type) should in general not be depended upon, since it might be subject to change without notice.

The function subtrees/1 and the constructor functions make_tree/2 and update_tree/2 can be a great help if one wants to traverse a syntax tree, visiting all its subtrees, but treat nodes of the tree in a uniform way in most or all cases. Using these functions makes this simple, and also assures that your code is not overly sensitive to extensions of the syntax tree data type, because any node types not explicitly handled by your code can be left to a default case.

For example:

    postorder(F, Tree) ->
        F(case subtrees(Tree) of
            [] -> Tree;
            List -> update_tree(Tree,
                                [[postorder(F, Subtree)
                                  || Subtree <- Group]
                                 || Group <- List])
          end).

maps the function F on Tree and all its subtrees, doing a post-order traversal of the syntax tree. (Note the use of update_tree/2 to preserve annotations.) For a simple function like:

    f(Node) ->
        case type(Node) of
            atom -> atom("a_" ++ atom_name(Node));
            _ -> Node
        end.

the call postorder(fun f/1, Tree) will yield a new representation of Tree in which all atom names have been extended with the prefix "a_", but nothing else (including annotations) has been changed.

See also: is_leaf/1, make_tree/2, update_tree/2.

to_records(Node)

-spec to_records(Node :: cerl()) -> cerl().

Translates an abstract syntax tree to a corresponding explicit record representation.

The records are defined in the file "cerl.hrl".

See also: from_records/1, type/1.

try_arg(Node)

-spec try_arg(Node :: c_try()) -> cerl().

Returns the expression subtree of an abstract try-expression.

See also: c_try/5.

try_body(Node)

-spec try_body(Node :: c_try()) -> cerl().

Returns the success body subtree of an abstract try-expression.

See also: c_try/5.

try_evars(Node)

-spec try_evars(Node :: c_try()) -> [cerl()].

Returns the list of exception variable subtrees of an abstract try-expression.

See also: c_try/5.

try_handler(Node)

-spec try_handler(Node :: c_try()) -> cerl().

Returns the exception body subtree of an abstract try-expression.

See also: c_try/5.

try_vars(Node)

-spec try_vars(Node :: c_try()) -> [cerl()].

Returns the list of success variable subtrees of an abstract try-expression.

See also: c_try/5.

tuple_arity(Node)

-spec tuple_arity(Node :: c_tuple() | c_literal()) -> non_neg_integer().

Returns the number of element subtrees of an abstract tuple.

Note: this is equivalent to length(tuple_es(Node)), but potentially more efficient.

See also: c_tuple/1, tuple_es/1.

tuple_es(Node)

-spec tuple_es(Node :: c_tuple() | c_literal()) -> [cerl()].

Returns the list of element subtrees of an abstract tuple.

See also: c_tuple/1.

type(Node)

-spec type(Node :: cerl()) -> ctype().

Returns the type tag of Node.

Current node types are:

alias

apply

binary

bitstr

call

case

catch

clause

cons

fun

let

letrec

literal

map

map_pair

module

opaque

primop

receive

seq

record

try

tuple

values

var

Note

The name of the primary constructor function for a node type is always the name of the type itself, prefixed by "c_"; recognizer predicates are correspondingly prefixed by "is_c_". Furthermore, to simplify preservation of annotations (cf. get_ann/1), there are analogous constructor functions prefixed by "ann_c_" and "update_c_", for setting the annotation list of the new node to either a specific value or to the annotations of an existing node, respectively.

The only purpose of the opaque type is to facilitate testing of the compiler.

See also: abstract/1, c_alias/2, c_apply/2, c_binary/1, c_bitstr/5, c_call/3, c_case/2, c_catch/1, c_clause/3, c_cons/2, c_fun/2, c_let/3, c_letrec/2, c_module/3, c_primop/2, c_receive/1, c_seq/2, c_record/2, c_try/5, c_tuple/1, c_values/1, c_var/1, data_type/1, from_records/1, get_ann/1, meta/1, subtrees/1, to_records/1.

unfold_literal(Node)

-spec unfold_literal(Node :: cerl()) -> cerl().

Ensures that literals have a fully expanded representation.

If Node represents a literal tuple or list constructor, its elements are rewritten recursively, and the node is reconstructed using c_cons_skel/2 or c_tuple_skel/1, respectively; otherwise, Node is not changed. The fold_literal/1 can be used to revert to the normal compact representation.

See also: c_cons/2, c_cons_skel/2, c_tuple/1, c_tuple_skel/1, fold_literal/1, is_literal/1.

update_c_alias(Node, Variable, Pattern)

-spec update_c_alias(Node :: c_alias(), Variable :: cerl(), Pattern :: cerl()) -> c_alias().

See also: c_alias/2.

update_c_apply(Node, Operator, Arguments)

-spec update_c_apply(Node :: c_apply(), Operator :: cerl(), Arguments :: [cerl()]) -> c_apply().

See also: c_apply/2.

update_c_binary(Node, Segments)

-spec update_c_binary(Node :: c_binary(), Segments :: [cerl()]) -> c_binary().

See also: c_binary/1.

update_c_bitstr(Node, Value, Size, Type, Flags)

-spec update_c_bitstr(Node :: c_bitstr(),
                      Value :: cerl(),
                      Size :: cerl(),
                      Type :: cerl(),
                      Flags :: cerl()) ->
                         c_bitstr().

Equivalent to update_c_bitstr(Node, Value, Size, abstract(1), Type, Flags).

update_c_bitstr(Node, Value, Size, Unit, Type, Flags)

-spec update_c_bitstr(Node :: c_bitstr(),
                      Value :: cerl(),
                      Size :: cerl(),
                      Unit :: cerl(),
                      Type :: cerl(),
                      Flags :: cerl()) ->
                         c_bitstr().

See also: c_bitstr/5, update_c_bitstr/5.

update_c_call(Node, Module, Name, Arguments)

-spec update_c_call(Node :: cerl(), Module :: cerl(), Name :: cerl(), Arguments :: [cerl()]) -> c_call().

See also: c_call/3.

update_c_case(Node, Argument, Clauses)

-spec update_c_case(Node :: c_case(), Argument :: cerl(), Clauses :: [cerl()]) -> c_case().

See also: c_case/2.

update_c_catch(Node, Body)

-spec update_c_catch(Node :: c_catch(), Body :: cerl()) -> c_catch().

See also: c_catch/1.

update_c_clause(Node, Patterns, Guard, Body)

-spec update_c_clause(Node :: c_clause(), Patterns :: [cerl()], Guard :: cerl(), Body :: cerl()) ->
                         c_clause().

See also: c_clause/3.

update_c_cons(Node, Head, Tail)

-spec update_c_cons(Node :: c_literal() | c_cons(), Head :: cerl(), Tail :: cerl()) ->
                       c_literal() | c_cons().

See also: c_cons/2.

update_c_cons_skel(Node, Head, Tail)

-spec update_c_cons_skel(Node :: c_cons() | c_literal(), Head :: cerl(), Tail :: cerl()) -> c_cons().

See also: c_cons_skel/2.

update_c_fname(Node, Name)

-spec update_c_fname(Node :: c_var(), Name :: atom()) -> c_var().

Like update_c_fname/3, but takes the arity from Node.

See also: c_fname/2, update_c_fname/3.

update_c_fname(Node, Name, Arity)

-spec update_c_fname(Node :: c_var(), Name :: atom(), Arity :: arity()) -> c_var().

Equivalent to update_c_var(Old, {Atom, Arity}).

See also: c_fname/2, update_c_fname/2.

update_c_fun(Node, Variables, Body)

-spec update_c_fun(Node :: c_fun(), Variables :: [cerl()], Body :: cerl()) -> c_fun().

See also: c_fun/2.

update_c_let(Node, Variables, Argument, Body)

-spec update_c_let(Node :: c_let(), Variables :: [cerl()], Argument :: cerl(), Body :: cerl()) ->
                      c_let().

See also: c_let/3.

update_c_letrec(Node, Definitions, Body)

-spec update_c_letrec(Node :: c_letrec(), Definitions :: [{cerl(), cerl()}], Body :: cerl()) ->
                         c_letrec().

See also: c_letrec/2.

update_c_map(Node, Map, Pairs)

(since OTP 17.0)

-spec update_c_map(Node :: c_map(), Map :: cerl(), Pairs :: [c_map_pair()]) -> c_map() | c_literal().

See also: c_map/1, c_map_pattern/1.

update_c_map_pair(Node, Operation, Key, Value)

(since OTP 17.0)

-spec update_c_map_pair(Node :: c_map_pair(), Operation :: map_op(), Key :: cerl(), Value :: cerl()) ->
                           c_map_pair().

See also: c_map_pair/2, c_map_pair_exact/2.

update_c_module(Node, Name, Exports, Attributes, Definitions)

-spec update_c_module(Node :: c_module(),
                      Name :: cerl(),
                      Exports :: [cerl()],
                      Attributes :: [{cerl(), cerl()}],
                      Definitions :: [{cerl(), cerl()}]) ->
                         c_module().

See also: c_module/4.

update_c_primop(Node, Name, Arguments)

-spec update_c_primop(Node :: cerl(), Name :: cerl(), Arguments :: [cerl()]) -> c_primop().

See also: c_primop/2.

update_c_receive(Node, Clauses, Timeout, Action)

-spec update_c_receive(Node :: c_receive(), Clauses :: [cerl()], Timeout :: cerl(), Action :: cerl()) ->
                          c_receive().

See also: c_receive/3.

update_c_record(Node, Arg, Id, Pairs)

(since OTP @OTP-19785@)

-spec update_c_record(Node :: c_record() | c_literal(),
                      Arg :: c_var() | c_literal(),
                      Id :: record_id(),
                      Pairs :: [c_record_pair()]) ->
                         c_record().

See also: c_record/2.

update_c_record_pair(Node, Key, Value)

(since OTP @OTP-19785@)

-spec update_c_record_pair(Node :: c_record_pair(), Key :: c_literal(), Value :: cerl()) ->
                              c_record_pair().

See also: c_record_pair/2.

update_c_seq(Node, Argument, Body)

-spec update_c_seq(Node :: c_seq(), Argument :: cerl(), Body :: cerl()) -> c_seq().

See also: c_seq/2.

update_c_try(Node, Argument, Variables, Body, ExceptionVars, Handler)

-spec update_c_try(Node :: c_try(),
                   Argument :: cerl(),
                   Variables :: [cerl()],
                   Body :: cerl(),
                   ExceptionVars :: [cerl()],
                   Handler :: cerl()) ->
                      c_try().

See also: c_try/5.

update_c_tuple(Node, Elements)

-spec update_c_tuple(Node :: c_tuple() | c_literal(), Elements :: [cerl()]) -> c_tuple() | c_literal().

See also: c_tuple/1.

update_c_tuple_skel(Node, Elements)

-spec update_c_tuple_skel(Node :: c_tuple(), Elements :: [cerl()]) -> c_tuple().

See also: c_tuple_skel/1.

update_c_values(Node, Elements)

-spec update_c_values(Node :: c_values(), Elements :: [cerl()]) -> c_values().

See also: c_values/1.

update_c_var(Node, Name)

-spec update_c_var(Node :: c_var(), Name :: var_name()) -> c_var().

See also: c_var/1.

update_data(Node, Type, Elements)

-spec update_data(Node :: cerl(), Type :: dtype(), Elements :: [cerl()]) -> c_lct().

See also: make_data/2.

update_data_skel(Node, Type, Elements)

-spec update_data_skel(Node :: cerl(), Type :: dtype(), Elements :: [cerl()]) -> c_lct().

See also: make_data_skel/2.

update_list(Node, List)

-spec update_list(Node :: cerl(), List :: [cerl()]) -> cerl().

Equivalent to update_list(Old, List, none).

update_list(Node, List, Tail)

-spec update_list(Node :: cerl(), List :: [cerl()], Tail :: cerl() | none) -> cerl().

See also: make_list/2, update_list/2.

update_tree(Node, Groups)

-spec update_tree(Node :: cerl(), Groups :: [[cerl()], ...]) -> cerl().

Creates a syntax tree with the given subtrees, and the same type and annotations as the node Node.

This is equivalent to ann_make_tree(get_ann(Node), type(Node), Groups), but potentially more efficient.

See also: ann_make_tree/3, get_ann/1, type/1, update_tree/3.

update_tree(Node, Type, Groups)

-spec update_tree(Node :: cerl(), Type :: ctype(), Groups :: [[cerl()], ...]) -> cerl().

Creates a syntax tree with the given type and subtrees, and the same annotations as the node Node.

This is equivalent to ann_make_tree(get_ann(Node), Type, Groups), but potentially more efficient.

See also: ann_make_tree/3, get_ann/1, update_tree/2.

values_arity(Node)

-spec values_arity(Node :: c_values()) -> non_neg_integer().

Returns the number of element subtrees of an abstract value list.

Note: This is equivalent to length(values_es(Node)), but potentially more efficient.

See also: c_values/1, values_es/1.

values_es(Node)

-spec values_es(Node :: c_values()) -> [cerl()].

Returns the list of element subtrees of an abstract value list.

See also: c_values/1, values_arity/1.

var_name(Node)

-spec var_name(Node :: c_var()) -> var_name().

Returns the name of an abstract variable.

See also: c_var/1.

cerl_clauses

Utility functions for Core Erlang case/receive clauses.

Note

The documentation of the public interface for the Erlang compiler can be found in module compile.

This module is an internal part of the compiler. Its API is not guaranteed to remain compatible between releases.

Syntax trees are defined in the module cerl.

Summary

Types

bindings()

cerl()

expr()

match_ret()

Functions

any_catchall(Clauses)

Returns true if any of the abstract clauses in the list is a catch-all, otherwise false.

eval_guard(Expr)

Tries to reduce a guard expression to a single constant value, if possible.

is_catchall(Clause)

Returns true if an abstract clause is a catch-all, otherwise false.

match(Pattern, Expr)

Matches a pattern against an expression.

match_list(Patterns, Exprs)

Like match/2, but matching a sequence of patterns against a sequence of expressions.

reduce(Cs)

Equivalent to reduce(Cs, []).

reduce(Clauses, Exprs)

Selects a single clause, if possible, or otherwise reduces the list of selectable clauses.

Types

bindings()

(not exported)

-type bindings() :: [{cerl(), cerl()}].

cerl()

(not exported)

-type cerl() :: cerl:cerl().

expr()

(not exported)

-type expr() :: any | cerl().

match_ret()

(not exported)

-type match_ret() :: none | {true, bindings()} | {false, bindings()}.

Functions

any_catchall(Clauses)

-spec any_catchall(Clauses :: [cerl()]) -> boolean().

Returns true if any of the abstract clauses in the list is a catch-all, otherwise false.

See is_catchall/1 for details.

Note: each node in Clauses must have type clause.

See also: is_catchall/1.

eval_guard(Expr)

-spec eval_guard(Expr :: cerl()) -> none | {value, term()}.

Tries to reduce a guard expression to a single constant value, if possible.

The returned value is {value, Term} if the guard expression Expr always yields the constant value Term, and is otherwise none.

Note that although guard expressions should only yield boolean values, this function does not guarantee that Term is either true or false. Also note that only simple constructs like let-expressions are examined recursively; general constant folding is not performed.

See also: is_catchall/1.

is_catchall(Clause)

-spec is_catchall(Clause :: cerl:c_clause()) -> boolean().

Returns true if an abstract clause is a catch-all, otherwise false.

A clause is a catch-all if all its patterns are variables, and its guard expression always evaluates to true; cf. eval_guard/1.

Note: Clause must have type clause.

See also: any_catchall/1, eval_guard/1.

match(Pattern, Expr)

-spec match(Pattern :: cerl(), Expr :: expr()) -> match_ret().

Matches a pattern against an expression.

The returned value is none if a match is impossible, {true, Bindings} if Pattern definitely matches Expr, and {false, Bindings} if a match is not definite, but cannot be excluded. Bindings is then a list of pairs {Var, SubExpr}, associating each variable in the pattern with either the corresponding subexpression of Expr, or with the atom any if no matching subexpression exists. (Recall that variables may not be repeated in a Core Erlang pattern.) The list of bindings is given in innermost-first order; this should only be of interest if Pattern contains one or more alias patterns. If the returned value is {true, []}, it implies that the pattern and the expression are syntactically identical.

Instead of a syntax tree, the atom any can be passed for Expr (or, more generally, be used for any subtree of Expr, in as much the abstract syntax tree implementation allows it); this means that it cannot be decided whether the pattern will match or not, and the corresponding variable bindings will all map to any. The typical use is for producing bindings for receive clauses.

Note: Binary-syntax patterns are never structurally matched against binary-syntax expressions by this function.

Examples:

Matching a pattern "{X, Y}" against the expression "{foo, f(Z)}" yields {true, Bindings} where Bindings associates "X" with the subtree "foo" and "Y" with the subtree "f(Z)".

Matching pattern "{X, {bar, Y}}" against expression "{foo, f(Z)}" yields {false, Bindings} where Bindings associates "X" with the subtree "foo" and "Y" with any (because it is not known if "{foo, Y}" might match the run-time value of "f(Z)" or not).

Matching pattern "{foo, bar}" against expression "{foo, f()}" yields {false, []}, telling us that there might be a match, but we cannot deduce any bindings.

Matching {foo, X = {bar, Y}} against expression "{foo, {bar, baz}}" yields {true, Bindings} where Bindings associates "Y" with "baz", and "X" with "{bar, baz}".

Matching a pattern "{X, Y}" against any yields {false, Bindings} where Bindings associates both "X" and "Y" with any.

match_list(Patterns, Exprs)

-spec match_list(Patterns :: [cerl()], Exprs :: [expr()]) -> match_ret().

Like match/2, but matching a sequence of patterns against a sequence of expressions.

Passing an empty list for Exprs is equivalent to passing a list of any atoms of the same length as Patterns.

See also: match/2.

reduce(Cs)

-spec reduce([cerl:c_clause()]) -> {true, {cerl:c_clause(), bindings()}} | {false, [cerl:c_clause()]}.

Equivalent to reduce(Cs, []).

reduce(Clauses, Exprs)

-spec reduce(Clauses :: [cerl:c_clause()], Exprs :: [expr()]) ->
                {true, {cerl:c_clause(), bindings()}} | {false, [cerl:c_clause()]}.

Selects a single clause, if possible, or otherwise reduces the list of selectable clauses.

The input is a list Clauses of abstract clauses (i.e., syntax trees of type clause), and a list of switch expressions Exprs. The function tries to uniquely select a single clause or discard unselectable clauses, with respect to the switch expressions. All abstract clauses in the list must have the same number of patterns. If Exprs is not the empty list, it must have the same length as the number of patterns in each clause; see match_list/2 for details.

A clause can only be selected if its guard expression always yields the atom true, and a clause whose guard expression always yields the atom false can never be selected. Other guard expressions are considered to have unknown value; cf. eval_guard/1.

If a particular clause can be selected, the function returns {true, {Clause, Bindings}}, where Clause is the selected clause and Bindings is a list of pairs {Var, SubExpr} associating the variables occurring in the patterns of Clause with the corresponding subexpressions in Exprs. The list of bindings is given in innermost-first order; see the match/2 function for details.

If no clause could be definitely selected, the function returns {false, NewClauses}, where NewClauses is the list of entries in Clauses that remain after eliminating unselectable clauses, preserving the relative order.

See also: eval_guard/1, match/2, match_list/2.

cerl_trees

Basic functions on Core Erlang abstract syntax trees.

Note

The public interface of the Erlang compiler can be found in module compile.

This module is an internal part of the compiler. Its API is not guaranteed to remain compatible between releases.

Syntax trees are defined in the module cerl.

Summary

Types

cerl()

Functions

depth(Tree)

Returns the length of the longest path in the tree.

fold(Function, Unit, Term)

Does a fold operation over the nodes of the tree.

free_variables(Tree)

Like variables/1, but only includes variables that are free in the tree.

get_label(Tree)

Retrieves the label for Tree.

label(T)

Equivalent to label(Tree, 0).

label(Tree, N)

Labels each expression in the tree.

map(Function, Tree)

Maps a function onto the nodes of a tree.

mapfold(Function, Initial, Tree)

Does a combined map/fold operation on the nodes of the tree.

mapfold(Pre, Post, Initial, Tree)

Does a combined map/fold operation on the nodes of the tree.

next_free_variable_name(Tree)

Returns a integer variable name higher than any other integer variable name in the syntax tree.

size(Tree)

Returns the number of nodes in Tree.

variables(Tree)

Returns an ordered-set list of the names of all variables in the syntax tree (including function-name variables.)

Types

cerl()

(not exported)

-type cerl() :: cerl:cerl().

Functions

depth(Tree)

-spec depth(Tree :: cerl()) -> non_neg_integer().

Returns the length of the longest path in the tree.

A leaf node has depth zero, the tree representing "{foo, bar}" has depth one, and so on.

fold(Function, Unit, Term)

-spec fold(Function :: fun((cerl(), term()) -> term()), Unit :: term(), Term :: cerl()) -> term().

Does a fold operation over the nodes of the tree.

The result is the value of Function(X1, Function(X2, ... Function(Xn, Unit) ... )), where X1, ..., Xn are the nodes of Tree in a post-order traversal.

See also: mapfold/3.

free_variables(Tree)

-spec free_variables(Tree :: cerl()) -> [cerl:var_name()].

Like variables/1, but only includes variables that are free in the tree.

See also: next_free_variable_name/1, variables/1.

get_label(Tree)

-spec get_label(Tree :: cerl()) -> top | integer().

Retrieves the label for Tree.

An exception is thrown if Tree does not have a label, or if Tree does not represent a well-formed Core Erlang syntax tree.

label(T)

-spec label(cerl()) -> {cerl(), integer()}.

Equivalent to label(Tree, 0).

label(Tree, N)

-spec label(Tree :: cerl(), N :: integer()) -> {cerl(), integer()}.

Labels each expression in the tree.

A term {label, L} is prefixed to the annotation list of each expression node, where L is a unique number for every node, except for variables (and function name variables) which get the same label if they represent the same variable. Constant literal nodes are not labeled.

The returned value is a tuple {NewTree, Max}, where NewTree is the labeled tree and Max is 1 plus the largest label value used. All previous annotation terms of the form {label, X} are deleted.

The values of L used in the tree is a dense range from N to Max - 1, where N =< Max =< N + size(Tree). Note that it is possible that no labels are used at all, i.e., N = Max.

Note: All instances of free variables will be given distinct labels.

See also: label/1, size/1.

map(Function, Tree)

-spec map(Function :: fun((cerl()) -> cerl()), Tree :: cerl()) -> cerl().

Maps a function onto the nodes of a tree.

This replaces each node in the tree by the result of applying the given function on the original node, bottom-up.

See also: mapfold/3.

mapfold(Function, Initial, Tree)

-spec mapfold(Function :: fun((cerl(), term()) -> {cerl(), term()}), Initial :: term(), Tree :: cerl()) ->
                 {cerl(), term()}.

Does a combined map/fold operation on the nodes of the tree.

This is similar to map/2, but also propagates a value from each application of Function to the next, starting with the given value Initial, while doing a post-order traversal of the tree, much like fold/3.

This is equivalent to mapfold/4 with an identity function as the pre-operation.

See also: fold/3, map/2, mapfold/4.

mapfold(Pre, Post, Initial, Tree)

-spec mapfold(Pre :: fun((cerl(), term()) -> {cerl(), term()} | skip),
              Post :: fun((cerl(), term()) -> {cerl(), term()}),
              Initial :: term(),
              Tree :: cerl()) ->
                 {cerl(), term()}.

Does a combined map/fold operation on the nodes of the tree.

It begins by calling Pre on the tree, using the Initial value. Pre must either return a tree with an updated accumulator or the atom skip.

If a tree is returned, this function deconstructs the top node of the returned tree and recurses on the children, using the returned value as the new initial and carrying the returned values from one call to the next. Finally it reassembles the top node from the children, calls Post on it and returns the result.

If skip is returned, it returns the tree and accumulator as is.

next_free_variable_name(Tree)

-spec next_free_variable_name(Tree :: cerl()) -> integer().

Returns a integer variable name higher than any other integer variable name in the syntax tree.

An exception is thrown if Tree does not represent a well-formed Core Erlang syntax tree.

See also: free_variables/1, variables/1.

size(Tree)

-spec size(Tree :: cerl()) -> non_neg_integer().

Returns the number of nodes in Tree.

variables(Tree)

-spec variables(Tree :: cerl()) -> [cerl:var_name()].

Returns an ordered-set list of the names of all variables in the syntax tree (including function-name variables.)

An exception is thrown if Tree does not represent a well-formed Core Erlang syntax tree.

See also: free_variables/1, next_free_variable_name/1.