diff options
Diffstat (limited to 'system/doc')
50 files changed, 1344 insertions, 1147 deletions
diff --git a/system/doc/design_principles/applications.xml b/system/doc/design_principles/applications.xml index 0a1b65ea8e..c673fde07e 100644 --- a/system/doc/design_principles/applications.xml +++ b/system/doc/design_principles/applications.xml @@ -11,7 +11,7 @@ Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except in compliance with the License. You may obtain a copy of the License at - + http://www.apache.org/licenses/LICENSE-2.0 Unless required by applicable law or agreed to in writing, software @@ -19,7 +19,7 @@ WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the License for the specific language governing permissions and limitations under the License. - + </legalnotice> <title>Applications</title> @@ -172,31 +172,136 @@ ch_app:stop([])</code> </section> <section> - <marker id="app_dir"></marker> - <title>Directory Structure</title> - <p>When packaging code using <c>systools</c>, the code for each - application is placed in a separate directory, - <c>lib/Application-Vsn</c>, where <c>Vsn</c> is the version number.</p> - <p>This can be useful to know, even if <c>systools</c> is not used, - since Erlang/OTP is packaged according to the OTP principles - and thus comes with this directory structure. The code server - (see the <c>code(3)</c> manual page in Kernel) automatically - uses code from - the directory with the highest version number, if more than one - version of an application is present.</p> - <p>The application directory structure can also be used in the - development environment. The version number can then - be omitted from the name.</p> - <p>The application directory has the following sub-directories:</p> - <list type="bulleted"> - <item><c>src</c> - Contains the Erlang source code.</item> - <item><c>ebin</c> - Contains the Erlang object code, the - <c>beam</c> files. The <c>.app</c> file is also placed here.</item> - <item><c>priv</c> - Used for application specific files. For - example, C executables are placed here. The function - <c>code:priv_dir/1</c> is to be used to access this directory.</item> - <item><c>include</c> - Used for include files.</item> - </list> + <marker id="app_dir"></marker> + <title>Directory Structure</title> + <p>When packaging code using <c>systools</c>, the code for each + application is placed in a separate directory, + <c>lib/Application-Vsn</c>, where <c>Vsn</c> is the version number.</p> + <p>This can be useful to know, even if <c>systools</c> is not used, + since Erlang/OTP is packaged according to the OTP principles + and thus comes with a specific directory structure. The code server + (see the <seealso marker="kernel:code"><c>code(3)</c></seealso> manual + page in Kernel) automatically uses code from + the directory with the highest version number, if more than one + version of an application is present.</p> + <section> + <title>Directory Structure guidelines for a Development Environment</title> + <p>Any directory structure for development will suffice as long as the released directory structure + adhere to the <seealso marker="#app_dir_released">description below</seealso>, + but it is encouraged that the same directory structure + also be used in a development environment. The version number should be omitted from the + application directory name since this is an artifact of the release step. + </p> + <p> Some sub-directories are <em>required</em>. Some sub-directories are <em>optional</em>, meaning that it should + only be used if the application itself requires it. Finally, some sub-directories are <em>recommended</em>, + meaning it is encouraged that it is used and used as described here. For example, both documentation + and tests are encouraged to exist in an application for it to be deemed a proper OTP application.</p> +<code type="none"> + ─ ${application} + ├── doc + │ ├── internal + │ ├── examples + │ └── src + ├── include + ├── priv + ├── src + │ └── ${application}.app.src + └── test +</code> + <list type="bulleted"> + <item><c>src</c> - Required. Contains the Erlang source code, the source of the <c>.app</c> file + and internal include files used by the application itself. Additional sub-directories within + <c>src</c> can be used as namespaces to organize source files. These directories should never + be deeper than one level.</item> + <item><c>priv</c> - Optional. Used for application specific files. </item> + <item><c>include</c> - Optional. Used for public include files that must be reachable from + other applications.</item> + <item><c>doc</c> - Recommended. Any source documentation should be placed in sub-directories here.</item> + <item><c>doc/internal</c> - Recommended. Any documentation that describes implementation details about + this application, not intended for publication, should be placed here.</item> + <item><c>doc/examples</c> - Recommended. Source code for examples on how to use this application should + be placed here. It is encouraged that examples are sourced to the public documentation from + this directory.</item> + <item><c>doc/src</c> - Recommended. All source files for documentation, such as Markdown, AsciiDoc or + XML-files, should be placed here.</item> + <item><c>test</c> - Recommended. All files regarding tests, such as test suites and test specifications, + should be placed here. </item> + </list> + + <p>Other directories in the development environment may be needed. If source code from languages other + than Erlang is used, for instance C-code for NIFs, that code should be placed in a separate directory. + By convention it is recommended to prefix such directories with the language name, for example + <c>c_src</c> for C, <c>java_src</c> for Java or <c>go_src</c> for Go. Directories with <c>_src</c> + suffix indicates that it is a part of the application and the compilation step. The final build artifacts + should target the <c>priv/lib</c> or <c>priv/bin</c> directories.</p> + <p>The <c>priv</c> directory holds assets that the application needs during runtime. Executables should + reside in <c>priv/bin</c> and dynamically-linked libraries should reside in <c>priv/lib</c>. Other assets + are free to reside within the <c>priv</c> directory but it is recommended it does so in a structured manner.</p> + <p>Source files from other languages that generate Erlang code, such as ASN.1 or Mibs, should be placed + in directories, at the top level or in <c>src</c>, with the same name as the source language, for example + <c>asn1</c> and <c>mibs</c>. Build artifacts should be placed in their respective language directory, + such as <c>src</c> for Erlang code or <c>java_src</c> for Java code.</p> + <p>The <c>.app</c> file for release may reside in the <c>ebin</c>-directory in a development environment + but it is encouraged that this is an artifact of the build step. By convention a <c>.app.src</c> file + is used, which resides in the <c>src</c> directory. This file is nearly identical as the + <c>.app</c> file but certain fields may be replaced during the build step, such as the application version.</p> + <p>Directory names should not be capitalized.</p> + <p>It is encouraged to omit empty directories.</p> + + </section> + + <section> + <marker id="app_dir_released"></marker> + <title>Directory Structure for a Released System</title> + <p>A released application must follow a certain structure. + </p> +<code type="none"> + ─ ${application}-${version} + ├── bin + ├── doc + │ ├── html + │ ├── man[1-9] + │ ├── pdf + │ ├── internal + │ └── examples + ├── ebin + │ └── ${application}.app + ├── include + ├── priv + │ ├── lib + │ └── bin + └── src +</code> + <list type="bulleted"> + <item><c>src</c> - Optional. Contains the Erlang source code and internal include files + used by the application itself. This directory is no longer required in a released application.</item> + <item><c>ebin</c> - Required. Contains the Erlang object code, the <c>beam</c> files. + The <c>.app</c> file must also be placed here.</item> + <item><c>priv</c> - Optional. Used for application specific files. <c>code:priv_dir/1</c> + is to be used to access this directory.</item> + <item><c>priv/lib</c> - Recommended. Any shared-object files that are used by the application, + such as NIFs or linked-in-drivers, should be placed here.</item> + <item><c>priv/bin</c> - Recommended. Any executable that is used by the application, + such as port-programs, should be placed here.</item> + <item><c>include</c> - Optional. Used for public include files that must be reachable from + other applications.</item> + <item><c>bin</c> - Optional. Any executable that is a product of the application, + such as escripts or shell-scripts, should be placed here.</item> + <item><c>doc</c> - Optional. Any released documentation should be placed in + sub-directories here.</item> + <item><c>doc/man1</c> - Recommended. Man pages for Application executables.</item> + <item><c>doc/man3</c> - Recommended. Man pages for module APIs.</item> + <item><c>doc/man6</c> - Recommended. Man pages for Application overview.</item> + <item><c>doc/html</c> - Optional. HTML pages for the entire Application.</item> + <item><c>doc/pdf</c> - Optional. PDF documentation for the entire Application.</item> + </list> + + <p>The <c>src</c> directory could be useful to release for debugging purposes but is not required. + The <c>include</c> directory should only be released if the applications has public include files.</p> + <p>The only documentation that is recommended to be released in this way are the man pages. HTML and PDF + will normally be distributed in some other manner.</p> + <p>It is encouraged to omit empty directories.</p> + </section> </section> <section> @@ -381,4 +486,3 @@ application:start(Application, Type)</code> <c>shutdown</c>, not <c>normal</c>.</p> </section> </chapter> - diff --git a/system/doc/design_principles/code_lock.dia b/system/doc/design_principles/code_lock.dia Binary files differindex 8e6ff8a898..eaa2aca5b0 100644 --- a/system/doc/design_principles/code_lock.dia +++ b/system/doc/design_principles/code_lock.dia diff --git a/system/doc/design_principles/code_lock.png b/system/doc/design_principles/code_lock.png Binary files differindex 745fd91920..40bd35fc74 100644 --- a/system/doc/design_principles/code_lock.png +++ b/system/doc/design_principles/code_lock.png diff --git a/system/doc/design_principles/code_lock_2.dia b/system/doc/design_principles/code_lock_2.dia Binary files differindex 142909a2f5..3b9ba554d8 100644 --- a/system/doc/design_principles/code_lock_2.dia +++ b/system/doc/design_principles/code_lock_2.dia diff --git a/system/doc/design_principles/code_lock_2.png b/system/doc/design_principles/code_lock_2.png Binary files differindex ecf7b0d799..3aca9dd5aa 100644 --- a/system/doc/design_principles/code_lock_2.png +++ b/system/doc/design_principles/code_lock_2.png diff --git a/system/doc/design_principles/fsm.xml b/system/doc/design_principles/fsm.xml deleted file mode 100644 index 4f2b75e6e8..0000000000 --- a/system/doc/design_principles/fsm.xml +++ /dev/null @@ -1,338 +0,0 @@ -<?xml version="1.0" encoding="utf-8" ?> -<!DOCTYPE chapter SYSTEM "chapter.dtd"> - -<chapter> - <header> - <copyright> - <year>1997</year><year>2016</year> - <holder>Ericsson AB. All Rights Reserved.</holder> - </copyright> - <legalnotice> - Licensed under the Apache License, Version 2.0 (the "License"); - you may not use this file except in compliance with the License. - You may obtain a copy of the License at - - http://www.apache.org/licenses/LICENSE-2.0 - - Unless required by applicable law or agreed to in writing, software - distributed under the License is distributed on an "AS IS" BASIS, - WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - See the License for the specific language governing permissions and - limitations under the License. - - </legalnotice> - - <title>gen_fsm Behaviour</title> - <prepared></prepared> - <docno></docno> - <date></date> - <rev></rev> - <file>fsm.xml</file> - </header> - <marker id="gen_fsm behaviour"></marker> - <note> - <p> - There is a new behaviour - <seealso marker="statem"><c>gen_statem</c></seealso> - that is intended to replace <c>gen_fsm</c> for new code. - It has the same features and add some really useful. - This module will not be removed for the foreseeable future - to keep old state machine implementations running. - </p> - </note> - <p>This section is to be read with the <c>gen_fsm(3)</c> manual page - in STDLIB, where all interface functions and callback - functions are described in detail.</p> - - <section> - <title>Finite-State Machines</title> - <p>A Finite-State Machine (FSM) can be described as a set of - relations of the form:</p> - <pre> -State(S) x Event(E) -> Actions(A), State(S')</pre> - <p>These relations are interpreted as meaning:</p> - <quote> - <p>If we are in state <c>S</c> and event <c>E</c> occurs, we - are to perform actions <c>A</c> and make a transition to - state <c>S'</c>.</p> - </quote> - <p>For an FSM implemented using the <c>gen_fsm</c> behaviour, - the state transition rules are written as a number of Erlang - functions, which conform to the following convention:</p> - <pre> -StateName(Event, StateData) -> - .. code for actions here ... - {next_state, StateName', StateData'}</pre> - </section> - - <section> - <title>Example</title> - <p>A door with a code lock can be viewed as an FSM. Initially, - the door is locked. Anytime someone presses a button, this - generates an event. Depending on what buttons have been pressed - before, the sequence so far can be correct, incomplete, or wrong.</p> - <p>If it is correct, the door is unlocked for 30 seconds (30,000 ms). - If it is incomplete, we wait for another button to be pressed. If - it is is wrong, we start all over, waiting for a new button - sequence.</p> - <p>Implementing the code lock FSM using <c>gen_fsm</c> results in - the following callback module:</p> - <marker id="ex"></marker> - <code type="none"><![CDATA[ --module(code_lock). --behaviour(gen_fsm). - --export([start_link/1]). --export([button/1]). --export([init/1, locked/2, open/2]). - -start_link(Code) -> - gen_fsm:start_link({local, code_lock}, code_lock, lists:reverse(Code), []). - -button(Digit) -> - gen_fsm:send_event(code_lock, {button, Digit}). - -init(Code) -> - {ok, locked, {[], Code}}. - -locked({button, Digit}, {SoFar, Code}) -> - case [Digit|SoFar] of - Code -> - do_unlock(), - {next_state, open, {[], Code}, 30000}; - Incomplete when length(Incomplete)<length(Code) -> - {next_state, locked, {Incomplete, Code}}; - _Wrong -> - {next_state, locked, {[], Code}} - end. - -open(timeout, State) -> - do_lock(), - {next_state, locked, State}.]]></code> - <p>The code is explained in the next sections.</p> - </section> - - <section> - <title>Starting gen_fsm</title> - <p>In the example in the previous section, the <c>gen_fsm</c> is - started by calling <c>code_lock:start_link(Code)</c>:</p> - <code type="none"> -start_link(Code) -> - gen_fsm:start_link({local, code_lock}, code_lock, lists:reverse(Code), []). - </code> - <p><c>start_link</c> calls the function <c>gen_fsm:start_link/4</c>, - which spawns and links to a new process, a <c>gen_fsm</c>.</p> - <list type="bulleted"> - <item> - <p>The first argument, <c>{local, code_lock}</c>, specifies - the name. In this case, the <c>gen_fsm</c> is locally - registered as <c>code_lock</c>.</p> - <p>If the name is omitted, the <c>gen_fsm</c> is not registered. - Instead its pid must be used. The name can also be given - as <c>{global, Name}</c>, in which case the <c>gen_fsm</c> is - registered using <c>global:register_name/2</c>.</p> - </item> - <item> - <p>The second argument, <c>code_lock</c>, is the name of - the callback module, that is, the module where the callback - functions are located.</p> - <p>The interface functions (<c>start_link</c> and <c>button</c>) - are then located in the same module as the callback - functions (<c>init</c>, <c>locked</c>, and <c>open</c>). This - is normally good programming practice, to have the code - corresponding to one process contained in one module.</p> - </item> - <item> - <p>The third argument, <c>Code</c>, is a list of digits that - which is passed reversed to the callback function <c>init</c>. - Here, <c>init</c> - gets the correct code for the lock as indata.</p> - </item> - <item> - <p>The fourth argument, <c>[]</c>, is a list of options. See - the <c>gen_fsm(3)</c> manual page for available options.</p> - </item> - </list> - <p>If name registration succeeds, the new <c>gen_fsm</c> process calls - the callback function <c>code_lock:init(Code)</c>. This function - is expected to return <c>{ok, StateName, StateData}</c>, where - <c>StateName</c> is the name of the initial state of the - <c>gen_fsm</c>. In this case <c>locked</c>, assuming the door is - locked to begin with. <c>StateData</c> is the internal state of - the <c>gen_fsm</c>. (For <c>gen_fsm</c>, the internal state is - often referred to 'state data' to - distinguish it from the state as in states of a state machine.) - In this case, the state data is the button sequence so far (empty - to begin with) and the correct code of the lock.</p> - <code type="none"> -init(Code) -> - {ok, locked, {[], Code}}.</code> - <p><c>gen_fsm:start_link</c> is synchronous. It does not return until - the <c>gen_fsm</c> has been initialized and is ready to - receive notifications.</p> - <p><c>gen_fsm:start_link</c> must be used if the <c>gen_fsm</c> is - part of a supervision tree, that is, started by a supervisor. There - is another function, <c>gen_fsm:start</c>, to start a standalone - <c>gen_fsm</c>, that is, a <c>gen_fsm</c> that is not part of a - supervision tree.</p> - </section> - - <section> - <title>Notifying about Events</title> - <p>The function notifying the code lock about a button event is - implemented using <c>gen_fsm:send_event/2</c>:</p> - <code type="none"> -button(Digit) -> - gen_fsm:send_event(code_lock, {button, Digit}).</code> - <p><c>code_lock</c> is the name of the <c>gen_fsm</c> and must - agree with the name used to start it. - <c>{button, Digit}</c> is the actual event.</p> - <p>The event is made into a message and sent to the <c>gen_fsm</c>. - When the event is received, the <c>gen_fsm</c> calls - <c>StateName(Event, StateData)</c>, which is expected to return a - tuple <c>{next_state,StateName1,StateData1}</c>. - <c>StateName</c> is the name of the current state and - <c>StateName1</c> is the name of the next state to go to. - <c>StateData1</c> is a new value for the state data of - the <c>gen_fsm</c>.</p> - <code type="none"><![CDATA[ -locked({button, Digit}, {SoFar, Code}) -> - case [Digit|SoFar] of - Code -> - do_unlock(), - {next_state, open, {[], Code}, 30000}; - Incomplete when length(Incomplete)<length(Code) -> - {next_state, locked, {Incomplete, Code}}; - _Wrong -> - {next_state, locked, {[], Code}}; - end. - -open(timeout, State) -> - do_lock(), - {next_state, locked, State}.]]></code> - <p>If the door is locked and a button is pressed, the complete - button sequence so far is compared with the correct code for - the lock and, depending on the result, the door is either unlocked - and the <c>gen_fsm</c> goes to state <c>open</c>, or the door - remains in state <c>locked</c>.</p> - </section> - - <section> - <title>Time-Outs</title> - <p>When a correct code has been given, the door is unlocked and - the following tuple is returned from <c>locked/2</c>:</p> - <code type="none"> -{next_state, open, {[], Code}, 30000};</code> - <p>30,000 is a time-out value in milliseconds. After this time, - that is, 30 seconds, a time-out occurs. Then, - <c>StateName(timeout, StateData)</c> is called. The time-out - then occurs when the door has been in state <c>open</c> for 30 - seconds. After that the door is locked again:</p> - <code type="none"> -open(timeout, State) -> - do_lock(), - {next_state, locked, State}.</code> - </section> - - <section> - <title>All State Events</title> - <p>Sometimes an event can arrive at any state of the <c>gen_fsm</c>. - Instead of sending the message with <c>gen_fsm:send_event/2</c> - and writing one clause handling the event for each state function, - the message can be sent with <c>gen_fsm:send_all_state_event/2</c> - and handled with <c>Module:handle_event/3</c>:</p> - <code type="none"> --module(code_lock). -... --export([stop/0]). -... - -stop() -> - gen_fsm:send_all_state_event(code_lock, stop). - -... - -handle_event(stop, _StateName, StateData) -> - {stop, normal, StateData}.</code> - </section> - - <section> - <title>Stopping</title> - - <section> - <title>In a Supervision Tree</title> - <p>If the <c>gen_fsm</c> is part of a supervision tree, no stop - function is needed. The <c>gen_fsm</c> is automatically - terminated by its supervisor. Exactly how this is done is - defined by a - <seealso marker="sup_princ#shutdown">shutdown strategy</seealso> - set in the supervisor.</p> - <p>If it is necessary to clean up before termination, the shutdown - strategy must be a time-out value and the <c>gen_fsm</c> must be - set to trap exit signals in the <c>init</c> function. When ordered - to shutdown, the <c>gen_fsm</c> then calls the callback function - <c>terminate(shutdown, StateName, StateData)</c>:</p> - <code type="none"> -init(Args) -> - ..., - process_flag(trap_exit, true), - ..., - {ok, StateName, StateData}. - -... - -terminate(shutdown, StateName, StateData) -> - ..code for cleaning up here.. - ok.</code> - </section> - - <section> - <title>Standalone gen_fsm</title> - <p>If the <c>gen_fsm</c> is not part of a supervision tree, a stop - function can be useful, for example:</p> - <code type="none"> -... --export([stop/0]). -... - -stop() -> - gen_fsm:send_all_state_event(code_lock, stop). -... - -handle_event(stop, _StateName, StateData) -> - {stop, normal, StateData}. - -... - -terminate(normal, _StateName, _StateData) -> - ok.</code> - <p>The callback function handling the <c>stop</c> event returns a - tuple, <c>{stop,normal,StateData1}</c>, where <c>normal</c> - specifies that it is a normal termination and <c>StateData1</c> - is a new value for the state data of the <c>gen_fsm</c>. This - causes the <c>gen_fsm</c> to call - <c>terminate(normal,StateName,StateData1)</c> and then - it terminates gracefully:</p> - </section> - </section> - - <section> - <title>Handling Other Messages</title> - <p>If the <c>gen_fsm</c> is to be able to receive other messages - than events, the callback function - <c>handle_info(Info, StateName, StateData)</c> must be implemented - to handle them. Examples of - other messages are exit messages, if the <c>gen_fsm</c> is linked to - other processes (than the supervisor) and trapping exit signals.</p> - <code type="none"> -handle_info({'EXIT', Pid, Reason}, StateName, StateData) -> - ..code to handle exits here.. - {next_state, StateName1, StateData1}.</code> - <p>The code_change method must also be implemented.</p> - <code type="none"> -code_change(OldVsn, StateName, StateData, Extra) -> - ..code to convert state (and more) during code change - {ok, NextStateName, NewStateData}</code> - </section> -</chapter> - diff --git a/system/doc/design_principles/part.xml b/system/doc/design_principles/part.xml index 6495211e04..899c7f2afe 100644 --- a/system/doc/design_principles/part.xml +++ b/system/doc/design_principles/part.xml @@ -4,7 +4,7 @@ <part xmlns:xi="http://www.w3.org/2001/XInclude"> <header> <copyright> - <year>1997</year><year>2016</year> + <year>1997</year><year>2017</year> <holder>Ericsson AB. All Rights Reserved.</holder> </copyright> <legalnotice> @@ -30,7 +30,6 @@ </header> <xi:include href="des_princ.xml"/> <xi:include href="gen_server_concepts.xml"/> - <xi:include href="fsm.xml"/> <xi:include href="statem.xml"/> <xi:include href="events.xml"/> <xi:include href="sup_princ.xml"/> diff --git a/system/doc/design_principles/spec_proc.xml b/system/doc/design_principles/spec_proc.xml index 5b156ac263..5f4e7ac685 100644 --- a/system/doc/design_principles/spec_proc.xml +++ b/system/doc/design_principles/spec_proc.xml @@ -4,7 +4,7 @@ <chapter> <header> <copyright> - <year>1997</year><year>2016</year> + <year>1997</year><year>2017</year> <holder>Ericsson AB. All Rights Reserved.</holder> </copyright> <legalnotice> @@ -45,61 +45,63 @@ <p>The <c>sys</c> module has functions for simple debugging of processes implemented using behaviours. The <c>code_lock</c> example from - <seealso marker="fsm#ex">gen_fsm Behaviour</seealso> + <seealso marker="statem#Example">gen_statem Behaviour</seealso> is used to illustrate this:</p> <pre> -% <input>erl</input> -Erlang (BEAM) emulator version 5.2.3.6 [hipe] [threads:0] +Erlang/OTP 20 [DEVELOPMENT] [erts-9.0] [source-5ace45e] [64-bit] [smp:8:8] [ds:8:8:10] [async-threads:10] [hipe] [kernel-poll:false] -Eshell V5.2.3.6 (abort with ^G) -1> <input>code_lock:start_link([1,2,3,4]).</input> -{ok,<0.32.0>} -2> <input>sys:statistics(code_lock, true).</input> +Eshell V9.0 (abort with ^G) +1> code_lock:start_link([1,2,3,4]). +Lock +{ok,<0.63.0>} +2> sys:statistics(code_lock, true). ok -3> <input>sys:trace(code_lock, true).</input> +3> sys:trace(code_lock, true). ok -4> <input>code_lock:button(4).</input> -*DBG* code_lock got event {button,4} in state closed +4> code_lock:button(1). +*DBG* code_lock receive cast {button,1} in state locked ok -*DBG* code_lock switched to state closed -5> <input>code_lock:button(3).</input> -*DBG* code_lock got event {button,3} in state closed +*DBG* code_lock consume cast {button,1} in state locked +5> code_lock:button(2). +*DBG* code_lock receive cast {button,2} in state locked ok -*DBG* code_lock switched to state closed -6> <input>code_lock:button(2).</input> -*DBG* code_lock got event {button,2} in state closed +*DBG* code_lock consume cast {button,2} in state locked +6> code_lock:button(3). +*DBG* code_lock receive cast {button,3} in state locked ok -*DBG* code_lock switched to state closed -7> <input>code_lock:button(1).</input> -*DBG* code_lock got event {button,1} in state closed +*DBG* code_lock consume cast {button,3} in state locked +7> code_lock:button(4). +*DBG* code_lock receive cast {button,4} in state locked ok -OPEN DOOR -*DBG* code_lock switched to state open -*DBG* code_lock got event timeout in state open -CLOSE DOOR -*DBG* code_lock switched to state closed -8> <input>sys:statistics(code_lock, get).</input> -{ok,[{start_time,{{2003,6,12},{14,11,40}}}, - {current_time,{{2003,6,12},{14,12,14}}}, - {reductions,333}, +Unlock +*DBG* code_lock consume cast {button,4} in state locked +*DBG* code_lock receive state_timeout lock in state open +Lock +*DBG* code_lock consume state_timeout lock in state open +8> sys:statistics(code_lock, get). +{ok,[{start_time,{{2017,4,21},{16,8,7}}}, + {current_time,{{2017,4,21},{16,9,42}}}, + {reductions,2973}, {messages_in,5}, {messages_out,0}]} -9> <input>sys:statistics(code_lock, false).</input> +9> sys:statistics(code_lock, false). ok -10> <input>sys:trace(code_lock, false).</input> +10> sys:trace(code_lock, false). ok -11> <input>sys:get_status(code_lock).</input> -{status,<0.32.0>, - {module,gen_fsm}, - [[{'$ancestors',[<0.30.0>]}, - {'$initial_call',{gen,init_it, - [gen_fsm,<0.30.0>,<0.30.0>, - {local,code_lock}, - code_lock, - [1,2,3,4], - []]}}], - running,<0.30.0>,[], - [code_lock,closed,{[],[1,2,3,4]},code_lock,infinity]]}</pre> +11> sys:get_status(code_lock). +{status,<0.63.0>, + {module,gen_statem}, + [[{'$initial_call',{code_lock,init,1}}, + {'$ancestors',[<0.61.0>]}], + running,<0.61.0>,[], + [{header,"Status for state machine code_lock"}, + {data,[{"Status",running}, + {"Parent",<0.61.0>}, + {"Logged Events",[]}, + {"Postponed",[]}]}, + {data,[{"State", + {locked,#{code => [1,2,3,4],remaining => [1,2,3,4]}}}]}]]} + </pre> </section> <section> diff --git a/system/doc/design_principles/statem.xml b/system/doc/design_principles/statem.xml index b63327291d..7febe31df3 100644 --- a/system/doc/design_principles/statem.xml +++ b/system/doc/design_principles/statem.xml @@ -4,7 +4,7 @@ <chapter> <header> <copyright> - <year>2016</year> + <year>2016</year><year>2017</year> <holder>Ericsson AB. All Rights Reserved.</holder> </copyright> <legalnotice> @@ -29,11 +29,11 @@ <rev></rev> <file>statem.xml</file> </header> - <marker id="gen_statem behaviour"></marker> + <marker id="gen_statem Behaviour" /> <p> This section is to be read with the <seealso marker="stdlib:gen_statem"><c>gen_statem(3)</c></seealso> - manual page in <c>STDLIB</c>, where all interface functions and callback + manual page in STDLIB, where all interface functions and callback functions are described in detail. </p> <note> @@ -50,9 +50,10 @@ <!-- =================================================================== --> <section> + <marker id="Event-Driven State Machines" /> <title>Event-Driven State Machines</title> <p> - Established Automata theory does not deal much with + Established Automata Theory does not deal much with how a state transition is triggered, but assumes that the output is a function of the input (and the state) and that they are @@ -94,7 +95,7 @@ State(S) x Event(E) -> Actions(A), State(S')</pre> <!-- =================================================================== --> <section> - <marker id="callback_modes" /> + <marker id="Callback Modes" /> <title>Callback Modes</title> <p> The <c>gen_statem</c> behavior supports two callback modes: @@ -109,8 +110,13 @@ State(S) x Event(E) -> Actions(A), State(S')</pre> </p> <pre> StateName(EventType, EventContent, Data) -> - .. code for actions here ... - {next_state, NewStateName, NewData}.</pre> + ... code for actions here ... + {next_state, NewStateName, NewData}. + </pre> + <p> + This form is used in most examples here for example in section + <seealso marker="#Example">Example</seealso>. + </p> </item> <item> <p> @@ -120,8 +126,14 @@ StateName(EventType, EventContent, Data) -> </p> <pre> handle_event(EventType, EventContent, State, Data) -> - .. code for actions here ... - {next_state, NewState, NewData}</pre> + ... code for actions here ... + {next_state, NewState, NewData} + </pre> + <p> + See section + <seealso marker="#One Event Handler">One Event Handler</seealso> + for an example. + </p> </item> </list> <p> @@ -134,10 +146,11 @@ handle_event(EventType, EventContent, State, Data) -> </p> <section> + <marker id="Choosing the Callback Mode" /> <title>Choosing the Callback Mode</title> <p> The two - <seealso marker="#callback_modes">callback modes</seealso> + <seealso marker="#Callback Modes">callback modes</seealso> give different possibilities and restrictions, but one goal remains: you want to handle all possible combinations of @@ -195,10 +208,211 @@ handle_event(EventType, EventContent, State, Data) -> <!-- =================================================================== --> <section> + <marker id="State Enter Calls" /> + <title>State Enter Calls</title> + <p> + The <c>gen_statem</c> behavior can regardless of callback mode + automatically + <seealso marker="stdlib:gen_statem#type-state_enter"> + call the state callback + </seealso> + with special arguments whenever the state changes + so you can write state entry actions + near the rest of the state transition rules. + It typically looks like this: + </p> + <pre> +StateName(enter, _OldState, Data) -> + ... code for state entry actions here ... + {keep_state, NewData}; +StateName(EventType, EventContent, Data) -> + ... code for actions here ... + {next_state, NewStateName, NewData}.</pre> + <p> + Depending on how your state machine is specified, + this can be a very useful feature, + but it forces you to handle the state enter calls in all states. + See also the + <seealso marker="#State Entry Actions"> + State Entry Actions + </seealso> + chapter. + </p> + </section> + +<!-- =================================================================== --> + + <section> + <marker id="Actions" /> + <title>Actions</title> + <p> + In the first section + <seealso marker="#Event-Driven State Machines"> + Event-Driven State Machines + </seealso> + actions were mentioned as a part of + the general state machine model. These general actions + are implemented with the code that callback module + <c>gen_statem</c> executes in an event-handling + callback function before returning + to the <c>gen_statem</c> engine. + </p> + <p> + There are more specific state-transition actions + that a callback function can order the <c>gen_statem</c> + engine to do after the callback function return. + These are ordered by returning a list of + <seealso marker="stdlib:gen_statem#type-action">actions</seealso> + in the + <seealso marker="stdlib:gen_statem#type-state_callback_result">return tuple</seealso> + from the + <seealso marker="stdlib:gen_statem#Module:StateName/3">callback function</seealso>. + These state transition actions affect the <c>gen_statem</c> + engine itself and can do the following: + </p> + <list type="bulleted"> + <item> + <seealso marker="stdlib:gen_statem#type-postpone"> + Postpone + </seealso> + the current event, see section + <seealso marker="#Postponing Events">Postponing Events</seealso> + </item> + <item> + <seealso marker="stdlib:gen_statem#type-hibernate"> + Hibernate + </seealso> + the <c>gen_statem</c>, treated in + <seealso marker="#Hibernation">Hibernation</seealso> + </item> + <item> + Start a + <seealso marker="stdlib:gen_statem#type-state_timeout"> + state time-out</seealso>, + read more in section + <seealso marker="#State Time-Outs">State Time-Outs</seealso> + </item> + <item> + Start a + <seealso marker="stdlib:gen_statem#type-generic_timeout"> + generic time-out</seealso>, + read more in section + <seealso marker="#Generic Time-Outs">Generic Time-Outs</seealso> + </item> + <item> + Start an + <seealso marker="stdlib:gen_statem#type-event_timeout">event time-out</seealso>, + see more in section + <seealso marker="#Event Time-Outs">Event Time-Outs</seealso> + </item> + <item> + <seealso marker="stdlib:gen_statem#type-reply_action"> + Reply + </seealso> + to a caller, mentioned at the end of section + <seealso marker="#All State Events">All State Events</seealso> + </item> + <item> + Generate the + <seealso marker="stdlib:gen_statem#type-action"> + next event + </seealso> + to handle, see section + <seealso marker="#Self-Generated Events">Self-Generated Events</seealso> + </item> + </list> + <p> + For details, see the + <seealso marker="stdlib:gen_statem#type-action"> + <c>gen_statem(3)</c> + </seealso> + manual page. + You can, for example, reply to many callers, + generate multiple next events, + and set time-outs to relative or absolute times. + </p> + </section> + +<!-- =================================================================== --> + + <section> + <marker id="Event Types" /> + <title>Event Types</title> + <p> + Events are categorized in different + <seealso marker="stdlib:gen_statem#type-event_type">event types</seealso>. + Events of all types are handled in the same callback function, + for a given state, and the function gets + <c>EventType</c> and <c>EventContent</c> as arguments. + </p> + <p> + The following is a complete list of event types and where + they come from: + </p> + <taglist> + <tag><c>cast</c></tag> + <item> + Generated by + <seealso marker="stdlib:gen_statem#cast/2"><c>gen_statem:cast</c></seealso>. + </item> + <tag><c>{call,From}</c></tag> + <item> + Generated by + <seealso marker="stdlib:gen_statem#call/2"><c>gen_statem:call</c></seealso>, + where <c>From</c> is the reply address to use + when replying either through the state transition action + <c>{reply,From,Msg}</c> or by calling + <seealso marker="stdlib:gen_statem#reply/1"><c>gen_statem:reply</c></seealso>. + </item> + <tag><c>info</c></tag> + <item> + Generated by any regular process message sent to + the <c>gen_statem</c> process. + </item> + <tag><c>state_timeout</c></tag> + <item> + Generated by state transition action + <seealso marker="stdlib:gen_statem#type-state_timeout"> + <c>{state_timeout,Time,EventContent}</c> + </seealso> + state timer timing out. + </item> + <tag><c>{timeout,Name}</c></tag> + <item> + Generated by state transition action + <seealso marker="stdlib:gen_statem#type-generic_timeout"> + <c>{{timeout,Name},Time,EventContent}</c> + </seealso> + generic timer timing out. + </item> + <tag><c>timeout</c></tag> + <item> + Generated by state transition action + <seealso marker="stdlib:gen_statem#type-event_timeout"> + <c>{timeout,Time,EventContent}</c> + </seealso> + (or its short form <c>Time</c>) + event timer timing out. + </item> + <tag><c>internal</c></tag> + <item> + Generated by state transition + <seealso marker="stdlib:gen_statem#type-action">action</seealso> + <c>{next_event,internal,EventContent}</c>. + All event types above can also be generated using + <c>{next_event,EventType,EventContent}</c>. + </item> + </taglist> + </section> + +<!-- =================================================================== --> + + <section> + <marker id="Example" /> <title>Example</title> <p> This example starts off as equivalent to the example in section - <seealso marker="fsm"><c>gen_fsm</c> Behavior</seealso>. + <seealso marker="fsm"><c>gen_fsm</c> Behavior</seealso>. In later sections, additions and tweaks are made using features in <c>gen_statem</c> that <c>gen_fsm</c> does not have. The end of this chapter provides the example again @@ -221,16 +435,14 @@ handle_event(EventType, EventContent, State, Data) -> This code lock state machine can be implemented using <c>gen_statem</c> with the following callback module: </p> - <marker id="ex"></marker> <code type="erl"><![CDATA[ -module(code_lock). -behaviour(gen_statem). -define(NAME, code_lock). --define(CALLBACK_MODE, state_functions). -export([start_link/1]). -export([button/1]). --export([init/1,terminate/3,code_change/4]). +-export([init/1,callback_mode/0,terminate/3,code_change/4]). -export([locked/3,open/3]). start_link(Code) -> @@ -242,7 +454,10 @@ button(Digit) -> init(Code) -> do_lock(), Data = #{code => Code, remaining => Code}, - {?CALLBACK_MODE,locked,Data}. + {ok, locked, Data}. + +callback_mode() -> + state_functions. locked( cast, {button,Digit}, @@ -250,19 +465,19 @@ locked( case Remaining of [Digit] -> do_unlock(), - {next_state,open,Data#{remaining := Code},10000}; + {next_state, open, Data#{remaining := Code}, + [{state_timeout,10000,lock}]}; [Digit|Rest] -> % Incomplete - {next_state,locked,Data#{remaining := Rest}}; + {next_state, locked, Data#{remaining := Rest}}; _Wrong -> - {next_state,locked,Data#{remaining := Code}} + {next_state, locked, Data#{remaining := Code}} end. -open(timeout, _, Data) -> +open(state_timeout, lock, Data) -> do_lock(), - {next_state,locked,Data}; + {next_state, locked, Data}; open(cast, {button,_}, Data) -> - do_lock(), - {next_state,locked,Data}. + {next_state, open, Data}. do_lock() -> io:format("Lock~n", []). @@ -273,7 +488,7 @@ terminate(_Reason, State, _Data) -> State =/= locked andalso do_lock(), ok. code_change(_Vsn, State, Data, _Extra) -> - {?CALLBACK_MODE,State,Data}. + {ok, State, Data}. ]]></code> <p>The code is explained in the next sections.</p> </section> @@ -281,6 +496,7 @@ code_change(_Vsn, State, Data, _Extra) -> <!-- =================================================================== --> <section> + <marker id="Starting gen_statem" /> <title>Starting gen_statem</title> <p> In the example in the previous section, <c>gen_statem</c> is @@ -308,7 +524,7 @@ start_link(Code) -> as <c>{global,Name}</c>, then the <c>gen_statem</c> is registered using <seealso marker="kernel:global#register_name/2"><c>global:register_name/2</c></seealso> - in <c>Kernel</c>. + in Kernel. </p> </item> <item> @@ -343,14 +559,8 @@ start_link(Code) -> <p> If name registration succeeds, the new <c>gen_statem</c> process calls callback function <c>code_lock:init(Code)</c>. - This function is expected to return <c>{CallbackMode,State,Data}</c>, - where - <seealso marker="#callback_modes"><c>CallbackMode</c></seealso> - selects callback module state function mode, in this case - <seealso marker="stdlib:gen_statem#type-callback_mode"><c>state_functions</c></seealso> - through macro <c>?CALLBACK_MODE</c>. That is, each state - has got its own handler function. - <c>State</c> is the initial state of the <c>gen_statem</c>, + This function is expected to return <c>{ok, State, Data}</c>, + where <c>State</c> is the initial state of the <c>gen_statem</c>, in this case <c>locked</c>; assuming that the door is locked to begin with. <c>Data</c> is the internal server data of the <c>gen_statem</c>. Here the server data is a <seealso marker="stdlib:maps">map</seealso> @@ -359,11 +569,12 @@ start_link(Code) -> that stores the remaining correct button sequence (the same as the <c>code</c> to begin with). </p> + <code type="erl"><![CDATA[ init(Code) -> do_lock(), Data = #{code => Code, remaining => Code}, - {?CALLBACK_MODE,locked,Data}. + {ok,locked,Data}. ]]></code> <p>Function <seealso marker="stdlib:gen_statem#start_link/3"><c>gen_statem:start_link</c></seealso> @@ -380,11 +591,27 @@ init(Code) -> can be used to start a standalone <c>gen_statem</c>, that is, a <c>gen_statem</c> that is not part of a supervision tree. </p> + + <code type="erl"><![CDATA[ +callback_mode() -> + state_functions. + ]]></code> + <p> + Function + <seealso marker="stdlib:gen_statem#Module:callback_mode/0"><c>Module:callback_mode/0</c></seealso> + selects the + <seealso marker="#Callback Modes"><c>CallbackMode</c></seealso> + for the callback module, in this case + <seealso marker="stdlib:gen_statem#type-callback_mode"><c>state_functions</c></seealso>. + That is, each state has got its own handler function. + </p> + </section> <!-- =================================================================== --> <section> + <marker id="Handling Events" /> <title>Handling Events</title> <p>The function notifying the code lock about a button event is implemented using @@ -404,11 +631,13 @@ button(Digit) -> The event is made into a message and sent to the <c>gen_statem</c>. When the event is received, the <c>gen_statem</c> calls <c>StateName(cast, Event, Data)</c>, which is expected to - return a tuple <c>{next_state,NewStateName,NewData}</c>. + return a tuple <c>{next_state, NewStateName, NewData}</c>, + or <c>{next_state, NewStateName, NewData, Actions}</c>. <c>StateName</c> is the name of the current state and <c>NewStateName</c> is the name of the next state to go to. <c>NewData</c> is a new value for the server data of - the <c>gen_statem</c>. + the <c>gen_statem</c>, and <c>Actions</c> is a list of + actions on the <c>gen_statem</c> engine. </p> <code type="erl"><![CDATA[ locked( @@ -417,19 +646,19 @@ locked( case Remaining of [Digit] -> % Complete do_unlock(), - {next_state,open,Data#{remaining := Code},10000}; + {next_state, open, Data#{remaining := Code}, + [{state_timeout,10000,lock}]}; [Digit|Rest] -> % Incomplete - {next_state,locked,Data#{remaining := Rest}}; + {next_state, locked, Data#{remaining := Rest}}; [_|_] -> % Wrong - {next_state,locked,Data#{remaining := Code}} + {next_state, locked, Data#{remaining := Code}} end. -open(timeout, _, Data) -> +open(state_timeout, lock, Data) -> do_lock(), - {next_state,locked,Data}; + {next_state, locked, Data}; open(cast, {button,_}, Data) -> - do_lock(), - {next_state,locked,Data}. + {next_state, open, Data}. ]]></code> <p> If the door is locked and a button is pressed, the pressed @@ -443,38 +672,55 @@ open(cast, {button,_}, Data) -> restarts from the start of the code sequence. </p> <p> - In state <c>open</c>, any button locks the door, as - any event cancels the event timer, so no - time-out event occurs after a button event. + If the whole code is correct, the server changes states + to <c>open</c>. + </p> + <p> + In state <c>open</c>, a button event is ignored + by staying in the same state. This can also be done + by returning <c>{keep_state, Data}</c> or in this case + since <c>Data</c> unchanged even by returning + <c>keep_state_and_data</c>. </p> </section> <section> - <title>Event Time-Outs</title> + <marker id="State Time-Outs" /> + <title>State Time-Outs</title> <p> When a correct code has been given, the door is unlocked and the following tuple is returned from <c>locked/2</c>: </p> <code type="erl"><![CDATA[ -{next_state,open,Data#{remaining := Code},10000}; +{next_state, open, Data#{remaining := Code}, + [{state_timeout,10000,lock}]}; ]]></code> <p> 10,000 is a time-out value in milliseconds. After this time (10 seconds), a time-out occurs. - Then, <c>StateName(timeout, 10000, Data)</c> is called. + Then, <c>StateName(state_timeout, lock, Data)</c> is called. The time-out occurs when the door has been in state <c>open</c> for 10 seconds. After that the door is locked again: </p> <code type="erl"><![CDATA[ -open(timeout, _, Data) -> +open(state_timeout, lock, Data) -> do_lock(), - {next_state,locked,Data}; + {next_state, locked, Data}; ]]></code> + <p> + The timer for a state time-out is automatically cancelled + when the state machine changes states. You can restart + a state time-out by setting it to a new time, which cancels + the running timer and starts a new. This implies that + you can cancel a state time-out by restarting it with + time <c>infinity</c>. + </p> </section> <!-- =================================================================== --> <section> + <marker id="All State Events" /> <title>All State Events</title> <p> Sometimes events can arrive in any state of the <c>gen_statem</c>. @@ -507,21 +753,24 @@ open(EventType, EventContent, Data) -> handle_event(EventType, EventContent, Data). handle_event({call,From}, code_length, #{code := Code} = Data) -> - {keep_state,Data,[{reply,From,length(Code)}]}. + {keep_state, Data, [{reply,From,length(Code)}]}. ]]></code> <p> This example uses <seealso marker="stdlib:gen_statem#call/2"><c>gen_statem:call/2</c></seealso>, which waits for a reply from the server. The reply is sent with a <c>{reply,From,Reply}</c> tuple - in an action list in the <c>{keep_state,...}</c> tuple - that retains the current state. + in an action list in the <c>{keep_state, ...}</c> tuple + that retains the current state. This return form is convenient + when you want to stay in the current state but do not know or + care about what it is. </p> </section> <!-- =================================================================== --> <section> + <marker id="One Event Handler" /> <title>One Event Handler</title> <p> If mode <c>handle_event_function</c> is used, @@ -533,12 +782,11 @@ handle_event({call,From}, code_length, #{code := Code} = Data) -> </p> <code type="erl"><![CDATA[ ... --define(CALLBACK_MODE, handle_event_function). - -... -export([handle_event/4]). ... +callback_mode() -> + handle_event_function. handle_event(cast, {button,Digit}, State, #{code := Code} = Data) -> case State of @@ -546,19 +794,19 @@ handle_event(cast, {button,Digit}, State, #{code := Code} = Data) -> case maps:get(remaining, Data) of [Digit] -> % Complete do_unlock(), - {next_state,open,Data#{remaining := Code},10000}; + {next_state, open, Data#{remaining := Code}, + [{state_timeout,10000,lock}]}; [Digit|Rest] -> % Incomplete - {keep_state,Data#{remaining := Rest}}; + {keep_state, Data#{remaining := Rest}}; [_|_] -> % Wrong - {keep_state,Data#{remaining := Code}} + {keep_state, Data#{remaining := Code}} end; open -> - do_lock(), - {next_state,locked,Data} + keep_state_and_data end; -handle_event(timeout, _, open, Data) -> +handle_event(state_timeout, lock, open, Data) -> do_lock(), - {next_state,locked,Data}. + {next_state, locked, Data}. ... ]]></code> @@ -567,9 +815,11 @@ handle_event(timeout, _, open, Data) -> <!-- =================================================================== --> <section> + <marker id="Stopping" /> <title>Stopping</title> <section> + <marker id="In a Supervision Tree" /> <title>In a Supervision Tree</title> <p> If the <c>gen_statem</c> is part of a supervision tree, @@ -597,7 +847,7 @@ init(Args) -> callback function <c>terminate(shutdown, State, Data)</c>. </p> <p> - In the following example, function <c>terminate/3</c> + In this example, function <c>terminate/3</c> locks the door if it is open, so we do not accidentally leave the door open when the supervision tree terminates: </p> @@ -609,6 +859,7 @@ terminate(_Reason, State, _Data) -> </section> <section> + <marker id="Standalone gen_statem" /> <title>Standalone gen_statem</title> <p> If the <c>gen_statem</c> is not part of a supervision tree, @@ -635,127 +886,132 @@ stop() -> <!-- =================================================================== --> <section> - <title>Actions</title> + <marker id="Event Time-Outs" /> + <title>Event Time-Outs</title> <p> - In the first sections actions were mentioned as a part of - the general state machine model. These general actions - are implemented with the code that callback module - <c>gen_statem</c> executes in an event-handling - callback function before returning - to the <c>gen_statem</c> engine. + A time-out feature inherited from <c>gen_statem</c>'s predecessor + <seealso marker="stdlib:gen_fsm"><c>gen_fsm</c></seealso>, + is an event time-out, that is, + if an event arrives the timer is cancelled. + You get either an event or a time-out, but not both. </p> <p> - There are more specific state-transition actions - that a callback function can order the <c>gen_statem</c> - engine to do after the callback function return. - These are ordered by returning a list of - <seealso marker="stdlib:gen_statem#type-action">actions</seealso> - in the - <seealso marker="stdlib:gen_statem#type-state_function_result">return tuple</seealso> - from the - <seealso marker="stdlib:gen_statem#Module:StateName/3">callback function</seealso>. - These state transition actions affect the <c>gen_statem</c> - engine itself and can do the following: + It is ordered by the state transition action + <c>{timeout,Time,EventContent}</c>, or just <c>Time</c>, + or even just <c>Time</c> instead of an action list + (the latter is a form inherited from <c>gen_fsm</c>. </p> - <list type="bulleted"> - <item>Postpone the current event</item> - <item>Hibernate the <c>gen_statem</c></item> - <item>Start an event time-out</item> - <item>Reply to a caller</item> - <item>Generate the next event to handle</item> - </list> <p> - In the example earlier was mentioned the event time-out - and replying to a caller. - An example of event postponing is included later in this chapter. - For details, see the - <seealso marker="stdlib:gen_statem#type-action"><c>gen_statem(3)</c></seealso> - manual page. - You can, for example, reply to many callers - and generate multiple next events to handle. + This type of time-out is useful to for example act on inactivity. + Let us restart the code sequence + if no button is pressed for say 30 seconds: </p> - </section> - -<!-- =================================================================== --> + <code type="erl"><![CDATA[ +... - <section> - <title>Event Types</title> +locked( + timeout, _, + #{code := Code, remaining := Remaining} = Data) -> + {next_state, locked, Data#{remaining := Code}}; +locked( + cast, {button,Digit}, + #{code := Code, remaining := Remaining} = Data) -> +... + [Digit|Rest] -> % Incomplete + {next_state, locked, Data#{remaining := Rest}, 30000}; +... + ]]></code> <p> - The previous sections mentioned a few - <seealso marker="stdlib:gen_statem#type-event_type">event types</seealso>. - Events of all types are handled in the same callback function, - for a given state, and the function gets - <c>EventType</c> and <c>EventContent</c> as arguments. + Whenever we receive a button event we start an event time-out + of 30 seconds, and if we get an event type <c>timeout</c> + we reset the remaining code sequence. </p> <p> - The following is a complete list of event types and where - they come from: + An event time-out is cancelled by any other event so you either + get some other event or the time-out event. It is therefore + not possible nor needed to cancel or restart an event time-out. + Whatever event you act on has already cancelled + the event time-out... </p> - <taglist> - <tag><c>cast</c></tag> - <item> - Generated by - <seealso marker="stdlib:gen_statem#cast/2"><c>gen_statem:cast</c></seealso>. - </item> - <tag><c>{call,From}</c></tag> - <item> - Generated by - <seealso marker="stdlib:gen_statem#call/2"><c>gen_statem:call</c></seealso>, - where <c>From</c> is the reply address to use - when replying either through the state transition action - <c>{reply,From,Msg}</c> or by calling - <seealso marker="stdlib:gen_statem#reply/1"><c>gen_statem:reply</c></seealso>. - </item> - <tag><c>info</c></tag> - <item> - Generated by any regular process message sent to - the <c>gen_statem</c> process. - </item> - <tag><c>timeout</c></tag> - <item> - Generated by state transition action - <c>{timeout,Time,EventContent}</c> (or its short form <c>Time</c>) - timer timing out. - </item> - <tag><c>internal</c></tag> - <item> - Generated by state transition action - <c>{next_event,internal,EventContent}</c>. - All event types above can also be generated using - <c>{next_event,EventType,EventContent}</c>. - </item> - </taglist> </section> <!-- =================================================================== --> <section> - <title>State Time-Outs</title> + <marker id="Generic Time-Outs" /> + <title>Generic Time-Outs</title> <p> - The time-out event generated by state transition action - <c>{timeout,Time,EventContent}</c> is an event time-out, - that is, if an event arrives the timer is cancelled. - You get either an event or a time-out, but not both. + The previous example of state time-outs only work if + the state machine stays in the same state during the + time-out time. And event time-outs only work if no + disturbing unrelated events occur. + </p> + <p> + You may want to start a timer in one state and respond + to the time-out in another, maybe cancel the time-out + without changing states, or perhaps run multiple + time-outs in parallel. All this can be accomplished with + <seealso marker="stdlib:gen_statem#type-generic_timeout">generic time-outs</seealso>. + They may look a little bit like + <seealso marker="stdlib:gen_statem#type-event_timeout">event time-outs</seealso> + but contain a name to allow for any number of them simultaneously + and they are not automatically cancelled. </p> <p> - Often you want a timer not to be cancelled by any event - or you want to start a timer in one state and respond - to the time-out in another. This can be accomplished - with a regular Erlang timer: - <seealso marker="erts:erlang#start_timer/4"><c>erlang:start_timer</c></seealso>. + Here is how to accomplish the state time-out + in the previous example by instead using a generic time-out + named <c>open_tm</c>: </p> + <code type="erl"><![CDATA[ +... +locked( + cast, {button,Digit}, + #{code := Code, remaining := Remaining} = Data) -> + case Remaining of + [Digit] -> + do_unlock(), + {next_state, open, Data#{remaining := Code}, + [{{timeout,open_tm},10000,lock}]}; +... + +open({timeout,open_tm}, lock, Data) -> + do_lock(), + {next_state,locked,Data}; +open(cast, {button,_}, Data) -> + {keep_state,Data}; +... + ]]></code> + <p> + Just as + <seealso marker="#State Time-Outs">state time-outs</seealso> + you can restart or cancel a specific generic time-out + by setting it to a new time or <c>infinity</c>. + </p> + <p> + Another way to handle a late time-out can be to not cancel it, + but to ignore it if it arrives in a state + where it is known to be late. + </p> + </section> + +<!-- =================================================================== --> + + <section> + <marker id="Erlang Timers" /> + <title>Erlang Timers</title> <p> - For the example so far in this chapter: using the - <c>gen_statem</c> event timer has the consequence that - if a button event is generated while in the <c>open</c> state, - the time-out is cancelled and the button event is delivered. - So, we choose to lock the door if this occurred. + The most versatile way to handle time-outs is to use + Erlang Timers; see + <seealso marker="erts:erlang#start_timer/4"><c>erlang:start_timer3,4</c></seealso>. + Most time-out tasks can be performed with the + time-out features in <c>gen_statem</c>, + but an example of one that can not is if you should need + the return value from + <seealso marker="erts:erlang#cancel_timer/2"><c>erlang:cancel_timer(Tref)</c></seealso>, that is; the remaining time of the timer. </p> <p> - Suppose that we do not want a button to lock the door, - instead we want to ignore button events in the <c>open</c> state. - Then we start a timer when entering the <c>open</c> state - and waits for it to expire while ignoring button events: + Here is how to accomplish the state time-out + in the previous example by instead using an Erlang Timer: </p> <code type="erl"><![CDATA[ ... @@ -766,25 +1022,37 @@ locked( [Digit] -> do_unlock(), Tref = erlang:start_timer(10000, self(), lock), - {next_state,open,Data#{remaining := Code, timer := Tref}}; + {next_state, open, Data#{remaining := Code, timer => Tref}}; ... open(info, {timeout,Tref,lock}, #{timer := Tref} = Data) -> do_lock(), - {next_state,locked,Data}; + {next_state,locked,maps:remove(timer, Data)}; open(cast, {button,_}, Data) -> {keep_state,Data}; ... ]]></code> <p> + Removing the <c>timer</c> key from the map when we + change to state <c>locked</c> is not strictly + necessary since we can only get into state <c>open</c> + with an updated <c>timer</c> map value. But it can be nice + to not have outdated values in the state <c>Data</c>! + </p> + <p> If you need to cancel a timer because of some other event, you can use <seealso marker="erts:erlang#cancel_timer/2"><c>erlang:cancel_timer(Tref)</c></seealso>. - Notice that a time-out message cannot arrive after this, - unless you have postponed it (see the next section) before, + Note that a time-out message cannot arrive after this, + unless you have postponed it before (see the next section), so ensure that you do not accidentally postpone such messages. + Also note that a time-out message may have arrived + just before you cancelling it, so you may have to read out + such a message from the process mailbox depending on + the return value from + <seealso marker="erts:erlang#cancel_timer/2"><c>erlang:cancel_timer(Tref)</c></seealso>. </p> <p> - Another way to cancel a timer is not to cancel it, + Another way to handle a late time-out can be to not cancel it, but to ignore it if it arrives in a state where it is known to be late. </p> @@ -793,6 +1061,7 @@ open(cast, {button,_}, Data) -> <!-- =================================================================== --> <section> + <marker id="Postponing Events" /> <title>Postponing Events</title> <p> If you want to ignore a particular event in the current state @@ -817,20 +1086,28 @@ open(cast, {button,_}, Data) -> ... ]]></code> <p> - The fact that a postponed event is only retried after a state change - translates into a requirement on the event and state space. - If you have a choice between storing a state data item - in the <c>State</c> or in the <c>Data</c>: - if a change in the item value affects which events that - are handled, then this item is to be part of the state. + Since a postponed event is only retried after a state change, + you have to think about where to keep a state data item. + You can keep it in the server <c>Data</c> + or in the <c>State</c> itself, + for example by having two more or less identical states + to keep a boolean value, or by using a complex state with + <seealso marker="#Callback Modes">callback mode</seealso> + <seealso marker="stdlib:gen_statem#type-callback_mode"><c>handle_event_function</c></seealso>. + If a change in the value changes the set of events that is handled, + then the value should be kept in the State. + Otherwise no postponed events will be retried + since only the server Data changes. </p> <p> - You want to avoid that you maybe much later decide - to postpone an event in one state and by misfortune it is never retried, - as the code only changes the <c>Data</c> but not the <c>State</c>. + This is not important if you do not postpone events. + But if you later decide to start postponing some events, + then the design flaw of not having separate states + when they should be, might become a hard to find bug. </p> <section> + <marker id="Fuzzy State Diagrams" /> <title>Fuzzy State Diagrams</title> <p> It is not uncommon that a state diagram does not specify @@ -847,6 +1124,7 @@ open(cast, {button,_}, Data) -> </section> <section> + <marker id="Selective Receive" /> <title>Selective Receive</title> <p> Erlang's selective receive statement is often used to @@ -926,6 +1204,70 @@ do_unlock() -> <!-- =================================================================== --> <section> + <marker id="State Entry Actions" /> + <title>State Entry Actions</title> + <p> + Say you have a state machine specification + that uses state entry actions. + Allthough you can code this using self-generated events + (described in the next section), especially if just + one or a few states has got state entry actions, + this is a perfect use case for the built in + <seealso marker="#State Enter Calls">state enter calls</seealso>. + </p> + <p> + You return a list containing <c>state_enter</c> from your + <seealso marker="stdlib:gen_statem#Module:callback_mode/0"><c>callback_mode/0</c></seealso> + function and the <c>gen_statem</c> engine will call your + state callback once with the arguments + <c>(enter, OldState, ...)</c> whenever the state changes. + Then you just need to handle these event-like calls in all states. + </p> + <code type="erl"><![CDATA[ +... +init(Code) -> + process_flag(trap_exit, true), + Data = #{code => Code}, + {ok, locked, Data}. + +callback_mode() -> + [state_functions,state_enter]. + +locked(enter, _OldState, Data) -> + do_lock(), + {keep_state,Data#{remaining => Code}}; +locked( + cast, {button,Digit}, + #{code := Code, remaining := Remaining} = Data) -> + case Remaining of + [Digit] -> + {next_state, open, Data}; +... + +open(enter, _OldState, _Data) -> + do_unlock(), + {keep_state_and_data, [{state_timeout,10000,lock}]}; +open(state_timeout, lock, Data) -> + {next_state, locked, Data}; +... + ]]></code> + <p> + You can repeat the state entry code by returning one of + <c>{repeat_state, ...}</c>, <c>{repeat_state_and_data,_}</c> + or <c>repeat_state_and_data</c> that otherwise behaves + exactly like their <c>keep_state</c> siblings. + See the type + <seealso marker="stdlib:gen_statem#type-state_callback_result"> + <c>state_callback_result()</c> + </seealso> + in the reference manual. + </p> + </section> + +<!-- =================================================================== --> + + <section> + <marker id="Self-Generated Events" /> <title>Self-Generated Events</title> <p> It can sometimes be beneficial to be able to generate events @@ -943,67 +1285,71 @@ do_unlock() -> from your state machine to itself. </p> <p> - One example of using self-generated events can be when you have - a state machine specification that uses state entry actions. - You can code that using a dedicated function - to do the state transition. But if you want that code to be - visible besides the other state logic, you can insert - an <c>internal</c> event that does the entry actions. - This has the same unfortunate consequence as using - state transition functions: everywhere you go to - the state, you must explicitly - insert the <c>internal</c> event - or use a state transition function. + One example for this is to pre-process incoming data, for example + decrypting chunks or collecting characters up to a line break. + Purists may argue that this should be modelled with a separate + state machine that sends pre-processed events + to the main state machine. + But to decrease overhead the small pre-processing state machine + can be implemented in the common state event handling + of the main state machine using a few state data variables + that then sends the pre-processed events as internal events + to the main state machine. </p> <p> - The following is an implementation of entry actions - using <c>internal</c> events with content <c>enter</c> - using a helper function <c>enter/3</c> for state entry: + The following example uses an input model where you give the lock + characters with <c>put_chars(Chars)</c> and then call + <c>enter()</c> to finish the input. </p> <code type="erl"><![CDATA[ ... --define(CALLBACK_MODE, state_functions). - +-export(put_chars/1, enter/0). ... +put_chars(Chars) when is_binary(Chars) -> + gen_statem:call(?NAME, {chars,Chars}). -init(Code) -> - process_flag(trap_exit, true), - Data = #{code => Code}, - enter(?CALLBACK_MODE, locked, Data). +enter() -> + gen_statem:call(?NAME, enter). ... -locked(internal, enter, _Data) -> +locked(enter, _OldState, Data) -> do_lock(), - {keep_state,Data#{remaining => Code}}; -locked( - cast, {button,Digit}, - #{code := Code, remaining := Remaining} = Data) -> - case Remaining of - [Digit] -> - enter(next_state, open, Data); + {keep_state,Data#{remaining => Code, buf => []}}; ... -open(internal, enter, _Data) -> - Tref = erlang:start_timer(10000, self(), lock), - do_unlock(), - {keep_state,Data#{timer => Tref}}; -open(info, {timeout,Tref,lock}, #{timer := Tref} = Data) -> - enter(next_state, locked, Data); +handle_event({call,From}, {chars,Chars}, #{buf := Buf} = Data) -> + {keep_state, Data#{buf := [Chars|Buf], + [{reply,From,ok}]}; +handle_event({call,From}, enter, #{buf := Buf} = Data) -> + Chars = unicode:characters_to_binary(lists:reverse(Buf)), + try binary_to_integer(Chars) of + Digit -> + {keep_state, Data#{buf := []}, + [{reply,From,ok}, + {next_event,internal,{button,Chars}}]} + catch + error:badarg -> + {keep_state, Data#{buf := []}, + [{reply,From,{error,not_an_integer}}]} + end; ... - -enter(Tag, State, Data) -> - {Tag,State,Data,[{next_event,internal,enter}]}. ]]></code> + <p> + If you start this program with <c>code_lock:start([17])</c> + you can unlock with <c>code_lock:put_chars(<<"001">>), + code_lock:put_chars(<<"7">>), code_lock:enter()</c>. + </p> </section> <!-- =================================================================== --> <section> + <marker id="Example Revisited" /> <title>Example Revisited</title> <p> - This section includes the example after all mentioned modifications - and some more using the entry actions, + This section includes the example after most of the mentioned + modifications and some more using state enter calls, which deserves a new state diagram: </p> <image file="../design_principles/code_lock_2.png"> @@ -1019,6 +1365,7 @@ enter(Tag, State, Data) -> </p> <section> + <marker id="Callback Mode: state_functions" /> <title>Callback Mode: state_functions</title> <p> Using state functions: @@ -1027,11 +1374,10 @@ enter(Tag, State, Data) -> -module(code_lock). -behaviour(gen_statem). -define(NAME, code_lock_2). --define(CALLBACK_MODE, state_functions). -export([start_link/1,stop/0]). -export([button/1,code_length/0]). --export([init/1,terminate/3,code_change/4]). +-export([init/1,callback_mode/0,terminate/3,code_change/4]). -export([locked/3,open/3]). start_link(Code) -> @@ -1047,40 +1393,44 @@ code_length() -> init(Code) -> process_flag(trap_exit, true), Data = #{code => Code}, - enter(?CALLBACK_MODE, locked, Data). + {ok, locked, Data}. -locked(internal, enter, #{code := Code} = Data) -> +callback_mode() -> + [state_functions,state_enter]. + +locked(enter, _OldState, #{code := Code} = Data) -> do_lock(), - {keep_state,Data#{remaining => Code}}; + {keep_state, Data#{remaining => Code}}; +locked( + timeout, _, + #{code := Code, remaining := Remaining} = Data) -> + {keep_state, Data#{remaining := Code}}; locked( cast, {button,Digit}, #{code := Code, remaining := Remaining} = Data) -> case Remaining of [Digit] -> % Complete - enter(next_state, open, Data); + {next_state, open, Data}; [Digit|Rest] -> % Incomplete - {keep_state,Data#{remaining := Rest}}; + {keep_state, Data#{remaining := Rest}, 30000}; [_|_] -> % Wrong - {keep_state,Data#{remaining := Code}} + {keep_state, Data#{remaining := Code}} end; locked(EventType, EventContent, Data) -> handle_event(EventType, EventContent, Data). -open(internal, enter, Data) -> - Tref = erlang:start_timer(10000, self(), lock), +open(enter, _OldState, _Data) -> do_unlock(), - {keep_state,Data#{timer => Tref}}; -open(info, {timeout,Tref,lock}, #{timer := Tref} = Data) -> - enter(next_state, locked, Data); + {keep_state_and_data, [{state_timeout,10000,lock}]}; +open(state_timeout, lock, Data) -> + {next_state, locked, Data}; open(cast, {button,_}, _) -> - {keep_state_and_data,[postpone]}; + {keep_state_and_data, [postpone]}; open(EventType, EventContent, Data) -> handle_event(EventType, EventContent, Data). handle_event({call,From}, code_length, #{code := Code}) -> - {keep_state_and_data,[{reply,From,length(Code)}]}. -enter(Tag, State, Data) -> - {Tag,State,Data,[{next_event,internal,enter}]}. + {keep_state_and_data, [{reply,From,length(Code)}]}. do_lock() -> io:format("Locked~n", []). @@ -1091,64 +1441,69 @@ terminate(_Reason, State, _Data) -> State =/= locked andalso do_lock(), ok. code_change(_Vsn, State, Data, _Extra) -> - {?CALLBACK_MODE,State,Data}. + {ok,State,Data}. ]]></code> </section> <section> + <marker id="Callback Mode: handle_event_function" /> <title>Callback Mode: handle_event_function</title> <p> This section describes what to change in the example to use one <c>handle_event/4</c> function. The previously used approach to first branch depending on event - does not work that well here because of the generated - entry actions, so this example first branches depending on state: + does not work that well here because of the state enter calls, + so this example first branches depending on state: </p> <code type="erl"><![CDATA[ ... --define(CALLBACK_MODE, handle_event_function). - -... -export([handle_event/4]). ... +callback_mode() -> + [handle_event_function,state_enter]. %% State: locked -handle_event(internal, enter, locked, #{code := Code} = Data) -> +handle_event( + enter, _OldState, locked, + #{code := Code} = Data) -> do_lock(), - {keep_state,Data#{remaining => Code}}; + {keep_state, Data#{remaining => Code}}; +handle_event( + timeout, _, locked, + #{code := Code, remaining := Remaining} = Data) -> + {keep_state, Data#{remaining := Code}}; handle_event( cast, {button,Digit}, locked, #{code := Code, remaining := Remaining} = Data) -> case Remaining of [Digit] -> % Complete - enter(next_state, open, Data); + {next_state, open, Data}; [Digit|Rest] -> % Incomplete - {keep_state,Data#{remaining := Rest}}; + {keep_state, Data#{remaining := Rest}, 30000}; [_|_] -> % Wrong - {keep_state,Data#{remaining := Code}} + {keep_state, Data#{remaining := Code}} end; %% %% State: open -handle_event(internal, enter, open, Data) -> - Tref = erlang:start_timer(10000, self(), lock), +handle_event(enter, _OldState, open, _Data) -> do_unlock(), - {keep_state,Data#{timer => Tref}}; -handle_event(info, {timeout,Tref,lock}, open, #{timer := Tref} = Data) -> - enter(next_state, locked, Data); + {keep_state_and_data, [{state_timeout,10000,lock}]}; +handle_event(state_timeout, lock, open, Data) -> + {next_state, locked, Data}; handle_event(cast, {button,_}, open, _) -> {keep_state_and_data,[postpone]}; %% %% Any state handle_event({call,From}, code_length, _State, #{code := Code}) -> - {keep_state_and_data,[{reply,From,length(Code)}]}. + {keep_state_and_data, [{reply,From,length(Code)}]}. ... ]]></code> </section> <p> Notice that postponing buttons from the <c>locked</c> state - to the <c>open</c> state feels like the wrong thing to do + to the <c>open</c> state feels like a strange thing to do for a code lock, but it at least illustrates event postponing. </p> </section> @@ -1156,6 +1511,7 @@ handle_event({call,From}, code_length, _State, #{code := Code}) -> <!-- =================================================================== --> <section> + <marker id="Filter the State" /> <title>Filter the State</title> <p> The example servers so far in this chapter @@ -1208,26 +1564,30 @@ format_status(Opt, [_PDict,State,Data]) -> <seealso marker="stdlib:gen_statem#Module:format_status/2"><c>Module:format_status/2</c></seealso> function. If you do not, a default implementation is used that does the same as this example function without filtering - the <c>Data</c> term, that is, <c>StateData = {State,Data}</c>. + the <c>Data</c> term, that is, <c>StateData = {State,Data}</c>, + in this example containing sensitive information. </p> </section> <!-- =================================================================== --> <section> + <marker id="Complex State" /> <title>Complex State</title> <p> The callback mode <seealso marker="stdlib:gen_statem#type-callback_mode"><c>handle_event_function</c></seealso> enables using a non-atom state as described in section - <seealso marker="#callback_modes">Callback Modes</seealso>, + <seealso marker="#Callback Modes">Callback Modes</seealso>, for example, a complex state term like a tuple. </p> <p> - One reason to use this is when you have - a state item that affects the event handling, - in particular in combination with postponing events. - We complicate the previous example + One reason to use this is when you have a state item + that when changed should cancel the + <seealso marker="#State Time-Outs">state time-out</seealso>, + or one that affects the event handling + in combination with postponing events. + We will complicate the previous example by introducing a configurable lock button (this is the state item in question), which in the <c>open</c> state immediately locks the door, @@ -1273,11 +1633,10 @@ format_status(Opt, [_PDict,State,Data]) -> -module(code_lock). -behaviour(gen_statem). -define(NAME, code_lock_3). --define(CALLBACK_MODE, handle_event_function). -export([start_link/2,stop/0]). -export([button/1,code_length/0,set_lock_button/1]). --export([init/1,terminate/3,code_change/4,format_status/2]). +-export([init/1,callback_mode/0,terminate/3,code_change/4,format_status/2]). -export([handle_event/4]). start_link(Code, LockButton) -> @@ -1295,68 +1654,68 @@ set_lock_button(LockButton) -> init({Code,LockButton}) -> process_flag(trap_exit, true), - Data = #{code => Code, remaining => undefined, timer => undefined}, - enter(?CALLBACK_MODE, {locked,LockButton}, Data, []). + Data = #{code => Code, remaining => undefined}, + {ok, {locked,LockButton}, Data}. + +callback_mode() -> + [handle_event_function,state_enter]. handle_event( {call,From}, {set_lock_button,NewLockButton}, {StateName,OldLockButton}, Data) -> - {next_state,{StateName,NewLockButton},Data, + {next_state, {StateName,NewLockButton}, Data, [{reply,From,OldLockButton}]}; handle_event( {call,From}, code_length, {_StateName,_LockButton}, #{code := Code}) -> {keep_state_and_data, [{reply,From,length(Code)}]}; +%% +%% State: locked handle_event( EventType, EventContent, {locked,LockButton}, #{code := Code, remaining := Remaining} = Data) -> - case {EventType,EventContent} of - {internal,enter} -> + case {EventType, EventContent} of + {enter, _OldState} -> do_lock(), - {keep_state,Data#{remaining := Code}}; - {{call,From},{button,Digit}} -> + {keep_state, Data#{remaining := Code}}; + {timeout, _} -> + {keep_state, Data#{remaining := Code}}; + {{call,From}, {button,Digit}} -> case Remaining of [Digit] -> % Complete - next_state( - {open,LockButton}, Data, - [{reply,From,ok}]); + {next_state, {open,LockButton}, Data, + [{reply,From,ok}]}; [Digit|Rest] -> % Incomplete - {keep_state,Data#{remaining := Rest}, + {keep_state, Data#{remaining := Rest, 30000}, [{reply,From,ok}]}; [_|_] -> % Wrong - {keep_state,Data#{remaining := Code}, + {keep_state, Data#{remaining := Code}, [{reply,From,ok}]} end end; +%% +%% State: open handle_event( EventType, EventContent, - {open,LockButton}, #{timer := Timer} = Data) -> - case {EventType,EventContent} of - {internal,enter} -> - Tref = erlang:start_timer(10000, self(), lock), + {open,LockButton}, Data) -> + case {EventType, EventContent} of + {enter, _OldState} -> do_unlock(), - {keep_state,Data#{timer := Tref}}; - {info,{timeout,Timer,lock}} -> - next_state({locked,LockButton}, Data, []); - {{call,From},{button,Digit}} -> + {keep_state_and_data, [{state_timeout,10000,lock}]}; + {state_timeout, lock} -> + {next_state, {locked,LockButton}, Data}; + {{call,From}, {button,Digit}} -> if Digit =:= LockButton -> - erlang:cancel_timer(Timer), - next_state( - {locked,LockButton}, Data, - [{reply,From,locked}]); + {next_state, {locked,LockButton}, Data, + [{reply,From,locked}]}; true -> {keep_state_and_data, [postpone]} end end. -next_state(State, Data, Actions) -> - enter(next_state, State, Data, Actions). -enter(Tag, State, Data, Actions) -> - {Tag,State,Data,[{next_event,internal,enter}|Actions]}. - do_lock() -> io:format("Locked~n", []). do_unlock() -> @@ -1366,7 +1725,7 @@ terminate(_Reason, State, _Data) -> State =/= locked andalso do_lock(), ok. code_change(_Vsn, State, Data, _Extra) -> - {?CALLBACK_MODE,State,Data}. + {ok,State,Data}. format_status(Opt, [_PDict,State,Data]) -> StateData = {State, @@ -1393,6 +1752,7 @@ format_status(Opt, [_PDict,State,Data]) -> <!-- =================================================================== --> <section> + <marker id="Hibernation" /> <title>Hibernation</title> <p> If you have many servers in one node @@ -1418,20 +1778,21 @@ format_status(Opt, [_PDict,State,Data]) -> </p> <code type="erl"><![CDATA[ ... +%% State: open handle_event( EventType, EventContent, - {open,LockButton}, #{timer := Timer} = Data) -> - case {EventType,EventContent} of - {internal,enter} -> - Tref = erlang:start_timer(10000, self(), lock), - do_unlock(), - {keep_state,Data#{timer := Tref},[hibernate]}; + {open,LockButton}, Data) -> + case {EventType, EventContent} of + {enter, _OldState} -> + do_unlock(), + {keep_state_and_data, + [{state_timeout,10000,lock},hibernate]}; ... ]]></code> <p> - The - <seealso marker="stdlib:gen_statem#type-hibernate"><c>[hibernate]</c></seealso> - action list on the last line + The atom + <seealso marker="stdlib:gen_statem#type-hibernate"><c>hibernate</c></seealso> + in the action list on the last line when entering the <c>{open,_}</c> state is the only change. If any event arrives in the <c>{open,_},</c> state, we do not bother to rehibernate, so the server stays @@ -1446,6 +1807,10 @@ handle_event( <c>{open,_}</c> state, which would clutter the code. </p> <p> + Another not uncommon scenario is to use the event time-out + to triger hibernation after a certain time of inactivity. + </p> + <p> This server probably does not use heap memory worth hibernating for. To gain anything from hibernation, your server would diff --git a/system/doc/design_principles/sup_princ.xml b/system/doc/design_principles/sup_princ.xml index 0a24e97950..06ca44a9f6 100644 --- a/system/doc/design_principles/sup_princ.xml +++ b/system/doc/design_principles/sup_princ.xml @@ -4,7 +4,7 @@ <chapter> <header> <copyright> - <year>1997</year><year>2016</year> + <year>1997</year><year>2017</year> <holder>Ericsson AB. All Rights Reserved.</holder> </copyright> <legalnotice> @@ -163,7 +163,9 @@ SupFlags = #{strategy => Strategy, ...}</code> SupFlags = #{intensity => MaxR, period => MaxT, ...}</code> <p>If more than <c>MaxR</c> number of restarts occur in the last <c>MaxT</c> seconds, the supervisor terminates all the child - processes and then itself.</p> + processes and then itself. + The termination reason for the supervisor itself in that case will be + <c>shutdown</c>.</p> <p>When the supervisor terminates, then the next higher-level supervisor takes some action. It either restarts the terminated supervisor or terminates itself.</p> @@ -173,6 +175,69 @@ SupFlags = #{intensity => MaxR, period => MaxT, ...}</code> <p>The keys <c>intensity</c> and <c>period</c> are optional in the supervisor flags map. If they are not given, they default to <c>1</c> and <c>5</c>, respectively.</p> + <section> + <title>Tuning the intensity and period</title> + <p>The default values are 1 restart per 5 seconds. This was chosen to + be safe for most systems, even with deep supervision hierarchies, + but you will probably want to tune the settings for your particular + use case.</p> + <p>First, the intensity decides how big bursts of restarts you want + to tolerate. For example, you might want to accept a burst of at + most 5 or 10 attempts, even within the same second, if it results + in a successful restart.</p> + <p>Second, you need to consider the sustained failure rate, if + crashes keep happening but not often enough to make the supervisor + give up. If you set intensity to 10 and set the period as low as 1, + the supervisor will allow child processes to keep restarting up to + 10 times per second, forever, filling your logs with crash reports + until someone intervenes manually.</p> + <p>You should therefore set the period to be long enough that you can + accept that the supervisor keeps going at that rate. For example, + if you have picked an intensity value of 5, then setting the period + to 30 seconds will give you at most one restart per 6 seconds for + any longer period of time, which means that your logs won't fill up + too quickly, and you will have a chance to observe the failures and + apply a fix.</p> + <p>These choices depend a lot on your problem domain. If you don't + have real time monitoring and ability to fix problems quickly, for + example in an embedded system, you might want to accept at most + one restart per minute before the supervisor should give up and + escalate to the next level to try to clear the error automatically. + On the other hand, if it is more important that you keep trying + even at a high failure rate, you might want a sustained rate of as + much as 1-2 restarts per second.</p> + <p>Avoiding common mistakes:</p> + <list type="bulleted"> + <item> + <p>Do not forget to consider the burst rate. If you set intensity + to 1 and period to 6, it gives the same sustained error rate as + 5/30 or 10/60, but will not allow even 2 restart attempts in + quick succession. This is probably not what you wanted.</p> + </item> + <item> + <p>Do not set the period to a very high value if you want to + tolerate bursts. If you set intensity to 5 and period to 3600 + (one hour), the supervisor will allow a short burst of 5 + restarts, but then gives up if it sees another single restart + almost an hour later. You probably want to regard those crashes + as separate incidents, so setting the period to 5 or 10 minutes + will be more reasonable.</p> + </item> + <item> + <p>If your application has multiple levels of supervision, then + do not simply set the restart intensities to the same values on + all levels. Keep in mind that the total number of restarts + (before the top level supervisor gives up and terminates the + application) will be the product of the intensity values of all + the supervisors above the failing child process.</p> + <p>For example, if the top level allows 10 restarts, and the next + level also allows 10, a crashing child below that level will be + restarted 100 times, which is probably excessive. Allowing at + most 3 restarts for the top level supervisor might be a better + choice in this case.</p> + </item> + </list> + </section> </section> <section> @@ -211,7 +276,6 @@ child_spec() = #{id => child_id(), % mandatory <list type="bulleted"> <item><c>supervisor:start_link</c></item> <item><c>gen_server:start_link</c></item> - <item><c>gen_fsm:start_link</c></item> <item><c>gen_statem:start_link</c></item> <item><c>gen_event:start_link</c></item> <item>A function compliant with these functions. For details, @@ -276,7 +340,7 @@ child_spec() = #{id => child_id(), % mandatory <p><c>modules</c> are to be a list with one element <c>[Module]</c>, where <c>Module</c> is the name of the callback module, if the child process is a supervisor, - gen_server, gen_fsm or gen_statem. + gen_server, gen_statem. If the child process is a gen_event, the value shall be <c>dynamic</c>.</p> <p>This information is used by the release handler during diff --git a/system/doc/design_principles/xmlfiles.mk b/system/doc/design_principles/xmlfiles.mk index e476255d62..fbcaf9c7d9 100644 --- a/system/doc/design_principles/xmlfiles.mk +++ b/system/doc/design_principles/xmlfiles.mk @@ -1,7 +1,7 @@ # # %CopyrightBegin% # -# Copyright Ericsson AB 2009-2016. All Rights Reserved. +# Copyright Ericsson AB 2009-2017. All Rights Reserved. # # Licensed under the Apache License, Version 2.0 (the "License"); # you may not use this file except in compliance with the License. @@ -24,7 +24,6 @@ DESIGN_PRINCIPLES_CHAPTER_FILES = \ des_princ.xml \ distributed_applications.xml \ events.xml \ - fsm.xml \ statem.xml \ gen_server_concepts.xml \ included_applications.xml \ diff --git a/system/doc/efficiency_guide/advanced.xml b/system/doc/efficiency_guide/advanced.xml index 016302fe50..e1760d0ded 100644 --- a/system/doc/efficiency_guide/advanced.xml +++ b/system/doc/efficiency_guide/advanced.xml @@ -87,15 +87,15 @@ </row> <row> <cell>Small Map</cell> - <cell>4 words + 2 words per entry (key and value) + the size of each key and value pair.</cell> + <cell>5 words + the size of all keys and values.</cell> </row> <row> - <cell>Large Map</cell> + <cell>Large Map (> 32 keys)</cell> <cell> - At least, 2 words + 2 x <c>N</c> words + 2 x log16(<c>N</c>) words + - the size of each key and value pair, where <c>N</c> is the number of pairs in the Map. - A large Map is represented as a tree internally where each node in the tree is a - "sparse tuple" of arity 16. + <c>N</c> x <c>F</c> words + the size of all keys and values.<br></br> + <c>N</c> is the number of keys in the Map.<br></br> + <c>F</c> is a sparsity factor that can vary between 1.6 and 1.8 + due to the probabilistic nature of the internal HAMT data structure. </cell> </row> <row> @@ -156,7 +156,7 @@ <seealso marker="erts:erl#max_processes"><c>+P</c></seealso> command-line flag in the <seealso marker="erts:erl"><c>erl(1)</c></seealso> - manual page in <c>erts</c>.</cell> + manual page in ERTS.</cell> </row> <row> <cell>Known nodes</cell> @@ -236,7 +236,7 @@ <seealso marker="erts:erl#max_ports"><c>+Q</c></seealso> command-line flag in the <seealso marker="erts:erl"><c>erl(1)</c></seealso> manual page - in <c>erts</c>.</cell> + in ERTS.</cell> </row> <row> <cell><marker id="files_sockets"></marker>Open files and diff --git a/system/doc/efficiency_guide/bench.erl b/system/doc/efficiency_guide/bench.erl index 1f60e858f6..a1be24b051 100644 --- a/system/doc/efficiency_guide/bench.erl +++ b/system/doc/efficiency_guide/bench.erl @@ -355,7 +355,7 @@ create_html_report(ResultList) -> {ok, OutputFile} = file:open("index.html", [write]), - %% Create the begining of the result html-file. + %% Create the beginning of the result html-file. Head = Title = "Benchmark Results", io:put_chars(OutputFile, "<html>\n"), io:put_chars(OutputFile, "<head>\n"), diff --git a/system/doc/efficiency_guide/binaryhandling.xml b/system/doc/efficiency_guide/binaryhandling.xml index 0295d18644..19f40c9abe 100644 --- a/system/doc/efficiency_guide/binaryhandling.xml +++ b/system/doc/efficiency_guide/binaryhandling.xml @@ -5,7 +5,7 @@ <header> <copyright> <year>2007</year> - <year>2016</year> + <year>2017</year> <holder>Ericsson AB, All Rights Reserved</holder> </copyright> <legalnotice> @@ -32,12 +32,9 @@ <file>binaryhandling.xml</file> </header> - <p>In R12B, the most natural way to construct and match binaries is - significantly faster than in earlier releases.</p> + <p>Binaries can be efficiently built in the following way:</p> - <p>To construct a binary, you can simply write as follows:</p> - - <p><em>DO</em> (in R12B) / <em>REALLY DO NOT</em> (in earlier releases)</p> + <p><em>DO</em></p> <code type="erl"><![CDATA[ my_list_to_binary(List) -> my_list_to_binary(List, <<>>). @@ -47,21 +44,13 @@ my_list_to_binary([H|T], Acc) -> my_list_to_binary([], Acc) -> Acc.]]></code> - <p>In releases before R12B, <c>Acc</c> is copied in every iteration. - In R12B, <c>Acc</c> is copied only in the first iteration and extra - space is allocated at the end of the copied binary. In the next iteration, - <c>H</c> is written into the extra space. When the extra space runs out, - the binary is reallocated with more extra space. The extra space allocated - (or reallocated) is twice the size of the - existing binary data, or 256, whichever is larger.</p> - - <p>The most natural way to match binaries is now the fastest:</p> + <p>Binaries can be efficiently matched like this:</p> - <p><em>DO</em> (in R12B)</p> + <p><em>DO</em></p> <code type="erl"><![CDATA[ my_binary_to_list(<<H,T/binary>>) -> [H|my_binary_to_list(T)]; -my_binary_to_list(<<>>) -> [].]]></code> +my_binary_to_list(<<>>) -> [].]]></code> <section> <title>How Binaries are Implemented</title> @@ -138,10 +127,7 @@ my_binary_to_list(<<>>) -> [].]]></code> pointer to the binary data. For each field that is matched out of a binary, the position in the match context is incremented.</p> - <p>In R11B, a match context was only used during a binary matching - operation.</p> - - <p>In R12B, the compiler tries to avoid generating code that + <p>The compiler tries to avoid generating code that creates a sub binary, only to shortly afterwards create a new match context and discard the sub binary. Instead of creating a sub binary, the match context is kept.</p> @@ -155,7 +141,7 @@ my_binary_to_list(<<>>) -> [].]]></code> <section> <title>Constructing Binaries</title> - <p>In R12B, appending to a binary or bitstring + <p>Appending to a binary or bitstring is specially optimized by the <em>runtime system</em>:</p> <code type="erl"><![CDATA[ @@ -292,7 +278,7 @@ Bin = <<Bin1,...>> %% Bin1 will be COPIED <p>Let us revisit the example in the beginning of the previous section:</p> - <p><em>DO</em> (in R12B)</p> + <p><em>DO</em></p> <code type="erl"><![CDATA[ my_binary_to_list(<<H,T/binary>>) -> [H|my_binary_to_list(T)]; @@ -304,15 +290,14 @@ my_binary_to_list(<<>>) -> [].]]></code> byte of the binary. 1 byte is matched out and the match context is updated to point to the second byte in the binary.</p> - <p>In R11B, at this point a - <seealso marker="#sub_binary">sub binary</seealso> - would be created. In R12B, - the compiler sees that there is no point in creating a sub binary, - because there will soon be a call to a function (in this case, + <p>At this point it would make sense to create a + <seealso marker="#sub_binary">sub binary</seealso>, + but in this particular example the compiler sees that + there will soon be a call to a function (in this case, to <c>my_binary_to_list/1</c> itself) that immediately will create a new match context and discard the sub binary.</p> - <p>Therefore, in R12B, <c>my_binary_to_list/1</c> calls itself + <p>Therefore <c>my_binary_to_list/1</c> calls itself with the match context instead of with a sub binary. The instruction that initializes the matching operation basically does nothing when it sees that it was passed a match context instead of a binary.</p> @@ -321,34 +306,10 @@ my_binary_to_list(<<>>) -> [].]]></code> the match context will simply be discarded (removed in the next garbage collection, as there is no longer any reference to it).</p> - <p>To summarize, <c>my_binary_to_list/1</c> in R12B only needs to create - <em>one</em> match context and no sub binaries. In R11B, if the binary - contains <em>N</em> bytes, <em>N+1</em> match contexts and <em>N</em> - sub binaries are created.</p> - - <p>In R11B, the fastest way to match binaries is as follows:</p> + <p>To summarize, <c>my_binary_to_list/1</c> only needs to create + <em>one</em> match context and no sub binaries.</p> - <p><em>DO NOT</em> (in R12B)</p> - <code type="erl"><![CDATA[ -my_complicated_binary_to_list(Bin) -> - my_complicated_binary_to_list(Bin, 0). - -my_complicated_binary_to_list(Bin, Skip) -> - case Bin of - <<_:Skip/binary,Byte,_/binary>> -> - [Byte|my_complicated_binary_to_list(Bin, Skip+1)]; - <<_:Skip/binary>> -> - [] - end.]]></code> - - <p>This function cleverly avoids building sub binaries, but it cannot - avoid building a match context in each recursion step. - Therefore, in both R11B and R12B, - <c>my_complicated_binary_to_list/1</c> builds <em>N+1</em> match - contexts. (In a future Erlang/OTP release, the compiler might be able - to generate code that reuses the match context.)</p> - - <p>Returning to <c>my_binary_to_list/1</c>, notice that the match context + <p>Notice that the match context in <c>my_binary_to_list/1</c> was discarded when the entire binary had been traversed. What happens if the iteration stops before it has reached the end of the binary? Will the optimization still work?</p> @@ -544,5 +505,15 @@ count3(<<>>, Count) -> Count.]]></code> not matched out.</p> </section> </section> + + <section> + <title>Historical Note</title> + + <p>Binary handling was significantly improved in R12B. Because + code that was efficient in R11B might not be efficient in R12B, + and vice versa, earlier revisions of this Efficiency Guide contained + some information about binary handling in R11B.</p> + </section> + </chapter> diff --git a/system/doc/efficiency_guide/commoncaveats.xml b/system/doc/efficiency_guide/commoncaveats.xml index ecfeff0349..b41ffc3902 100644 --- a/system/doc/efficiency_guide/commoncaveats.xml +++ b/system/doc/efficiency_guide/commoncaveats.xml @@ -4,7 +4,7 @@ <chapter> <header> <copyright> - <year>2001</year><year>2016</year> + <year>2001</year><year>2017</year> <holder>Ericsson AB. All Rights Reserved.</holder> </copyright> <legalnotice> @@ -148,10 +148,10 @@ multiple_setelement(T0) -> <p><c>size/1</c> returns the size for both tuples and binaries.</p> - <p>Using the new BIFs <c>tuple_size/1</c> and <c>byte_size/1</c>, introduced - in R12B, gives the compiler and the runtime system more opportunities for - optimization. Another advantage is that the new BIFs can help Dialyzer to - find more bugs in your program.</p> + <p>Using the BIFs <c>tuple_size/1</c> and <c>byte_size/1</c> + gives the compiler and the runtime system more opportunities for + optimization. Another advantage is that the BIFs give Dialyzer more + type information.</p> </section> <section> diff --git a/system/doc/efficiency_guide/functions.xml b/system/doc/efficiency_guide/functions.xml index 4a8248e65c..0a8ee7eb34 100644 --- a/system/doc/efficiency_guide/functions.xml +++ b/system/doc/efficiency_guide/functions.xml @@ -4,7 +4,7 @@ <chapter> <header> <copyright> - <year>2001</year><year>2016</year> + <year>2001</year><year>2017</year> <holder>Ericsson AB. All Rights Reserved.</holder> </copyright> <legalnotice> @@ -65,7 +65,7 @@ atom_map1(six) -> 6.</code> thus, quite efficient even if there are many values) to select which one of the first three clauses to execute (if any).</item> - <item>>If none of the first three clauses match, the fourth clause + <item>If none of the first three clauses match, the fourth clause match as a variable always matches.</item> <item>If the guard test <c>is_integer(Int)</c> succeeds, the fourth @@ -183,15 +183,6 @@ explicit_map_pairs(Map, Xs0, Ys0) -> A fun contains an (indirect) pointer to the function that implements the fun.</p> - <warning><p><em>Tuples are not fun(s)</em>. - A "tuple fun", <c>{Module,Function}</c>, is not a fun. - The cost for calling a "tuple fun" is similar to that - of <c>apply/3</c> or worse. - Using "tuple funs" is <em>strongly discouraged</em>, - as they might not be supported in a future Erlang/OTP release, - and because there exists a superior alternative from R10B, - namely the <c>fun Module:Function/Arity</c> syntax.</p></warning> - <p><c>apply/3</c> must look up the code for the function to execute in a hash table. It is therefore always slower than a direct call or a fun call.</p> diff --git a/system/doc/efficiency_guide/introduction.xml b/system/doc/efficiency_guide/introduction.xml index ca4a41c798..dca2dec95e 100644 --- a/system/doc/efficiency_guide/introduction.xml +++ b/system/doc/efficiency_guide/introduction.xml @@ -4,7 +4,7 @@ <chapter> <header> <copyright> - <year>2001</year><year>2016</year> + <year>2001</year><year>2017</year> <holder>Ericsson AB. All Rights Reserved.</holder> </copyright> <legalnotice> @@ -46,14 +46,6 @@ to find out where the performance bottlenecks are and optimize only the bottlenecks. Let other code stay as clean as possible.</p> - <p>Fortunately, compiler and runtime optimizations introduced in - Erlang/OTP R12B makes it easier to write code that is both clean and - efficient. For example, the ugly workarounds needed in R11B and earlier - releases to get the most speed out of binary pattern matching are - no longer necessary. In fact, the ugly code is slower - than the clean code (because the clean code has become faster, not - because the uglier code has become slower).</p> - <p>This Efficiency Guide cannot really teach you how to write efficient code. It can give you a few pointers about what to avoid and what to use, and some understanding of how certain language features are implemented. diff --git a/system/doc/efficiency_guide/listhandling.xml b/system/doc/efficiency_guide/listhandling.xml index 2ebc877820..4f2497359d 100644 --- a/system/doc/efficiency_guide/listhandling.xml +++ b/system/doc/efficiency_guide/listhandling.xml @@ -4,7 +4,7 @@ <chapter> <header> <copyright> - <year>2001</year><year>2016</year> + <year>2001</year><year>2017</year> <holder>Ericsson AB. All Rights Reserved.</holder> </copyright> <legalnotice> @@ -90,7 +90,7 @@ tail_recursive_fib(N, Current, Next, Fibs) -> <p>Lists comprehensions still have a reputation for being slow. They used to be implemented using funs, which used to be slow.</p> - <p>In recent Erlang/OTP releases (including R12B), a list comprehension:</p> + <p>A list comprehension:</p> <code type="erl"><![CDATA[ [Expr(E) || E <- List]]]></code> @@ -102,7 +102,7 @@ tail_recursive_fib(N, Current, Next, Fibs) -> [Expr(E)|'lc^0'(Tail, Expr)]; 'lc^0'([], _Expr) -> [].</code> - <p>In R12B, if the result of the list comprehension will <em>obviously</em> + <p>If the result of the list comprehension will <em>obviously</em> not be used, a list will not be constructed. For example, in this code:</p> <code type="erl"><![CDATA[ @@ -131,6 +131,14 @@ some_function(...), 'lc^0'(Tail, Expr); 'lc^0'([], _Expr) -> [].</code> + <p>The compiler also understands that assigning to '_' means that + the value will not used. Therefore, the code in the following example + will also be optimized:</p> + + <code type="erl"><![CDATA[ +_ = [io:put_chars(E) || E <- List], +ok.]]></code> + </section> <section> @@ -209,11 +217,11 @@ some_function(...), <section> <title>Recursive List Functions</title> - <p>In Section 7.2, the following myth was exposed: + <p>In section about myths, the following myth was exposed: <seealso marker="myths#tail_recursive">Tail-Recursive Functions are Much Faster Than Recursive Functions</seealso>.</p> - <p>To summarize, in R12B there is usually not much difference between + <p>There is usually not much difference between a body-recursive list function and tail-recursive function that reverses the list at the end. Therefore, concentrate on writing beautiful code and forget about the performance of your list functions. In the diff --git a/system/doc/efficiency_guide/myths.xml b/system/doc/efficiency_guide/myths.xml index 5d3ad78b23..778cd06c09 100644 --- a/system/doc/efficiency_guide/myths.xml +++ b/system/doc/efficiency_guide/myths.xml @@ -24,7 +24,7 @@ The Initial Developer of the Original Code is Ericsson AB. </legalnotice> - <title>The Eight Myths of Erlang Performance</title> + <title>The Seven Myths of Erlang Performance</title> <prepared>Bjorn Gustavsson</prepared> <docno></docno> <date>2007-11-10</date> @@ -35,80 +35,33 @@ <marker id="myths"></marker> <p>Some truths seem to live on well beyond their best-before date, perhaps because "information" spreads faster from person-to-person - than a single release note that says, for example, that funs - have become faster.</p> + than a single release note that says, for example, that body-recursive + calls have become faster.</p> <p>This section tries to kill the old truths (or semi-truths) that have become myths.</p> <section> - <title>Myth: Funs are Slow</title> - <p>Funs used to be very slow, slower than <c>apply/3</c>. - Originally, funs were implemented using nothing more than - compiler trickery, ordinary tuples, <c>apply/3</c>, and a great - deal of ingenuity.</p> - - <p>But that is history. Funs was given its own data type - in R6B and was further optimized in R7B. - Now the cost for a fun call falls roughly between the cost for a call - to a local function and <c>apply/3</c>.</p> - </section> - - <section> - <title>Myth: List Comprehensions are Slow</title> - - <p>List comprehensions used to be implemented using funs, and in the - old days funs were indeed slow.</p> - - <p>Nowadays, the compiler rewrites list comprehensions into an ordinary - recursive function. Using a tail-recursive function with - a reverse at the end would be still faster. Or would it? - That leads us to the next myth.</p> - </section> - - <section> <title>Myth: Tail-Recursive Functions are Much Faster Than Recursive Functions</title> <p><marker id="tail_recursive"></marker>According to the myth, - recursive functions leave references - to dead terms on the stack and the garbage collector has to copy - all those dead terms, while tail-recursive functions immediately - discard those terms.</p> - - <p>That used to be true before R7B. In R7B, the compiler started - to generate code that overwrites references to terms that will never - be used with an empty list, so that the garbage collector would not - keep dead values any longer than necessary.</p> - - <p>Even after that optimization, a tail-recursive function is - still most of the times faster than a body-recursive function. Why?</p> - - <p>It has to do with how many words of stack that are used in each - recursive call. In most cases, a recursive function uses more words - on the stack for each recursion than the number of words a tail-recursive - would allocate on the heap. As more memory is used, the garbage - collector is invoked more frequently, and it has more work traversing - the stack.</p> - - <p>In R12B and later releases, there is an optimization that - in many cases reduces the number of words used on the stack in - body-recursive calls. A body-recursive list function and a - tail-recursive function that calls <seealso - marker="stdlib:lists#reverse/1">lists:reverse/1</seealso> at - the end will use the same amount of memory. - <c>lists:map/2</c>, <c>lists:filter/2</c>, list comprehensions, - and many other recursive functions now use the same amount of space - as their tail-recursive equivalents.</p> - - <p>So, which is faster? - It depends. On Solaris/Sparc, the body-recursive function seems to - be slightly faster, even for lists with a lot of elements. On the x86 - architecture, tail-recursion was up to about 30% faster.</p> - - <p>So, the choice is now mostly a matter of taste. If you really do need - the utmost speed, you must <em>measure</em>. You can no longer be - sure that the tail-recursive list function always is the fastest.</p> + using a tail-recursive function that builds a list in reverse + followed by a call to <c>lists:reverse/1</c> is faster than + a body-recursive function that builds the list in correct order; + the reason being that body-recursive functions use more memory than + tail-recursive functions.</p> + + <p>That was true to some extent before R12B. It was even more true + before R7B. Today, not so much. A body-recursive function + generally uses the same amount of memory as a tail-recursive + function. It is generally not possible to predict whether the + tail-recursive or the body-recursive version will be + faster. Therefore, use the version that makes your code cleaner + (hint: it is usually the body-recursive version).</p> + + <p>For a more thorough discussion about tail and body recursion, + see <url href="http://ferd.ca/erlang-s-tail-recursion-is-not-a-silver-bullet.html">Erlang's Tail Recursion is Not a Silver Bullet</url>.</p> <note><p>A tail-recursive function that does not need to reverse the list at the end is faster than a body-recursive function, @@ -199,6 +152,29 @@ vanilla_reverse([], Acc) -> <p>That was once true, but from R6B the BEAM compiler can see that a variable is not used.</p> + + <p>Similarly, trivial transformations on the source-code level + such as converting a <c>case</c> statement to clauses at the + top-level of the function seldom makes any difference to the + generated code.</p> + </section> + + <section> + <title>Myth: A NIF Always Speeds Up Your Program</title> + + <p>Rewriting Erlang code to a NIF to make it faster should be + seen as a last resort. It is only guaranteed to be dangerous, + but not guaranteed to speed up the program.</p> + + <p>Doing too much work in each NIF call will + <seealso marker="erts:erl_nif#WARNING">degrade responsiveness + of the VM</seealso>. Doing too little work may mean that + the gain of the faster processing in the NIF is eaten up by + the overhead of calling the NIF and checking the arguments.</p> + + <p>Be sure to read about + <seealso marker="erts:erl_nif#lengthy_work">Long-running NIFs</seealso> + before writing a NIF.</p> </section> </chapter> diff --git a/system/doc/efficiency_guide/part.xml b/system/doc/efficiency_guide/part.xml index 6e10a0c031..5673ddd320 100644 --- a/system/doc/efficiency_guide/part.xml +++ b/system/doc/efficiency_guide/part.xml @@ -39,5 +39,6 @@ <xi:include href="drivers.xml"/> <xi:include href="advanced.xml"/> <xi:include href="profiling.xml"/> + <xi:include href="retired_myths.xml"/> </part> diff --git a/system/doc/efficiency_guide/processes.xml b/system/doc/efficiency_guide/processes.xml index f2d9712f51..3b64c863ff 100644 --- a/system/doc/efficiency_guide/processes.xml +++ b/system/doc/efficiency_guide/processes.xml @@ -4,7 +4,7 @@ <chapter> <header> <copyright> - <year>2001</year><year>2016</year> + <year>2001</year><year>2017</year> <holder>Ericsson AB. All Rights Reserved.</holder> </copyright> <legalnotice> @@ -146,14 +146,14 @@ loop() -> <section> <title>Constant Pool</title> - <p>Constant Erlang terms (also called <em>literals</em>) are now + <p>Constant Erlang terms (also called <em>literals</em>) are kept in constant pools; each loaded module has its own pool. - The following function does no longer build the tuple every time + The following function does not build the tuple every time it is called (only to have it discarded the next time the garbage collector was run), but the tuple is located in the module's constant pool:</p> - <p><em>DO</em> (in R12B and later)</p> + <p><em>DO</em></p> <code type="erl"> days_in_month(M) -> element(M, {31,28,31,30,31,30,31,31,30,31,30,31}).</code> @@ -222,7 +222,7 @@ kilo_byte(N, Acc) -> <pre> 4> <input>T = ets:new(tab, []).</input> -17 +#Ref<0.1662103692.2407923716.214181> 5> <input>ets:insert(T, {key,efficiency_guide:kilo_byte()}).</input> true 6> <input>erts_debug:size(element(2, hd(ets:lookup(T, key)))).</input> @@ -235,9 +235,7 @@ true return the same value. Sharing has been lost.</p> <p>In a future Erlang/OTP release, it might be implemented a - way to (optionally) preserve sharing. There are no plans to make - preserving of sharing the default behaviour, as that would - penalize the vast majority of Erlang applications.</p> + way to (optionally) preserve sharing.</p> </section> </section> @@ -261,10 +259,6 @@ true The estone benchmark, for example, is entirely sequential. So is the most common implementation of the "ring benchmark"; usually one process is active, while the others wait in a <c>receive</c> statement.</p> - - <p>The <seealso marker="percept:percept">percept</seealso> application - can be used to profile your application to see how much potential (or lack - thereof) it has for concurrency.</p> </section> </chapter> diff --git a/system/doc/efficiency_guide/profiling.xml b/system/doc/efficiency_guide/profiling.xml index 1f3d503170..bf50a03fa6 100644 --- a/system/doc/efficiency_guide/profiling.xml +++ b/system/doc/efficiency_guide/profiling.xml @@ -128,7 +128,7 @@ performance impact. Using <c>fprof</c> is just a matter of calling a few library functions, see the <seealso marker="tools:fprof">fprof</seealso> manual page in - <c>tools</c> .<c>fprof</c> was introduced in R8.</p> + Tools .<c>fprof</c> was introduced in R8.</p> </section> <section> @@ -138,7 +138,7 @@ and in which function calls this time has been spent. Time is shown as percentage of total time and absolute time. For more information, see the <seealso marker="tools:eprof">eprof</seealso> - manual page in <c>tools</c>.</p> + manual page in Tools.</p> </section> <section> @@ -152,7 +152,7 @@ optimization. Using <c>cover</c> is just a matter of calling a few library functions, see the <seealso marker="tools:cover">cover</seealso> manual page in - <c>tools</c>.</p> + Tools.</p> </section> <section> @@ -165,7 +165,7 @@ any modules to profile (compared with <c>cover</c>). For more information, see the <seealso marker="tools:cprof">cprof</seealso> manual page in - <c>tools</c>.</p> + Tools.</p> </section> <section> diff --git a/system/doc/efficiency_guide/retired_myths.xml b/system/doc/efficiency_guide/retired_myths.xml new file mode 100644 index 0000000000..9b914a3b6e --- /dev/null +++ b/system/doc/efficiency_guide/retired_myths.xml @@ -0,0 +1,63 @@ +<?xml version="1.0" encoding="utf-8" ?> +<!DOCTYPE chapter SYSTEM "chapter.dtd"> + +<chapter> + <header> + <copyright> + <year>2016</year> + <year>2017</year> + <holder>Ericsson AB, All Rights Reserved</holder> + </copyright> + <legalnotice> + Licensed under the Apache License, Version 2.0 (the "License"); + you may not use this file except in compliance with the License. + You may obtain a copy of the License at + + http://www.apache.org/licenses/LICENSE-2.0 + + Unless required by applicable law or agreed to in writing, software + distributed under the License is distributed on an "AS IS" BASIS, + WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + See the License for the specific language governing permissions and + limitations under the License. + + The Initial Developer of the Original Code is Ericsson AB. + </legalnotice> + <title>Retired Myths</title> + <prepared>Bjorn Gustavsson</prepared> + <docno></docno> + <date>2016-06-07</date> + <rev></rev> + <file>retired_myths.xml</file> + </header> + + <p>We belive that the truth finally has caught with the following, + retired myths.</p> + + <section> + <marker id="retired_myths"/> + <title>Myth: Funs are Slow</title> + <p>Funs used to be very slow, slower than <c>apply/3</c>. + Originally, funs were implemented using nothing more than + compiler trickery, ordinary tuples, <c>apply/3</c>, and a great + deal of ingenuity.</p> + + <p>But that is history. Funs was given its own data type + in R6B and was further optimized in R7B. + Now the cost for a fun call falls roughly between the cost for a call + to a local function and <c>apply/3</c>.</p> + </section> + + <section> + <title>Myth: List Comprehensions are Slow</title> + + <p>List comprehensions used to be implemented using funs, and in the + old days funs were indeed slow.</p> + + <p>Nowadays, the compiler rewrites list comprehensions into an ordinary + recursive function. Using a tail-recursive function with + a reverse at the end would be still faster. Or would it? + That leads us to the myth that tail-recursive functions are faster + than body-recursive functions.</p> + </section> +</chapter> diff --git a/system/doc/embedded/embedded_nt.xml b/system/doc/embedded/embedded_nt.xml index a1a4b90f3c..8e05100585 100644 --- a/system/doc/embedded/embedded_nt.xml +++ b/system/doc/embedded/embedded_nt.xml @@ -62,7 +62,7 @@ <p>For Windows NT running on standard PCs with ISA and/or PCI bus, an extension card with a hardware watchdog can be installed.</p> <p>For more information, see the <c>heart(3)</c> manual page in - <c>kernel</c>.</p> + Kernel.</p> </section> </section> @@ -72,7 +72,7 @@ to install the Erlang process as a Windows system service. This service can start after Windows NT has booted.</p> <p>For more information, see the <c>erlsrv</c> manual page - in <c>erts</c>.</p> + in ERTS.</p> </section> </chapter> diff --git a/system/doc/embedded/embedded_solaris.xml b/system/doc/embedded/embedded_solaris.xml index f8febcc546..eaa334fb39 100644 --- a/system/doc/embedded/embedded_solaris.xml +++ b/system/doc/embedded/embedded_solaris.xml @@ -190,7 +190,7 @@ esac</pre> the onboard hardware watchdog can be activated, provided a VME bus driver is added to the operating system (see also Installation Problems).</p> - <p>See also the <c>heart(3)</c> manual page in <c>kernel</c>.</p> + <p>See also the <c>heart(3)</c> manual page in Kernel.</p> </section> <section> @@ -206,7 +206,7 @@ esac</pre> <pre> chown 0 /usr/sbin/reboot chmod 4755 /usr/sbin/reboot</pre> - <p>See also the <c>heart(3)</c> manual page in <c>kernel</c>.</p> + <p>See also the <c>heart(3)</c> manual page in Kernel.</p> </section> <section> @@ -413,8 +413,8 @@ chown root mod_syslog]]></code> <section> <title>Related Documents</title> <p>See the <c>os_mon(3)</c> application, - the <c>application(3)</c> manual page in <c>kernel</c>, - and the <c>erl(1)</c> manual page in <c>erts</c>.</p> + the <c>application(3)</c> manual page in Kernel, + and the <c>erl(1)</c> manual page in ERTS.</p> </section> </section> @@ -474,7 +474,7 @@ chown root mod_syslog]]></code> default, it must be called <c>start</c> and reside in <c><![CDATA[<ERL_INSTALL_DIR>/bin]]></c>. Another start program can be used, by using configuration parameter - <c>start_prg</c> in application <c>sasl</c>.</p> + <c>start_prg</c> in application SASL.</p> <p>The start program must call <c>run_erl</c> as shown below. It must also take an optional parameter, which defaults to <c><![CDATA[<ERL_INSTALL_DIR>/releases/start_erl.data]]></c>.</p> @@ -484,7 +484,7 @@ chown root mod_syslog]]></code> <p>The <c><![CDATA[<RELDIR>]]></c> directory is where new release packets are installed, and where the release handler keeps information about releases. For more information, see the - <c>release_handler(3)</c> manual page in <c>sasl</c>.</p> + <c>release_handler(3)</c> manual page in SASL.</p> <p>The following script illustrates the default behaviour of the program:</p> <code type="none"><![CDATA[ @@ -624,7 +624,7 @@ export RELDIR exec $BINDIR/erlexec -boot $RELDIR/$VSN/start -config $RELDIR/$VSN/sys $*</code> <p>If a diskless and/or read-only client node with the - <c>sasl</c> configuration parameter <c>static_emulator</c> set + SASL configuration parameter <c>static_emulator</c> set to <c>true</c> is about to start, the <c>-boot</c> and <c>-config</c> flags must be changed.</p> <p>As such a client cannot diff --git a/system/doc/embedded/starting.xml b/system/doc/embedded/starting.xml index 720383e8ac..11bf9b412a 100644 --- a/system/doc/embedded/starting.xml +++ b/system/doc/embedded/starting.xml @@ -69,7 +69,7 @@ default, it must be called <c>start</c> and reside in <c><![CDATA[<ERL_INSTALL_DIR>/bin]]></c>. Another start program can be used, by using the configuration parameter <c>start_prg</c> in - the application <c>sasl</c>.</p> + application SASL.</p> <p>The start program must call <c>run_erl</c> as shown below. It must also take an optional parameter which defaults to <c><![CDATA[<ERL_INSTALL_DIR>/bin/start_erl.data]]></c>. @@ -80,8 +80,8 @@ </p> <p>The <c><![CDATA[<RELDIR>]]></c> directory is where new release packets are installed, and where the release handler keeps information - about releases. See <c>release_handler(3)</c> in the - application <c>sasl</c> for further information. + about releases. See <c>release_handler(3)</c> in + application SASL for further information. </p> <p>The following script illustrates the default behaviour of the program. @@ -228,7 +228,7 @@ export PROGNAME export RELDIR exec $BINDIR/erlexec -boot $RELDIR/$VSN/start -config $RELDIR/$VSN/sys $* </code> - <p>If a diskless and/or read-only client node with the <c>sasl</c> + <p>If a diskless and/or read-only client node with the SASL configuration parameter <c>static_emulator</c> set to <c>true</c> is about to start the <c>-boot</c> and <c>-config</c> flags must be changed. As such a client can not read a new <c>start_erl.data</c> diff --git a/system/doc/getting_started/conc_prog.xml b/system/doc/getting_started/conc_prog.xml index f3136898ad..7936e0d484 100644 --- a/system/doc/getting_started/conc_prog.xml +++ b/system/doc/getting_started/conc_prog.xml @@ -4,7 +4,7 @@ <chapter> <header> <copyright> - <year>2003</year><year>2016</year> + <year>2003</year><year>2017</year> <holder>Ericsson AB. All Rights Reserved.</holder> </copyright> <legalnotice> @@ -355,8 +355,8 @@ pong ! {ping, self()},</code> <p>Let us rewrite the ping pong program with "ping" and "pong" on different computers. First a few things are needed to set up to get this to work. The distributed Erlang - implementation provides a basic security mechanism to prevent - unauthorized access to an Erlang system on another computer. + implementation provides a very basic authentication mechanism to prevent + unintentional access to an Erlang system on another computer. Erlang systems which talk to each other must have the same <em>magic cookie</em>. The easiest way to achieve this is by having a file called <c>.erlang.cookie</c> in your home diff --git a/system/doc/oam/oam_intro.xml b/system/doc/oam/oam_intro.xml index cdcb6e3111..8b8d69e638 100644 --- a/system/doc/oam/oam_intro.xml +++ b/system/doc/oam/oam_intro.xml @@ -178,7 +178,7 @@ <section> <title>MIB Structure</title> <p>The top-level OTP MIB is called <c>OTP-REG</c> and it is - included in the <c>sasl</c> application. All other OTP MIBs + included in the SASL application. All other OTP MIBs import some objects from this MIB.</p> <p>Each MIB is contained in one application. The MIB text @@ -188,7 +188,7 @@ <c><![CDATA[include/<MIB>.hrl]]></c>, and the compiled MIBs are stored under <c><![CDATA[priv/mibs/<MIB>.bin]]></c>. For example, the <c>OTP-MIB</c> is included in the - <c>sasl</c> application:</p> + SASL application:</p> <code type="none"> sasl-1.3/mibs/OTP-MIB.mib @@ -211,11 +211,11 @@ snmp:c("MY-MIB", [{il, ["sasl/priv/mibs"]}]).</code> <p>The following MIBs are defined in the OTP system:</p> <list type="bulleted"> - <item><p><c>OTP-REG)</c> (in <c>sasl</c>) contains the top-level + <item><p><c>OTP-REG)</c> (in SASL) contains the top-level OTP registration objects, used by all other MIBs.</p></item> - <item><p><c>OTP-TC</c> (in <c>sasl</c>) contains the general + <item><p><c>OTP-TC</c> (in SASL) contains the general Textual Conventions, which can be used by any other MIB.</p></item> - <item><p><c>OTP-MIB</c> (in <c>sasl</c>) contains objects for + <item><p><c>OTP-MIB</c> (in SASL) contains objects for instrumentation of the Erlang nodes, the Erlang machines, and the applications in the system.</p></item> <item><p><c>OTP-OS-MON-MIB</c> (in <c>oc_mon</c>) contains diff --git a/system/doc/programming_examples/bit_syntax.xml b/system/doc/programming_examples/bit_syntax.xml index 0af295b7b7..d1dd52c5ab 100644 --- a/system/doc/programming_examples/bit_syntax.xml +++ b/system/doc/programming_examples/bit_syntax.xml @@ -4,7 +4,7 @@ <chapter> <header> <copyright> - <year>2003</year><year>2015</year> + <year>2003</year><year>2017</year> <holder>Ericsson AB. All Rights Reserved.</holder> </copyright> <legalnotice> @@ -32,6 +32,8 @@ <section> <title>Introduction</title> + <p>The complete specification for the bit syntax appears in the + <seealso marker="doc/reference_manual:expressions#bit_syntax">Reference Manual</seealso>.</p> <p>In Erlang, a Bin is used for constructing binaries and matching binary patterns. A Bin is written with the following syntax:</p> <code type="none"><![CDATA[ @@ -45,7 +47,7 @@ Bin = <<E1, E2, ... En>>]]></code> <<E1, E2, ... En>> = Bin ]]></code> <p>Here, <c>Bin</c> is bound and the elements are bound or unbound, as in any match.</p> - <p>Since Erlang R12B, a Bin does not need to consist of a whole number of bytes.</p> + <p>A Bin does not need to consist of a whole number of bytes.</p> <p>A <em>bitstring</em> is a sequence of zero or more bits, where the number of bits does not need to be divisible by 8. If the number @@ -165,8 +167,9 @@ end.]]></code> separated by hyphens.</p> <taglist> <tag>Type</tag> - <item>The type can be <c>integer</c>, <c>float</c>, or - <c>binary</c>.</item> + <item>The most commonly used types are <c>integer</c>, <c>float</c>, and <c>binary</c>. + See <seealso marker="doc/reference_manual:expressions#bit_syntax">Bit Syntax Expressions in the Reference Manual</seealso> for a complete description. +</item> <tag>Signedness</tag> <item>The signedness specification can be either <c>signed</c> or <c>unsigned</c>. Notice that signedness only matters for @@ -181,7 +184,7 @@ end.]]></code> <item>The unit size is given as <c>unit:IntegerLiteral</c>. The allowed range is 1-256. It is multiplied by the <c>Size</c> specifier to give the effective size of - the segment. Since Erlang R12B, the unit size specifies the alignment + the segment. The unit size specifies the alignment for binary segments without size.</item> </taglist> <p><em>Example:</em></p> @@ -319,21 +322,15 @@ foo(<<A:8,Rest/bitstring>>) ->]]></code> <section> <title>Appending to a Binary</title> - <p>Since Erlang R12B, the following function for creating a binary out of - a list of triples of integers is efficient:</p> + <p>Appending to a binary in an efficient way can be done as follows:</p> <code type="none"><![CDATA[ triples_to_bin(T) -> triples_to_bin(T, <<>>). triples_to_bin([{X,Y,Z} | T], Acc) -> - triples_to_bin(T, <<Acc/binary,X:32,Y:32,Z:32>>); % inefficient before R12B + triples_to_bin(T, <<Acc/binary,X:32,Y:32,Z:32>>); triples_to_bin([], Acc) -> Acc.]]></code> - <p>In previous releases, this function was highly inefficient, because - the binary constructed so far (<c>Acc</c>) was copied in each recursion step. - That is no longer the case. For more information, see - <seealso marker="doc/efficiency_guide:introduction"> - Efficiency Guide</seealso>.</p> </section> </chapter> diff --git a/system/doc/programming_examples/records.xml b/system/doc/programming_examples/records.xml index da346dd0b3..074aa636b4 100644 --- a/system/doc/programming_examples/records.xml +++ b/system/doc/programming_examples/records.xml @@ -93,7 +93,7 @@ person</pre> at compile time, not at runtime. For details on records in the shell, see the <seealso marker="stdlib:shell">shell(3)</seealso> - manual page in <c>stdlib</c>.</p> + manual page in STDLIB.</p> </section> <section> diff --git a/system/doc/reference_manual/character_set.xml b/system/doc/reference_manual/character_set.xml index d25f2c001d..ef14bf1372 100644 --- a/system/doc/reference_manual/character_set.xml +++ b/system/doc/reference_manual/character_set.xml @@ -4,7 +4,7 @@ <chapter> <header> <copyright> - <year>2014</year><year>2015</year> + <year>2014</year><year>2017</year> <holder>Ericsson AB. All Rights Reserved.</holder> </copyright> <legalnotice> @@ -32,9 +32,9 @@ <section> <title>Character Set</title> - <p>Since Erlang 4.8/OTP R5A, the syntax of Erlang tokens is extended to - allow the use of the full ISO-8859-1 (Latin-1) character set. This - is noticeable in the following ways:</p> + <p>The syntax of Erlang tokens allow the use of the full + ISO-8859-1 (Latin-1) character set. This is noticeable in the + following ways:</p> <list type="bulleted"> <item> <p>All the Latin-1 printable characters can be used and are @@ -102,13 +102,16 @@ <tcaption>Character Classes</tcaption> </table> <p>In Erlang/OTP R16B the syntax of Erlang tokens was extended to - handle Unicode. The support is limited to - string literals and comments. Atoms, module names, and - function names are restricted to the ISO-Latin-1 range. + handle Unicode. The support was limited to + string literals and comments. More about the usage of Unicode in Erlang source files can be found in <seealso marker="stdlib:unicode_usage#unicode_in_erlang">STDLIB's User's Guide</seealso>.</p> + <p>From Erlang/OTP 20, atoms and function names are also allowed + to contain Unicode characters outside the ISO-Latin-1 range. + Module names, application names, and node names are still + restricted to the ISO-Latin-1 range.</p> </section> <section> <title>Source File Encoding</title> diff --git a/system/doc/reference_manual/code_loading.xml b/system/doc/reference_manual/code_loading.xml index f6fd2911fa..f5e5e74841 100644 --- a/system/doc/reference_manual/code_loading.xml +++ b/system/doc/reference_manual/code_loading.xml @@ -4,7 +4,7 @@ <chapter> <header> <copyright> - <year>2003</year><year>2015</year> + <year>2003</year><year>2016</year> <holder>Ericsson AB. All Rights Reserved.</holder> </copyright> <legalnotice> diff --git a/system/doc/reference_manual/data_types.xml b/system/doc/reference_manual/data_types.xml index e63825b97d..93c679357b 100644 --- a/system/doc/reference_manual/data_types.xml +++ b/system/doc/reference_manual/data_types.xml @@ -4,7 +4,7 @@ <chapter> <header> <copyright> - <year>2003</year><year>2015</year> + <year>2003</year><year>2017</year> <holder>Ericsson AB. All Rights Reserved.</holder> </copyright> <legalnotice> @@ -50,10 +50,7 @@ <item><em><c>base</c></em><c>#</c><em><c>value</c></em> <br></br> Integer with the base <em><c>base</c></em>, that must be an - integer in the range 2..36. <br></br> - - In Erlang 5.2/OTP R9B and earlier versions, the allowed range - is 2..16.</item> + integer in the range 2..36.</item> </list> <p><em>Examples:</em></p> <pre> @@ -455,7 +452,7 @@ hello <<"77">> 16> <input>float_to_binary(7.0).</input> <<"7.00000000000000000000e+00">> -17> <input>binary_to_float(<<"7.000e+00>>").</input> +17> <input>binary_to_float(<<"7.000e+00">>).</input> 7.0</pre> </section> </chapter> diff --git a/system/doc/reference_manual/distributed.xml b/system/doc/reference_manual/distributed.xml index 0a4a323fe9..b519609717 100644 --- a/system/doc/reference_manual/distributed.xml +++ b/system/doc/reference_manual/distributed.xml @@ -4,7 +4,7 @@ <chapter> <header> <copyright> - <year>2003</year><year>2015</year> + <year>2003</year><year>2017</year> <holder>Ericsson AB. All Rights Reserved.</holder> </copyright> <legalnotice> @@ -42,6 +42,19 @@ <p>The distribution mechanism is implemented using TCP/IP sockets. How to implement an alternative carrier is described in the <seealso marker="erts:alt_dist">ERTS User's Guide</seealso>.</p> + <warning> + <p> + Starting a distributed node without also specifying + <seealso marker="erts:erl#proto_dist"><c>-proto_dist inet_tls</c></seealso> + will expose the node to attacks that may give the attacker + complete access to the node and in extension the cluster. + When using un-secure distributed nodes, make sure that the + network is configured to keep potential attackers out. + See the <seealso marker="ssl:ssl_distribution"> + Using SSL for Erlang Distribution</seealso> User's Guide + for details on how to setup a secure distributed node. + </p> + </warning> </section> <section> diff --git a/system/doc/reference_manual/errors.xml b/system/doc/reference_manual/errors.xml index e764cf431f..b16c5da6eb 100644 --- a/system/doc/reference_manual/errors.xml +++ b/system/doc/reference_manual/errors.xml @@ -4,7 +4,7 @@ <chapter> <header> <copyright> - <year>2003</year><year>2015</year> + <year>2003</year><year>2017</year> <holder>Ericsson AB. All Rights Reserved.</holder> </copyright> <legalnotice> @@ -49,8 +49,7 @@ The Erlang programming language has built-in features for handling of run-time errors.</p> <p>A run-time error can also be emulated by calling - <c>erlang:error(Reason)</c> or <c>erlang:error(Reason, Args)</c> - (those appeared in Erlang 5.4/OTP-R10).</p> + <c>erlang:error(Reason)</c> or <c>erlang:error(Reason, Args)</c>.</p> <p>A run-time error is another name for an exception of class <c>error</c>. </p> @@ -79,7 +78,6 @@ <p>Exceptions are run-time errors or generated errors and are of three different classes, with different origins. The <seealso marker="expressions#try">try</seealso> expression - (new in Erlang 5.4/OTP R10B) can distinguish between the different classes, whereas the <seealso marker="expressions#catch">catch</seealso> expression cannot. They are described in @@ -94,7 +92,7 @@ <cell align="left" valign="middle"><c>error</c></cell> <cell align="left" valign="middle">Run-time error, for example, <c>1+a</c>, or the process called - <c>erlang:error/1,2</c> (new in Erlang 5.4/OTP R10B)</cell> + <c>erlang:error/1,2</c></cell> </row> <row> <cell align="left" valign="middle"><c>exit</c></cell> @@ -111,7 +109,7 @@ and a stack trace (which aids in finding the code location of the exception).</p> <p>The stack trace can be retrieved using - <c>erlang:get_stacktrace/0</c> (new in Erlang 5.4/OTP R10B) + <c>erlang:get_stacktrace/0</c> from within a <c>try</c> expression, and is returned for exceptions of class <c>error</c> from a <c>catch</c> expression.</p> <p>An exception of class <c>error</c> is also known as a run-time diff --git a/system/doc/reference_manual/expressions.xml b/system/doc/reference_manual/expressions.xml index 355fd3cfef..cf2d5034aa 100644 --- a/system/doc/reference_manual/expressions.xml +++ b/system/doc/reference_manual/expressions.xml @@ -4,7 +4,7 @@ <chapter> <header> <copyright> - <year>2003</year><year>2016</year> + <year>2003</year><year>2017</year> <holder>Ericsson AB. All Rights Reserved.</holder> </copyright> <legalnotice> @@ -123,10 +123,9 @@ member(_Elem, []) -> or <c>receive</c> expression must be bound in all branches to have a value outside the expression. Otherwise they are regarded as 'unsafe' outside the expression.</p> - <p>For the <c>try</c> expression introduced in - Erlang 5.4/OTP R10B, variable scoping is limited so that + <p>For the <c>try</c> expression variable scoping is limited so that variables bound in the expression are always 'unsafe' outside - the expression. This is to be improved.</p> + the expression.</p> </section> <section> @@ -189,7 +188,6 @@ f([$p,$r,$e,$f,$i,$x | Str]) -> ...</pre> <pre> case {Value, Result} of {?THRESHOLD+1, ok} -> ...</pre> - <p>This feature was added in Erlang 5.0/OTP R7.</p> </section> </section> @@ -1348,8 +1346,8 @@ catch ExceptionBodyN end</code> <p>This is an enhancement of - <seealso marker="#catch">catch</seealso> that appeared in - Erlang 5.4/OTP R10B. It gives the possibility to:</p> + <seealso marker="#catch">catch</seealso>. + It gives the possibility to:</p> <list type="bulleted"> <item>Distinguish between different exception classes.</item> <item>Choose to handle only the desired ones.</item> @@ -1541,7 +1539,16 @@ end</pre> <pre> 1> <input>[X*2 || X <- [1,2,3]].</input> [2,4,6]</pre> - <p>More examples are provoded in + <p>When there are no generators or bit string generators, a list comprehension + returns either a list with one element (the result of evaluating <c>Expr</c>) + if all filters are true or an empty list otherwise.</p> + <p><em>Example:</em></p> + <pre> +1> <input>[2 || is_integer(2)].</input> +[2] +2> <input>[x || is_integer(x)].</input> +[]</pre> + <p>More examples are provided in <seealso marker="doc/programming_examples:list_comprehensions"> Programming Examples.</seealso></p> diff --git a/system/doc/reference_manual/introduction.xml b/system/doc/reference_manual/introduction.xml index abb4ed407d..afbdfa7434 100644 --- a/system/doc/reference_manual/introduction.xml +++ b/system/doc/reference_manual/introduction.xml @@ -4,7 +4,7 @@ <chapter> <header> <copyright> - <year>2003</year><year>2015</year> + <year>2003</year><year>2017</year> <holder>Ericsson AB. All Rights Reserved.</holder> </copyright> <legalnotice> @@ -80,14 +80,14 @@ <item>A <em>list</em> is any number of items. For example, an argument list can consist of zero, one, or more arguments.</item> </list> - <p>If a feature has been added recently, in Erlang 5.0/OTP R7 or - later, this is mentioned in the text.</p> + <p>If a feature has been added in R13A or later, + this is mentioned in the text.</p> </section> <section> <title>Complete List of BIFs</title> <p>For a complete list of BIFs, their arguments and return values, - see <seealso marker="erts:erlang#process_flag/2">erlang(3)</seealso> + see <seealso marker="erts:erlang">erlang(3)</seealso> manual page in ERTS.</p> </section> diff --git a/system/doc/reference_manual/macros.xml b/system/doc/reference_manual/macros.xml index 350bb1d123..a341307ab7 100644 --- a/system/doc/reference_manual/macros.xml +++ b/system/doc/reference_manual/macros.xml @@ -4,7 +4,7 @@ <chapter> <header> <copyright> - <year>2003</year><year>2015</year> + <year>2003</year><year>2017</year> <holder>Ericsson AB. All Rights Reserved.</holder> </copyright> <legalnotice> @@ -286,7 +286,6 @@ t.erl:5: Warning: -warning("Macro VERSION not defined -- using default version." argument, is expanded to a string containing the tokens of the argument. This is similar to the <c>#arg</c> stringifying construction in C.</p> - <p>The feature was added in Erlang 5.0/OTP R7.</p> <p><em>Example:</em></p> <code type="none"> -define(TESTCALL(Call), io:format("Call ~s: ~w~n", [??Call, Call])). diff --git a/system/doc/reference_manual/modules.xml b/system/doc/reference_manual/modules.xml index 96968b547e..4a97bfeb7b 100644 --- a/system/doc/reference_manual/modules.xml +++ b/system/doc/reference_manual/modules.xml @@ -4,7 +4,7 @@ <chapter> <header> <copyright> - <year>2003</year><year>2016</year> + <year>2003</year><year>2017</year> <holder>Ericsson AB. All Rights Reserved.</holder> </copyright> <legalnotice> @@ -143,7 +143,6 @@ fact(0) -> % | standard behaviours:</p> <list type="bulleted"> <item><c>gen_server</c></item> - <item><c>gen_fsm</c></item> <item><c>gen_statem</c></item> <item><c>gen_event</c></item> <item><c>supervisor</c></item> diff --git a/system/doc/reference_manual/records.xml b/system/doc/reference_manual/records.xml index 12a3e697cd..6b26e2c242 100644 --- a/system/doc/reference_manual/records.xml +++ b/system/doc/reference_manual/records.xml @@ -4,7 +4,7 @@ <chapter> <header> <copyright> - <year>2003</year><year>2015</year> + <year>2003</year><year>2017</year> <holder>Ericsson AB. All Rights Reserved.</holder> </copyright> <legalnotice> @@ -72,9 +72,9 @@ <pre> #Name{Field1=Expr1,...,FieldK=ExprK, _=ExprL}</pre> <p>Omitted fields then get the value of evaluating <c>ExprL</c> - instead of their default values. This feature was added in - Erlang 5.1/OTP R8 and is primarily intended to be used to create - patterns for ETS and Mnesia match functions.</p> + instead of their default values. This feature is primarily + intended to be used to create patterns for ETS and Mnesia match + functions.</p> <p><em>Example:</em></p> <pre> -record(person, {name, phone, address}). diff --git a/system/doc/reference_manual/typespec.xml b/system/doc/reference_manual/typespec.xml index f17e5df277..a0ea41cb3b 100644 --- a/system/doc/reference_manual/typespec.xml +++ b/system/doc/reference_manual/typespec.xml @@ -11,7 +11,7 @@ Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except in compliance with the License. You may obtain a copy of the License at - + http://www.apache.org/licenses/LICENSE-2.0 Unless required by applicable law or agreed to in writing, software @@ -47,7 +47,7 @@ <list type="bulleted"> <item>To document function interfaces</item> <item>To provide more information for bug detection tools, - such as <c>Dialyzer</c></item> + such as Dialyzer</item> <item>To be exploited by documentation tools, such as EDoc, for generating program documentation of various forms</item> </list> @@ -63,7 +63,7 @@ Types consist of, and are built from, a set of predefined types, for example, <c>integer()</c>, <c>atom()</c>, and <c>pid()</c>. Predefined types represent a typically infinite set of Erlang terms that - belong to this type. For example, the type <c>atom()</c> stands for the + belong to this type. For example, the type <c>atom()</c> denotes the set of all Erlang atoms. </p> <p> @@ -131,19 +131,19 @@ | nonempty_improper_list(Type1, Type2) %% Type1 and Type2 as above | nonempty_list(Type) %% Proper non-empty list - Map :: map() %% stands for a map of any size - | #{} %% stands for the empty map + Map :: map() %% denotes a map of any size + | #{} %% denotes the empty map | #{PairList} - Tuple :: tuple() %% stands for a tuple of any size + Tuple :: tuple() %% denotes a tuple of any size | {} | {TList} PairList :: Pair | Pair, PairList - Pair :: Type := Type %% denotes a pair that must be present - | Type => Type + Pair :: Type := Type %% denotes a mandatory pair + | Type => Type %% denotes an optional pair TList :: Type | Type, TList @@ -161,7 +161,7 @@ that <c>M</c> or <c>N</c>, or both, are zero. </p> <p> - Because lists are commonly used, they have shorthand type notations. + Because lists are commonly used, they have shorthand type notations. The types <c>list(T)</c> and <c>nonempty_list(T)</c> have the shorthands <c>[T]</c> and <c>[T,...]</c>, respectively. The only difference between the two shorthands is that <c>[T]</c> can be an @@ -169,14 +169,18 @@ </p> <p> Notice that the shorthand for <c>list()</c>, that is, the list of - elements of unknown type, is <c>[_]</c> (or <c>[any()]</c>), not <c>[]</c>. + elements of unknown type, is <c>[_]</c> (or <c>[any()]</c>), not <c>[]</c>. The notation <c>[]</c> specifies the singleton type for the empty list. </p> <p> The general form of maps is <c>#{PairList}</c>. The key types in <c>PairList</c> are allowed to overlap, and if they do, the leftmost pair takes precedence. A map pair has a key in - <c>PairList</c> if it belongs to this type. + <c>PairList</c> if it belongs to this type. A <c>PairList</c> may contain + both 'mandatory' and 'optional' pairs where 'mandatory' denotes that + a key type, and its associated value type, must be present. + In the case of an 'optional' pair it is not required for the key type to + be present. </p> <p> Notice that the syntactic representation of <c>map()</c> is @@ -184,8 +188,8 @@ The notation <c>#{}</c> specifies the singleton type for the empty map. </p> <p> - For convenience, the following types are also built-in. - They can be thought as predefined aliases for the type unions also shown in + For convenience, the following types are also built-in. + They can be thought as predefined aliases for the type unions also shown in the table. </p> <table> @@ -201,37 +205,37 @@ <row> <cell><c>bitstring()</c></cell><cell><c><<_:_*1>></c></cell> </row> - <row> + <row> <cell><c>boolean()</c></cell><cell><c>'false' | 'true'</c></cell> </row> - <row> + <row> <cell><c>byte()</c></cell><cell><c>0..255</c></cell> </row> <row> <cell><c>char()</c></cell><cell><c>0..16#10ffff</c></cell> </row> - <row> + <row> <cell><c>nil()</c></cell><cell><c>[]</c></cell> </row> <row> <cell><c>number()</c></cell><cell><c>integer() | float()</c></cell> </row> - <row> + <row> <cell><c>list()</c></cell><cell><c>[any()]</c></cell> </row> - <row> + <row> <cell><c>maybe_improper_list()</c></cell><cell><c>maybe_improper_list(any(), any())</c></cell> </row> - <row> + <row> <cell><c>nonempty_list()</c></cell><cell><c>nonempty_list(any())</c></cell> </row> <row> <cell><c>string()</c></cell><cell><c>[char()]</c></cell> </row> - <row> + <row> <cell><c>nonempty_string()</c></cell><cell><c>[char(),...]</c></cell> </row> - <row> + <row> <cell><c>iodata()</c></cell><cell><c>iolist() | binary()</c></cell> </row> <row> @@ -243,7 +247,7 @@ <row> <cell><c>module()</c></cell><cell><c>atom()</c></cell> </row> - <row> + <row> <cell><c>mfa()</c></cell><cell><c>{module(),atom(),arity()}</c></cell> </row> <row> @@ -259,7 +263,7 @@ <cell><c>timeout()</c></cell><cell><c>'infinity' | non_neg_integer()</c></cell> </row> <row> - <cell><c>no_return()</c></cell><cell><c>none()</c></cell> + <cell><c>no_return()</c></cell><cell><c>none()</c></cell> </row> <tcaption>Built-in types, predefined aliases</tcaption> </table> @@ -284,11 +288,11 @@ </row> <tcaption>Additional built-in types</tcaption> </table> - + <p> Users are not allowed to define types with the same names as the predefined or built-in ones. This is checked by the compiler and - its violation results in a compilation error. + its violation results in a compilation error. </p> <note> <p> @@ -394,13 +398,13 @@ <pre> -record(rec, {field1 :: Type1, field2, field3 :: Type3}).</pre> <p> - For fields without type annotations, their type defaults to any(). + For fields without type annotations, their type defaults to any(). That is, the previous example is a shorthand for the following: </p> <pre> -record(rec, {field1 :: Type1, field2 :: any(), field3 :: Type3}).</pre> <p> - In the presence of initial values for fields, + In the presence of initial values for fields, the type must be declared after the initialization, as follows: </p> <pre> @@ -409,11 +413,13 @@ The initial values for fields are to be compatible with (that is, a member of) the corresponding types. This is checked by the compiler and results in a compilation error - if a violation is detected. For fields without initial values, - the singleton type <c>'undefined'</c> is added to all declared types. - In other words, the following two record declarations have identical - effects: + if a violation is detected. </p> + <note> + <p>Before Erlang/OTP 19, for fields without initial values, + the singleton type <c>'undefined'</c> was added to all declared types. + In other words, the following two record declarations had identical + effects:</p> <pre> -record(rec, {f1 = 42 :: integer(), f2 :: float(), @@ -423,26 +429,27 @@ f2 :: 'undefined' | float(), f3 :: 'undefined' | 'a' | 'b'}).</pre> <p> - For this reason, it is recommended that records contain initializers, - whenever possible. + This is no longer the case. If you require <c>'undefined'</c> in your record field + type, you must explicitly add it to the typespec, as in the 2nd example. </p> + </note> <p> - Any record, containing type information or not, once defined, + Any record, containing type information or not, once defined, can be used as a type using the following syntax: </p> <pre> #rec{}</pre> <p> - In addition, the record fields can be further specified when using + In addition, the record fields can be further specified when using a record type by adding type information about the field as follows: </p> <pre> #rec{some_field :: Type}</pre> <p> - Any unspecified fields are assumed to have the type in the original + Any unspecified fields are assumed to have the type in the original record declaration. </p> </section> - + <section> <title>Specifications for Functions</title> <p> @@ -456,9 +463,9 @@ else a compilation error occurs. </p> <p> - This form can also be used in header files (.hrl) to declare type - information for exported functions. - Then these header files can be included in files that (implicitly or + This form can also be used in header files (.hrl) to declare type + information for exported functions. + Then these header files can be included in files that (implicitly or explicitly) import these functions. </p> <p> @@ -472,14 +479,14 @@ <pre> -spec Function(ArgName1 :: Type1, ..., ArgNameN :: TypeN) -> RT.</pre> <p> - A function specification can be overloaded. + A function specification can be overloaded. That is, it can have several types, separated by a semicolon (<c>;</c>): </p> <pre> -spec foo(T1, T2) -> T3 ; (T4, T5) -> T6.</pre> <p> - A current restriction, which currently results in a warning + A current restriction, which currently results in a warning (not an error) by the compiler, is that the domains of the argument types cannot overlap. For example, the following specification results in a warning: @@ -488,9 +495,9 @@ -spec foo(pos_integer()) -> pos_integer() ; (integer()) -> integer().</pre> <p> - Type variables can be used in specifications to specify relations for - the input and output arguments of a function. - For example, the following specification defines the type of a + Type variables can be used in specifications to specify relations for + the input and output arguments of a function. + For example, the following specification defines the type of a polymorphic identity function: </p> <pre> @@ -539,8 +546,8 @@ -spec foo({X, integer()}) -> X when X :: atom() ; ([Y]) -> Y when Y :: number().</pre> <p> - Some functions in Erlang are not meant to return; - either because they define servers or because they are used to + Some functions in Erlang are not meant to return; + either because they define servers or because they are used to throw exceptions, as in the following function: </p> <pre> my_error(Err) -> erlang:throw({error, Err}).</pre> @@ -552,4 +559,3 @@ <pre> -spec my_error(term()) -> no_return().</pre> </section> </chapter> - diff --git a/system/doc/top/Makefile b/system/doc/top/Makefile index 7f9cec540b..116ec688fa 100644 --- a/system/doc/top/Makefile +++ b/system/doc/top/Makefile @@ -35,7 +35,7 @@ RELSYSDIR = "$(RELEASE_PATH)/doc" GIF_FILES = -INFO_FILES = ../../README ../../COPYRIGHT PR.template +INFO_FILES = ../../../README.md ../../COPYRIGHT PR.template TOPDOCDIR=. diff --git a/system/doc/top/src/erl_html_tools.erl b/system/doc/top/src/erl_html_tools.erl index d55c2e1164..28a0649658 100644 --- a/system/doc/top/src/erl_html_tools.erl +++ b/system/doc/top/src/erl_html_tools.erl @@ -387,9 +387,7 @@ subst("#copyright#", _Info, _Group) -> "copyright Copyright © 1991-2004"; subst("#groups#", Info, _Group) -> [ - "<table border=0 width=\"90%\" cellspacing=3 cellpadding=5>\n", - subst_groups(Info), - "</table>\n" + subst_groups(Info) ]; subst("#applinks#", Info, Group) -> subst_applinks(Info, Group); @@ -476,16 +474,10 @@ subst_unknown_groups([{_Group,Heading,Apps} | Groups], Text0, Left) -> group_table(Heading,Apps) -> - [ - " <tr>\n", - " <td colspan=2 class=header>\n", - " <font size=\"+1\"><b>",Heading,"</b></font>\n", - " </td>\n", - " </tr>\n", + ["<h2>",Heading,"</h2>", + "<table class=\"group-table\">\n", subst_apps(Apps), - " <tr>\n", - " <td colspan=2><font size=1> </font></td>\n", - " </tr>\n" + "</table>\n" ]. % Count and split the applications in half to get the right sort @@ -500,17 +492,11 @@ subst_apps([]) -> subst_app(App, [{VSN,_Path,Link,Text}]) -> [ " <tr class=app>\n", - " <td align=left valign=top>\n", - " <table border=0 width=\"100%\" cellspacing=0 cellpadding=0>\n", - " <tr class=app>\n", - " <td align=left valign=top>\n", + " <td>\n", " <a href=\"",Link,"\" target=\"_top\">",uc(App),"</a>\n", " <a href=\"",Link,"\" target=\"_top\">",VSN,"</a>\n", - " </td>\n", - " </tr>\n", - " </table>\n" " </td>\n", - " <td align=left valign=top>\n", + " <td>\n", Text,"\n", " </td>\n", " </tr>\n" @@ -518,27 +504,14 @@ subst_app(App, [{VSN,_Path,Link,Text}]) -> subst_app(App, [{VSN,_Path,Link,Text} | VerInfos]) -> [ " <tr class=app>\n", - " <td align=left valign=top>\n", - " <table border=0 width=\"100%\" cellspacing=0 cellpadding=0>\n", - " <tr class=app>\n", - " <td align=left valign=top>\n", + " <td>\n", " <a href=\"",Link,"\" target=\"_top\">",uc(App), - "</a> <br>\n", + "</a>\n", " <a href=\"",Link,"\" target=\"_top\">",VSN,"</a>\n", - " </td>\n", - " <td align=right valign=top width=50>\n", - " <table border=0 width=40 cellspacing=0 cellpadding=0>\n", - " <tr class=app>\n", - " <td align=left valign=top class=appnums>\n", + " <td class=appnums>\n", subst_vsn(VerInfos), - " </td>\n", - " </tr>\n", - " </table>\n" - " </td>\n", - " </tr>\n", - " </table>\n" " </td>\n", - " <td align=left valign=top>\n", + " <td>\n", Text,"\n", " </td>\n", " </tr>\n" diff --git a/system/doc/top/src/otp_man_index.erl b/system/doc/top/src/otp_man_index.erl index 12aaba1423..655d7265f7 100644 --- a/system/doc/top/src/otp_man_index.erl +++ b/system/doc/top/src/otp_man_index.erl @@ -154,10 +154,10 @@ gen_html(RefPages, OutFile)-> SortedPages = lists:sort(RefPages), lists:foreach(fun({_,Module, App, AppDocDir, RefPagePath}) -> - io:fwrite(Out, " <TR>\n",[]), - io:fwrite(Out, " <TD><A HREF=\"~s\">~s</A></TD>\n", + io:fwrite(Out, " <tr>\n",[]), + io:fwrite(Out, " <td><a href=\"~s\">~s</a></td>\n", [RefPagePath, Module]), - io:fwrite(Out, " <TD><A HREF=\"~s\">~s</A></TD>\n", + io:fwrite(Out, " <td><a HREF=\"~s\">~s</a></td>\n", [filename:join(AppDocDir, "index.html"), App]), io:fwrite(Out, " </TR>\n",[]) @@ -175,41 +175,40 @@ gen_html(RefPages, OutFile)-> html_header() -> "<!DOCTYPE HTML PUBLIC \"-//W3C//DTD HTML 4.01 Transitional//EN\">\n" "<!-- This file was generated by the otp_man_index -->\n" - "<HTML>\n" - "<HEAD>\n" + "<html>\n" + "<head>\n" " <link rel=\"stylesheet\" href=\"otp_doc.css\" type=\"text/css\"/>\n" - " <TITLE>Erlang/OTP Manual Page Index</TITLE>\n" - "</HEAD>\n" - "<BODY BGCOLOR=\"#FFFFFF\" TEXT=\"#000000\" LINK=\"#0000FF\" VLINK=\"#FF00FF\" ALINK=\"#FF0000\">\n" - "<CENTER>\n" + " <title>Erlang/OTP Manual Page Index</title>\n" + "</head>\n" + "<body>\n" + "<center>\n" "<!-- A HREF=\"http://www.erlang.org/\">\n" "<img alt=\"Erlang logo\" src=\"erlang-logo.png\"/>\n" - "</A><BR -->\n" - "<SMALL>\n" - "[<A HREF=\"index.html\">Up</A> | <A HREF=\"http://www.erlang.org/\">Erlang</A>]\n" - "</SMALL><BR>\n" - "<P/><FONT SIZE=\"+4\">OTP Reference Page Index</FONT><BR>\n" - "</CENTER>\n" - "<CENTER>\n" - "<P/>\n" - "<TABLE BORDER=1>\n" - "<TR>\n" - " <TH>Manual Page</TH><TH>Application</TH>\n" - "</TR>\n". + "</a><br -->\n" + "<small>\n" + "[ <A HREF=\"index.html\">Up</A> | <A HREF=\"http://www.erlang.org/\">Homepage</A> ]\n" + "</small><br>\n" + "<h1>OTP Reference Page Index</h1>\n" + "</center>\n" + "<center>\n" + "<table class=\"man-index\">\n" + "<tr>\n" + " <th>Manual Page</th><th>Application</th>\n" + "</tr>\n". html_footer(Year) -> - "</TABLE>\n" - "</CENTER>\n" - "<P/>\n" - "<CENTER>\n" - "<HR/>\n" - "<SMALL>\n" + "</table>\n" + "</center>\n" + "<p/>\n" + "<center>\n" + "<hr/>\n" + "<small>\n" "Copyright © 1991-" ++ Year ++ "\n" "<a href=\"http://www.ericsson.com/technology/opensource/erlang/\">\n" "Ericsson AB</a>\n" - "</SMALL>\n" - "</CENTER>\n" - "</BODY>\n" - "</HTML>\n". + "</small>\n" + "</center>\n" + "</body>\n" + "</html>\n". diff --git a/system/doc/top/templates/applications.html.src b/system/doc/top/templates/applications.html.src index 1f73c44d69..7e939ddcd6 100644 --- a/system/doc/top/templates/applications.html.src +++ b/system/doc/top/templates/applications.html.src @@ -24,31 +24,53 @@ limitations under the License. <title>Erlang/OTP #version# Applications</title> <style type="text/css"> <!-- - BODY { background: white } + BODY { background: #fefefe; color: #111; } - BODY { font-family: Verdana, Arial, Helvetica, sans-serif } - TH { font-family: Verdana, Arial, Helvetica, sans-serif } - TD { font-family: Verdana, Arial, Helvetica, sans-serif } - P { font-family: Verdana, Arial, Helvetica, sans-serif } + BODY { font-family: sans-serif } - .header { background: #222; color: #fff } - .app { background: #ccc } + .header { background: #333; color: #fefefe; } - a.anum:link { color: green; text-decoration: none } - a.anum:active { color: green; text-decoration: none } - a.anum:visited { color: green; text-decoration: none } + a:link { color: #303f9f; text-decoration: none } + a:active { color: #303f9f; text-decoration: none } + a:visited { color: #303f9f; text-decoration: none } - a:link { text-decoration: none } - a:active { text-decoration: none } - a:visited { text-decoration: none } + h1,h2{ + text-align: center; + } + table { + margin: 1em 10%; + width: 80%; + border-collapse: collapse; + min-width: 50%; + } + + table, th, td { + border: 1px solid #666; + } + + th, td { + padding: 0.5em; + text-align: left; + } + + tr:hover { + background-color: #f5f5f5; + } + + tr:nth-child(even) { + background-color: #f2f2f2; + } + + th { + background-color: #777; + color: #fefefe; + } --> </style> </head> -<body bgcolor=white text="#000000" link="#0000ff" vlink="#ff00ff" - alink="#ff0000"> -<center> +<body> + <h1>Erlang/OTP Applications</h1> #groups# -</center> </body> </html> diff --git a/system/doc/top/templates/index.html.src b/system/doc/top/templates/index.html.src index d2a6736d34..747d19cf7e 100644 --- a/system/doc/top/templates/index.html.src +++ b/system/doc/top/templates/index.html.src @@ -2,7 +2,7 @@ <!-- %CopyrightBegin% -Copyright Ericsson AB 2009-2016. All Rights Reserved. +Copyright Ericsson AB 2009-2017. All Rights Reserved. Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except in compliance with the License. @@ -29,20 +29,24 @@ limitations under the License. </script> </head> -<body bgcolor=white text="#000000" link="#0000ff" vlink="#ff00ff" - alink="#ff0000"> +<body> <div id="container"> <div id="leftnav"> <div class="innertube"> -<img alt="Erlang logo" src="erlang-logo.png"/ > -<p/> -<small><a href="applications.html">Applications</a><br> -<a href="man_index.html">Modules</a></small> -<p/> -<a href="javascript:openAllFlips()">Expand All</a><br> -<a href="javascript:closeAllFlips()">Contract All</a> -<p/> +<div class="erlang-logo-wrapper"> + <img alt="Erlang logo" src="erlang-logo.png" class="erlang-logo"/ > +</div> + +<ul class="section-links"> + <li><a href="applications.html">Applications</a></li> + <li><a href="man_index.html" class="modules">Modules</a></li> +</ul> + +<ul class="expand-collapse-items"> + <li><a href="javascript:openAllFlips()">Expand All</a></li> + <li><a href="javascript:closeAllFlips()">Contract All</a></li> +</ul> <ul class="flipMenu"> <li>System Documentation @@ -60,8 +64,8 @@ limitations under the License. </ul> </li> </ul> -<b>Application Groups</b> -<br/> + +<h3>Application Groups</h3> <ul class="flipMenu"> #applinks# @@ -73,24 +77,12 @@ limitations under the License. <div id="content"> <div class="innertube"> -<center> -<font size="+1"><b>Erlang/OTP #otp_base_vsn#</b></font><br> -</center> -<center> -<p> -<font size="+1">Welcome to Erlang/OTP, a complete<br> -development environment<br> -for concurrent programming.</font> -</p> -</center> -<br> -<br> -<br> -<p><b> -<font size="+1"> -Some hints that may get you started faster -</font> -</b></p> + <h1 class="main-title">Erlang/OTP #otp_base_vsn#</h1> + <p class="main-description"> + Welcome to Erlang/OTP, a complete development environment for concurrent programming. + </p> + + <h2>Some hints that may get you started faster</h2> <ul> @@ -149,10 +141,11 @@ verification, comment support including paragraph filling, skeletons, tags support and more. See the <a href="#tools#/index.html"> Tools</a> application for details. <p> -There are also Erlang plugins for +There are also Erlang plugins for other code editors +<a href="http://github.com/vim-erlang">Vim (vim-erlang)</a> , +<a href="http://atom.io/packages/language-erlang"> Atom </a> , <a href="http://erlide.org/index.html">Eclipse (ErlIDE)</a> and -<a href="http://ignatov.github.io/intellij-erlang/">IntelliJ IDEA</a> -if you prefer a more graphical environment, which are both under active development. +<a href="http://ignatov.github.io/intellij-erlang/">IntelliJ IDEA</a>. <li>When developing with Erlang/OTP you usually test your programs from the interactive shell (see <a href="getting_started/users_guide.html"> Getting Started With Erlang</a>) where you can call individual diff --git a/system/doc/tutorial/c_port.xmlsrc b/system/doc/tutorial/c_port.xmlsrc index 695f16515d..ff0997fb54 100644 --- a/system/doc/tutorial/c_port.xmlsrc +++ b/system/doc/tutorial/c_port.xmlsrc @@ -4,7 +4,7 @@ <chapter> <header> <copyright> - <year>2000</year><year>2015</year> + <year>2000</year><year>2016</year> <holder>Ericsson AB. All Rights Reserved.</holder> </copyright> <legalnotice> @@ -98,11 +98,11 @@ loop(Port) -> {call, Caller, Msg} -> Port ! {self(), {command, encode(Msg)}}, receive - {Port, {data, Data}} -> + {Port, {data, Data}} -> Caller ! {complex, decode(Data)} end, loop(Port) - end.</pre> + end.</pre> <p>Assuming that both the arguments and the results from the C functions are less than 256, a simple encoding/decoding scheme is employed. In this scheme, <c>foo</c> is represented by byte diff --git a/system/doc/tutorial/c_portdriver.xmlsrc b/system/doc/tutorial/c_portdriver.xmlsrc index 933e2395a3..c4cf6daa3b 100644 --- a/system/doc/tutorial/c_portdriver.xmlsrc +++ b/system/doc/tutorial/c_portdriver.xmlsrc @@ -4,7 +4,7 @@ <chapter> <header> <copyright> - <year>2000</year><year>2015</year> + <year>2000</year><year>2017</year> <holder>Ericsson AB. All Rights Reserved.</holder> </copyright> <legalnotice> @@ -161,8 +161,8 @@ decode([Int]) -> Int.</pre> <title>Running the Example</title> <p><em>Step 1.</em> Compile the C code:</p> <pre> -unix> <input>gcc -o exampledrv -fpic -shared complex.c port_driver.c</input> -windows> <input>cl -LD -MD -Fe exampledrv.dll complex.c port_driver.c</input></pre> +unix> <input>gcc -o example_drv.so -fpic -shared complex.c port_driver.c</input> +windows> <input>cl -LD -MD -Fe example_drv.dll complex.c port_driver.c</input></pre> <p><em>Step 2.</em> Start Erlang and compile the Erlang code:</p> <pre> > <input>erl</input> diff --git a/system/doc/tutorial/complex6_nif.c b/system/doc/tutorial/complex6_nif.c index b656ed43ce..f6c06e94f4 100644 --- a/system/doc/tutorial/complex6_nif.c +++ b/system/doc/tutorial/complex6_nif.c @@ -1,4 +1,4 @@ -#include "erl_nif.h" +#include <erl_nif.h> extern int foo(int x); extern int bar(int y); diff --git a/system/doc/tutorial/erl_interface.xmlsrc b/system/doc/tutorial/erl_interface.xmlsrc index de50af42cf..bf9bd36597 100644 --- a/system/doc/tutorial/erl_interface.xmlsrc +++ b/system/doc/tutorial/erl_interface.xmlsrc @@ -4,7 +4,7 @@ <chapter> <header> <copyright> - <year>2000</year><year>2015</year> + <year>2000</year><year>2017</year> <holder>Ericsson AB. All Rights Reserved.</holder> </copyright> <legalnotice> @@ -162,9 +162,9 @@ int main() { the include files <c>erl_interface.h</c> and <c>ei.h</c>, and also to the libraries <c>erl_interface</c> and <c>ei</c>:</p> <pre> -unix> <input>gcc -o extprg -I/usr/local/otp/lib/erl_interface-3.2.1/include \\ </input> -<input> -L/usr/local/otp/lib/erl_interface-3.2.1/lib \\ </input> -<input> complex.c erl_comm.c ei.c -lerl_interface -lei</input></pre> +unix> <input>gcc -o extprg -I/usr/local/otp/lib/erl_interface-3.9.2/include \\ </input> +<input> -L/usr/local/otp/lib/erl_interface-3.9.2/lib \\ </input> +<input> complex.c erl_comm.c ei.c -lerl_interface -lei -lpthread</input></pre> <p>In Erlang/OTP R5B and later versions of OTP, the <c>include</c> and <c>lib</c> directories are situated under <c>OTPROOT/lib/erl_interface-VSN</c>, where <c>OTPROOT</c> is @@ -184,7 +184,7 @@ Eshell V4.9.1.2 (abort with ^G) {ok,complex2}</pre> <p><em>Step 3.</em> Run the example:</p> <pre> -2> <input>complex2:start("extprg").</input> +2> <input>complex2:start("./extprg").</input> <0.34.0> 3> <input>complex2:foo(3).</input> 4 |