Elm Exactly
A Standard Definition of Elm?Draft version 0.4 / Appendix E

EImplementation-Dependent Details

Where implementations of Standard Elm legitimately differ, the body of the definition states only what every implementation must satisfy, using an abstract parameter where one is needed. This appendix gives, for each such parameter or unspecified point, what the body requires of it and what two implementations choose. The implementations are Elm 0.19.1 with the elm/core 1.0.5 kernel on JavaScript, written Elm/JS, and eco 0.2.0 producing native code, written eco; eco’s output for JavaScript behaves as Elm/JS does, except for Bytes at the boundary (Section E.8.5). Each section states the requirement, with a reference to the body, and then gives a table with one row per implementation: its choice, and the consequences for programs. An implementation conforms on a point when its choice meets the requirement. The requirements concern the programs to which the definition gives a value. Where a program elaborates and the definition gives it a value, a conforming implementation’s result is one of its values; where the definition gives it none (the evaluation of its modules reaches Debug.todo, or does not end), the program has no meaning, and the definition requires nothing of an implementation, which may stop, run for ever, or run the program to some result. So Elm/JS, for which (&&) False (Debug.todo "x") is False where the definition gives no value, conforms on a program whose modules evaluate it. A program that has a meaning is held to its traces (Section 9.5). Where a step of it has no result, as when an application of update reaches Debug.todo, no further message is handled (rule (183)), and an implementation that handles further messages does not conform. Section E.10 collects every known point on which an implementation does not conform, with the ruling that settles it. The facts recorded here describe the versions named; they are not part of the definition.

E.1The Int Range and Normalisation

The body requires the following of the type Int (Chapter 2, Section 6.3 and Section D.4).

  • IntRange\IntRange is a set of integers containing every integer nn with −231≤n≤231−1-2^{31}\leq n\leq 2^{31}-1; Int has one zero.

  • norm\norm maps every integer into IntRange\IntRange and is the identity on IntRange\IntRange. Int addition, subtraction, multiplication, negation, absolute value and power with a non-negative exponent give norm\norm of the exact result, and an integer constant spelling nn denotes norm(n)\norm(n).

  • For b≠0b\neq 0, a // b is norm\norm of the truncation of a/ba/b toward zero; x // 0, modBy 0 x and remainderBy 0 x are 00.

  • For e<0e<0, b ^ e at Int is 11 when b=1b=1, 11 or −1-1 by the parity of ee when b=−1b=-1, and 00 otherwise.

  • round, floor, ceiling and truncate give the integer they denote when it lies in IntRange\IntRange, the least or greatest member of IntRange\IntRange when it lies below or above it (an infinity included), and 00 for NaN.

A value of type Int is always a member of IntRange\IntRange: never a fraction, NaN, an infinity or a negative zero.

E.1.1The Range and Normalisation

Impl.ChoiceConsequences for programs
Elm/JSAn Int is an IEEE 754 double. +, - and * give the exact result rounded to the nearest double: exact while its magnitude is at most 2532^{53}, rounded above that, an infinity beyond the largest double. An integer constant is reduced modulo 2642^{64} into [−263,263)[-2^{63},2^{63}) as two’s complement.No IntRange\IntRange and norm\norm describe Elm/JS: Int results above 2532^{53} in magnitude are inexact, an overflow gives an infinity, and other operations below leave the integers. Programs whose Int results stay within ±253\pm 2^{53} compute exactly.
ecoIntRange\IntRange is [−263,263−1][-2^{63},2^{63}-1], and norm(n)\norm(n) is the mm in IntRange\IntRange with m≡n(mod264)m\equiv n \pmod{2^{64}} (64-bit two’s complement wrap). Integer constants likewise: 0xFFFFFFFFFFFFFFFF denotes −1-1.Conforms. Overflow wraps silently: the greatest Int plus 11 is the least; abs and negate of the least Int give it back.

E.1.2Integer Division and Remainders

Impl.ChoiceConsequences for programs
Elm/JSa // b is the quotient a/ba/b converted to a 32-bit integer (truncation, then reduction modulo 2322^{32} into [−231,231)[-2^{31},2^{31}); NaN and the infinities give 00), so x // 0 is 00. modBy 0 x stops the program with the message “Cannot perform mod 0. Division by zero error.” remainderBy 0 x is NaN, held as an Int.Quotients outside ±231\pm 2^{31} wrap: 5000000000 // 1 is 705032704. modBy 0 ends the program; NaN from remainderBy 0 spreads through later arithmetic (remainderBy 0 7 + 1 is NaN).
ecoTruncated division on 64 bits; x // 0, modBy 0 x and remainderBy 0 x are 00; the least Int // -1 is the least Int.Conforms.

E.1.3Powers with a Negative Exponent

