Add shared human/task asset batches with reviewed atomic publication, explicit reference rebinds, ownership inspection and qualified glyph/scene budgets. Expose the same authoring and capacity results through Assets and MCP. Deliver isolated guest test targets, retained visual evidence and immutable runtime lifecycle/control observations. Preserve provider qualification and installed authoring examples alongside the completed discussion lessons. Close AGD-106 coordination and the delivered discussion workflows through housekeeping, updating lesson references and preserving qualification limits. Sound remains outside the asset delivery wave. Validation: 579 module tests and 31 additional desktop, process and installed checks passed; native glyph/scene 16/17 boundaries qualified. Discussion validation passed after housekeeping.
22 KiB
PBS Dynamic Semantics Specification
Status: Draft v1 (Temporary)
Applies to: runtime-observable behavior of PBS core programs
1. Purpose
This document defines the normative dynamic semantics of PBS core.
Its purpose is to make runtime behavior convergent across implementations by fixing:
- execution ordering,
- runtime evaluation of expressions and statements,
- abrupt completion and propagation behavior,
- runtime behavior of effect surfaces such as
optionalandresult, - the execution boundary between ordinary PBS code, function values, contract calls, and host-backed calls.
2. Scope
This document defines:
- the observable execution model of PBS core,
- evaluation order for expressions, statements, and blocks,
- runtime branch selection for
ifandswitch, - runtime application behavior for
apply, call sugar, methods, contracts, function values, and host-backed call surfaces, - runtime behavior of
optional,result<E>,else,!, andhandle, - abrupt completion (
return,break,continue) and trap propagation, - determinism requirements that affect execution behavior.
This document does not define:
- static typing or overload resolution rules,
- GC algorithm internals,
- exact IR shape or lowering passes,
- diagnostics catalog wording,
- the full PBX binary format.
3. Authority and Precedence
Normative precedence:
- Runtime authority (provider specifications; mirror and provenance policy)
- Bytecode authority (provider Core ISA)
3. Core Syntax Specification.md4. Static Semantics Specification.md- This document
If a rule here conflicts with higher authority, it is invalid.
4. Normative Inputs
This document depends on, at minimum:
1. Language Charter.md3. Core Syntax Specification.md4. Static Semantics Specification.md5. Manifest, Stdlib, and SDK Resolution Specification.md6.2. Host ABI Binding and Loader Resolution Specification.md
This document integrates the following accepted decisions:
discussion/lessons/DSC-0007-pbs-learn-to-discussion-lessons-migration/LSN-0020-pbs-runtime-values-identity-memory-boundaries-legacy.mddiscussion/lessons/DSC-0007-pbs-learn-to-discussion-lessons-migration/LSN-0022-pbs-globals-lifecycle-and-published-entrypoint-legacy.md
5. Already-Settled Inputs
The following inputs are already fixed elsewhere and must not be contradicted here:
- PBS prioritizes determinism and compatibility over ergonomics when the two conflict.
- The existing synthetic frame lifecycle remains preserved; PBS exposes no sync or coroutine construct.
- No non-deterministic async execution model is part of PBS v1.
- Function application is defined on the canonical
applysurface, with call sugar desugaring toapply. optional Tfunction fallthrough yieldsnone.result<E>function fallthrough is a compile-time error.ok(...)anderr(...)are special result-flow forms rather than ordinary first-class runtime constructors.- Lifecycle bootstrap is one-shot and fail-fast.
[Frame]denotes the logical userland frame root, not the physical published entrypoint by itself.
6. Execution Baseline
PBS execution is single-threaded per program instance in v1.
User-visible execution is deterministic and does not expose concurrent interleaving.
User-visible sequencing is defined by:
- evaluation order,
- branch selection,
- abrupt completion,
- result propagation,
- trap propagation,
- and host-call boundaries.
VM-internal frame layout, temporary storage, and lowering steps are not observable unless they change one of the semantic effects above.
PBS uses the existing synthetic frame lifecycle. Runtime GC opportunities, including successful root return, follow the runtime contract; there is no PBS sync statement.
6.1 Lifecycle bootstrap
Executable PBS programs have a logical bootstrap sequence before ordinary frame execution.
Normative order:
- materialize globals for each file according to dependency order,
- execute that file's non-project
[Init], if present, - compose those steps into one synthetic module init per module,
- execute project init exactly once, if present, after all module initializers,
- then invoke the userland callable marked with
[Frame].
The [Init] colocated with [Frame] is project init. It MUST NOT also run as a file-init fragment.
Lifecycle bootstrap is one-shot:
- no automatic retry occurs after boot failure,
- failure during module init aborts boot,
- failure during project init aborts boot.
Common lifecycle assembly materializes this order from the typed declaration. PBS remains the language source of marker meaning; it is not the owner of the published wrapper.
6.2 Logical frame root and physical wrapper
PBS distinguishes the logical frame root from the physical published entrypoint:
- the userland callable marked with
[Frame]is the logical frame root, - the compiler-published synthetic wrapper is the physical executable root,
- the wrapper owns final
FRAME_RET, - and the wrapper invokes the logical frame root after bootstrap is complete.
Nominal manifest metadata does not participate in this runtime boot choice.
7. Evaluation Order and Single Evaluation
7.1 Default rule
The default evaluation rule is strict left-to-right unless a construct explicitly states otherwise.
Boolean && and and are equivalent eager conjunction operators; || and or
are equivalent eager disjunction operators. None provides short-circuit
evaluation. Each operand is evaluated once, left then right, before the operation,
unless abrupt completion prevents subsequent evaluation. A false left operand
of conjunction or true left operand of disjunction does not skip the right one.
Use nested if when a later call or access must depend on a prior check:
if index >= 0 {
if index < values.length {
if let value = values[index] { consume(value); }
}
}
This is an illustrative body fragment; values, index and consume come from
the surrounding program. index < values.length && read(values[index]) does not
protect the access. The installed production examples count evaluation effects
and distinguish the safe guard from deliberately faulting eager operands.
7.2 Call evaluation
For application:
- form the call target,
- evaluate any receiver or callable artifact needed for target formation exactly once,
- evaluate arguments in source order from left to right,
- invoke the resolved target,
- produce one of:
- normal return,
- explicit
result<E>propagation, - or
trap.
This rule applies to canonical apply and to direct-call sugar that desugars to apply.
apply chains are parsed right-associatively, but their observable evaluation still follows the left-to-right rule above.
7.3 Exactly-once guarantees
The following expressions are evaluated exactly once where they appear:
ifcondition,switchselector,- the left operand of
opt else fallback, - the payload expression of
some(expr), - the operand of
expr!, - the operand of
handle expr { ... }, - explicit closure capture values,
- call receivers, callees, and argument expressions as required by the call rule above.
8. Blocks and Abrupt Completion
Statements in a block execute in source order.
Only the final unsemicoloned expression in a block contributes to the block result.
Abrupt completion terminates the current construct immediately and prevents later sibling evaluation.
At minimum, the following are abrupt-completion forms:
return,break,continue,!on an error path,trap.
9. optional
9.1 Runtime model
optional has exactly two runtime states:
some(payload)none
none is the canonical absence of payload.
9.2 Construction
some(expr) evaluates expr eagerly and exactly once before forming the some(payload) carrier.
9.3 Extraction
opt else fallback:
- evaluates the left operand exactly once,
- yields the extracted payload if that operand evaluates to
some(payload), - otherwise evaluates
fallbackand yields its value.
else is extraction with fallback, not error handling.
In particular, values[index] else fallback evaluates the array access first.
A vacant position at a valid index can yield none and select the fallback;
an invalid index faults, including in an empty array, before any fallback can
recover a value. See specification 14 for the fixed-array contract.
9.4 Trap behavior
optional is trap-free by itself.
Any trap associated with some(expr) or opt else fallback arises only from evaluating the relevant subexpressions.
10. result<E>
10.1 Runtime role
result<E> is the runtime carrier for success-or-modeled-failure at function boundaries and in expressions whose static type is result<E> P.
Expected, recoverable failures belong to result<E>, not to trap.
10.2 !
expr!:
- evaluates
exprexactly once, - yields the extracted success payload if
exprsucceeds, - performs immediate enclosing-function return with the same
err(...)ifexpryields error.
! does not:
- remap errors,
- intercept traps,
- or continue ordinary evaluation after the propagated error path is chosen.
10.3 handle
handle expr { ... }:
- evaluates
exprexactly once, - yields the extracted success payload directly if
exprsucceeds, - selects exactly one matching arm if
expryields error, - executes that arm,
- requires the arm to terminate with either
ok(payload)orerr(E2.case).
ok(payload) in a handle arm recovers locally and makes the handle expression yield payload.
err(E2.case) in a handle arm performs immediate enclosing-function return with err(E2.case).
For the remap-only case, a short form such as E1.case -> E2.case is sugar for an arm block that returns err(E2.case).
handle may execute user-defined logic inside an arm, but it remains specific to modeled result errors.
handle does not intercept or convert traps.
11. Function application and closures
11.1 Canonical role of apply
apply is the canonical universal call surface in PBS v1.
The same observable call model applies to:
- top-level functions,
- struct methods,
- service methods,
- contract calls,
Fncalls,- host-backed calls.
Callable-specific dispatch may differ internally, but it does not change the user-visible sequencing model defined in this document.
11.2 Effect boundaries
apply does not introduce implicit effect composition.
If a callable returns:
optional<P>, extraction remains explicit throughelse,result<E> P, propagation or processing remains explicit through!orhandle.
11.3 Closure creation and invocation
Explicit capture lists snapshot values at creation. Object references retain identity. Calls complete within the current frame; objects may remain reachable between frames. See First-class functions and explicit value captures.
12. Branch Selection
12.1 if
if evaluates its condition exactly once.
If the condition is true, only the selected then branch executes.
If the condition is false, only the selected else branch executes.
The non-selected branch is not evaluated, even partially.
12.2 switch
switch evaluates its selector exactly once and executes exactly one selected arm.
The non-selected arms are not evaluated.
switch is restricted to statically discriminable selector categories in v1:
- literal-comparable scalar values,
- enum values,
- canonical
strvalues, - and any other selector category admitted elsewhere by explicit specification.
switch does not accept:
result,error,- structs,
- string object/reference types distinct from canonical
str, - heap-backed selector categories.
Matching is exact and deterministic:
- enum selectors match by canonical enum-case identity,
- scalar selectors match by the exact equality rule for that scalar category,
strselectors match by canonical static string identity.
switch does not perform structural matching, guard evaluation, or user-defined equality dispatch.
13. Trap, Determinism, and Host Interaction
13.1 Trap boundary
trap is reserved for failures that are:
- outside the ordinary userland contract,
- not suitably representable as the declared
result<E>surface, - caused by runtime or host invariant failure,
- or severe enough that ordinary userland recovery is not part of the v1 language model.
PBS v1 does not define try/catch for traps.
Traps are not part of ordinary recoverable control flow.
Any trap aborts the current PBS program execution rather than returning control to ordinary userland flow.
Control then transfers to runtime or firmware crash handling outside the ordinary language model.
13.2 Host interaction
Host calls must not introduce user-visible reordering of already-defined PBS evaluation order.
Expected operational failures of host-backed surfaces should be modeled through their declared contract rather than through ad hoc trap usage.
Cross-boundary host/userland interaction remains stack-value-based as defined by the host-boundary decision track; direct host-memory manipulation is not part of PBS userland semantics.
14. TODO
The following items remain editorial or cross-spec integration tasks rather than open semantic agenda questions:
- the final wording split between this document and
16. Runtime Execution and Initialization Specification.mdfor crash handoff after trap, - the final wording split between this document and
10. Memory and Lifetime Specification.mdfor retention/allocation facts that arise during ordinary execution, - conformance-oriented example coverage once
13. Conformance Test Specification.mdis expanded.
15. Non-Goals
- Reopening grammar or static typing unless current text is impossible to execute normatively.
- Defining exact GC collection strategy.
- Designing future async, actor, or scheduler models.
- Specifying backend optimization policy.
16. Exit Criteria
This document is ready to move beyond temporary draft status only when:
- every runtime-observable core construct has deterministic evaluation wording,
- trap versus status-value behavior is explicit for every effect-bearing construct,
- host-call interaction rules are stated without relying on informal prose elsewhere,
- the document can drive runtime conformance tests without decision backfill,
- the remaining TODO items are reduced to editorial integration rather than semantic uncertainty.
Existing values and input runtime alignment
The PBS input and value alignment contract governs int/Int32, long/Int64, exact builtin carriers, the Pad/Button/LowPad and Touch API, named-argument evaluation order, migration diagnostics and executable conformance. It supersedes older input-object and untyped executable-lowering descriptions.
Typed arrays and optional execution extension
The Array owner chapter defines the complete type, optional-flow and storage contract. This chapter supplies common evaluation and abrupt-completion rules; Array-specific evaluation, presence and mutation rules are defined by that owner.
Controlled pause and resume hooks
Source-selected BeforePause/BeforeResume functions lower to existing runtime roles 1/2. Runtime owns invocation ordering, continuation, fuel and failures. Home's existing handoff precedes BeforePause; suspension completes after normal hook return. Reactivation precedes BeforeResume; no normal gameplay instruction is eligible until that hook returns. Direct suspension and Shell handoff follow the runtime contract without an additional gameplay reaction tick. Missing hooks preserve existing transitions.
Controlled calls retain the same VM stacks, suspended values, environments, globals and heap roots, restoring the continuation on outer return and handing control immediately to the OS. Mutations persist. They MUST NOT reprepare entry, repeat Init, reset the boot guard, or add gameplay ticks/logical frames. Ordinary calls to marked functions do not themselves acquire controlled-call semantics.
Each controlled invocation has 1,500,000 virtual cycles total, sliced at at most 250,000 admitted cycles per host update, with the runtime's whole-instruction overshoot rule. Slices/debugger stops do not renew fuel. There is no wall-clock deadline. FRAME_SYNC, including in a callee, traps before frame/GC/publication effects. Fatal traps/host failures and unfinished fuel exhaustion fail the session, block gameplay and retain the existing crash envelope, without retry, rollback or compensation. HALT is OS termination, not successful hook return. Existing capability/service rules apply, without auto-save, flush, disk wait, transition veto or reason argument. MemcardBoot and persistence follow the dedicated memcard chapter.
Memcard integration
The Memcard Bootstrap and SDK contract defines the additional [MemcardBoot] marker, exact signature, neutral once-only bootstrap, project identity/slot validation and complete installed mem ABI. Its requirements apply in addition to this chapter; pause/resume remain independent.
Result groups and explicit animation time
A result success evaluates its payload once. Propagation and handle evaluate their operand once; only the selected recovery arm runs. Error remapping returns the enclosing error; traps are not caught. Animation advances only through explicit ticks. Queries/emissions are pure with respect to playback; repeated play/select resets the selected clip even when its name is unchanged.
See Core Sprite and Animation for the complete API, ranges, state table and conformance obligations.
Isolated guest tests preserve lifecycle and visibility
The selected test entrypoint MUST own exactly one program lifecycle. Existing MemcardBoot, bootstrap, Init and Frame rules and budgets remain normative. Test support MUST use normal PBS visibility and exist only in explicitly selected roots. Work MUST be distributed across guest frames; the host MUST advance in bounded blocks and inspect tagged logs between blocks, including completion/failure when available. Timeout, cancellation and explicit completion are distinct.
Test-only support MUST emit versioned JSON via existing sdk/log and the target's declared logTag. Every envelope contains schemaVersion 1, suiteId, eventId, kind, nullable caseId for suite events, and payload. Kinds are suite_start, case_start, assertion, checkpoint, case_end and suite_end. Assertions MUST retain name/message, optional expected/actual and boolean passed. Checkpoints MAY reference retained visual evidence IDs; ordinary game log text MUST NOT be interpreted as test events.
Host validation MUST enforce declared tag, schema/types, event order, suite/case identity, expected case catalogue and consistent duplicate event IDs. Reconsulting a native sequence MUST NOT reapply it. Unread gaps or sequence discontinuity, malformed/conflicting events, session/epoch changes and native faults MUST prevent success. Case states are passed, failed, not_run and infrastructure_failure. Pass requires a nonempty suite, at least one assertion, explicit suite completion, every expected case completed, no failed assertion and no loss/protocol/fault condition. Fault alone, missing cases or an empty suite MUST NOT become a successful assertion report. Accepted contract implementation is in progress under PLN-0172.
Structured assertion detail and host retention
Optional expected/actual values MUST retain independent availability flags, so an omitted value differs from an observed null. Native sequence/frame/timestamp, source/tag/application and the original event MUST remain correlated in transcript entries. Wall timestamps MUST NOT determine the verdict. An optional boolean passed on case_end/suite_end MAY explicitly reject that case/suite; it MUST NOT override a failed assertion. Non-boolean completion flags are invalid. Checkpoint artifact IDs MUST pass current project admission before inclusion as valid links.
The initial host accumulator retains at most 16 MiB and 100000 native records per run. Exceeding a host retention bound MUST report explicit infrastructure failure with the bound and retained position, never silently discard records or pass. These are host transcript bounds and do not alter firmware budgets. The installed isolated-tests example uses target-only helpers with complete versioned JSON literals and predicate booleans; it assumes no new guest string formatting ABI.
Guest producer continuity and native retention
Every structured guest event payload MUST include a zero-based contiguous integer ordinal; suite_end MUST include eventCount counting all unique events including itself. Retries with the same event identity/content are idempotent. Missing or inconsistent ordinals/final counts fail as infrastructure errors, even if native sequences remain contiguous. Native overflow records historical eviction; only unread gap or actual continuity loss causes a retention failure. Preserve the overflow observation separately.
Encoded guest messages MUST fit 256 UTF-8 bytes and stay within the unchanged 10 messages/application/frame budget, including ordinary application logs. The runner drains every pending native page before another bounded advance. Native continuity alone cannot detect events dropped before ring insertion. No new guest ABI, formatting facility or increased execution/logging budget is introduced.