ECMA-262 in Lean

Reading page · generated from lean/Ecma/Host.lean, lean/Ecma/Host/Laws/

The host and its laws

What the specification leaves to the host, and the 72 laws it requires of one, by topic. Each law names its clause, quotes the sentence that governs it, and says how the Lean reads it (4 law has no single sentence and says why). scripts/law_quotes.py checks every quotation against the pinned spec.html.

The host

From lean/Ecma/Host.lean

What the specification leaves to the host (Host): the host-defined and implementation-defined operations, by clause, and its choices at the points the specification names, by primitive. Every call of the host is logged (Run.hostStep): the host reads the state and the log, and only the machine appends to the log. The laws a host must meet are Ecma.Host.Laws.

structure

Host

Host.lean:24

The host: the operations the specification leaves to it (host-defined and implementation-defined operations, by clause), and its choices at the points the specification names (implementation-approximated values, implementation-defined choices, whether it is a web browser), by primitive, and its choice of integers.

structure Host (M : Model) where
hook : ClauseId → List (Val M) → Run M (Val M)
choice : PrimId → List (Val M) → Run M (Val M)

the next job to run (§9.5): the log position of the call that scheduled it, or none

nextJob : Run M (Option Nat) := Run.stop .residue

the jobs the host may take in this state, by their scheduling's log position: the surrounding agent's, ready now

owns : State M → Nat → Bool := fun _ _ => true

the milliseconds elapsed by the host's own clock as it takes its next job in this state; unlike TimeNow's time value it never goes back (Host.WF.elapsedMono)

elapsed : State M → M.Math := fun _ => M.ofNat 0

the host-defined preparation steps of a job, by that position

prepareJob : Nat → Run M Unit := fun _ => Run.stop .residue

the host-defined cleanup steps of a job, by that position

cleanupJob : Nat → Run M Unit := fun _ => Run.stop .residue

what the host does when the agent has no Job to run (§9.5 leaves the scheduling to the host, §9.7 the other agents of the cluster): an algorithm of its own to run as one, its preparation done, after which the agent's Jobs go on unless it answers empty; or none, and the agent's Jobs are done

idle : Run M (Option AlgId) := pure none

a Job of the host's own that the agent runs before its next queued one (§9.6: its scripts and modules): an algorithm of the host's and its arguments, its preparation done; or none

first : Run M (Option (AlgId × List (Val M))) := pure none

the host-defined cleanup steps after first's or idle's algorithm, given what it returned: none where the agent's Jobs are done; else whether it ran ECMAScript code, so that ClearKeptObjects and the host's collection follow as after a Job (§9.10)

idleEnd : Val M → Run M (Option Bool) := fun _ => pure none

whether the host performs ClearKeptObjects (§9.10) now, a synchronous run of ECMAScript code having ended (§9.9.1 leaves its scheduling to the host)

clearsKept : Run M Bool := Run.stop .residue

the objects and symbols the host collects at a job boundary (§9.10.3), having emptied their WeakRefs and cells (Host.WF.collect); none by default

collect : Run M (List (Val M)) := pure []

whether the host's resources run out at pushing an execution context in this state

exhausts : State M → Bool := fun _ => false

whether the host's resources run out at allocating an object (MakeBasicObject) in this state

exhaustsHeap : State M → Bool := fun _ => false
def

State.hostView

Host.lean:63

The state as the host reads it: the machine's bookkeeping of the running computation (the Parse Nodes whose SDOs are running, the built-in calls' arguments) empty.

def State.hostView (s : State M) : State M := { s with evalNodes := [], passed := [] }
structure

Books

Host.lean:66

A state's bookkeeping (State.hostView's) and host-call log.

structure Books (M : Model) where
def

State.books

Host.lean:72

s's bookkeeping and host-call log.

def State.books (s : State M) : Books M :=  { evalNodes := s.evalNodes, passed := s.passed, hostLog := s.hostLog }
def

State.restoreBooks

Host.lean:76

t with the bookkeeping and host-call log pre.

def State.restoreBooks (t : State M) (pre : Books M) : State M :=  { t with evalNodes := pre.evalNodes, passed := pre.passed, hostLog := pre.hostLog }
def

Res.hostStep

Host.lean:83

A host step's result over the books before it, pre: the host's writes to the log and the bookkeeping are dropped; an answer a adds the entry e a; a resumed step is run on the view of the state it is resumed with, over that state's books; a call runs on the step's state, and the same step goes on after it.

def Res.hostStep {α : Type} (pre : Books M) (e : α → HostCall M) : Res M α → Res M α  | .ok a s => .ok a { s.restoreBooks pre with hostLog := e a :: pre.hostLog }  | .esc c s => .esc c (s.restoreBooks pre)  | .stop r => .stop r
def

Run.hostStep

Host.lean:90

A host step, logged: the host reads the state's view (State.hostView) and the log, and only the machine appends to the log. The books are read first, so the host has the state's only reference.

def Run.hostStep {α : Type} (e : α → HostCall M) (m : Run M α) : Run M α := fun s =>  Res.hostStep s.books e (m s.hostView)
def

activeScriptOrModule

Host.lean:95

The active script or module (§9.4.1): the ScriptOrModule of the topmost execution context that has a non-null one, else null.

def activeScriptOrModule (s : State M) : Val M :=  M.seqFoldl (fun r ctx => match ctx with    | .ref a => match M.heapGet s.heap a with      | some (.record _ fs) => match M.recGet fs Known.fScriptOrModule with        | some .null | none => r        | some v => v      | _ => r    | _ => r) .null s.stack
def

ctxRealm

Host.lean:105

The Realm component of the execution context ctx where it is an address, else null.

def ctxRealm (s : State M) : Val M → Val M  | .ref a => match M.heapGet s.heap a with    | some (.record _ fs) => match M.recGet fs Known.fRealm with      | some (.ref r) => .ref r      | _ => .null    | _ => .null  | _ => .null
def

runningRealm

Host.lean:114

The running execution context's Realm (§9.4): the topmost execution context's, by ctxRealm.

def runningRealm (s : State M) : Val M := ctxRealm s (M.seqFoldl (fun _ ctx => ctx) .null s.stack)
def

Host.hookL

Host.lean:118

A host-defined operation, logged with the active script or module and the running Realm at the call; an escaping completion is its answer (the algorithm boundary).

def Host.hookL (H : Host M) (c : ClauseId) (xs : List (Val M)) : Run M (Val M) := fun s =>  Run.hostStep (.hook c xs (activeScriptOrModule s) (runningRealm s)) (Run.boundary (H.hook c xs)) s
def

Host.choiceL

Host.lean:122

A host choice, logged; an escaping completion is its answer.

def Host.choiceL (H : Host M) (q : PrimId) (xs : List (Val M)) : Run M (Val M) :=  Run.hostStep (.choice q xs) (Run.boundary (H.choice q xs))
def

Host.supports

Host.lean:126

Whether the host supports the Annex B section whose clause is c? (hostSupports, asked of H).

def Host.supports (H : Host M) : Option ClauseId → Run M Bool  | some c => do bool (← H.choiceL Known.pWebBrowser [.choice 0, .clause c])  | none => return false
def

Host.allocL

Host.lean:132

A Model primitive, an implementation limit at allocating an object when the host's resources run out (exhaustsHeap, read on the host's view of the state).

def Host.allocL (H : Host M) (q : PrimId) (xs : List (Val M)) : Run M (Val M) := fun s =>  if q == Known.pMakeObject && H.exhaustsHeap s.hostView then .stop .implLimit else prim q xs s
def

hostPrim

Host.lean:136

A primitive the host decides.

Lean, 18 lines
def hostPrim (p : PrimId) : Bool :=  Known.pApprox ≤ p && p ≤ Known.pWebBrowser || p == Known.pNaNEncoding || p == Known.pApproxInteger    || p == Known.pHostInitializeBuiltinContext || p == Known.pHostReportErrors    || p == Known.pDiscardContextResources || p == Known.pSpinWaitHint    || Known.pAdditionalTimeout ≤ p && p ≤ Known.pTimeNow    || p == Known.pParseDateString || p == Known.pCanAllocate    || Known.pDebuggerEnabled ≤ p && p ≤ Known.pNativeFunctionSource    || p == Known.pEscapePattern    || Known.pHasTimeZoneRules ≤ p && p ≤ Known.pLastTransitionBefore    || Known.pHostGlobalObject ≤ p && p ≤ Known.pMayCleanup || p == Known.pSortStep || p == Known.pForInStep    || p == Known.pPropertyOrder || p == Known.pOmitSharedArrayBuffer || p == Known.pHostSupportsOptional    || Known.pLocaleUppercase ≤ p && p ≤ Known.pLocaleNumberString || p == Known.pLocaleDateString    || p == Known.pSuspendAgentUntil    || p == Known.pExpandedYearForm || p == Known.pHostExtendIntrinsics || p == Known.pHostExtendObject    || Known.pHostJobCallbackData ≤ p && p ≤ Known.pHostCleanupCallJobCallback    || Known.pHostSelectAgent ≤ p && p ≤ Known.pAgentWoken || p == Known.pWakeAgent || p == Known.pChooseReadsBytesFrom    || Known.pAgentNextJob ≤ p && p ≤ Known.pAgentCleanupJob    || p == Known.pApproxPower || p == Known.pBigIntTooLarge || p == Known.pStringTooLarge
def

builtinBind

Host.lean:159

§18: a built-in function's parameters bound to the arguments args by its header: those before a rest parameter from the front, those after it from the end of the arguments past the front ones, the rest parameter's List the middle; a parameter without an argument is not present (.missing), extra arguments without a rest parameter are dropped.

def builtinBind (h : Header) (args : List (Val M)) : List (Slot × Val M) × Option (Slot × List (Val M)) :=  let fill (ps : List Param) (vs : List (Val M)) := ps.zipIdx.map fun (p, i) => (p.x, vs.getD i .missing)  let front := h.params.takeWhile (!·.rest)  match h.params.drop front.length with  | [] => (fill front args, none)  | r :: back =>    let mid := args.drop front.length    let k := mid.length - min back.length mid.length    (fill front args ++ fill back (mid.drop k), some (r.x, mid.take k))

The laws of a host

From lean/Ecma/Host/Laws.lean

What the specification requires of the host, stated over a Host and never assumed: a law constrains what one call of the host gives, given the state and the host-call log (State.hostLog) before it. The machine owns the log: a host reads it, and a host step adds only its own entry. Each law is a field of the structure of its topic (Ecma/Host/Laws/), and its docstring says the clause of the specification it reads, quotes the sentence that governs it, and gives its reading (scripts/law_quotes.py checks the quotations against spec.html).

structure

Host.WF

Laws.lean:29

The laws of a host: those of every topic.

Proved of the engine's host under every option set: Engine.SpecHost.wfBy, which is Implements.host.

structure Host.WF {M : Model} (H : Host M) : Prop extends    H.JobLaws, H.TimeLaws, H.MemoryLaws, H.RegExpLaws, H.OrderLaws, H.LocaleLaws, H.OptionalLaws, H.ValueLaws,    H.HookLaws, H.ChangeLaws

All 72 laws

Each law is a field of the structure of its topic, and Host.WF is all of them. Two read their sentence more strictly than it is written, and are for the list of proposed normative changes; two more weakly:

  • escapePattern stricter requires \/ and the line terminators' escapes, where the text also allows /.
  • nativeFunctionSource stricter one form, function name() { [native code] }, where the text allows any NativeFunction.
  • collect weaker liveness's second condition, about future executions, is left out.
  • agentNextJob weaker there is no law about a timeout.