Impl.ChoiceConsequences for programs
Elm/JSThe real power, held as an Int: at Int, 2 ^ -1 is 0.5 and 0 ^ -1 is an infinity.Does not conform: the result is not an integer.
eco00 for every base, 1 and -1 included. For e≥0e\geq 0, the power reduced modulo 2642^{64}, as norm\norm.Does not conform for the bases 11 and −1-1: at Int, 1 ^ -1 is 00, not 11.

E.1.4Conversion from Float

Impl.ChoiceConsequences for programs
Elm/JSround, floor and ceiling of NaN or an infinity give NaN or that infinity, held as an Int. truncate converts to a 32-bit integer (NaN and the infinities give 00).Does not conform: round (0/0) is NaN, and truncate 3e10 is -64771072.
ecoSaturating conversion to 64 bits: NaN gives 00; values above or below IntRange\IntRange, infinities included, give its greatest or least member.Conforms: truncate 3e10 is 30000000000, and round (1/0) and truncate 1e20 are 9223372036854775807.

E.1.5Negative Zero

Impl.ChoiceConsequences for programs
Elm/JSnegate 0, 0 * -1, modBy 4 -4, remainderBy 4 -4, round -0.4 and ceiling -0.5 give a negative zero held as an Int.Does not conform. The sign shows after conversion: 1 / toFloat (negate 0) is -Infinity. Equality does not see it.
ecoInt has one zero.Conforms: 1 / toFloat (negate 0) is Infinity.

In Elm/JS a value of type Int may thus be a fraction, NaN, an infinity or a negative zero, none of which is a member of any IntRange\IntRange; Elm/JS does not conform at the extremes of Int. A program whose exact Int results, quotients and conversions from Float all lie between −231-2^{31} and 231−12^{31}-1, which applies neither modBy 0, remainderBy 0 nor Int ^ with a negative exponent, and which leaves no variable of class number to the default of Float (Section E.6.3), has the same meaning in every implementation listed here, apart from the sign of a zero seen through toFloat.

E.2Characters and Strings

The body requires the following (Chapter 2, Section 6.3 and Section D.4).

  • Char is an abstract class of characters with an injective function toCode into the Int range, under which the character with code point hh has the code hh, for every Unicode scalar value hh; a string is a finite sequence of characters. Char.fromCode n is the character with code point nn when nn is a Unicode scalar value, and otherwise a character of the implementation’s choosing, which has a code like every other.

  • The escape \u{hh} denotes a Unicode scalar value: surrogate code points are excluded.

  • Chars are ordered by toCode; strings are ordered lexicographically by their sequences of characters.

  • The letters of identifiers are classified by the general categories of a version of the Unicode standard chosen by the implementation.

  • Case mapping is outside the initial basis and has no requirement.

E.2.1What a Character Is

Impl.ChoiceConsequences for programs
Elm/JSA Char is a JavaScript string of one code point, one or two UTF-16 code units; case mapping can make it longer. toCode gives its first code point, and NaN for a lone high surrogate. fromCode n gives U+FFFD for n<0n<0 or n>10FFFF16n>\mathrm{10FFFF}_{16}, and passes surrogates through. A string is a sequence of UTF-16 code units. A surrogate escape is accepted.toCode is not injective on the Chars Elm/JS can make: the two-character result of Char.toUpper 'ß' has the code of 'S'. A string holding a lone surrogate makes String.toList run until memory is exhausted.
ecoA Char is one code point in 00 to 10FFFF16\mathrm{10FFFF}_{16}; a surrogate code point is a Char of its own. toCode is the code point; fromCode as Elm/JS. A string is a sequence of UTF-16 code units: a valid surrogate pair is one character, a lone surrogate is one character. A surrogate escape is accepted.toCode is injective. String.fromList (String.toList s) is s for every string.

In both, String.length and string indices count UTF-16 code units, so a character above U+FFFF counts twice: the length of a three-character string whose middle character is U+1F600 is 44.

E.2.2The Order of Characters and Strings

Impl.ChoiceConsequences for programs
Elm/JSChars and strings both by UTF-16 code units.The two orders agree with each other but not with toCode: a character above U+FFFF sorts below the characters U+E000 to U+FFFF. Does not conform.
ecoChars by code point; strings by UTF-16 code units.Char order conforms; string order does not, for strings comparing a character above U+FFFF with one in U+E000 to U+FFFF. Char order and the order of one-character strings then disagree.

E.2.3The Unicode Version of Identifiers

Impl.ChoiceConsequences for programs
Elm/JSThe Unicode tables of the Haskell system that built the compiler.A letter assigned in a later Unicode version than one implementation knows is not a letter there: an identifier using it is accepted by one implementation and rejected by the other.
ecoUnicode 14.0.0.

E.2.4Case Mapping

Impl.ChoiceConsequences for programs
Elm/JSFull case mapping of the host’s Unicode version, with the final sigma rule; toLocaleUpper and toLocaleLower use the host’s locale in a browser.Char.toUpper 'ß' is the two-character "SS", held as a Char. String.toLower lowers a word-final capital sigma to final sigma.
ecoSimple case mapping of Unicode 17.0, one code point to one; no final sigma rule; toLocaleUpper and toLocaleLower are toUpper and toLower.Char.toUpper 'ß' is 'ß'; case mapping keeps the length of a string.

The predicates of the module Char (isUpper, isLower, isAlpha, isDigit, isOctDigit and isHexDigit) are, in both, defined by their elm/core text over ASCII code ranges, and agree.

E.3Floating-Point Operations

The body requires the following of the type Float (Section 6.3 and Section D.4).

  • compare on Floats is a total order: −0-0 and +0+0 are equal, NaN equals NaN and is greater than every other Float.

  • At Float, <, <=, > and >= are the IEEE predicates, false when an operand is NaN; on tuples and lists they are the lexicographic order derived from compare.

  • At Float, min and max are the minimum and maximum of IEEE 754-2019: NaN when either argument is NaN, and −0-0 below +0+0, whatever the order of the arguments. At every other comparable type they give the results of their elm/core definitions.

  • At Float, clamp lo hi x is min (max x lo) hi, with the min and max above: hihi when lo>hilo>hi, NaN when any argument is NaN, and clamp 0 1 -0 is +0+0. At Int it is given by its elm/core definition through < and >: lolo when x<lox<lo, else hihi when x>hix>hi, else xx, so that clamp 10 0 5 is 1010.

  • At Float, +, -, *, /, sqrt and negate are the operations of IEEE 754-2019, correctly rounded, with no latitude in accuracy (Figure 50).

  • The power and the transcendental functions (the trigonometric functions, their inverses, atan2 and the logarithm under logBase) denote the real function rounded to a Float, with special values as IEEE 754-2019 recommends; their accuracy is implementation-dependent.

In both implementations a Float is an IEEE 754 binary64 number, and +, -, *, / and sqrt are the IEEE operations rounding to nearest.

E.3.1compare with NaN

Impl.ChoiceConsequences for programs
Elm/JSLT if a<ba<b, EQ if aa and bb are equal, else GT: any comparison with NaN is GT.Does not conform: compare 1 nan and compare nan 1 are both GT. Sorting, Dict and Set with NaN keys have no defined result.
ecoThe total order of the body.Conforms: compare 1 nan is LT and compare nan nan is EQ; NaNs sort last and are one key of a Dict or Set.

E.3.2The Order Operators

Impl.ChoiceConsequences for programs
Elm/JSThe IEEE predicate when an operand is written as a constant; otherwise derived from compare above.Does not conform: with one = 1, one > nan is True while 1 > nan is False, and nan >= nan is True when neither operand is a constant.
ecoIEEE predicates at Float on every path; on tuples and lists, by compare.Conforms: nan < 1 is False, and [ nan ] > [ 1 ] is True.

E.3.3min, max and clamp

Impl.ChoiceConsequences for programs
Elm/JSThe elm/core definitions, at every type, through the comparison of compare above, which makes any comparison with NaN GT and the two zeros EQ.min and max do not conform at Float when an argument is NaN or both are zeros: the result depends on the order of the arguments. min nan 1 and max 1 nan are 1, where the body gives NaN. clamp conforms at Int; at Float it does not conform when lo>hilo>hi, when an argument is NaN, or with zeros of different signs: clamp 10 0 5 is 10, clamp 0 1 nan is 1, clamp nan 1 0.5 is 0.5 and clamp 0 1 -0 is −0-0, where the body gives +0+0, NaN, NaN and +0+0.
ecoAt Float, IEEE 754-2019 minimum and maximum (NaN in either argument gives NaN; −0<+0-0<+0), and clamp lo hi x is min (max x lo) hi. At every other type, the elm/core definitions.min, max and clamp conform.

E.3.4Special Values and Accuracy

Impl.ChoiceConsequences for programs
Elm/JSThe host’s ECMAScript Math functions, whose accuracy the host chooses. ^ at Float follows ECMAScript: 1 ^ (1/0) is NaN.Does not conform for the special values of ^: IEEE 754-2019 gives 11. logBase 10 1000 is 2.9999999999999996.
eco^ at Float follows C99 Annex F (1 ^ (1/0) is 11); sin and cos are those of the code generator, tan x is computed as sin x / cos x, and the inverse trigonometric functions are those of the C mathematics library.Accuracy is that of the functions named. The special values of ^ conform, but no test of eco checks them.

E.4Equality

The body requires that equality be structural, with IEEE equality at Float; the identity of values plays no part, so a value containing NaN is not equal to itself. When an equality test reaches two functions, its result is an unspecified Bool: APPLY\APPLY gives the set of both Bools (Section 6.5, rule (84) and Section D.4).

E.4.1Identity