LawTopicClauseReading
nextJobJob9.5 Jobs and Host Operations to Enqueue JobsThe job the host takes next is one it may take now (Host.mayRun), each taken once.
agentNextJob
weaker
Job9.5 Jobs and Host Operations to Enqueue JobsAgentNextJob answers empty or a job it may take now (Host.mayRun), the state as it was.
ownsAgentJob9.5 Jobs and Host Operations to Enqueue JobsWith more than one agent in the cluster, a job the host may take is the surrounding agent's.
ownsSingleJob9.5 Jobs and Host Operations to Enqueue JobsWith one agent in the cluster, the host may take every scheduled job, so that none is left when its Jobs are done (drained).
promiseJobPreparedJob9.5.5 HostEnqueuePromiseJobThe host's preparation of a promise job whose realm is not null does both (promisePrepared).
agentPrepareJobJob9.5 Jobs and Host Operations to Enqueue JobsAgentPrepareJob(k) answers the job scheduled at k, prepared as promisePrepared says.
jobCleanupJob9.5 Jobs and Host Operations to Enqueue JobsAfter a job's cleanup the execution context stack is empty.
agentCleanupJobJob9.5 Jobs and Host Operations to Enqueue JobsAgentCleanupJob answers unused and leaves the agent's execution context stack empty.
jobCallbackDefaultJob9.5.2 HostMakeJobCallbackWhere the host answers that it is not a web browser, HostJobCallbackData answers empty and the steps around the callback's call unused, the state as it was.
callJobCallbackJob9.5.3 HostCallJobCallbackThe host's steps before and after the call answer unused, so the call's result is returned.
selectAgentJob9.8 Forward ProgressHostSelectAgent answers empty or another Agent Record of the cluster that can run (canRunAgent), the state as it was.
timeNowTime21.4.3.1 Date.nowTimeNow answers a time value identifying an instant (instantTimeValue), the state as it was.
elapsedMonoTimeNo sentenceAs the host takes its next job, its clock reads no less than any elapsed time logged.
timeoutAfterTime9.5.6 HostEnqueueTimeoutJobAs the host takes a timeout job, its clock reads at least milliseconds past the elapsed time logged before the call that scheduled it.
additionalTimeoutTime25.4.3.14 DoWaitAdditionalTimeout answers a non-negative mathematical value, the state as it was.
timeZoneNameSuffixTime21.4.4.41.3 TimeZoneStringTimeZoneNameSuffix answers "" or " (" name ")", the state as it was.
systemTimeZoneStringTime21.4.1.24 SystemTimeZoneIdentifierSystemTimeZoneString answers "UTC", an available named time zone identifier whose IsNonPrimaryTimeZoneId is false, or a String UTCOffset matches (utcOffsetNs), the state as it was.
primaryTimeZoneIdTime21.4.1.23 AvailableNamedTimeZoneIdentifiersPrimaryTimeZoneId answers "UTC" or an available named time zone identifier whose IsNonPrimaryTimeZoneId is false, the state as it was.
supportsOnlyUTCTime21.4.1.24 SystemTimeZoneIdentifierSupportsOnlyUTC answers a Boolean, the state as it was.
parseDateStringTime21.4.3.2 Date.parseParseDateString answers NaN or a time value (instantTimeValue), never -0𝔽, the state as it was.
dateFormUTCTime21.4.3.2 Date.parseA valid String of the format that is no local time gives the time value of its fields less its offset, NaN out of a time value's range (sec-expanded-years).
dateFormLocalTime21.4.3.2 Date.parseA valid date-time form without an offset gives UTC of its fields (sec-utc-t): the fields themselves where the system time zone is "UTC", less the offset where it is an offset time zone.
dateFormIllegalTime21.4.3.2 Date.parseA String of the format's shape with an out-of-bounds element gives NaN.
expandedYearFormTime21.4.4.36 Date.prototype.toISOStringExpandedYearForm, whether a year from 0 to 9999 is written as an expanded year, answers a Boolean, the state as it was.
nanEncodingMemory25.1.3.17 NumericToRawBytesFor a NaN and a format with a trailing significand field (2 ≤ p), NaNEncoding answers one NaN bit pattern of the format in every state, the state as it was.
canAllocateMemory6.2.9.1 CreateByteDataBlockCanAllocate, whether such a Data Block can be created, answers a Boolean, the state as it was.
resizeArrayBufferMemory25.1.3.8 HostResizeArrayBufferbuffer's [[ArrayBufferData]] does not become null; on handled its [[ArrayBufferByteLength]] is newByteLength.
omitSharedArrayBufferMemory25.2.3 The SharedArrayBuffer ConstructorOmitSharedArrayBuffer is one Boolean in every state, the state as it was.
spinWaitHintMemory25.4.12 Atomics.pauseSpinWaitHint answers unused, the state as it was.
chooseReadsBytesFromMemory25.1.3.15 GetRawBytesFromSharedBlockChooseReadsBytesFrom(execution, eventsRecord, block, byteIndex, elementSize) answers a new List of elementSize events of execution, the one at index i a write event on block whose memory range contains byteIndex + i; the state as it was but for the new List.
chooseReadsValidMemory29.7.5 Valid ExecutionsWhere execution is a valid execution whose memory order agrees with the interleaving order and whose Shared Data Block events are formed, it stays one with the read appended to eventsRecord, reading the chosen events.
escapePattern
stricter
RegExp22.2.6.13.1 EscapeRegExpPatternEscapePattern answers a String S, the same for the same pattern and flags at every call, the state as it was: pattern with each / kept or written \/ and each LineTerminator written as its escape, the empty pattern as (?:) (EscapeOf), which as far as / and LineTerminators go can be a RegularExpressionBody (BodySafe). That S "must behave identically" is the specification's claim about its own semantics, no law: it was proved of this engine's escape at the git tag escape-sim-proved.
sortStepOrder23.1.3.30.1 SortIndexedPropertiesAt the host's state and the last result a sort of n elements reaches by the calls h, SortStep asks for a call on two indices less than n, or answers a permutation that, for every consistent comparator giving every result in h, meets its conditions; otherwise the order is the host's.
sortStepEndsOrder23.1.3.30.1 SortIndexedPropertiesThe sequence is finite: a sort makes finitely many calls, whatever their results.
forInStepOrder14.7.5.9 EnumerateObjectPropertiesAfter a history that obeyed the rules (ForInRun), ForInStep answers an action that obeys them (ForInRules); and CreateForInIterator(obj)'s next action where no object of the chain is exotic, none changed shape since the enumeration began (State.shapeLog), and every action so far was its.
propertyOrderOrder9.3.2 CreateIntrinsicsPropertyOrder, the order an intrinsic's properties are created in, answers a new List of the given properties, each once.
listSeparatorLocale23.1.3.32.1 LocalizedListSeparatorLocalizedListSeparator answers a String, the state as it was.
localeCaseLocale22.1.3.26 String.prototype.toLocaleLowerCaseLocaleLowercase and LocaleUppercase answer a new List of code points.
localeCompareLocale22.1.3.12 String.prototype.localeCompareBy one total preorder of all Strings, LocaleCompare answers a negative, positive or zero Number, never NaN, and +0𝔽 for canonically equivalent Strings, the state as it was.
localeNumberStringLocale21.1.3.4 Number.prototype.toLocaleStringLocaleNumberString answers a String, or empty for toString's, the state as it was.
localeDateStringLocale21.4.4.38 Date.prototype.toLocaleDateStringLocaleDateString answers a String, or empty for the form without a locale, for an object with a [[DateValue]] slot, and a String or throw (a TypeError) for any other value, the state as it was.
webBrowserOptionalB Additional ECMAScript Features for Web BrowsersWebBrowser, whether the host is a web browser or otherwise supports the feature its arguments name, is one Boolean for the same arguments in every state, the state as it was.
webBrowserSupportsOptionalB Additional ECMAScript Features for Web BrowsersWhere the host is a web browser, it is a web browser or otherwise supports every clause c.
debuggerEnabledOptional14.16.1 Runtime Semantics: EvaluationDebuggerEnabled answers a Boolean, the state as it was.
debuggerActionOptional14.16.1 Runtime Semantics: EvaluationDebuggerAction answers unused; what it may change is invariantsKept's.
nativeFunctionSource
stricter
Optional20.2.3.5 Function.prototype.toStringNativeFunctionSource answers function , a name nativeName admits and () { [native code] }, the name func.[[InitialName]] where that is a String, the state as it was.
approxValue21.3.2.9 Math.cbrtApprox answers a Number, the state as it was.
approxPowerValue6.1.6.1.3 Number::exponentiateApproxPower(base, exponent) answers a Number, the state as it was.
approxIntegerValue19.2.5 parseIntApproxInteger answers an integer, the state as it was.
bigIntTooLargeValueNo sentenceBigIntTooLarge answers a Boolean, the state as it was.
stringTooLargeValueNo sentenceStringTooLarge answers a Boolean, the state as it was.
hostChoiceValue7.1.4.1.3 RoundMVResultHostChoice answers one of its arguments, the state as it was.
mathRandomValue21.3.2.28 Math.randomMath.random answers such a Number (unitNum), never an abrupt completion, the state as it was.
hookCompletionHook4.2 Hosts and ImplementationsA host hook's answer is no break, continue or return completion (a value that is no Completion Record is a normal completion's).
privateElementSameKindHook7.3.29 HostEnsureCanAddPrivateElementThe [[Type]] of HostEnsureCanAddPrivateElement's answer is one function of its argument, whatever the state of the call.
supportedImportAttributesHook16.2.1.12.1 HostGetSupportedImportAttributesEvery call answers a List of the same Strings in the same order (the default's new empty List at each call conforms, so "the same List" is its contents).
getCodeForEvalHook19.2.1.3 HostGetCodeForEvalHostGetCodeForEval answers a String or no-code.
hasSourceTextAvailableHook20.2.5 HostHasSourceTextAvailableHostHasSourceTextAvailable's answer is one function of its argument, whatever the state of the call.
invariantsKeptChange6.1.7.3 Invariants of the Essential Internal MethodsAcross a host step every object is still an object and keeps to the invariants (objKept).
agentFixedChange9.6 AgentsA host step keeps the surrounding agent, its Agent Record's sort and those fields (agentKept).
hostGlobalObjectChange9.3.1 InitializeHostDefinedRealmHostGlobalObject answers empty (the state as it was) or an Object.
hostThisValueChange9.3.1 InitializeHostDefinedRealmHostThisValue answers empty (the state as it was) or an Object.
hostGlobalPropertiesChange9.3.1 InitializeHostDefinedRealmHostGlobalProperties answers unused and changes only global's own properties (onlyPropsOf).
hostExtendIntrinsicsChange2 ConformanceHostExtendIntrinsics(realm) answers unused and only adds own properties to realm's intrinsics (intrinsicOf), none to an object whose [[Extensible]] is not true, and no "caller" or "arguments" to a function.
hostExtendObjectChange2 ConformanceHostExtendObject(o) answers unused and only adds own properties to o, none if its [[Extensible]] is not true, and no "caller" or "arguments" to a function.
hostInitializeBuiltinContextChange10.3.3 BuiltinCallOrConstructHostInitializeBuiltinContext answers unused and changes only calleeContext, which keeps its kind and every component the execution context tables define (contextField).
hostReportCleanupErrorChange9.9.4.1 HostEnqueueFinalizationRegistryCleanupJobHostReportCleanupError answers unused.
hostReportErrorsChangeNo sentenceHostReportErrors answers unused.
mayCleanupChange9.12 CleanupFinalizationRegistryMayCleanup answers empty or such a cell (emptyCell), the state as it was.
discardContextResourcesChange15.10.3 PrepareForTailCallDiscardContextResources answers unused, the state as it was.
contextResourcesChange15.10.3 PrepareForTailCallThe host's resources run out at a push onto the execution context stack (Host.exhausts) only while some context on it holds resources no DiscardContextResources discarded (liveContexts).
collect
weaker
Change9.9.3 ExecutionThe host's collection empties, together, the WeakRefs, FinalizationRegistry cells, WeakMap entries and WeakSet elements of a set of objects and Symbols none of which is kept alive, and changes nothing else (Collected); a host that collects nothing meets it.

The laws of jobs and agents

From lean/Ecma/Host/Laws/Jobs.lean

Which job the host takes next, its preparation and cleanup, the job callbacks, and which agent runs (sec-jobs, sec-agents, sec-forward-progress). A job is named by the log position of the call that scheduled it. The host takes jobs through two interfaces, Host.nextJob/prepareJob/cleanupJob for the surrounding agent and the choices AgentNextJob, AgentPrepareJob and AgentCleanupJob for an agent of a cluster; one set of requirements (Host.mayRun, promisePrepared) governs both.

def

wakeFinite

Jobs.lean:20

Whether SuspendAgentUntil's timeout wakes within maxTime.

def wakeFinite {M : Model} : List (Val M) → Bool  | [_, .math t] => !M.lt (M.ofNat maxTime) t  | _ => false
def

pendingFinite

Jobs.lean:26

The agent x's pending suspension in a log with agents: whether its wake time is finite (wakeFinite), or none if it is not suspended or a newer WakeAgent woke its signifier sig.

def pendingFinite {M : Model} (x sig : Val M) : List (HostCall M × Val M) → Option Bool  | [] => none  | (.choice q vs _, a) :: es =>    if q == Known.pWakeAgent && vs.any (Val.same sig) then none    else if q == Known.pSuspendAgentUntil && Val.same a x then some (wakeFinite vs)    else pendingFinite x sig es  | _ :: es => pendingFinite x sig es
def

hasScheduledJob

Jobs.lean:35

Whether the agent x has a job scheduled in the log that has not been taken.

def hasScheduledJob {M : Model} (s : State M) (x : Val M) : Bool :=  let ags := jobAgents s  (s.hostLog.reverse.zipIdx).any fun (e, k) =>    e.schedulesJob && ags[k]?.any (Val.same (sigOf s x)) && !s.hostLog.any (·.takes k)
def

canRunAgent

Jobs.lean:42

Whether the agent x can run: it is not suspended with an infinite timeout, or it waits for a message or a job (idleWait) and has a scheduled job (hasScheduledJob).

def canRunAgent {M : Model} (s : State M) (x : Val M) : Bool :=  (pendingFinite x (sigOf s x) (withAgents s.agent s.hostLog)).getD true ||    idleWait s x && hasScheduledJob s x
def

HostCall.callOf

Jobs.lean:49

A logged call is one of the host-defined operation with that sec-id.

def HostCall.callOf (sec : String) : HostCall M → Bool  | .hook c _ _ _ _ => Gen.clauses[c]? == some sec  | _ => false
def

calledAt

Jobs.lean:54

The call at log position k (counted from the first) is one of the host-defined operation sec.

def calledAt (log : List (HostCall M)) (sec : String) (k : Nat) : Prop :=  log.reverse[k]?.any (·.callOf sec) = true
def

taken

Jobs.lean:58

The job scheduled at log position k has been taken to run.

def taken (log : List (HostCall M)) (k : Nat) : Prop := log.any (·.takes k) = true
def

jobHooks

Jobs.lean:62
def jobHooks : List String :=  ["sec-hostenqueuegenericjob", "sec-hostenqueuepromisejob", "sec-hostenqueuetimeoutjob",    "sec-host-cleanup-finalization-registry"]
def

Host.mayRun

Jobs.lean:69

The job scheduled at log position k may be taken now: a HostEnqueue…Job call scheduled it, it has not been taken, the host may take it (Host.owns), and a promise job only after every earlier-scheduled promise job the host may take.

def Host.mayRun (H : Host M) (s : State M) (k : Nat) : Prop :=  (∃ sec ∈ jobHooks, calledAt s.hostLog sec k) ∧ ¬taken s.hostLog k ∧ H.owns s k = true ∧    (calledAt s.hostLog "sec-hostenqueuepromisejob" k →      ∀ i < k, calledAt s.hostLog "sec-hostenqueuepromisejob" i → H.owns s i = true → taken s.hostLog i)
def

preparedToEvaluate

Jobs.lean:76

An execution is prepared to evaluate ECMAScript code (sec-jobs): the execution context stack is not empty, and the Realm component of its topmost execution context is a Realm Record.

def preparedToEvaluate (s : State M) : Prop :=  M.eq (M.seqLen s.stack) (M.ofNat 0) = false ∧    ∃ pre top r, stackList s = pre ++ [top] ∧ fieldOf s Known.fRealm top = some r ∧      isRecordOf s "Realm Record" r = true
def

activeIs

Jobs.lean:84

sm is the active script or module (sec-jobs): GetActiveScriptOrModule() is sm, and if sm is a Script Record or Module Record, the Realm component of the topmost execution context whose ScriptOrModule component is sm is sm.[[Realm]].

def activeIs (s : State M) (sm : Val M) : Prop :=  activeScriptOrModule s = sm ∧    (isRecordOf s "Script Record" sm = true ∨ isRecordOf s "Module Record" sm = true →      ∃ pre ec post, stackList s = pre ++ ec :: post ∧ fieldOf s Known.fScriptOrModule ec = some sm ∧        (∀ c ∈ post, fieldOf s Known.fScriptOrModule c ≠ some sm) ∧        ∃ r, fieldOf s Known.fRealm ec = some r ∧ fieldOf s Known.fRealm sm = some r)
def

promisePrepared

Jobs.lean:94

After the preparation of the job scheduled at log position k, from s to s': where a HostEnqueuePromiseJob call whose realm is not null scheduled it, execution is prepared to evaluate ECMAScript code, and the script or module active at that call is active.

def promisePrepared (s : State M) (k : Nat) (s' : State M) : Prop :=  ∀ c job realm xs sm rl r, s.hostLog.reverse[k]? = some (.hook c (job :: realm :: xs) sm rl r) →    Gen.clauses[c]? = some "sec-hostenqueuepromisejob" → realm ≠ .null → preparedToEvaluate s' ∧ activeIs s' sm
structure

Host.JobLaws

Jobs.lean:99

The laws of jobs and agents.

Proved as part of Host.WF.

structure Host.JobLaws (H : Host M) : Prop where

11 laws

9.5 Jobs and Host Operations to Enqueue Jobs the requirements' first item sec-jobs

At some future point in time, when there is no running context in the agent for which the job is scheduled and that agent's execution context stack is empty, the implementation must: … Invoke the Job Abstract Closure.

9.5.5 HostEnqueuePromiseJob sec-hostenqueuepromisejob

Jobs must run in the same order as the HostEnqueuePromiseJob invocations that scheduled them.

The job the host takes next is one it may take now (Host.mayRun), each taken once.

nextJob
Lean
nextJob : ∀ s k s', H.nextJob s = .ok (some k) s' → H.mayRun s k
9.5 Jobs and Host Operations to Enqueue Jobs the requirements' first item, in an agent of a cluster sec-jobs

At some future point in time, when there is no running context in the agent for which the job is scheduled and that agent's execution context stack is empty, the implementation must: … Invoke the Job Abstract Closure.

AgentNextJob answers empty or a job it may take now (Host.mayRun), the state as it was.

agentNextJob
Lean
agentNextJob : H.asks Known.pAgentNextJob fun _ s r =>  r = .enum Known.eEmpty ∨ ∃ k, r = .math (M.ofNat k) ∧ H.mayRun s k
9.5 Jobs and Host Operations to Enqueue Jobs the requirements' first item sec-jobs

in the agent for which the job is scheduled

With more than one agent in the cluster, a job the host may take is the surrounding agent's.

ownsAgent
Lean
ownsAgent : ∀ s k, H.owns s k = true → (clusterSigs s).length ≤ 1 ∨  (jobAgents s)[k]?.any (Val.same (sigOf s s.agent)) = true
9.5 Jobs and Host Operations to Enqueue Jobs the requirements' first item sec-jobs

At some future point in time, when there is no running context in the agent for which the job is scheduled and that agent's execution context stack is empty, the implementation must:

With one agent in the cluster, the host may take every scheduled job, so that none is left when its Jobs are done (drained).

ownsSingle
Lean
ownsSingle : ∀ s k, (clusterSigs s).length ≤ 1 → (∃ sec ∈ jobHooks, calledAt s.hostLog sec k) →  H.owns s k = true
9.5.5 HostEnqueuePromiseJob the requirements sec-hostenqueuepromisejob

If realm is not null, each time job is invoked the implementation must perform implementation-defined steps such that execution is prepared to evaluate ECMAScript code at the time of job's invocation.

If realm is not null, each time job is invoked the implementation must perform implementation-defined steps such that scriptOrModule is the active script or module at the time of job's invocation.

9.5 Jobs and Host Operations to Enqueue Jobs the requirements' first item, in an agent of a cluster sec-jobs

Perform any host-defined preparation steps. Invoke the Job Abstract Closure.

9.5.5 HostEnqueuePromiseJob sec-hostenqueuepromisejob

each time job is invoked the implementation must perform implementation-defined steps such that execution is prepared to evaluate ECMAScript code at the time of job's invocation

AgentPrepareJob(k) answers the job scheduled at k, prepared as promisePrepared says.

agentPrepareJob
Lean
agentPrepareJob : ∀ vs s r s', H.choice Known.pAgentPrepareJob vs s = .ok r s' →  ∃ k, vs = [.math (M.ofNat k)] ∧ scheduled s.hostLog k = some r ∧ promisePrepared s k s'
9.5 Jobs and Host Operations to Enqueue Jobs the requirements' first item sec-jobs

Perform any host-defined cleanup steps, after which the execution context stack must be empty.

After a job's cleanup the execution context stack is empty.

jobCleanup
Lean
jobCleanup : ∀ k s s', H.cleanupJob k s = .ok () s' → M.eq (M.seqLen s'.stack) (M.ofNat 0) = true
9.5 Jobs and Host Operations to Enqueue Jobs the requirements' first item, in an agent of a cluster sec-jobs

Perform any host-defined cleanup steps, after which the execution context stack must be empty.

AgentCleanupJob answers unused and leaves the agent's execution context stack empty.

agentCleanupJob
Lean
agentCleanupJob : ∀ vs s r s', H.choice Known.pAgentCleanupJob vs s = .ok r s' →  r = .enum Known.eUnused ∧ M.eq (M.seqLen s'.stack) (M.ofNat 0) = true
9.5.2 HostMakeJobCallback sec-hostmakejobcallback

ECMAScript hosts that are not web browsers must use the default implementation of HostMakeJobCallback.

9.5.3 HostCallJobCallback sec-hostcalljobcallback

ECMAScript hosts that are not web browsers must use the default implementation of HostCallJobCallback.

Where the host answers that it is not a web browser, HostJobCallbackData answers empty and the steps around the callback's call unused, the state as it was.

jobCallbackDefault
Lean
jobCallbackDefault : ∀ q vs s r s', H.choice Known.pWebBrowser [.choice 1, .absent] s = .ok (.bool false) s →  q ∈ [Known.pHostJobCallbackData, Known.pHostPrepareCallJobCallback, Known.pHostCleanupCallJobCallback] →  Run.boundary (H.choice q vs) s = .ok r s' →  s' = s ∧ r = .enum (if q = Known.pHostJobCallbackData then Known.eEmpty else Known.eUnused)
9.5.3 HostCallJobCallback the requirements sec-hostcalljobcallback

It must perform and return the result of Call(jobCallback.[[Callback]], thisValue, argList).

The host's steps before and after the call answer unused, so the call's result is returned.

callJobCallback
Lean
callJobCallback : ∀ q vs s r s', q = Known.pHostPrepareCallJobCallback ∨ q = Known.pHostCleanupCallJobCallback →  Run.boundary (H.choice q vs) s = .ok r s' → r = .enum Known.eUnused
9.8 Forward Progress sec-forward-progress

in a set of agents that share an executing thread, one agent eventually makes forward progress

HostSelectAgent answers empty or another Agent Record of the cluster that can run (canRunAgent), the state as it was.

selectAgent
Lean
selectAgent : H.asks Known.pHostSelectAgent fun _ s r => r = .enum Known.eEmpty ∨  isRecordOf s "Agent Record" r = true ∧ (clusterSigs s).any (Val.same (sigOf s r)) = true ∧    Val.same (sigOf s r) (sigOf s s.agent) = false ∧ Val.same r s.agent = false ∧ canRunAgent s r = true

The laws of time and dates

From lean/Ecma/Host/Laws/Time.lean

The host's clock, its time zone and Date.parse (sec-time-values-and-time-range, sec-systemtimezoneidentifier, sec-date.parse). The model has no local political rules for any time zone: GetNamedTimeZoneOffsetNanoseconds and GetNamedTimeZoneEpochNanoseconds run their default implementations, so "UTC" is the one available named time zone, and the system time zone is it or an offset time zone.

def

instantTimeValue

Time.lean:22

n is a time value identifying an instant: a finite integral Number from -8.64 × 10^15 to 8.64 × 10^15 (sec-time-values-and-time-range).

def instantTimeValue (n : M.Num) : Prop :=  M.numView n = .posZero ∨ M.numView n = .negZero ∨ ∃ m, M.numView n = .finite m ∧ M.isInt m = true ∧    M.lt m (M.neg (M.ofNat maxTime)) = false ∧ M.lt (M.ofNat maxTime) m = false
def

timeZoneNameSuffix

Time.lean:27

x is the empty String, or " (" then a time zone name then ")" (TimeZoneString step 9).

def timeZoneNameSuffix (x : M.Str) : Prop :=  M.strEq x (M.strLit "") = true ∨    ∃ n, M.strEq x (M.strConcat (M.strLit " (") (M.strConcat n (M.strLit ")"))) = true
def

digits2

Time.lean:32

Two decimal digits at the front of l: their value and the rest.

def digits2 : List Nat → Option (Nat × List Nat)  | a :: b :: l => if 48 ≤ a ∧ a ≤ 57 ∧ 48 ≤ b ∧ b ≤ 57 then some ((a - 48) * 10 + (b - 48), l) else none  | _ => none
def

fractionNs

Time.lean:37

A TemporalDecimalFraction's 1 to 9 digits as nanoseconds.

def fractionNs (ds : List Nat) : Option Nat :=  if 1 ≤ ds.length ∧ ds.length ≤ 9 ∧ ds.all (fun c => 48 ≤ c ∧ c ≤ 57) then    some ((ds ++ List.replicate (9 - ds.length) 48).foldl (fun a c => a * 10 + (c - 48)) 0)  else none
def

utcOffsetNs

Time.lean:45

ParseTimeZoneOffsetString of a String UTCOffset matches, by its code units: its sign, Hour, MinuteSeconds (the TimeSeparators all ":" or all empty) and fraction as nanoseconds; none where UTCOffset does not match (IsTimeZoneOffsetString is false).

Lean, 27 lines
def utcOffsetNs : List Nat → Option Int  | [] => none  | c :: l => do    let sign : Int ← if c = 43 then some 1 else if c = 45 then some (-1) else none    let (h, l) ← digits2 l    guard (h ≤ 23)    let ns ← match l with      | [] => some 0      | l => do        let (ext, l) := match l with          | 58 :: l => (true, l)          | l => (false, l)        let (mi, l) ← digits2 l        guard (mi ≤ 59)        match l with        | [] => some (mi * 60 * 10 ^ 9)        | l => do          let l ← if ext then (match l with            | 58 :: l => some l            | _ => none) else some l          let (sc, l) ← digits2 l          guard (sc ≤ 59)          let f ← match l with            | [] => some 0            | c :: ds => if c = 46 ∨ c = 44 then fractionNs ds else none          some ((mi * 60 + sc) * 10 ^ 9 + f)    return sign * ((h * 3600 * 10 ^ 9 + ns : Nat) : Int)
def

sysTimeZone

Time.lean:75

SystemTimeZoneIdentifier() at s is id: "UTC" where SupportsOnlyUTC() is true, else SystemTimeZoneString().

def sysTimeZone (H : Host M) (s : State M) (id : M.Str) : Prop :=  H.choice Known.pSupportsOnlyUTC [] s = .ok (.bool true) s ∧ M.strEq id (M.strLit "UTC") = true ∨    H.choice Known.pSupportsOnlyUTC [] s = .ok (.bool false) s ∧      H.choice Known.pSystemTimeZoneString [] s = .ok (.str id) s
structure

Host.TimeLaws

Time.lean:81

The laws of time and dates.

Proved as part of Host.WF.

structure Host.TimeLaws (H : Host M) : Prop where

13 laws

21.4.3.1 Date.now sec-date.now

This function returns the time value designating the UTC date and time of the occurrence of the call to it.

No sentence the host's clock (Host.elapsed, logged as it takes each job) is what timeoutAfter's "after" is measured on; that it never goes back is what makes "after" mean later.

As the host takes its next job, its clock reads no less than any elapsed time logged.

elapsedMono
Lean
elapsedMono : ∀ s k s', H.nextJob s = .ok k s' → ∀ j t, HostCall.next j t ∈ s.hostLog →  M.lt (H.elapsed s) t = false
9.5.6 HostEnqueueTimeoutJob sec-hostenqueuetimeoutjob

It schedules timeoutJob in the realm realm in the agent signified by realm.[[AgentSignifier]] to be performed after at least milliseconds milliseconds.

As the host takes a timeout job, its clock reads at least milliseconds past the elapsed time logged before the call that scheduled it.

timeoutAfter
Lean
timeoutAfter : ∀ s pre c job realm ms a rl r rest s',  s.hostLog = pre ++ .hook c [job, realm, .num ms] a rl r :: rest →  Gen.clauses[c]? = some "sec-hostenqueuetimeoutjob" → H.nextJob s = .ok (some rest.length) s' →  mathAfter (lastElapsed rest) (H.elapsed s) ms = true
25.4.3.14 DoWait step 23 sec-dowait

Let additionalTimeout be an implementation-defined non-negative mathematical value.

AdditionalTimeout answers a non-negative mathematical value, the state as it was.

additionalTimeout
Lean
additionalTimeout : H.asks Known.pAdditionalTimeout fun _ _ r => ∃ m, r = .math m ∧ M.lt m (M.ofNat 0) = false
21.4.4.41.3 TimeZoneString step 9 sec-timezoneestring

either the empty String or the string-concatenation of the code unit 0x0020 (SPACE), the code unit 0x0028 (LEFT PARENTHESIS), an implementation-defined time zone name, and the code unit 0x0029 (RIGHT PARENTHESIS)

TimeZoneNameSuffix answers "" or " (" name ")", the state as it was.

timeZoneNameSuffix
Lean
timeZoneNameSuffix : H.asks Known.pTimeZoneNameSuffix fun _ _ r => ∃ x, r = .str x ∧ timeZoneNameSuffix x
21.4.1.24 SystemTimeZoneIdentifier step 2 sec-systemtimezoneidentifier

Let systemTimeZoneString be the String representing the host environment's current time zone, either a primary time zone identifier or an offset time zone identifier.

21.4.1.19 Time Zone Identifiers sec-time-zone-identifiers

ECMAScript implementations must support an available named time zone with the identifier "UTC", which must be the primary time zone identifier for the UTC time zone.

SystemTimeZoneString answers "UTC", an available named time zone identifier whose IsNonPrimaryTimeZoneId is false, or a String UTCOffset matches (utcOffsetNs), the state as it was.

systemTimeZoneString
Lean
systemTimeZoneString : H.asks Known.pSystemTimeZoneString fun _ s r => ∃ x, r = .str x ∧  (M.strEq x (M.strLit "UTC") = true ∨    (∃ a s' xs, H.choice Known.pAvailableNamedTimeZoneIds [] s = .ok (.ref a) s' ∧      listAt s' (.ref a) = some xs ∧ Val.str x ∈ xs ∧      H.choice Known.pIsNonPrimaryTimeZoneId [.str x] s = .ok (.bool false) s) ∨    ∃ l, unitsAre x l ∧ (utcOffsetNs l).isSome)
21.4.1.23 AvailableNamedTimeZoneIdentifiers step 4.b.i sec-availablenamedtimezoneidentifiers

Set primary to the primary time zone identifier associated with identifier.

PrimaryTimeZoneId answers "UTC" or an available named time zone identifier whose IsNonPrimaryTimeZoneId is false, the state as it was.

primaryTimeZoneId
Lean
primaryTimeZoneId : H.asks Known.pPrimaryTimeZoneId fun _ s r => ∃ x, r = .str x ∧  (M.strEq x (M.strLit "UTC") = true ∨    (∃ a s' xs, H.choice Known.pAvailableNamedTimeZoneIds [] s = .ok (.ref a) s' ∧      listAt s' (.ref a) = some xs ∧ Val.str x ∈ xs ∧      H.choice Known.pIsNonPrimaryTimeZoneId [.str x] s = .ok (.bool false) s))
21.4.1.24 SystemTimeZoneIdentifier step 1 sec-systemtimezoneidentifier

If the implementation only supports the UTC time zone, return "UTC".

SupportsOnlyUTC answers a Boolean, the state as it was.

supportsOnlyUTC
Lean
supportsOnlyUTC : ∀ s r s', H.choice Known.pSupportsOnlyUTC [] s = .ok r s' → s' = s ∧ ∃ b, r = .bool b
21.4.3.2 Date.parse sec-date.parse

it returns a Number, the UTC time value corresponding to the date and time

ParseDateString answers NaN or a time value (instantTimeValue), never -0𝔽, the state as it was.

parseDateString
Lean
parseDateString : H.asks Known.pParseDateString fun _ _ r =>  ∃ n, r = .num n ∧ (M.numView n = .nan ∨ instantTimeValue n) ∧ M.numView n ≠ .negZero
21.4.3.2 Date.parse sec-date.parse

When the MM or DD elements are absent, "01" is used. When the HH, mm, or ss elements are absent, "00" is used. When the sss element is absent, "000" is used. When the UTC offset representation is absent, date-only forms are interpreted as a UTC time

A valid String of the format that is no local time gives the time value of its fields less its offset, NaN out of a time value's range (sec-expanded-years).

dateFormUTC
Lean
dateFormUTC : ∀ x s r s' (f : DateForm), H.choice Known.pParseDateString [.str x] s = .ok r s' →  f.fits → f.legal → f.isLocal = false → unitsAre x f.units → tvResult r (f.ms - f.offsetMin * 60000)
21.4.3.2 Date.parse sec-date.parse

When the UTC offset representation is absent, date-only forms are interpreted as a UTC time and date-time forms are interpreted as a local time.

A valid date-time form without an offset gives UTC of its fields (sec-utc-t): the fields themselves where the system time zone is "UTC", less the offset where it is an offset time zone.

dateFormLocal
Lean
dateFormLocal : ∀ x s r s' (f : DateForm) id, H.choice Known.pParseDateString [.str x] s = .ok r s' →  f.fits → f.legal → f.isLocal = true → unitsAre x f.units → sysTimeZone H s id →  (M.strEq id (M.strLit "UTC") = true → tvResult r f.ms) ∧  ∀ l o, unitsAre id l → utcOffsetNs l = some o → tvResult r (f.ms - o.tdiv 1000000)
21.4.3.2 Date.parse sec-date.parse

Strings that are unrecognizable or contain out-of-bounds format element values shall cause this function to return NaN.

A String of the format's shape with an out-of-bounds element gives NaN.

dateFormIllegal
Lean
dateFormIllegal : ∀ x s r s' (f : DateForm), H.choice Known.pParseDateString [.str x] s = .ok r s' →  f.fits → f.illegal → unitsAre x f.units → ∃ n, r = .num n ∧ M.numView n = .nan
21.4.4.36 Date.prototype.toISOString step 7 sec-date.prototype.toisostring

Return a String representation of tv in the Date Time String Format on the UTC time scale, including all format elements and the UTC offset representation "Z".

ExpandedYearForm, whether a year from 0 to 9999 is written as an expanded year, answers a Boolean, the state as it was.

expandedYearForm
Lean
expandedYearForm : H.asks Known.pExpandedYearForm fun _ _ r => ∃ b, r = .bool b

The laws of shared memory and buffers

From lean/Ecma/Host/Laws/Memory.lean

NaN encodings, Data Blocks, HostResizeArrayBuffer, and the bytes a shared read takes (sec-numerictorawbytes, sec-createbytedatablock, sec-hostresizearraybuffer, sec-memory-model). The memory model's validity (Ecma.MemoryModel) is read by chooseReadsValid alone.

def

cutArgs

Memory.lean:20

HostSelectAgent's agent and n.

def cutArgs {M : Model} : List (Val M) → Option (Val M × M.Math)  | [a, n] => match n with    | .math n => some (a, n)    | _ => none  | _ => none
def

HostCall.cutOf

Memory.lean:28

A logged HostSelectAgent that selected an agent: the agent it was called in and the number of events of its [[EventList]] it gave.

def HostCall.cutOf {M : Model} : HostCall M → Option (Val M × M.Math)  | .choice q vs r => if q == Known.pHostSelectAgent && selects r then cutArgs vs else none  | _ => none
def

cutsOf

Memory.lean:33

The switches of a log (newest first), oldest first.

def cutsOf {M : Model} (log : List (HostCall M)) : List (Val M × M.Math) := log.reverse.filterMap HostCall.cutOf
def

eventPlace

Memory.lean:38

The place in the interleaving order of event i of the [[EventList]] of the agent whose signifier is sig: the first of the switches cuts away from that agent after the event (past all of them where there is none), then i.

def eventPlace {M : Model} (s : State M) (cuts : List (Val M × M.Math)) (sig : Val M) (i : Nat) : Nat × Nat :=  ((cuts.findIdx? fun c => Val.same (sigOf s c.1) sig && M.lt (M.ofNat i) c.2).getD cuts.length, i)
def

placeLe

Memory.lean:42

The place p is not after q.

def placeLe (p q : Nat × Nat) : Bool := p.1 < q.1 || p.1 == q.1 && p.2 ≤ q.2
def

placed

Memory.lean:45

The events es from position i, each with its place f.

def placed {M : Model} (f : Nat → Nat × Nat) : Nat → List (Val M) → List (Val M × (Nat × Nat))  | _, [] => []  | i, e :: es => (e, f i) :: placed f (i + 1) es
def

fieldElems

Memory.lean:50

The elements of the List in field f of the Record v; none where there is none.

def fieldElems {M : Model} (s : State M) (f : FieldId) (v : Val M) : List (Val M) :=  ((fieldOf s f v).bind (listElems s)).getD []
def

execEvents

Memory.lean:54

The events of the candidate execution ex: its Agent Events Records' [[EventList]]s.

def execEvents {M : Model} (s : State M) (ex : Val M) : List (Val M) :=  (fieldElems s Known.fEventsRecords ex).flatMap (fieldElems s Known.fEventList)
def

placedEvents

Memory.lean:58

The events of ex, each with its place in the interleaving order of the switches cuts.

def placedEvents {M : Model} (s : State M) (cuts : List (Val M × M.Math)) (ex : Val M) : List (Val M × (Nat × Nat)) :=  (fieldElems s Known.fEventsRecords ex).flatMap fun er =>    placed (eventPlace s cuts ((fieldOf s Known.fAgentSignifier er).getD .absent)) 0 (fieldElems s Known.fEventList er)
def

mathField

Memory.lean:63

The mathematical value in field f of the Record v; none where there is none.

def mathField {M : Model} (s : State M) (f : FieldId) (v : Val M) : Option M.Math :=  match fieldOf s f v with  | some (.math x) => some x  | _ => none
def

writesByte

Memory.lean:69

e is a write event (isWrite) whose [[Block]] is block and whose memory range contains loc.

def writesByte {M : Model} (isWrite : State M → Val M → Bool) (s : State M) (block : Val M) (loc : M.Math)    (e : Val M) : Bool :=  isWrite s e && (fieldOf s Known.fBlock e).any (Val.same · block) &&    match mathField s Known.fByteIndex e, mathField s Known.fElementSize e with    | some i, some k => !M.lt loc i && M.lt loc (M.add i k)    | _, _ => false
def

nanBits

Memory.lean:81

A natural number is a NaN's encoding in the IEEE 754-2019 binary interchange format of w exponent bits and precision p: w + p bits (the sign free), the biased exponent all ones and the trailing significand not zero.

def nanBits (w p k : Nat) : Prop :=  k < 2 ^ (w + p) ∧ (k / 2 ^ (p - 1)) % 2 ^ w = 2 ^ w - 1 ∧ k % 2 ^ (p - 1) ≠ 0
def

isWriteEvent

Memory.lean:85

A WriteSharedMemory or ReadModifyWriteSharedMemory event.

def isWriteEvent (s : State M) (e : Val M) : Bool :=  isRecordOf s "WriteSharedMemory" e || isRecordOf s "ReadModifyWriteSharedMemory" e
def

memNames

Memory.lean:89

The memory model's names: Data's fields, enums and sorts.

def memNames : MemoryModel.View.Names := ⟨Gen.fields.idxOf?, Gen.enums.idxOf?, Gen.sorts.idxOf?⟩
def

interleaved

Memory.lean:93

mo orders the events of the candidate execution ex as the interleaving order of the log's switches places them.

def interleaved (s : State M) (ex : Val M) (mo : MemoryModel.Rel M.Addr) : Prop :=  ∀ a b pa pb, (.ref a, pa) ∈ placedEvents s (cutsOf s.hostLog) ex → (.ref b, pb) ∈ placedEvents s (cutsOf s.hostLog) ex →    a ≠ b → placeLe pa pb = true → mo a b
structure

Host.MemoryLaws

Memory.lean:98

The laws of shared memory and buffers.

Proved as part of Host.WF.

structure Host.MemoryLaws (H : Host M) : Prop where

7 laws

25.1.3.17 NumericToRawBytes step 1 sec-numerictorawbytes

An implementation must always choose the same encoding for each implementation distinguishable NaN value.

For a NaN and a format with a trailing significand field (2 ≤ p), NaNEncoding answers one NaN bit pattern of the format in every state, the state as it was.

nanEncoding
Lean
nanEncoding : ∀ (v : M.Num) (w p : Nat), M.numView v = .nan → 2 ≤ p → ∃ k, nanBits w p k ∧  ∀ s, H.choice Known.pNaNEncoding [.num v, .math (M.ofNat w), .math (M.ofNat p)] s =    .ok (.math (M.ofNat k)) s
6.2.9.1 CreateByteDataBlock step 2 sec-createbytedatablock

If it is impossible to create such a Data Block, throw a RangeError exception.

CanAllocate, whether such a Data Block can be created, answers a Boolean, the state as it was.

canAllocate
Lean
canAllocate : H.asks Known.pCanAllocate fun _ _ r => ∃ b, r = .bool b
25.1.3.8 HostResizeArrayBuffer the requirements sec-hostresizearraybuffer

The abstract operation does not detach buffer.

If the abstract operation completes normally with handled, buffer.[[ArrayBufferByteLength]] is newByteLength.

buffer's [[ArrayBufferData]] does not become null; on handled its [[ArrayBufferByteLength]] is newByteLength.

resizeArrayBuffer
Lean
resizeArrayBuffer : ∀ c a n s r s', Gen.clauses[c]? = some "sec-hostresizearraybuffer" →  H.answers c [.obj a, n] s r s' →  (∀ f, Gen.fields[f]? = some "ArrayBufferData" → slotOf s a f ≠ some .null → slotOf s' a f ≠ some .null) ∧  (∀ e, normalValue r = some (.enum e) → Gen.enums[e]? = some "handled" →    ∀ f m, Gen.fields[f]? = some "ArrayBufferByteLength" → n = .math m →      ∃ m', slotOf s' a f = some (.math m') ∧ M.eq m' m = true)
25.2.3 The SharedArrayBuffer Constructor sec-sharedarraybuffer-constructor

Whenever a host does not provide concurrent access to SharedArrayBuffers it may omit the "SharedArrayBuffer" property of the global object.

OmitSharedArrayBuffer is one Boolean in every state, the state as it was.

omitSharedArrayBuffer
Lean
omitSharedArrayBuffer : ∃ b, H.asks Known.pOmitSharedArrayBuffer fun _ _ r => r = .bool b
25.4.12 Atomics.pause sec-atomics.pause

It has no observable behaviour other than timing.

SpinWaitHint answers unused, the state as it was.

spinWaitHint
Lean
spinWaitHint : H.asks Known.pSpinWaitHint fun _ _ r => r = .enum Known.eUnused
25.1.3.15 GetRawBytesFromSharedBlock step 6 sec-getrawbytesfromsharedblock

Let rawValue be a List of length elementSize whose elements are nondeterministically chosen byte values.

ChooseReadsBytesFrom(execution, eventsRecord, block, byteIndex, elementSize) answers a new List of elementSize events of execution, the one at index i a write event on block whose memory range contains byteIndex + i; the state as it was but for the new List.

chooseReadsBytesFrom
Lean
chooseReadsBytesFrom : ∀ vs s r s', H.choice Known.pChooseReadsBytesFrom vs s = .ok r s' →  ∃ ex er block idx size ws, vs = [ex, er, block, .math idx, .math size] ∧ listOf ws s = .ok r s' ∧    M.eq (M.ofNat ws.length) size = true ∧    ∀ j w, ws[j]? = some w → w ∈ execEvents s ex ∧ writesByte isWriteEvent s block (M.add idx (M.ofNat j)) w = true
29.7.5 Valid Executions sec-valid-executions

A candidate execution execution is a valid execution (or simply an execution) if all of the following are true.

Where execution is a valid execution whose memory order agrees with the interleaving order and whose Shared Data Block events are formed, it stays one with the read appended to eventsRecord, reading the chosen events.

chooseReadsValid
Lean
chooseReadsValid : ∀ vs s r s', H.choice Known.pChooseReadsBytesFrom vs s = .ok r s' →  ∀ ex er b idx size, vs = [ex, er, .ref b, .math idx, .math size] →  ∃ ws : List M.Addr, listOf (ws.map .ref) s = .ok r s' ∧    ∀ (d : CloSite → List (Val M) → List (Val M) → Run M (Val M)) rbf hsw mo k (ev : MemoryModel.NewEvent M),      let x := MemoryModel.View.exec memNames d s ex      MemoryModel.ValidWith x rbf hsw → MemoryModel.MemoryOrder x rbf hsw mo → interleaved s ex mo →      MemoryModel.View.Formed memNames d s ex → x.records[k]? = some (MemoryModel.View.eventsRecord memNames s er) →      ev.IsRead → ev.block = b → ev.byteIndex = idx → ev.elementSize = size → (∃ m, size = M.ofNat m) →      MemoryModel.ReadsValid x rbf hsw k ev ws

The law of EscapeRegExpPattern

From lean/Ecma/Host/Laws/RegExp.lean

EscapePattern's String (sec-escaperegexppattern step 5), over code units.

def

lineTerminatorUnit

RegExp.lean:18

A LineTerminator's code unit (§12.3): LF, CR, LS, PS.

def lineTerminatorUnit (c : Nat) : Bool := c == 0x0A || c == 0x0D || c == 0x2028 || c == 0x2029
def

terminatorEscape

RegExp.lean:21

What follows the \ in a LineTerminator's escape: n, r, u2028, u2029.

def terminatorEscape (c : Nat) : List Nat :=  if c == 0x0A then [110] else if c == 0x0D then [114] else if c == 0x2028 then [117, 50, 48, 50, 56]  else [117, 50, 48, 50, 57]
inductive

Escaped

RegExp.lean:28

Escaped b p e: e is p with code units escaped (§22.2.6.13.1 step 5): a / kept or written \/, a LineTerminator written as its escape (terminatorEscape), every other unit kept. b: the unit before is an unescaped \, so that a LineTerminator after it is written as the escape's letters alone.

inductive Escaped : Bool → List Nat → List Nat → Prop  | nil (b) : Escaped b [] []  | keep {b c p e} : lineTerminatorUnit c = false → Escaped (!b && c == 92) p e → Escaped b (c :: p) (c :: e)  | slash {p e} : Escaped false p e → Escaped false (47 :: p) (92 :: 47 :: e)  | terminator {c p e} : lineTerminatorUnit c = true → Escaped false p e →      Escaped false (c :: p) (92 :: terminatorEscape c ++ e)  | terminatorAfter {c p e} : lineTerminatorUnit c = true → Escaped false p e →      Escaped true (c :: p) (terminatorEscape c ++ e)
def

EscapeOf

RegExp.lean:38

EscapePattern's String for the pattern p, as code units: the empty pattern as (?:), any other escaped.

def EscapeOf (p e : List Nat) : Prop := (p = [] ∧ e = [40, 63, 58, 41]) ∨ (p ≠ [] ∧ Escaped false p e)
def

bodySafe

RegExp.lean:42

One scan of e for BodySafe: no LineTerminator, and each / follows an unescaped \ or is within a class. esc: the unit before is an unescaped \; cls: within a class, where [ is a character and ] closes it.

def bodySafe : (esc cls : Bool) → List Nat → Bool  | _, _, [] => true  | true, cls, c :: e => !lineTerminatorUnit c && bodySafe false cls e  | false, cls, c :: e => !lineTerminatorUnit c && (cls || c != 47) &&      bodySafe (c == 92) (if c == 91 then true else if c == 93 then false else cls) e
def

BodySafe

RegExp.lean:52

As far as / and LineTerminators go, e can be the text of a RegularExpressionBody (§12.9.5): it is not empty, holds no LineTerminator, and each / follows an unescaped \ or is within a class […] (RegularExpressionClass). Where a class or an escape is left open at the end is not checked: that is not a Pattern either.

def BodySafe (e : List Nat) : Prop := e ≠ [] ∧ bodySafe false false e = true
structure

Host.RegExpLaws

RegExp.lean:55

The law of EscapeRegExpPattern.

Proved as part of Host.WF.

structure Host.RegExpLaws (H : Host M) : Prop where

1 laws

22.2.6.13.1 EscapeRegExpPattern steps 4–5 sec-escaperegexppattern

Let escapedPattern be a String in the form of a patternSymbol equivalent to pattern interpreted as UTF-16 encoded Unicode code points

Multiple calls to this abstract operation using the same values for pattern and flags must produce identical results.

The code points / or any LineTerminator occurring in the pattern shall be escaped in escapedPattern as necessary to ensure that the string-concatenation of "/", escapedPattern, "/", and flags can be parsed (in an appropriate lexical context) as a RegularExpressionLiteral

EscapePattern answers a String S, the same for the same pattern and flags at every call, the state as it was: pattern with each / kept or written \/ and each LineTerminator written as its escape, the empty pattern as (?:) (EscapeOf), which as far as / and LineTerminators go can be a RegularExpressionBody (BodySafe). That S "must behave identically" is the specification's claim about its own semantics, no law: it was proved of this engine's escape at the git tag escape-sim-proved.

escapePattern
Lean
escapePattern : ∀ pattern flags s r s', H.choice Known.pEscapePattern [.str pattern, .str flags] s = .ok r s' →  s' = s ∧ (∃ S, r = .str S ∧ ∃ p e, unitsAre pattern p ∧ unitsAre S e ∧ EscapeOf p e ∧ BodySafe e) ∧    ∀ s2 r2 s2', H.choice Known.pEscapePattern [.str pattern, .str flags] s2 = .ok r2 s2' → r2 = r

The laws of sorting and enumeration

From lean/Ecma/Host/Laws/Order.lean

The order SortIndexedProperties sorts in, the steps of EnumerateObjectProperties, and the order of the intrinsics' properties.

def

sortCall

Order.lean:18

SortStep's answer to call the comparator on the elements at j and k, the host's state then st: a new List « j, k, st ».

def sortCall {M : Model} (j k : Nat) (st : Val M) : Run M (Val M) :=  listOf [.math (M.ofNat j), .math (M.ofNat k), st]
def

sortDone

Order.lean:22

SortStep's answer to finish with the order σ: a new Record whose [[Value]] is a new List of σ.

def sortDone {M : Model} (σ : List Nat) : Run M (Val M) := do  let l ← listOf (σ.map fun i => .math (M.ofNat i))  return .ref (← alloc (.record Known.sRecord (M.recSet M.recEmpty Known.fValue l)))
def

cmpOrder

Order.lean:30

The order a comparator's result gives (§23.1.3.30.1 <C, =C, >C): none for NaN and for ±∞, whose ℝ is not defined (§5.2.6).

def cmpOrder (r : M.Num) : Option Ordering :=  match M.numView r with  | .posZero | .negZero => some .eq  | .finite m => some (if M.lt m (M.ofNat 0) then .lt else .gt)  | _ => none
def

consistentCmp

Order.lean:38

§23.1.3.30.1: c is a consistent comparator for the elements at the indices less than n: a non-NaN Number for each pair, =C reflexive and symmetric, =C, <C and >C transitive.

def consistentCmp (n : Nat) (c : Nat → Nat → M.Num) : Prop :=  (∀ a b, a < n → b < n → cmpOrder (c a b) ≠ none) ∧  (∀ a, a < n → cmpOrder (c a a) = some .eq) ∧  (∀ a b, a < n → b < n → cmpOrder (c a b) = some .eq → cmpOrder (c b a) = some .eq) ∧  ∀ (o : Ordering) a b d, a < n → b < n → d < n →    cmpOrder (c a b) = some o → cmpOrder (c b d) = some o → cmpOrder (c a d) = some o
def

sortOrderOk

Order.lean:47

§23.1.3.30.1: the order σ (new[i] is old[σ[i]], so π(j) is j's index in σ) puts each element before every element it is <C, and before every later element it is =C (stable).

def sortOrderOk (n : Nat) (c : Nat → Nat → M.Num) (σ : List Nat) : Prop :=  ∀ j k, j < n → k < n →    (cmpOrder (c j k) = some .lt → σ.idxOf j < σ.idxOf k) ∧    (j < k → cmpOrder (c j k) = some .eq → σ.idxOf j < σ.idxOf k)
def

sortCallStep

Order.lean:54

One call of a sort of n elements: SortStep, given the host's state st and the result res, asks for a call on the elements at j and k, with the state st' it is given back.

def sortCallStep (H : Host M) (n : Nat) (st res st' : Val M) (j k : Nat) : Prop :=  ∃ s r s', H.choice Known.pSortStep [.math (M.ofNat n), st, res] s = .ok r s' ∧ sortCall j k st' s = .ok r s'
inductive

SortReach

Order.lean:60

A sort of n elements reaches SortStep's arguments st (the host's state) and res (the last call's result) by the calls h, oldest first, each with the Number it returned: it starts from empty and empty, and each call SortStep asks for returns any Number.

inductive SortReach (H : Host M) (n : Nat) : Val M → Val M → List (Nat × Nat × M.Num) → Prop where
| start : SortReach H n (.enum Known.eEmpty) (.enum Known.eEmpty) []
def

sortNext

Order.lean:67

A sort of n elements goes from SortStep's arguments b to a: from arguments the sort reaches, a call whose result is any Number.

def sortNext (H : Host M) (n : Nat) (a b : Val M × Val M) : Prop :=  (∃ h, SortReach H n b.1 b.2 h) ∧ ∃ j k x, sortCallStep H n b.1 b.2 a.1 j k ∧ a.2 = .num x
structure

Host.OrderLaws

Order.lean:71

The laws of sorting and enumeration.

Proved as part of Host.WF.

structure Host.OrderLaws (H : Host M) : Prop where

4 laws

23.1.3.30.1 SortIndexedProperties step 4 and the paragraph after it sec-sortindexedproperties

Sort items using an implementation-defined sequence of calls to sortCompare.

Unless the sort order is specified to be implementation-defined, it must satisfy all of the following conditions

At the host's state and the last result a sort of n elements reaches by the calls h, SortStep asks for a call on two indices less than n, or answers a permutation that, for every consistent comparator giving every result in h, meets its conditions; otherwise the order is the host's.

sortStep
Lean
sortStep : ∀ n st res h s r s', SortReach H n st res h →  H.choice Known.pSortStep [.math (M.ofNat n), st, res] s = .ok r s' →  (∃ j k st', j < n ∧ k < n ∧ sortCall j k st' s = .ok r s') ∨  ∃ σ, σ.Perm (List.range n) ∧    (∀ c, consistentCmp n c → (∀ e ∈ h, c e.1 e.2.1 = e.2.2) → sortOrderOk n c σ) ∧ sortDone σ s = .ok r s'
23.1.3.30.1 SortIndexedProperties steps 4–5 sec-sortindexedproperties

Sort items using an implementation-defined sequence of calls to sortCompare.

The sequence is finite: a sort makes finitely many calls, whatever their results.

sortStepEnds
Lean
sortStepEnds : ∀ n, WellFounded (sortNext H n)
14.7.5.9 EnumerateObjectProperties sec-enumerate-object-properties

The mechanics and order of enumerating the properties is not specified but must conform to the rules specified below.

the iterator must behave as would the iterator given by CreateForInIterator(obj) until one of the following occurs

After a history that obeyed the rules (ForInRun), ForInStep answers an action that obeys them (ForInRules); and CreateForInIterator(obj)'s next action where no object of the chain is exotic, none changed shape since the enumeration began (State.shapeLog), and every action so far was its.

forInStep
Lean
forInStep : ∀ obj h s r s', H.choice Known.pForInStep [.obj obj, h] s = .ok r s' → ∀ es,  forInHist s h = some es → ForInRun obj es → ∃ act, actRecord act s = .ok r s' ∧ ForInRules obj es act ∧    (cfiApplies s obj h es → act = cfiNext obj es)
9.3.2 CreateIntrinsics step 2 sec-createintrinsics

Set fields of realmRecord.[[Intrinsics]] with the values listed in

PropertyOrder, the order an intrinsic's properties are created in, answers a new List of the given properties, each once.

propertyOrder
Lean
propertyOrder : ∀ o l s r s', H.choice Known.pPropertyOrder [o, l] s = .ok r s' →  ∃ xs ys, listElems s l = some xs ∧ ys.Perm xs ∧ listOf ys s = .ok r s'

The laws of the locale-sensitive methods

From lean/Ecma/Host/Laws/Locale.lean

The list separator, locale case mapping and comparison, and the locale forms of Number and Date.

def

dateValued

Locale.lean:16

The value is an object with a [[DateValue]] internal slot.

def dateValued {M : Model} (s : State M) : Val M → Bool  | .obj a => (slotOf s a Known.fDateValue).isSome  | _ => false
def

negNum

Locale.lean:23

n is a negative Number.

def negNum (n : M.Num) : Prop :=  M.numView n = .negInf ∨ ∃ m, M.numView n = .finite m ∧ M.lt m (M.ofNat 0) = true
def

posNum

Locale.lean:27

n is a positive Number.

def posNum (n : M.Num) : Prop :=  M.numView n = .posInf ∨ ∃ m, M.numView n = .finite m ∧ M.lt (M.ofNat 0) m = true
def

zeroNum

Locale.lean:31

n is +0𝔽 or -0𝔽.

def zeroNum (n : M.Num) : Prop := M.numView n = .posZero ∨ M.numView n = .negZero
def

canonEquiv

Locale.lean:35

Two Strings are canonically equivalent according to the Unicode Standard: their code points have the same canonical decomposition (NFD, UAX #15).

def canonEquiv (a b : M.Str) : Prop :=  M.normalize .NFD (Prims.Strings.strPoints a) = M.normalize .NFD (Prims.Strings.strPoints b)
structure

Host.LocaleLaws

Locale.lean:39

The laws of the locale-sensitive methods.

Proved as part of Host.WF.

structure Host.LocaleLaws (H : Host M) : Prop where

5 laws

23.1.3.32.1 LocalizedListSeparator sec-localizedlistseparator

LocalizedListSeparator ( ): a String

It returns an implementation-defined String appropriate for use as a list separator in the host environment's current locale (such as ", ").

LocalizedListSeparator answers a String, the state as it was.

listSeparator
Lean
listSeparator : ∀ c xs s r s', Gen.clauses[c]? = some "sec-localizedlistseparator" → H.answers c xs s r s' →  s' = s ∧ ∃ x, r = .str x

It works exactly the same as toLowerCase except that it is intended to yield a locale-sensitive result corresponding with conventions of the host environment's current locale.

LocaleLowercase and LocaleUppercase answer a new List of code points.

localeCase
Lean
localeCase : ∀ q l s r s', q = Known.pLocaleUppercase ∨ q = Known.pLocaleLowercase → H.choice q [l] s = .ok r s' →  ∃ cps : List M.Math, (∀ c ∈ cps, Prims.Strings.isPoint c = true) ∧ listOf (cps.map .math) s = .ok r s'
22.1.3.12 String.prototype.localeCompare sec-string.prototype.localecompare

this method, when considered as a method of two arguments, is required to be a consistent comparator defining a total ordering on the set of all Strings

This method is also required to recognize and honour canonical equivalence according to the Unicode Standard

By one total preorder of all Strings, LocaleCompare answers a negative, positive or zero Number, never NaN, and +0𝔽 for canonically equivalent Strings, the state as it was.

localeCompare
Lean
localeCompare : ∃ le : M.Str → M.Str → Prop, (∀ a b, le a b ∨ le b a) ∧ (∀ a b c, le a b → le b c → le a c) ∧  ∀ a b s r s', H.choice Known.pLocaleCompare [.str a, .str b] s = .ok r s' → s' = s ∧ ∃ n, r = .num n ∧    (¬le b a → negNum n) ∧ (¬le a b → posNum n) ∧ (le a b → le b a → zeroNum n) ∧    (canonEquiv a b → M.numView n = .posZero)
21.1.3.4 Number.prototype.toLocaleString sec-number.prototype.tolocalestring

This method is implementation-defined, and it is permissible, but not encouraged, for it to return the same thing as toString.

LocaleNumberString answers a String, or empty for toString's, the state as it was.

localeNumberString
Lean
localeNumberString : H.asks Known.pLocaleNumberString fun _ _ r => r = .enum Known.eEmpty ∨ ∃ x, r = .str x
21.4.4.38 Date.prototype.toLocaleDateString (and toLocaleString, toLocaleTimeString) sec-date.prototype.tolocaledatestring

This method returns a String value. The contents of the String are implementation-defined

LocaleDateString answers a String, or empty for the form without a locale, for an object with a [[DateValue]] slot, and a String or throw (a TypeError) for any other value, the state as it was.

localeDateString
Lean
localeDateString : ∀ k v s r s', H.choice Known.pLocaleDateString [k, v] s = .ok r s' → s' = s ∧  (dateValued s v = true → r = .enum Known.eEmpty ∨ ∃ x, r = .str x) ∧  (dateValued s v = false → r = .enum Known.eThrow ∨ ∃ x, r = .str x)

The laws of the optional features

From lean/Ecma/Host/Laws/Optional.lean

Whether the host is a web browser and the normative optional features it supports, the debugger statement, and a built-in function's source text.

def

identLike

Optional.lean:16

An ASCII IdentifierName.

def identLike : List Char → Bool  | c :: cs => (c.isAlpha || c == '_' || c == '$') && cs.all fun c => c.isAlphanum || c == '_' || c == '$'  | [] => false
def

keyLike

Optional.lean:21

A built-in's property key as its name: an IdentifierName or [Symbol. IdentifierName ].

def keyLike (cs : List Char) : Bool :=  identLike cs || "[Symbol.".toList.isPrefixOf cs && cs.getLast? == some ']' && identLike (cs.drop 8).dropLast
def

nameLike

Optional.lean:26

A name of these forms is matched by |NativeFunctionAccessor?| PropertyName: a key, or get or set and a key.

def nameLike (cs : List Char) : Bool :=  keyLike cs || ("get ".toList.isPrefixOf cs || "set ".toList.isPrefixOf cs) && keyLike (cs.drop 4)
def

nativeName

Optional.lean:30

A name NativeFunctionSource's law admits: empty, or of those forms.

def nativeName (cs : List Char) : Bool := cs.isEmpty || nameLike cs
def

nativeWrap

Optional.lean:33

function NAME() { [native code] }.

def nativeWrap (cs : List Char) : String := "function " ++ String.ofList cs ++ "() { [native code] }"
structure

Host.OptionalLaws

Optional.lean:38

The laws of the optional features.

Proved as part of Host.WF.

structure Host.OptionalLaws (H : Host M) : Prop where

5 laws

B Additional ECMAScript Features for Web Browsers sec-additional-ecmascript-features-for-web-browsers

The ECMAScript language syntax and semantics defined in this annex are required when the ECMAScript host is a web browser.

WebBrowser, whether the host is a web browser or otherwise supports the feature its arguments name, is one Boolean for the same arguments in every state, the state as it was.

webBrowser
Lean
webBrowser : ∀ vs, ∃ b, ∀ s, H.choice Known.pWebBrowser vs s = .ok (.bool b) s
B Additional ECMAScript Features for Web Browsers sec-additional-ecmascript-features-for-web-browsers

Web browsers are required to support all such features.

Where the host is a web browser, it is a web browser or otherwise supports every clause c.

webBrowserSupports
Lean
webBrowserSupports : ∀ c s, H.choice Known.pWebBrowser [.choice 1, .absent] s = .ok (.bool true) s →  H.choice Known.pWebBrowser [.choice 0, .clause c] s = .ok (.bool true) s
14.16.1 Runtime Semantics: Evaluation step 1 sec-debugger-statement-runtime-semantics-evaluation

If an implementation-defined debugging facility is available and enabled, then

DebuggerEnabled answers a Boolean, the state as it was.

debuggerEnabled
Lean
debuggerEnabled : H.asks Known.pDebuggerEnabled fun _ _ r => ∃ b, r = .bool b
14.16.1 Runtime Semantics: Evaluation step 1.a sec-debugger-statement-runtime-semantics-evaluation

Perform an implementation-defined debugging action.

DebuggerAction answers unused; what it may change is invariantsKept's.

debuggerAction
Lean
debuggerAction : ∀ vs s r s', H.choice Known.pDebuggerAction vs s = .ok r s' → r = .enum Known.eUnused
20.2.3.5 Function.prototype.toString step 3 sec-function.prototype.tostring

The representation must have the syntax of a NativeFunction. Additionally, if func has an [[InitialName]] internal slot and func.[[InitialName]] is a String, the portion of the returned String that would be matched by NativeFunctionAccessor? PropertyName must be func.[[InitialName]].

NativeFunctionSource answers function , a name nativeName admits and () { [native code] }, the name func.[[InitialName]] where that is a String, the state as it was.

nativeFunctionSource
Lean
nativeFunctionSource : ∀ f s r s', H.choice Known.pNativeFunctionSource [f] s = .ok r s' →  s' = s ∧ ∃ cs, nativeName cs = true ∧ r = .str (M.strLit (nativeWrap cs)) ∧    ∀ a sl ps y, f = .obj a → M.heapGet s.heap a = some (.object sl ps) →      M.recGet sl Known.fInitialName = some (.str y) → M.strEq y (M.strLit (String.ofList cs)) = true

The laws of the values the implementation chooses

From lean/Ecma/Host/Laws/Values.lean

Implementation-approximated values, implementation-defined choices, Math.random, and the maximum BigInt size.

def

unitNum

Values.lean:18

n is a Number with positive sign, greater than or equal to +0 and less than 1.

def unitNum (n : M.Num) : Prop :=  M.numView n = .posZero ∨    ∃ m, M.numView n = .finite m ∧ M.lt (M.ofNat 0) m = true ∧ M.lt m (M.ofNat 1) = true
structure

Host.ValueLaws

Values.lean:23

The laws of the values the implementation chooses.

Proved as part of Host.WF.

structure Host.ValueLaws (H : Host M) : Prop where

7 laws

21.3.2.9 Math.cbrt step 3, and every "implementation-approximated Number value" of the Math functions sec-math.cbrt

Return an implementation-approximated Number value representing the cube root of ℝ(n).

Approx answers a Number, the state as it was.

approx
Lean
approx : H.asks Known.pApprox fun _ _ r => ∃ n, r = .num n
6.1.6.1.3 Number::exponentiate step 13 sec-numeric-types-number-exponentiate

Return an implementation-approximated Number value representing the result of raising ℝ(base) to the ℝ(exponent) power.

ApproxPower(base, exponent) answers a Number, the state as it was.

approxPower
Lean
approxPower : H.asks Known.pApproxPower fun _ _ r => ∃ n, r = .num n
19.2.5 parseInt step 11 sec-parseint-string-radix

mathInt may be an implementation-approximated integer representing the integer value denoted by numberString in radix-radixMV notation

ApproxInteger answers an integer, the state as it was.

approxInteger
Lean
approxInteger : ∀ (x : M.Math) s r s', H.choice Known.pApproxInteger [.math x] s = .ok r s' →  s' = s ∧ ∃ m, r = .math m ∧ M.isInt m = true
No sentence ECMA-262 sets no maximum size of a BigInt (sec-ecmascript-language-types-bigint-type: "The value may be any size and is not limited to a particular bit-width"); the proposed reading of erratum BigIntMaximumSize, a proposed normative change, asks the host whether a result would exceed the implementation's maximum.

BigIntTooLarge answers a Boolean, the state as it was.

bigIntTooLarge
Lean
bigIntTooLarge : H.asks Known.pBigIntTooLarge fun _ _ r => ∃ b, r = .bool b
No sentence ECMA-262 defines String values up to length 2^53 - 1 and leaves implementations' smaller maximum String lengths unspecified; the proposed reading of erratum StringMaximumLength asks the host whether a String of length len exceeds the implementation's maximum String length.

StringTooLarge answers a Boolean, the state as it was.

stringTooLarge
Lean
stringTooLarge : H.asks Known.pStringTooLarge fun _ _ r => ∃ b, r = .bool b
7.1.4.1.3 RoundMVResult step 4, and every "implementation-defined choice of either" two values sec-roundmvresult

Let chosen be an implementation-defined choice of either option1 or option2.

HostChoice answers one of its arguments, the state as it was.

hostChoice
Lean
hostChoice : H.asks Known.pHostChoice fun vs _ r => r ∈ vs
21.3.2.28 Math.random sec-math.random

This function returns a Number value with positive sign, greater than or equal to +0𝔽 but strictly less than 1𝔽

Math.random answers such a Number (unitNum), never an abrupt completion, the state as it was.

mathRandom
Lean
mathRandom : ∀ c xs s r s', Gen.clauses[c]? = some "sec-math.random" → H.answers c xs s r s' →  s' = s ∧ ∃ n, r = .num n ∧ unitNum n

The laws of the host hooks

From lean/Ecma/Host/Laws/Hooks.lean

What every host hook returns, and the hooks that must answer alike at every call (sec-hosts-and-implementations).

structure

Host.HookLaws

Hooks.lean:18

The laws of the host hooks.

Proved as part of Host.WF.

structure Host.HookLaws (H : Host M) : Prop where

5 laws

4.2 Hosts and Implementations sec-hosts-and-implementations

A host hook must conform to at least the following requirements: It must return either a normal completion or a throw completion.

A host hook's answer is no break, continue or return completion (a value that is no Completion Record is a normal completion's).

hookCompletion
Lean
hookCompletion : ∀ c xs s r s', H.answers c xs s r s' → compType r = Known.eNormal ∨ compType r = Known.eThrow
7.3.29 HostEnsureCanAddPrivateElement the requirements sec-hostensurecanaddprivateelement

Any two calls of this abstract operation with the same argument must return the same kind of Completion Record.

The [[Type]] of HostEnsureCanAddPrivateElement's answer is one function of its argument, whatever the state of the call.

privateElementSameKind
Lean
privateElementSameKind : ∃ kind : List (Val M) → EnumId, ∀ c xs s r s',  Gen.clauses[c]? = some "sec-hostensurecanaddprivateelement" → H.answers c xs s r s' → compType r = kind xs
16.2.1.12.1 HostGetSupportedImportAttributes the requirements sec-hostgetsupportedimportattributes

It must return a List of Strings, each indicating a supported attribute. Each time this operation is called, it must return the same List with the same contents in the same order.

Every call answers a List of the same Strings in the same order (the default's new empty List at each call conforms, so "the same List" is its contents).

supportedImportAttributes
Lean
supportedImportAttributes : ∃ ids : List M.Str, ∀ c xs s r s',  Gen.clauses[c]? = some "sec-hostgetsupportedimportattributes" → H.answers c xs s r s' →  listElems s' r = some (ids.map .str)
19.2.1.3 HostGetCodeForEval sec-hostgetcodeforeval

HostGetCodeForEval ( arg: an Object, ): a String or no-code

HostGetCodeForEval answers a String or no-code.

getCodeForEval
Lean
getCodeForEval : ∀ c xs s r s', Gen.clauses[c]? = some "sec-hostgetcodeforeval" → H.answers c xs s r s' →  (∃ e, r = .enum e ∧ Gen.enums[e]? = some "no-code") ∨ ∃ x, r = .str x
20.2.5 HostHasSourceTextAvailable the requirements sec-hosthassourcetextavailable

It must be deterministic with respect to its parameters. Each time it is called with a specific func as its argument, it must return the same result.

HostHasSourceTextAvailable's answer is one function of its argument, whatever the state of the call.

hasSourceTextAvailable
Lean
hasSourceTextAvailable : ∃ f : List (Val M) → Val M, ∀ c xs s r s',  Gen.clauses[c]? = some "sec-hosthassourcetextavailable" → H.answers c xs s r s' → r = f xs

The laws of what a host step may change

From lean/Ecma/Host/Laws/Changes.lean

The objects' invariants, the agent's fixed fields, the Realm's global object and its properties, extensions, execution contexts, the FinalizationRegistry cleanup, tail calls' resources, and collection.

def

discardedIn

Changes.lean:19

The log has a DiscardContextResources choice for the execution context ctx.

def discardedIn (log : List (HostCall M)) : Val M → Bool  | .ref a => log.any fun    | .choice q [.ref b] _ => q == Known.pDiscardContextResources && M.addrEq a b    | _ => false  | _ => false
def

liveContexts

Changes.lean:26

The execution contexts on the stack whose resources no DiscardContextResources choice discarded.

def liveContexts (s : State M) : Nat := (stackList s).countP (!discardedIn s.hostLog ·)
def

onlyPropsOf

Changes.lean:30

s' is s but for its heap, where every cell but g's is as it was and g keeps its internal slots: only g's own properties change, and new cells may be allocated.

def onlyPropsOf (g : M.Addr) (s s' : State M) : Prop :=  s' = { s with heap := s'.heap } ∧  (∀ a c, a ≠ g → M.heapGet s.heap a = some c → M.heapGet s'.heap a = some c) ∧  ∀ sl ps, M.heapGet s.heap g = some (.object sl ps) → ∃ ps', M.heapGet s'.heap g = some (.object sl ps')
def

onlyAdds

Changes.lean:38

s' is s but for its heap, where only the objects to admits gain own properties: every other cell is as it was, and such an object keeps its internal slots and the properties it had, and gains none unless its [[Extensible]] is true; new cells may be allocated.

def onlyAdds (to : M.Addr → Prop) (s s' : State M) : Prop :=  s' = { s with heap := s'.heap } ∧  (∀ a c, M.heapGet s.heap a = some c → (∀ sl ps, to a → c ≠ .object sl ps) → M.heapGet s'.heap a = some c) ∧  ∀ a sl ps, to a → M.heapGet s.heap a = some (.object sl ps) → ∃ ps', M.heapGet s'.heap a = some (.object sl ps') ∧    (∀ k v, M.propsGet ps k = some v → M.propsGet ps' k = some v) ∧    (M.recGet sl Known.fExtensible ≠ some (.bool true) → ∀ k, (M.propsGet ps' k).isSome → (M.propsGet ps k).isSome)
def

attrsAt

Changes.lean:46

The fields of the attribute Record that the property k of ps refers to in s.

def attrsAt (s : State M) (ps : M.Props (Val M)) (k : M.Str ⊕ M.Sym) : Option (M.Rec (Val M)) :=  match M.propsGet ps k with  | some (.ref p) => match M.heapGet s.heap p with    | some (.record _ fs) => some fs    | _ => none  | _ => none
def

attrsKept

Changes.lean:56

§6.1.7.3 at a non-configurable property, from its attributes fs to fs': every attribute but [[Writable]] and [[Value]] is as it was; [[Writable]] is as it was or turns from true to false; [[Value]] is as it was unless [[Writable]] was true.

def attrsKept (fs fs' : M.Rec (Val M)) : Prop :=  (∀ f, f ≠ Known.fWritable → f ≠ Known.fValue → M.recGet fs' f = M.recGet fs f) ∧  (M.recGet fs' Known.fWritable = M.recGet fs Known.fWritable ∨    M.recGet fs Known.fWritable = some (.bool true) ∧ M.recGet fs' Known.fWritable = some (.bool false)) ∧  (M.recGet fs Known.fWritable ≠ some (.bool true) → M.recGet fs' Known.fValue = M.recGet fs Known.fValue)
def

objKept

Changes.lean:66

sec-invariants-of-the-essential-internal-methods at an object, from slots sl and properties ps in s to sl' and ps' in s': [[Extensible]] is as it was or turns from true to false; an object whose [[Extensible]] is not true keeps its [[Prototype]] and gains no property; a non-configurable property stays, its attributes as attrsKept allows.

def objKept (s s' : State M) (sl : M.Rec (Val M)) (ps : M.Props (Val M)) (sl' : M.Rec (Val M))    (ps' : M.Props (Val M)) : Prop :=  (M.recGet sl' Known.fExtensible = M.recGet sl Known.fExtensible ∨    M.recGet sl Known.fExtensible = some (.bool true) ∧ M.recGet sl' Known.fExtensible = some (.bool false)) ∧  (M.recGet sl Known.fExtensible ≠ some (.bool true) → M.recGet sl' Known.fPrototype = M.recGet sl Known.fPrototype ∧    ∀ k, (M.propsGet ps' k).isSome → (M.propsGet ps k).isSome) ∧  ∀ k fs, attrsAt s ps k = some fs → M.recGet fs Known.fConfigurable ≠ some (.bool true) →    ∃ fs', attrsAt s' ps' k = some fs' ∧ attrsKept fs fs'
def

contextField

Changes.lean:77

The components every execution context has (§9.4 Table 26), and those of an ECMAScript code execution context (Table 27) and a generator's (Table 28).

def contextField (f : FieldId) : Prop :=  f = Known.fCodeState ∨ f = Known.fFunction ∨ f = Known.fRealm ∨ f = Known.fScriptOrModule ∨    f = Known.fLexicalEnvironment ∨ f = Known.fVariableEnvironment ∨ f = Known.fPrivateEnvironment ∨    f = Known.fGenerator
inductive

intrinsicOf

Changes.lean:86

a is one of realm's intrinsics in s: an object realm.[[Intrinsics]] holds, or one a property of an intrinsic holds ([[Value]], [[Get]] or [[Set]]). Right after CreateIntrinsics(realm) these are the objects it created (IntrinsicObjects: the well-known intrinsics and every object their properties hold).

inductive intrinsicOf (s : State M) (realm : M.Addr) : M.Addr → Prop  | named {k fs i k' is f a} : M.heapGet s.heap realm = some (.record k fs) →      M.recGet fs Known.fIntrinsics = some (.ref i) → M.heapGet s.heap i = some (.record k' is) →      M.recGet is f = some (.obj a) → intrinsicOf s realm a  | held {o sl ps key p k fs f a} : intrinsicOf s realm o → M.heapGet s.heap o = some (.object sl ps) →      M.propsGet ps key = some (.ref p) → M.heapGet s.heap p = some (.record k fs) →      (f = Known.fValue ∨ f = Known.fGetter ∨ f = Known.fSetter) → M.recGet fs f = some (.obj a) →      intrinsicOf s realm a
def

noForbiddenProps

Changes.lean:97

§17.1: a function object (one with a [[Call]]) has an own "caller" or "arguments" property in s' only if it had it in s.

def noForbiddenProps (s s' : State M) : Prop :=  ∀ a sl ps' k, M.heapGet s'.heap a = some (.object sl ps') → (M.recGet sl Known.fCall).isSome →    (M.strEq k (M.strLit "caller") = true ∨ M.strEq k (M.strLit "arguments") = true) →    (M.propsGet ps' (.inl k)).isSome → ∃ ps, M.heapGet s.heap a = some (.object sl ps) ∧ (M.propsGet ps (.inl k)).isSome
def

emptyCell

Changes.lean:103

c is a Record that reg.[[Cells]] contains, whose [[WeakRefTarget]] is empty.

def emptyCell (s : State M) (reg : Val M) (c : M.Addr) : Prop :=  ∃ r sl ps l xs o i k fs, reg = .obj r ∧ M.heapGet s.heap r = some (.object sl ps) ∧    M.recGet sl Known.fCells = some (.ref l) ∧ M.heapGet s.heap l = some (.list xs o) ∧    M.seqGet xs i = some (.ref c) ∧ M.heapGet s.heap c = some (.record k fs) ∧    M.recGet fs Known.fWeakRefTarget = some (.enum Known.eEmpty)
def

agentFixedField

Changes.lean:111

The Agent Record fields whose values cannot change (§9.7: [[LittleEndian]], [[Signifier]], [[IsLockFreeN]]) and [[GlobalSymbolRegistry]], which is never reassigned.

def agentFixedField (f : FieldId) : Prop :=  f = fieldNamed "LittleEndian" ∨ f = fieldNamed "Signifier" ∨ f = fieldNamed "IsLockFree1" ∨    f = fieldNamed "IsLockFree2" ∨ f = fieldNamed "IsLockFree8" ∨ f = fieldNamed "GlobalSymbolRegistry"
def

agentKept

Changes.lean:117

From s to s', the surrounding agent is the same, and its Agent Record keeps its sort and the fields agentFixedField names.

def agentKept (s s' : State M) : Prop :=  s'.agent = s.agent ∧ ∀ a k fs, s.agent = .ref a → M.heapGet s.heap a = some (.record k fs) →    ∃ fs', M.heapGet s'.heap a = some (.record k fs') ∧ ∀ f, agentFixedField f → M.recGet fs' f = M.recGet fs f

Collection (sec-weakref-execution).

def

keptAlive

Changes.lean:124

v is in the [[KeptAlive]] List of an agent's Agent Record in s.

def keptAlive (s : State M) (v : Val M) : Prop :=  ∃ ag l xs, isRecordOf s "Agent Record" ag = true ∧ fieldOf s (fieldNamed "KeptAlive") ag = some l ∧    listAt s l = some xs ∧ v ∈ xs
def

weakMapEntry

Changes.lean:129

a is a Record a WeakMap's [[WeakMapData]] List contains.

def weakMapEntry (s : State M) (a : M.Addr) : Prop :=  ∃ o sl ps l es, M.heapGet s.heap o = some (.object sl ps) ∧ M.recGet sl (fieldNamed "WeakMapData") = some l ∧    listAt s l = some es ∧ Val.ref a ∈ es
def

weakSetData

Changes.lean:134

a is the List a WeakSet's [[WeakSetData]] is.

def weakSetData (s : State M) (a : M.Addr) : Prop :=  ∃ o sl ps, M.heapGet s.heap o = some (.object sl ps) ∧ M.recGet sl (fieldNamed "WeakSetData") = some (.ref a)
def

Rec.Emptied

Changes.lean:138

fs' is fs with the fields gs set to empty where its field k is an element of xs, else fs.

def Rec.Emptied (xs : List (Val M)) (k : FieldId) (gs : List FieldId) (fs fs' : M.Rec (Val M)) : Prop :=  (∃ v ∈ xs, M.recGet fs k = some v) ∧ fs' = gs.foldl (fun r g => M.recSet r g (.enum Known.eEmpty)) fs ∨    (¬∃ v ∈ xs, M.recGet fs k = some v) ∧ fs' = fs
def

Cell.Emptied

Changes.lean:146

The cell c at a becomes c' by sec-weakref-execution's steps for the set xs: a WeakRef's and a FinalizationRegistry cell's [[WeakRefTarget]] in xs is set to empty; a WeakMap entry whose [[Key]] is in xs has its [[Key]] and [[Value]] set to empty; a WeakSet's elements in xs are replaced by empty; nothing else changes.

def Cell.Emptied (s : State M) (xs : List (Val M)) (a : M.Addr) : Cell M → Cell M → Prop  | .object sl ps, .object sl' ps' => ps' = ps ∧ Rec.Emptied xs Known.fWeakRefTarget [Known.fWeakRefTarget] sl sl'  | .record k fs, .record k' fs' => k' = k ∧      (weakMapEntry s a ∧ Rec.Emptied xs (fieldNamed "Key") [fieldNamed "Key", Known.fValue] fs fs' ∨        ¬weakMapEntry s a ∧ Rec.Emptied xs Known.fWeakRefTarget [Known.fWeakRefTarget] fs fs')  | .list ys o, .list ys' o' => o' = o ∧ (¬weakSetData s a → ys' = ys) ∧ M.seqLen ys' = M.seqLen ys ∧      ∀ i v, M.seqGet ys i = some v →        v ∈ xs ∧ M.seqGet ys' i = some (.enum Known.eEmpty) ∨ v ∉ xs ∧ M.seqGet ys' i = some v  | c, c' => c' = c
def

Machine.Kont.Holds

Changes.lean:157

Values held directly by a continuation.

def Machine.Kont.Holds {M : Model} : Machine.Kont M → Val M → Prop  | .args _ done _, v => v ∈ done  | .all _ xs, v => v ∈ xs  | .bind w, v => v = w  | .scope (.passed outer inner), v => v ∈ outer ∨ v ∈ inner  | .loop l, v | .test l, v => match l.st with    | .each a _ _ | .keys a _ => v = .ref a    | _ => False  | .tstep _ _ _ key env _ _ _, v => v = key ∨ v ∈ env  | _, _ => False
def

Machine.Frame.Holds

Changes.lean:169

Values directly in a suspended execution context's frame.

def Machine.Frame.Holds {M : Model} (fr : Machine.Frame M) (v : Val M) : Prop :=  v ∈ fr.slots.toList ∨ ∃ k ∈ fr.konts, k.Holds v
def

Val.Holds

Changes.lean:173

Subvalues referenced by a compound value.

def Val.Holds {M : Model} : Val M → Val M → Prop  | .comp _ x y, v => v = x ∨ v = y  | .clo _ caps, v => v ∈ caps  | .ty _ _ _ env, v => v ∈ env  | .cond _ _ _ _ env, v => v ∈ env  | .tuple vs, v => v ∈ vs  | _, _ => False
inductive

Reachable

Changes.lean:185

§9.9.2 (sec-liveness): values strongly reachable from the roots of s without following weak references (WeakRef.[[WeakRefTarget]], WeakSet.[[WeakSetData]], WeakMap.[[WeakMapData]] entries whose [[Key]] is not itself reachable, or FinalizationRegistry cell [[WeakRefTarget]] / [[UnregisterToken]] fields).

Lean, 39 lines
inductive Reachable (s : State M) : Val M → Prop  | stack {v} : v ∈ stackList s → Reachable s v  | resumed : Reachable s s.resumed  | suspended : Reachable s s.suspended  | agent : Reachable s s.agent  | evalStep {p} : p ∈ s.evalSteps → Reachable s p.2  | passed {v} : v ∈ s.passed → Reachable s v  | waiterBlock {b i w} : (b, i, w) ∈ s.waiterLists → Reachable s (.ref b)  | waiterRec {b i w} : (b, i, w) ∈ s.waiterLists → Reachable s (.ref w)  | critical {w} : w ∈ s.critical → Reachable s (.ref w)  | shared {b} : b ∈ s.shared → Reachable s (.ref b)  | frame {ctx frs fr v} : (ctx, frs) ∈ s.frames → Reachable s (.ref ctx) →      fr ∈ frs → fr.Holds v → Reachable s v  | val {u v} : Reachable s u → u.Holds v → Reachable s v  | objSlot {a sl ps f v} : Reachable s (.obj a) → M.heapGet s.heap a = some (.object sl ps) →      f ≠ Known.fWeakRefTarget → f ≠ fieldNamed "WeakMapData" →      f ≠ fieldNamed "WeakSetData" → f ≠ Known.fCells →      M.recGet sl f = some v → Reachable s v  | objKeySym {a sl ps sym u} : Reachable s (.obj a) → M.heapGet s.heap a = some (.object sl ps) →      M.propsGet ps (.inr sym) = some u → Reachable s (.sym sym)  | objProp {a sl ps k v} : Reachable s (.obj a) → M.heapGet s.heap a = some (.object sl ps) →      M.propsGet ps k = some v → Reachable s v  | finRegHeld {a sl ps l cs c k fs v} : Reachable s (.obj a) → M.heapGet s.heap a = some (.object sl ps) →      M.recGet sl Known.fCells = some (.ref l) → listAt s (.ref l) = some cs →      .ref c ∈ cs → M.heapGet s.heap c = some (.record k fs) →      M.recGet fs (fieldNamed "HeldValue") = some v → Reachable s v  | weakMapVal {a sl ps l es e ek fs k v} : Reachable s (.obj a) → M.heapGet s.heap a = some (.object sl ps) →      M.recGet sl (fieldNamed "WeakMapData") = some (.ref l) → listAt s (.ref l) = some es →      .ref e ∈ es → M.heapGet s.heap e = some (.record ek fs) →      M.recGet fs (fieldNamed "Key") = some k → Reachable s k →      M.recGet fs Known.fValue = some v → Reachable s v  | recField {a k fs f v} : Reachable s (.ref a) → M.heapGet s.heap a = some (.record k fs) →      M.recGet fs f = some v → Reachable s v  | listElem {a xs o v} : Reachable s (.ref a) → M.heapGet s.heap a = some (.list xs o) →      v ∈ seqList xs → Reachable s v  | envField {a k fs b f v} : Reachable s (.ref a) → M.heapGet s.heap a = some (.env k fs b) →      M.recGet fs f = some v → Reachable s v  | envBind {a k fs b nm v} : Reachable s (.ref a) → M.heapGet s.heap a = some (.env k fs b) →      M.propsGet b nm = some v → Reachable s v
def

Collected

Changes.lean:228

sec-weakref-execution: s' is s after the steps, performed atomically, for the set xs of objects and Symbols, none of them in an agent's [[KeptAlive]] List or strongly reachable (Reachable) (sec-liveness): every cell as Cell.Emptied says, every other component as it was.

def Collected (s : State M) (xs : List (Val M)) (s' : State M) : Prop :=  (∀ x ∈ xs, ((∃ a, x = .obj a) ∨ ∃ y, x = .sym y) ∧ ¬keptAlive s x ∧ ¬Reachable s x) ∧    s' = { s with heap := s'.heap } ∧    ∀ a, (M.heapGet s'.heap a).isSome = (M.heapGet s.heap a).isSome ∧      ∀ c, M.heapGet s.heap a = some c → ∃ c', M.heapGet s'.heap a = some c' ∧ Cell.Emptied s xs a c c'
structure

Host.ChangeLaws

Changes.lean:235

The laws of what a host step may change.

Proved as part of Host.WF.

structure Host.ChangeLaws (H : Host M) : Prop where

14 laws

6.1.7.3 Invariants of the Essential Internal Methods sec-invariants-of-the-essential-internal-methods

An implementation must not allow these invariants to be circumvented in any manner such as by providing alternative interfaces that implement the functionality of the essential internal methods without enforcing their invariants.

Across a host step every object is still an object and keeps to the invariants (objKept).

invariantsKept
Lean
invariantsKept : ∀ s s', H.Step s s' → ∀ a sl ps, M.heapGet s.heap a = some (.object sl ps) →  ∃ sl' ps', M.heapGet s'.heap a = some (.object sl' ps') ∧ objKept s s' sl ps sl' ps'
9.6 Agents sec-agents

The values of [[LittleEndian]], [[Signifier]], [[IsLockFree1]], [[IsLockFree2]], and [[IsLockFree8]] cannot change.

The [[GlobalSymbolRegistry]] List is append-only and never reassigned.

A host step keeps the surrounding agent, its Agent Record's sort and those fields (agentKept).

agentFixed
Lean
agentFixed : ∀ s s', H.Step s s' → agentKept s s'
9.3.1 InitializeHostDefinedRealm steps 10–10.a sec-initializehostdefinedrealm

If the host requires use of a specific object to serve as realm's global object, then … Let global be such an object created in a host-defined manner.

HostGlobalObject answers empty (the state as it was) or an Object.

hostGlobalObject
Lean
hostGlobalObject : ∀ vs s r s', H.choice Known.pHostGlobalObject vs s = .ok r s' →  r = .enum Known.eEmpty ∧ s' = s ∨ ∃ a, r = .obj a
9.3.1 InitializeHostDefinedRealm steps 12–12.a sec-initializehostdefinedrealm

If the host requires that the this binding in realm's global scope return an object other than the global object, then … Let thisValue be such an object created in a host-defined manner.

HostThisValue answers empty (the state as it was) or an Object.

hostThisValue
Lean
hostThisValue : ∀ vs s r s', H.choice Known.pHostThisValue vs s = .ok r s' →  r = .enum Known.eEmpty ∧ s' = s ∨ ∃ a, r = .obj a
9.3.1 InitializeHostDefinedRealm step 17 sec-initializehostdefinedrealm

Create any host-defined global object properties on global.

HostGlobalProperties answers unused and changes only global's own properties (onlyPropsOf).

hostGlobalProperties
Lean
hostGlobalProperties : ∀ realm g s r s', H.choice Known.pHostGlobalProperties [realm, .obj g] s = .ok r s' →  r = .enum Known.eUnused ∧ onlyPropsOf g s s'
2 Conformance sec-conformance

a conforming implementation of ECMAScript may provide properties not described in this specification, and values for those properties, for objects that are described in this specification

17.1 Forbidden Extensions sec-forbidden-extensions

Built-in functions, strict functions created using the Function constructor, generator functions created using the Generator constructor, async functions created using the AsyncFunction constructor, and functions created using the bind method also must not be created with such own properties.

HostExtendIntrinsics(realm) answers unused and only adds own properties to realm's intrinsics (intrinsicOf), none to an object whose [[Extensible]] is not true, and no "caller" or "arguments" to a function.

hostExtendIntrinsics
Lean
hostExtendIntrinsics : ∀ vs s r s', H.choice Known.pHostExtendIntrinsics vs s = .ok r s' →  r = .enum Known.eUnused ∧ onlyAdds (fun a => ∃ realm, vs = [.ref realm] ∧ intrinsicOf s realm a) s s' ∧    noForbiddenProps s s'
2 Conformance sec-conformance

a conforming implementation of ECMAScript may provide properties not described in this specification, and values for those properties, for objects that are described in this specification

HostExtendObject(o) answers unused and only adds own properties to o, none if its [[Extensible]] is not true, and no "caller" or "arguments" to a function.

hostExtendObject
Lean
hostExtendObject : ∀ o s r s', H.choice Known.pHostExtendObject [.obj o] s = .ok r s' →  r = .enum Known.eUnused ∧ onlyAdds (· = o) s s' ∧ noForbiddenProps s s'
10.3.3 BuiltinCallOrConstruct step 8 sec-builtincallorconstruct

Perform any necessary implementation-defined initialization of calleeContext.

HostInitializeBuiltinContext answers unused and changes only calleeContext, which keeps its kind and every component the execution context tables define (contextField).

hostInitializeBuiltinContext
Lean
hostInitializeBuiltinContext : ∀ ctx s r s', H.choice Known.pHostInitializeBuiltinContext [.ref ctx] s = .ok r s' →  r = .enum Known.eUnused ∧ s' = { s with heap := s'.heap } ∧    (∀ a c, a ≠ ctx → M.heapGet s.heap a = some c → M.heapGet s'.heap a = some c) ∧    ∀ k fs, M.heapGet s.heap ctx = some (.record k fs) → ∃ fs', M.heapGet s'.heap ctx = some (.record k fs') ∧      ∀ f, contextField f → M.recGet fs' f = M.recGet fs f
9.9.4.1 HostEnqueueFinalizationRegistryCleanupJob step 2 sec-host-cleanup-finalization-registry

If cleanupResult is an abrupt completion, perform any host-defined steps for reporting the error.

HostReportCleanupError answers unused.

hostReportCleanupError
Lean
hostReportCleanupError : ∀ vs s r s', H.choice Known.pHostReportCleanupError vs s = .ok r s' →  r = .enum Known.eUnused
No sentence HostReportErrors is HTML's report-an-exception hook called by the readings overlay on an abrupt settle result of a PromiseReactionJob.

HostReportErrors answers unused.

hostReportErrors
Lean
hostReportErrors : ∀ vs s r s', H.choice Known.pHostReportErrors vs s = .ok r s' →  r = .enum Known.eUnused
9.12 CleanupFinalizationRegistry step 3 sec-cleanup-finalization-registry

While finalizationRegistry.[[Cells]] contains a Record cell such that cell.[[WeakRefTarget]] is empty, an implementation may perform the following steps: 1. Choose any such cell.

MayCleanup answers empty or such a cell (emptyCell), the state as it was.

mayCleanup
Lean
mayCleanup : ∀ reg s r s', H.choice Known.pMayCleanup [reg] s = .ok r s' →  s' = s ∧ (r = .enum Known.eEmpty ∨ ∃ c, r = .ref c ∧ emptyCell s reg c)
15.10.3 PrepareForTailCall step 2 sec-preparefortailcall

Discard all resources associated with the current execution context.

DiscardContextResources answers unused, the state as it was.

discardContextResources
Lean
discardContextResources : H.asks Known.pDiscardContextResources fun _ _ r => r = .enum Known.eUnused
15.10.3 PrepareForTailCall sec-preparefortailcall

A tail position call must either release any transient internal resources associated with the currently executing function execution context before invoking the target function or reuse those resources in support of the target function.

The host's resources run out at a push onto the execution context stack (Host.exhausts) only while some context on it holds resources no DiscardContextResources discarded (liveContexts).

contextResources
Lean
contextResources : ∀ s, H.exhausts s = true → 0 < liveContexts s
9.9.3 Execution sec-weakref-execution

At any time, if a set of objects and/or symbols objSet is not live, an ECMAScript implementation may perform the following steps atomically

9.9.2 Liveness sec-liveness

Any element in objSet is included in any agent's [[KeptAlive]] List.

The host's collection empties, together, the WeakRefs, FinalizationRegistry cells, WeakMap entries and WeakSet elements of a set of objects and Symbols none of which is kept alive, and changes nothing else (Collected); a host that collects nothing meets it.

collect
Lean
collect : ∀ s xs s', H.collect s = .ok xs s' → Collected s xs s'

What the host's laws are stated over

From lean/Ecma/Host/Laws/Basic.lean

A host's answer (Host.answers, Host.asks), a host step (Host.Step), and the readings of the state the laws share: Completion Records' kinds, Records by sort, the execution context stack, Strings as code units, and the agent and elapsed-time helpers.

def

selects

Basic.lean:22

A HostSelectAgent answer that selects an agent.

def selects {M : Model} : Val M → Bool  | .ref _ => true  | _ => false
def

numValue

Basic.lean:27

The mathematical value of a finite or zero Number; none for ±∞𝔽 and NaN.

def numValue {M : Model} (n : M.Num) : Option M.Math :=  match M.numView n with  | .posZero | .negZero => some (M.ofNat 0)  | .finite m => some m  | _ => none
def

lastElapsed

Basic.lean:34

The elapsed time the newest next of the log logged; 0 where there is none.

def lastElapsed {M : Model} : List (HostCall M) → M.Math  | [] => M.ofNat 0  | .next _ t :: _ => t  | _ :: log => lastElapsed log
def

mathAfter

Basic.lean:40

t₁ ≥ t₀ + ℝ(ms): never for ms +∞, always for ms −∞ or NaN.

def mathAfter {M : Model} (t₀ t₁ : M.Math) (ms : M.Num) : Bool :=  match numValue ms with  | some m => !M.lt t₁ (M.add t₀ m)  | none => match M.numView ms with    | .posInf => false    | _ => true
def

fieldOf

Basic.lean:48

A field of the Record a value refers to.

def fieldOf {M : Model} (s : State M) (f : FieldId) : Val M → Option (Val M)  | .ref a => match M.heapGet s.heap a with    | some (.record _ fs) => M.recGet fs f    | _ => none  | _ => none
def

slotOf

Basic.lean:55

An internal slot of the object at a.

def slotOf {M : Model} (s : State M) (a : M.Addr) (f : FieldId) : Option (Val M) :=  match M.heapGet s.heap a with  | some (.object sl _) => M.recGet sl f  | _ => none
def

listElems

Basic.lean:61

The elements of the List a value refers to.

def listElems {M : Model} (s : State M) : Val M → Option (List (Val M))  | .ref a => match M.heapGet s.heap a with    | some (.list xs _) => some (M.seqFoldl (fun l v => l ++ [v]) [] xs)    | _ => none  | _ => none
def

HostCall.switchFrom

Basic.lean:68

A logged HostSelectAgent that selected an agent: the surrounding agent it was called in.

def HostCall.switchFrom {M : Model} : HostCall M → Option (Val M)  | .choice q (a :: _) (.ref _) => if q == Known.pHostSelectAgent then some a else none  | _ => none
def

withAgents

Basic.lean:74

The log (newest first), each call with the agent it ran in: cur after the newest switch, a switch's surrounding agent at it and before it.

def withAgents {M : Model} (cur : Val M) : List (HostCall M) → List (HostCall M × Val M)  | [] => []  | e :: log => let a := e.switchFrom.getD cur; (e, a) :: withAgents a log
def

sigOf

Basic.lean:79

An Agent Record's signifier, its [[Signifier]].

def sigOf {M : Model} (s : State M) (x : Val M) : Val M := (fieldOf s Known.fSignifier x).getD .absent
def

isEmptyV

Basic.lean:82

empty.

def isEmptyV {M : Model} : Val M → Bool  | .enum e => e == Known.eEmpty  | _ => false
def

pendingList

Basic.lean:87

The waiter list of the agent x's pending suspension (signifier sig) in a log with agents.

def pendingList {M : Model} (x sig : Val M) : List (HostCall M × Val M) → Option (Val M)  | [] => none  | (.choice q vs _, a) :: es =>    if q == Known.pWakeAgent && vs.any (Val.same sig) then none    else if q == Known.pSuspendAgentUntil && Val.same a x then vs.head?    else pendingList x sig es  | _ :: es => pendingList x sig es
def

idleWait

Basic.lean:97

The agent x's pending suspension is the host's own wait for a message or a job: its waiter list is empty (SuspendThisAgent's is a WaiterList).

def idleWait {M : Model} (s : State M) (x : Val M) : Bool :=  ((pendingList x (sigOf s x) (withAgents s.agent s.hostLog)).map isEmptyV).getD false
def

jobAgentOf

Basic.lean:103

The signifier of the agent whose job a logged call e, run in the agent a, schedules: its realm's [[AgentSignifier]] (§9.5: "in the agent signified by realm.[[AgentSignifier]]"), else (a promise job of no realm) a's.

def jobAgentOf {M : Model} (s : State M) : HostCall M × Val M → Val M  | (.hook _ (_ :: realm :: _) _ _ _, a) => (fieldOf s Known.fAgentSignifier realm).getD (sigOf s a)  | (_, a) => sigOf s a
def

jobAgents

Basic.lean:108

The signifiers of the agents of the jobs the log's calls schedule, by log position.

def jobAgents {M : Model} (s : State M) : Array (Val M) :=  ((withAgents s.agent s.hostLog).map (jobAgentOf s)).reverse.toArray
def

clusterSigs

Basic.lean:113

The signifiers of the surrounding agent's cluster: its candidate execution's Agent Events Records' [[AgentSignifier]]s.

def clusterSigs {M : Model} (s : State M) : List (Val M) :=  match ((fieldOf s Known.fCandidateExecution s.agent).bind (fieldOf s Known.fEventsRecords)).bind (listElems s) with  | some ers => ers.filterMap (fieldOf s Known.fAgentSignifier)  | none => []
def

Host.answers

Basic.lean:122

r is the host-defined operation c's answer to xs in s, the state then s'; an escaping completion is its answer.

def Host.answers (H : Host M) (c : ClauseId) (xs : List (Val M)) (s : State M) (r : Val M) (s' : State M) : Prop :=  Run.boundary (H.hook c xs) s = .ok r s'
def

Host.asks

Basic.lean:126

The host answers the question q without changing the state, and its answer has P.

def Host.asks (H : Host M) (q : PrimId) (P : List (Val M) → State M → Val M → Prop) : Prop :=  ∀ vs s r s', H.choice q vs s = .ok r s' → s' = s ∧ P vs s r
def

Host.Step

Basic.lean:132

A host step from s to s': a host-defined operation's or a host choice's answer, the next job, whether to clear kept objects, a job's preparation or cleanup, the host's own first Job, what it does when the agent has no Job, and its cleanup after either.

def Host.Step (H : Host M) (s s' : State M) : Prop :=  (∃ c xs r, H.answers c xs s r s') ∨ (∃ q vs r, Run.boundary (H.choice q vs) s = .ok r s') ∨    (∃ k, H.nextJob s = .ok k s') ∨ (∃ b, H.clearsKept s = .ok b s') ∨    (∃ k, H.prepareJob k s = .ok () s') ∨ (∃ k, H.cleanupJob k s = .ok () s') ∨    (∃ a, H.first s = .ok a s') ∨ (∃ a, H.idle s = .ok a s') ∨ ∃ v b, H.idleEnd v s = .ok b s'
def

compType

Basic.lean:139

A Completion Record's [[Type]]; a value that is no Completion Record is a normal completion's.

def compType : Val M → EnumId  | .comp t _ _ => t  | _ => Known.eNormal
def

normalValue

Basic.lean:144

The value of a normal completion; a value that is no Completion Record is its own.

def normalValue : Val M → Option (Val M)  | .comp t v _ => if t == Known.eNormal then some v else none  | v => some v
def

dataSubSort

Basic.lean:149

k is the sort t or a subsort of it, by the data's SortDef.super (to depth f).

def dataSubSort : Nat → SortId → SortId → Bool  | 0, k, t => k == t  | f + 1, k, t => k == t || (((Gen.sortDefs[k]?).join.map (·.super)).getD []).any (dataSubSort f · t)
def

isRecordOf

Basic.lean:154

A value is a Record of the sort named sort, or of a subsort of it.

def isRecordOf (s : State M) (sort : String) : Val M → Bool  | .ref a => match M.heapGet s.heap a, Gen.sorts.idxOf? sort with    | some (.record k _), some t => dataSubSort 64 k t    | _, _ => false  | _ => false
def

fieldNamed

Basic.lean:161

A field id by its name in the data.

def fieldNamed (f : String) : FieldId := (Gen.fields.idxOf? f).getD 0
def

stackList

Basic.lean:164

The execution context stack as a List, the topmost last.

def stackList (s : State M) : List (Val M) := M.seqFoldl (fun l v => l ++ [v]) [] s.stack
def

listAt

Basic.lean:167

The elements of the List a value refers to.

def listAt (s : State M) : Val M → Option (List (Val M))  | .ref a => match M.heapGet s.heap a with    | some (.list sq _) => some (seqList sq)    | _ => none  | _ => none
def

unitsMatch

Basic.lean:174

The code units us are the naturals l.

def unitsMatch : List M.Math → List Nat → Prop  | [], [] => True  | u :: us, c :: l => M.eq u (M.ofNat c) = true ∧ unitsMatch us l  | _, _ => False
def

unitsAre

Basic.lean:180

The String x's code units are l.

def unitsAre (x : M.Str) (l : List Nat) : Prop := unitsMatch (seqList (M.strUnits x)) l

The Date Time String Format, over code units

From lean/Ecma/Host/Laws/DateFormat.lean

The Strings of the Date Time String Format (sec-date-time-string-format) as integers and code units: what ParseDateString's laws (Ecma.Host.TimeLaws) are stated over.

def

decUnits

DateFormat.lean:17

The last n decimal digits of v, the most significant first, as code units.

def decUnits : Nat → Nat → List Nat  | 0, _ => []  | n + 1, v => (48 + v / 10 ^ n % 10) :: decUnits n v
def

numIs

DateFormat.lean:22

n is the integral Number t: +0𝔽 for 0, else the finite Number whose value is t.

def numIs {M : Model} (n : M.Num) (t : Int) : Prop :=  if t = 0 then M.numView n = .posZero else ∃ m, M.numView n = .finite m ∧ M.eq m (intMath t) = true
def

tvResult

DateFormat.lean:26

r is the time value of the instant t: t where it is in range, else NaN.

def tvResult {M : Model} (r : Val M) (t : Int) : Prop :=  ∃ n, r = .num n ∧ if inTime t then numIs n t else M.numView n = .nan
def

daysInMonth

DateFormat.lean:30

The days of month mo (1 to 12) of year y.

def daysInMonth (y : Int) (mo : Nat) : Nat :=  [31, 28 + leapDays y, 31, 30, 31, 30, 31, 31, 30, 31, 30, 31].getD (mo - 1) 0
structure

DateTimePart

DateFormat.lean:36

A date-time form's time part (§21.4.1.32): THH:mm, then optionally :ss and then optionally .sss, then the UTC offset representation: none, "Z" (some none), or a sign (true for "-"), HH, ":" and mm.

structure DateTimePart where
h : Nat
mi : Nat
sec : Option (Nat × Option Nat)
off : Option (Option (Bool × Nat × Nat))
structure

DateForm

DateFormat.lean:45

A String of the Date Time String Format's shape (§21.4.1.32): YYYY, or an expanded year's sign (true for "-") and six digits; optionally -MM and then optionally -DD; optionally a time part.

structure DateForm where
sign : Option Bool
md : Option (Nat × Option Nat)
def

DateForm.signUnits

DateFormat.lean:54

"-" or "+".

def signUnits (neg : Bool) : List Nat := if neg then [45] else [43]
def

DateForm.offUnits

DateFormat.lean:57

The UTC offset representation's code units.

def offUnits : Option (Option (Bool × Nat × Nat)) → List Nat  | none => []  | some none => [90]  | some (some (n, h, m)) => signUnits n ++ decUnits 2 h ++ [58] ++ decUnits 2 m
def

DateForm.secPart

DateFormat.lean:63

:ss and .sss's code units.

def secPart : Option (Nat × Option Nat) → List Nat  | none => []  | some (sc, none) => [58] ++ decUnits 2 sc  | some (sc, some ms) => [58] ++ decUnits 2 sc ++ [46] ++ decUnits 3 ms
def

DateForm.timeUnits

DateFormat.lean:69

A time part's code units.

def timeUnits (p : DateTimePart) : List Nat :=  [84] ++ decUnits 2 p.h ++ [58] ++ decUnits 2 p.mi ++ secPart p.sec ++ offUnits p.off
def

DateForm.yearPart

DateFormat.lean:73

The year's code units.

def yearPart (f : DateForm) : List Nat :=  match f.sign with  | none => decUnits 4 f.year  | some n => signUnits n ++ decUnits 6 f.year
def

DateForm.mdPart

DateFormat.lean:79

-MM and -DD's code units.

def mdPart : Option (Nat × Option Nat) → List Nat  | none => []  | some (mo, none) => [45] ++ decUnits 2 mo  | some (mo, some d) => [45] ++ decUnits 2 mo ++ [45] ++ decUnits 2 d
def

DateForm.timePart

DateFormat.lean:85

The time part's code units, if any.

def timePart : Option DateTimePart → List Nat  | none => []  | some p => timeUnits p
def

DateForm.units

DateFormat.lean:90

The String's code units.

def units (f : DateForm) : List Nat := f.yearPart ++ mdPart f.md ++ timePart f.time
def

DateForm.yearInt

DateFormat.lean:93

The year.

def yearInt (f : DateForm) : Int := if f.sign = some true then -(f.year : Int) else f.year
def

DateForm.month

DateFormat.lean:95

The month, "01" where absent.

def month (f : DateForm) : Nat := (f.md.map (·.1)).getD 1
def

DateForm.day

DateFormat.lean:97

The day, "01" where absent.

def day (f : DateForm) : Nat := (f.md.bind (·.2)).getD 1
def

DateForm.hour

DateFormat.lean:99

The hour, "00" where absent.

def hour (f : DateForm) : Nat := (f.time.map (·.h)).getD 0
def

DateForm.minute

DateFormat.lean:101

The minute, "00" where absent.

def minute (f : DateForm) : Nat := (f.time.map (·.mi)).getD 0
def

DateForm.second

DateFormat.lean:103

The second, "00" where absent.

def second (f : DateForm) : Nat := (f.time.bind fun p => p.sec.map (·.1)).getD 0
def

DateForm.milli

DateFormat.lean:105

The millisecond, "000" where absent.

def milli (f : DateForm) : Nat := (f.time.bind fun p => p.sec.bind (·.2)).getD 0
def

DateForm.offset

DateFormat.lean:108

The UTC offset representation's sign, hours and minutes; none for "Z" or none.

def offset (f : DateForm) : Option (Bool × Nat × Nat) := (f.time.bind (·.off)).join
def

DateForm.offsetMin

DateFormat.lean:111

The UTC offset in minutes, 0 for "Z" or none.

def offsetMin (f : DateForm) : Int :=  match f.offset with  | some (n, h, m) => (if n then -1 else 1) * ((h * 60 + m : Nat) : Int)  | none => 0
def

DateForm.isLocal

DateFormat.lean:117

A date-time form without a UTC offset: a local time.

def isLocal (f : DateForm) : Bool := match f.time with  | some p => p.off.isNone  | none => false
def

DateForm.ms

DateFormat.lean:122

The time value of the fields, before the UTC offset is applied.

def ms (f : DateForm) : Int := dateMs f.yearInt f.month f.day f.hour f.minute f.second f.milli
def

DateForm.fits

DateFormat.lean:125

Each element's value has as many digits as the element.

def fits (f : DateForm) : Prop :=  f.year < (if f.sign.isSome then 10 ^ 6 else 10 ^ 4) ∧ f.month < 100 ∧ f.day < 100 ∧ f.hour < 100 ∧    f.minute < 100 ∧ f.second < 100 ∧ f.milli < 1000 ∧ ∀ n h m, f.offset = some (n, h, m) → h < 100 ∧ m < 100
def

DateForm.legal

DateFormat.lean:132

A valid instance of the format: each element in bounds, a day of the month, "24" only as 24:00, 24:00:00 or 24:00:00.000, an offset's HH from 00 to 23 (UTCOffset's Hour), and no year 0 as -000000 (§21.4.1.32.1).

def legal (f : DateForm) : Prop :=  1 ≤ f.month ∧ f.month ≤ 12 ∧ 1 ≤ f.day ∧ f.day ≤ daysInMonth f.yearInt f.month ∧    (f.hour ≤ 23 ∨ f.hour = 24 ∧ f.minute = 0 ∧ f.second = 0 ∧ f.milli = 0) ∧ f.minute ≤ 59 ∧ f.second ≤ 59 ∧    (∀ n h m, f.offset = some (n, h, m) → h ≤ 23 ∧ m ≤ 59) ∧ ¬(f.sign = some true ∧ f.year = 0)
def

DateForm.illegal

DateFormat.lean:139

An element out of the bounds the format's table gives it (MM 01 to 12, DD 01 to 31, HH 00 to 24, mm and ss 00 to 59), or the year 0 as -000000.

def illegal (f : DateForm) : Prop :=  f.month = 0 ∨ 12 < f.month ∨ f.day = 0 ∨ 31 < f.day ∨ 24 < f.hour ∨ 59 < f.minute ∨ 59 < f.second ∨    (∃ n h m, f.offset = some (n, h, m) ∧ (24 < h ∨ 59 < m)) ∨ (f.sign = some true ∧ f.year = 0)