Impl.ChoiceConsequences for programs
Elm/JSStructural, but True at once when both operands are the same object. At Float, x == 0 with 0 written as an Int constant tests whether x is zero or NaN.Does not conform: p == p with p = ( nan, 1 ) is True, and nan == 0 is True (nan /= 0 is False).
ecoStructural, but its code gives True at once when both operands are the same object, in the equality kernel and in the inline fast path; whether two occurrences are the same object depends on optimisation. IEEE at Float on every path.Does not conform for values containing NaN: by the code, p == p as above is True, while a separately built ( nan, 1 ) is unequal to p. Two of eco’s tests of known Elm bugs expect False for p == p and for other containers compared with themselves, as the definition gives, but eco’s test harness does not run them.

E.4.2Functions

Impl.ChoiceConsequences for programs
Elm/JSTrue for the same object; otherwise the program stops with the message “Trying to use (==) on functions”.Does not conform: (\x -> x) == (\x -> x + 0) and Just f == Just g end the program.
ecoTrue if the two are the same object, else False, at any depth. A lambda that captures no variable is one object however often it is evaluated; a partial application is a new object each time.Conforms: the result is one member of the set. f == f is True; (\x -> x) == (\x -> x + 0) is False.

E.5Bitwise Operations and String Conversion

The functions of the module Bitwise are outside the initial basis (Chapter C), and so are the conversions String.toInt, String.fromInt and String.fromFloat; the body places no requirement on them. They are recorded here because they reveal the Int range.

E.5.1Bitwise Operations

Impl.ChoiceConsequences for programs
Elm/JS32 bits: operands converted to 32-bit integers, results signed 32-bit, shift counts taken modulo 32; shiftRightZfBy gives an unsigned 32-bit result.shiftLeftBy 32 1 is 1; shiftRightZfBy 0 -1 is 4294967295.
eco64 bits, signed; shift counts taken modulo 64; shiftRightZfBy gives its 64-bit result read as signed.shiftLeftBy 32 1 is 4294967296, shiftLeftBy 63 1 is the least Int, and shiftRightZfBy 0 -1 is -1.

E.5.2Conversion between Numbers and Strings

Impl.ChoiceConsequences for programs
Elm/JSString.toInt reads an optional sign and decimal digits into a double, with no overflow check and no length limit; "-0" gives a negative zero. String.fromInt and String.fromFloat use the host’s printing of numbers.Long numerals give rounded results rather than Nothing. String.fromInt prints 102110^{21} as "1e+21", and an Int holding 0.5 as "0.5".
ecoString.toInt gives Nothing when the numeral is outside IntRange\IntRange or longer than 64 code units, and the exact value otherwise. String.fromInt prints the exact decimal. String.fromFloat prints the shortest digits that read back to the same Float: fixed notation for magnitudes from 10−610^{-6} up to 102110^{21}, exponent notation otherwise, and "0" for −0-0.String.toInt and String.fromInt are exact over IntRange\IntRange.

E.6Evaluation Order and Debug

The body requires the following (Section 6.7, Section 6.5 and Chapter 7).

  • The order in which the parts of a phrase are evaluated carries no meaning; the groups of a let are evaluated in an order consistent with their dependencies, and the order among independent bindings is not specified.

  • Each top-level value is evaluated once, when its module is initialised, in dependency order; an implementation may evaluate it later or repeatedly provided the results agree.

  • Debug.log l v evaluates to vv, and any output it makes is outside the definition; Debug.todo s has no value; Debug.toString gives an implementation-dependent String.

Since evaluation has no other effect, the choices below are observable only through the output of Debug.log, through which of several subexpressions without a value is reached first, and through resources.

E.6.1The Order of Evaluation within a Phrase

Impl.ChoiceConsequences for programs
Elm/JSlet bindings by dependency groups, dependencies first. Record fields by field name; tuple and list components, and the function and arguments of an application, left to right.Conforms.
ecolet bindings by dependency groups, dependencies first; named bindings before bindings _ = e, and not in source order among themselves; a run of bindings _ = e in source order. Record fields of type Int, Float and Char first, then the rest, each by field name. Tuple and list components and arguments in no fixed order. The callback of a basis function such as List.map may be applied in another order when it makes no use of Debug.Conforms. The output of several Debug.log calls in one let may appear in a different order from Elm/JS.

E.6.2Top-level Values

Impl.ChoiceConsequences for programs
Elm/JSEach once, at start-up, before main runs, in dependency order.Conforms. A top-level value whose evaluation reaches Debug.todo stops the program at start-up, used or not.
ecoOn first use. A value of type Int, Float or Char is computed again at each use; a top-level value of function type evaluates its body again at each call; any other value is computed once.Conforms. A Debug.log in a top-level value may print once per use instead of once.

In both, a main in a module other than the main module is evaluated once, and a top-level value needed while it is itself being evaluated, which has no value, ends the program: by exhausting the stack, or, in Elm/JS compiled for debugging, with a report of infinite recursion.

E.6.3Number Specialisation

The body requires the following (Section 4.10 and Section 6.2).

  • A type variable of class number that nothing fixes is Float. An implementation that fixes the types of numbers before the program runs meets this by closing each such variable to Float; nothing more need be evaluated.

  • A declaration whose type scheme quantifies a variable of class number has its default copy, at Float, and a copy for each other type at which a phrase uses it, whether or not that phrase is evaluated. Each copy of a top-level declaration is evaluated when its module is, and each copy of a let declaration when the let is.

A copy that the program does not need, and that has no value, therefore leaves the program without one when it is evaluated with its module, and the definition then requires nothing of an implementation (the beginning of this appendix); evaluated in a step of a running program, such as an application of update, it leaves that step without a result, which a conforming implementation must respect.

Impl.ChoiceConsequences for programs
Elm/JSOne representation for Int and Float, which behaves as Float. A value is evaluated once, with that representation.Conforms, except in a step of a running program where a copy that is not needed has no value: Elm/JS carries on (Section E.10). A computation with a number that nothing fixes gives the value of the default copy.
ecoMonomorphises: a definition is copied only for the types at which the program uses it, and a number variable that nothing fixes is closed to Int. A copy of a top-level value is evaluated on first use (Section E.6); the copies of a let declaration are bindings of the let, evaluated when it is.Does not conform for a number that nothing fixes: 2 ^ -1 == 0 is True, where the definition gives False. Closing such variables to Float instead would conform. Conforms on copies.

On copies, the implementations differ only where a copy that the program does not need has no value. With check h = if h == 0 then Debug.todo "h" else h and x = check (2 ^ -1) used as x + 0.5 and, in a branch that is not taken, as x // 1, the copy of x at Int exists and has no value, since 2 ^ -1 is 00 there:

x isDefinitionElm/JSeco
top-levelthe copy at Int is evaluated with the module: no value, so no meaningruns: x is 0.50.5 once, and x + 0.5 is 11runs: the copy at Int is never used, so never evaluated
bound by a let evaluated with the modulethe copy at Int is evaluated with the let: no value, so no meaningruns, as abovestops at the Debug.todo, as the definition’s evaluation would
bound by a let in updatethe copy at Int is evaluated with the let: the step has no result, and no further message is handledhandles further messages: does not conformstops handling messages: conforms

In the first two rows the program has no meaning, and both implementations conform. Where only the copy at Float is used, no copy at Int is made, and the program has a value in the definition and in both implementations.

E.6.4Debug

Impl.ChoiceConsequences for programs
Elm/JSDebug.log l v writes l: followed by Debug.toString v to the host’s console. Debug.todo s stops the program with “TODO in module … on line …” and s. A program using Debug is rejected when compiled with --optimize.Conforms. A program using Debug cannot be compiled for production.
ecoDebug.log l v writes l: followed by Debug.toString v to the program’s output when it is evaluated. Debug.todo s writes “Debug.todo: ” and s to the error output and ends the process with status 1. Debug is accepted with --optimize, and its output kept.Conforms.

Debug.toString gives the same text in both for the forms tested, such as { age = 3, name = "x" }, Just -1 and 0 for −0-0; for Floats it follows String.fromFloat (Section E.5).

E.7Resource Limits

The body places no bound on the size of a phrase (Section 2.10) or on the resources evaluation uses; an implementation that stops for lack of resources is outside the definition (Section 6.7).

E.7.1The Size of Phrases

Impl.ChoiceConsequences for programs
Elm/JSNo limit.
ecoOn every target, a program is rejected that has a function or lambda with more than 2047 parameters, a lambda whose parameters and captured variables together exceed 2047, a record type or record with more than 2047 fields, a constructor with more than 2040 fields, or a nullary constructor that is not among the first 1024 constructors of its type. For native code the closure limit is checked again after each polymorphic function is copied for every type at which it is used.Programs beyond these limits are rejected. A closure within the limit in the source can exceed it in native code: 700 local polymorphic functions each used at three types inside one lambda make 2100 captured variables.

E.7.2Stack and Memory

Impl.ChoiceConsequences for programs
Elm/JSThe host’s stack and memory. Deep recursion that is not a self tail call stops with a RangeError the host can catch, at about ten thousand frames. A Cmd.batch nested 100000 deep exhausts the stack.Recursion over a long list must be a self tail call, which runs in constant stack.
ecoThe program runs on a stack of 64 MiB. Exhausting it ends the process with a segmentation fault; exhausting memory ends it with the message “eco: out of memory” and an abort. Deeply nested Cmd.batch values are handled without recursion.Far deeper recursion succeeds than in Elm/JS, but its failure cannot be caught. Self tail calls run in constant stack.

E.8Platform and Ports

The body defines tasks, commands, subscriptions and the encoding of values at ports in Chapter 8, and the execution of a program in Section 9.4. It requires only that messages be handled one at a time, each update seeing the model the previous one produced, and the effects of an earlier update being dispatched before those of a later one. It leaves the following unspecified or weakly specified.

  • The order in which the commands of one batch are performed, and the relative order of effects handled by different managers.

  • An incoming port value is an event, handled after the step in progress completes, never during it.

  • Outgoing port values are delivered after the step that produced them, in order per port; what the host does with them is outside the definition.

  • An incoming value that does not match the port’s type is rejected at the boundary; the program is unaffected.

  • Absent flags are the JSON value null.

  • Bytes is a payload type in every position, in ports and in flags, and its values cross the boundary as byte sequences, which are not JSON values; how a host represents a byte sequence is outside the definition (Section 8.7).

  • JSON numbers are finite decimal rationals. A Float that is NaN or an infinity is encoded as null, and −0-0 as the number 00; an incoming number decodes at Int exactly when it is an integer in IntRange\IntRange, an incoming zero being the one Int zero, and at Float as the nearest float, +0+0 for a zero and an infinity for a number beyond the finite floats (Section 8.7).

  • JSON objects are unordered, and error messages are unspecified.

  • A spawned process that fails ends, and nothing else happens; killing a finished process has no effect; the task Process.sleep d waits at least max⁡(0,d)\max(0,d) milliseconds, and for non-finite dd the delay is unspecified.

  • The set of managers, beyond the task manager and ports, is a parameter of the platform.

E.8.1The Order of Commands

Impl.ChoiceConsequences for programs
Elm/JSA manager receives the commands of a batch in reverse order: Cmd.batch [ perform a, perform b ] runs b first, and Cmd.batch [ out 1, out 2 ] delivers 2 then 1. Several subscriptions to one incoming port receive a value last first. Managers are served in the order the program declares them and its ports.Conforms. Programs that depend on these orders, or on the order of port declarations, behave differently in eco.
ecoThe same reverse order within a batch and among subscriptions to one port. Managers are served in no fixed order.Conforms.

E.8.2Incoming Port Values

Impl.ChoiceConsequences for programs
Elm/JSThe host’s send decodes the value and runs update for each current subscription before it returns. A value that does not decode makes send throw “Trying to send an unexpected type of value through port” to the host; the program is unaffected.Does not conform for delivery: a value sent from inside an outgoing subscriber is handled during the step in progress, and a reply can be lost because the subscription for it is not yet installed (elm/core issues 1110, 1141, 1154). Conforms for mismatches.
ecoThe value is checked when the host sends it, then queued, and delivered after the work in progress; a send from inside a subscriber is queued too. A mismatch is reported to the host by an error code and the same message, and the program is unaffected; but when the port’s type cannot be checked at the send, the value is checked on delivery, and a mismatch then ends the process.Conforms for delivery. Does not conform for a mismatch found on delivery.

E.8.3Outgoing Port Values

Impl.ChoiceConsequences for programs
Elm/JSDelivered later: a port waits one timer tick before its first delivery, so that the host can subscribe after the program starts, and after each batch. A value sent when the port has no subscriber is discarded.Conforms.
ecoDelivered at once, during the dispatch of the update that issued it; the program waits while subscribers run. Values are kept until the port’s first subscriber and then handed to it in order; once a port has had a subscriber, a value sent when it has none is discarded.Conforms.

E.8.4Values at the Boundary

Impl.ChoiceConsequences for programs
Elm/JSHost values are JavaScript values. An incoming Int is any finite number with no fractional part. A Json.Encode.Value passes any host value through, functions and undefined included. Objects are written with their keys in field-name order; of several missing fields, the last by name is reported.Outgoing Ints above 2532^{53} are inexact. NaN and the infinities pass as Floats in both directions. Does not conform: an outgoing NaN or infinity is delivered as a host number, where the definition delivers null; an outgoing −0-0 is delivered as −0-0; an incoming −0-0 at an Int port gives a negative zero, and at a Float port −0-0, where the definition gives 00 and +0+0. An incoming NaN or infinity is a host value outside JSON, and outside the definition.
ecoHost values are JSON text, byte sequences apart (Section E.8.5). An incoming Int is an integer, or a float with an integral value, in IntRange\IntRange. An outgoing NaN or infinity is written as null. Keys in field-name order; missing fields are reported in the order of the type’s fields.9223372036854775808 and 1e300 are rejected as Ints. A host value that is not JSON cannot be sent. Conforms for NaN and the infinities.

E.8.5Bytes at the Boundary

The body admits Bytes wherever a payload type may appear, alone or inside tuples, closed records, Maybe, List and Array, in the types of ports and in the flags of main (Section 5.4); its values cross as byte sequences (Section 8.7). This rule follows the implementations that provide binary data at the boundary. Each implementation chooses the host representation of a byte sequence; in the table, eco/JS is eco’s output for JavaScript.

Impl.ChoiceConsequences for programs
Elm/JSNo representation: a port or flags type in which Bytes occurs is rejected.Does not conform: every program with Bytes in a payload or flags type is rejected.
eco/JSBytes in any payload position, in ports and in flags; a byte sequence is a Uint8Array at the host.Conforms.
ecoBytes only as the whole payload of a port, a byte sequence being raw bytes at the host; Bytes inside a payload type, and in flags, is rejected.Does not conform: programs with Bytes nested in a payload type, or in flags, are rejected.

E.8.6Flags

Impl.ChoiceConsequences for programs
Elm/JSAbsent flags are the JavaScript value undefined, which no decoder for null or Maybe accepts. Flags that do not decode make init throw “Problem with the flags given to your Elm program on initialization.”Does not conform: a program with flags of type Maybe Int started without flags does not start.
ecoAbsent flags are null. Flags that do not decode stop an executable with a message and an abort; an embedding host receives an error code and may try again.Conforms: the program above starts with Nothing.

E.8.7Processes

Impl.ChoiceConsequences for programs
Elm/JSA failing spawned process ends silently. Killing a finished or already killed process throws a TypeError. Process.sleep uses the host’s timers: a delay of 00, a negative delay, a non-finite delay or one above 231−12^{31}-1 ms is about 1 ms.Killing twice ends the program (elm/core issue 955): does not conform. A delay above 231−12^{31}-1 ms, about 24.8 days, is cut short: does not conform.
ecoA failing spawned process ends with a warning on the error output. Killing a finished process has no effect. A delay of 00 or less resumes at once; a non-finite delay, or one above 231−12^{31}-1 ms, is 1 ms.The warning is outside the definition: conforms. A delay above 231−12^{31}-1 ms is cut short: does not conform.

In both, a process runs until it waits for a timer, a message or another primitive task, and is never suspended at an andThen alone; this is one of the behaviours the body allows.

E.8.8Managers and Programs on a Platform

Impl.ChoiceConsequences for programs
Elm/JSEvery effect module the program uses is a manager: among them Task, Time, Http, Random, Browser.Events and Browser.AnimationManager. Browser programs run their init and draw their view; a main of type Html msg is drawn once. Several programs may be started on one page.Every command and subscription of these managers is performed.
ecoIn native code the managers are Task, Time, Http, those of eco’s system package, and ports. A command or subscription for any other manager, such as Random.generate or Browser.Events, is discarded. Browser.element, document and application return their record without running init; Browser.Navigation ends the program with status 1; Browser.Dom tasks fail with NotFound. A main of type Html msg is evaluated and not drawn. One program per process.Only worker programs, Platform.worker, run natively. Programs relying on Random or browser managers do nothing observable in those effects.

E.9Extensions of eco

The body admits no flags type beyond the port payload types (Section 5.4); Bytes is one of them, and is not an extension (Section E.8.5). eco accepts the following programs, which are not Standard Elm.

Impl.ChoiceConsequences for programs
Elm/JSNone.
ecoA program of type Program System.Environment model msg, with System.Environment from eco’s system package, has its flags decoded by a built-in decoder, with no check of the payload type.Programs using this extension are eco programs, not Standard Elm, and are rejected by Elm 0.19.1.

E.10Known Divergences

The tables below list every known point on which an implementation does not conform: the implementation (Elm/JS, eco, or both), the construct, what the implementation does, what the definition says, and the ruling that settles the point. Where a ruling chose a meaning neither implementation has, both are listed.

E.10.1Int Arithmetic

Impl.ConstructImplementationDefinitionRuling
Elm/JSInt + - * beyond ±253\pm 2^{53}rounded to a double; an infinity beyond the largest doublenorm\norm of the exact resultA40
Elm/JSinteger constant at or above 2632^{63}reduced modulo 2642^{64}, then held as a doublenorm(n)\norm(n)A9
Elm/JSa // b, quotient outside ±231\pm 2^{31}reduced to 32 bitsnorm\norm of the truncated quotientA41
Elm/JSmodBy 0 xprogram stops00A42
Elm/JSremainderBy 0 xNaN held as an Int00A42
Elm/JSInt b ^ e, e<0e<0a fraction or an infinity11, ±1\pm 1 or 00A43
ecoInt b ^ e, e<0e<0, b=±1b=\pm 10011, or ±1\pm 1 by parityA43
Elm/JSround, floor, ceiling of NaN or an infinityNaN or the infinity held as an Int00, or a bound of IntRange\IntRangeA44
Elm/JStruncate outside ±231\pm 2^{31}reduced to 32 bitssaturated to IntRange\IntRangeA44
Elm/JSnegate 0 and other Int zerosa negative zeroone zeroA45

E.10.2Float, Order and Equality

Impl.ConstructImplementationDefinitionRuling
Elm/JScompare with NaNalways GTtotal order, NaN greatestA46
Elm/JS<, <=, >, >= with NaNdepends on whether an operand is a constantIEEE predicatesA47
Elm/JSFloat min, max with NaN or two zerosdepends on the order of the arguments: min nan 1 and max 1 nan are 1IEEE 754-2019 minimum and maximum: NaN for bothA48
Elm/JSFloat clamp with lo>hilo>hi, a NaN argument, or zeros of different signselm/core definition: clamp 10 0 5 is 10, clamp 0 1 nan is 1, clamp nan 1 0.5 is 0.5, clamp 0 1 -0 is −0-0min (max x lo) hi with IEEE 754-2019 minimum and maximum: +0+0, NaN, NaN, +0+0A47, A48, A49
Elm/JSFloat 1 ^ (1/0)NaN11A65
bothv == v with vv containing NaNTrue when both operands are one objectFalseA50
Elm/JSFloat x == 0, 0 an Int constantTrue for NaNFalse for NaNA50
Elm/JS== reaching two functionsprogram stopsan unspecified BoolA51

E.10.3Characters and Strings

Impl.ConstructImplementationDefinitionRuling
both\u{D800} and other surrogate escapesacceptednot an escape sequenceA8
Elm/JStoCode of a lone surrogate; Chars from case mappingNaN; a Char of two characterstoCode injective into the integersA52
Elm/JSChar orderby UTF-16 code unitsby toCodeA53
bothString orderby UTF-16 code unitslexicographic by characters ordered by toCodeA53

E.10.4Evaluation

Impl.ConstructImplementationDefinitionRuling
Elm/JS(&&) a b, (||) a b applied in prefix form, in a step of a running programsecond argument evaluated only when needed: (&&) False (Debug.todo "x") is False, and further messages are handledordinary strict functions: the step has no result, and no further message is handledA56, A94
Elm/JSlambdas made in a self tail-recursive functionshare the function’s changing parameters: three closures give [3,3,3]each holds the values of its own call: [3,2,1]A63
Elm/JSa let declaration in update whose copy at Int, not needed, has no valueevaluated once, as Float; further messages are handledthe copy at Int is evaluated: the step has no result, and no further message is handledA87, A94
ecoa number variable that nothing fixes, such as that of 2 ^ -1 == 0Int: TrueFloat: False, as Elm/JS givesA27

E.10.5Programs and Ports

Impl.ConstructImplementationDefinitionRuling
Elm/JSincoming port valueupdate runs inside the host’s sendan event handled after the step in progressA68
ecoincoming value not matching the port, found on deliverythe process endsrejected at the boundary; program unaffectedA71
Elm/JSabsent flagsundefined: Maybe flags rejectednullA72
Elm/JSoutgoing Float NaN or infinitypassed as a host numbernullA88
Elm/JS−0-0 across a portpassed as −0-0; an incoming −0-0 at Int is a negative zerothe number 00; 00 at Int, +0+0 at FloatA88
Elm/JSProcess.kill of a finished processprogram stopsno effectA80
bothProcess.sleep d, d>231−1d>2^{31}-1about 1 msat least dd msA81
botha main of unsupported type outside the main modulerejectedan ordinary valueA32, A82
bothtwo ports of one name, or a port named after a manageraccepted; the program stops at start-uprejected by elaborationA84
Elm/JSBytes in a port or flags typerejecteda payload type, crossing as a byte sequenceA92
ecoBytes inside a payload type, or in flags, native coderejecteda payload type, crossing as a byte sequenceA92

E.10.6Elaboration

Impl.ConstructImplementationDefinitionRuling
botha pattern ( ) with a gapaccepted as unitnot a phraseA1
botha rigid type variable escaping its annotationthe compiler fails with an internal errordoes not elaborateA20
ecoa record extended through a row variable by a field it already hasaccepted, the outer field winningdoes not elaborateA23
Elm/JSunannotated mutually recursive values used at several typesaccepted; some such programs fail at run timeeach member monomorphic within its groupA24
ecotwo literal patterns that denote one value, spelt differentlysecond not reported redundantrejected as redundantA31
ecoa constrained type variable as a row variable, { number | x : Int }annotation accepted; every use failsill formedA36
ecopolymorphic recursion through annotated functions, native coderejectedelaboratesA39
ecoa closure over 2047 variables after copying polymorphic functions, native coderejectedelaboratesA39
ecophrases beyond the size limits of Section E.7rejectedelaborateA13, A34
bothimport modid\mv{modid} as Basics for a module other than Basicsaccepted (not tested)does not elaborateA91

Discussions

Discuss this chapter·Search the discussions on GitHub

Discussions are on GitHub; one about this chapter has [ch:appendix-implementation] in its title.

A Standard Definition of Elm? (Draft version 0.4) © Rupert Smith. The text is licensed under CC BY 4.0: share and adapt it freely, with credit and a link to the licence.