summaryrefslogtreecommitdiff
path: root/chapter31/docs
diff options
context:
space:
mode:
Diffstat (limited to 'chapter31/docs')
-rw-r--r--chapter31/docs/31-grammar.ja.md6
-rw-r--r--chapter31/docs/31-grammar.md26
-rw-r--r--chapter31/docs/audio.md62
-rw-r--r--chapter31/docs/construction-groups.md241
-rw-r--r--chapter31/docs/deferred-construction.md385
-rw-r--r--chapter31/docs/drawing.md84
-rw-r--r--chapter31/docs/escape-flow.md147
-rw-r--r--chapter31/docs/examples/Breakout.smp369
-rw-r--r--chapter31/docs/examples/Clock.smp128
-rw-r--r--chapter31/docs/examples/Dijkstra.smp19
-rw-r--r--chapter31/docs/examples/Graphics.smp19
-rw-r--r--chapter31/docs/examples/README.md57
-rw-r--r--chapter31/docs/examples/TicTacToe.smp57
-rw-r--r--chapter31/docs/examples/TicTacToeGraphical.smp98
-rw-r--r--chapter31/docs/graphics.md119
15 files changed, 667 insertions, 1150 deletions
diff --git a/chapter31/docs/31-grammar.ja.md b/chapter31/docs/31-grammar.ja.md
index f4635f21..eca363c1 100644
--- a/chapter31/docs/31-grammar.ja.md
+++ b/chapter31/docs/31-grammar.ja.md
@@ -47,7 +47,7 @@ constructorParameterList : (constructorParameter ','?)+ ;
constructorParameter : type '^'? bindingModifier? IDENTIFIER ;
// ^ accepts an unfinished struct reference; ? independently permits null.
// Only self may be read while incomplete; ^ arguments may be stored/forwarded.
-// A new result is incomplete iff an actual argument is. See construction-groups.md.
+// A new result is incomplete iff an actual argument is. See ../../chapter29/README.md#incomplete-types.
// A method is an ordinary fixed function binding in a struct definition.
// The compiler supplies self; it is not written in parameterList.
@@ -82,7 +82,7 @@ primitiveType
assignment : expression (assignmentOperator assignment)? ;
assignmentOperator
- : '=' | '+=' | '-=' | '*=' | '/=' | '&=' | '|=' | '^='
+ : '=' | '+=' | '-=' | '*=' | '/=' | '%=' | '&=' | '|=' | '^='
| '<<=' | '>>=' | '>>>='
;
@@ -113,7 +113,7 @@ additiveExpression
;
multiplicativeExpression
- : unaryExpression (('*' | '/') unaryExpression)*
+ : unaryExpression (('*' | '/' | '%') unaryExpression)*
;
unaryExpression
diff --git a/chapter31/docs/31-grammar.md b/chapter31/docs/31-grammar.md
index 19f834af..37300c46 100644
--- a/chapter31/docs/31-grammar.md
+++ b/chapter31/docs/31-grammar.md
@@ -64,7 +64,7 @@ constructorParameterList : (constructorParameter ','?)+ ;
constructorParameter : type '^'? bindingModifier? IDENTIFIER ;
// ^ accepts an unfinished struct reference; ? independently permits null.
// Only self may be read while incomplete; ^ arguments may be stored/forwarded.
-// A new result is incomplete iff an actual argument is. See construction-groups.md.
+// A new result is incomplete iff an actual argument is. See ../../chapter29/README.md#incomplete-types.
// A method is an ordinary fixed function binding in a struct definition.
// The compiler supplies self; it is not written in parameterList.
@@ -102,7 +102,7 @@ primitiveType
assignment : expression (assignmentOperator assignment)? ;
assignmentOperator
- : '=' | '+=' | '-=' | '*=' | '/=' | '&=' | '|=' | '^='
+ : '=' | '+=' | '-=' | '*=' | '/=' | '%=' | '&=' | '|=' | '^='
| '<<=' | '>>=' | '>>>='
;
@@ -133,7 +133,7 @@ additiveExpression
;
multiplicativeExpression
- : unaryExpression (('*' | '/') unaryExpression)*
+ : unaryExpression (('*' | '/' | '%') unaryExpression)*
;
unaryExpression
@@ -185,7 +185,14 @@ argumentList : assignment (',' assignment)* ','? ;
// Allocation invokes the declared constructor; inline initializer blocks from
// earlier chapters are replaced by constructor arguments.
-newExpression : 'new' type ('[' assignment ']' | callSuffix)? ;
+newExpression
+ : 'new' type ('[' '~'? assignment ']' arrayInitializer? | arrayInitializer | callSuffix)?
+ ;
+// With no explicit length, type must end in [] or [~] and the initializer is a list.
+arrayInitializer
+ : '{' (assignment (',' assignment)* ','?)? '}'
+ | '{' ('int' | 'i32' | 'i64' | 'u32') IDENTIFIER '->' statement* '}'
+ ;
INTEGER_LITERAL : [1-9] DIGIT* | '0' [0-7]* | '0' [xX] HEX_DIGIT+ ;
// The f suffix also accepts an integer-shaped token, e.g. 12f.
@@ -195,10 +202,13 @@ FLOAT_LITERAL : DIGIT+ ('.' DIGIT* ('e' DIGIT+)? | 'e' '-'? DIGIT+) 'f'?
// Interpolation re-enters the ordinary expression grammar, recursively.
stringExpression : '"' (STRING_TEXT | ESCAPE | '%%' | interpolation)* '"' ;
interpolation : '%' format? '(' assignment ')' ;
-format : FORMAT_FLAG* FORMAT_WIDTH? ('.' FORMAT_WIDTH?)? FORMAT_KIND ;
+format : FORMAT_FLAG* FORMAT_WIDTH? ('.' FORMAT_WIDTH?)? FORMAT_KIND TIME_STYLE? ;
// Flags: - + space # 0. Width/precision: decimal digits, no expressions.
-// Kinds: d i u o x X f F e E g G a A c s b.
-// Duplicate/inapplicable flags and precision on c/b are rejected.
+// Kinds: d i u o x X f F e E g G a A c s b t.
+// TIME_STYLE: F r R M D T, allowed only after t; default F (ISO UTC).
+// Time styles: ISO, 12-hour, 24-hour, elapsed MM:SS.mmm, DD/MM/YY, HH:MM:SS.
+// Duplicate/inapplicable flags and precision on c/b/t are rejected.
+// Time accepts width and left alignment only; see time.md.
// STRING_TEXT excludes double quote, backslash, and percent.
CHARACTER_LITERAL : '\'' (ESCAPE | ~['\\]) '\'' ;
fragment ESCAPE : '\\' [0ntr\\'"%] ;
@@ -228,7 +238,7 @@ there is no inheritance chain, AST, or additional compiler pass.
| `assignment` through `primaryExpression` | [`Expressions`](../src/main/java/com/seaofnodes/simple/parser/Expressions.java): `parseAssignment`, `parseExpression`, `parseLogical`, `parseBitwise`, `parseEquality`, `parseComparison`, `parseShift`, `parseAddition`, `parseMultiplication`, `parseUnary`, `parsePrimary` |
| `postfixExpression`, member selection and updates | `Expressions.parsePostfix` / `parsePostfixMethod` dispatch to [`References.parseField`](../src/main/java/com/seaofnodes/simple/parser/References.java); `References.parseName` handles bare names, implicit receivers, and forward references |
| `functionExpression`, `parameterList`, calls, `argumentList` | [`Functions`](../src/main/java/com/seaofnodes/simple/parser/Functions.java): `parseFunction`, `parseConstructor`, shared `parameters` and `arguments`, then `parseBody` |
-| `newExpression` | [`Allocations.parseNew`](../src/main/java/com/seaofnodes/simple/parser/Allocations.java); the allocation-helper graph builder follows the expression routines |
+| `newExpression`, `arrayInitializer` | [`Allocations.parseNew`](../src/main/java/com/seaofnodes/simple/parser/Allocations.java), [`ArrayInitializers`](../src/main/java/com/seaofnodes/simple/parser/ArrayInitializers.java); private initialization, list checks, and generator loops |
| `stringExpression`, `interpolation` | [`Strings.parse`](../src/main/java/com/seaofnodes/simple/parser/Strings.java), using `Lexer.stringPart` / `stringFormat`; normal expression parsing resumes inside each interpolation |
| Literals, identifiers, comments, token matching | [`Lexer`](../src/main/java/com/seaofnodes/simple/parser/Lexer.java); it also supplies source-location snapshots used by diagnostics and serialized IR |
diff --git a/chapter31/docs/audio.md b/chapter31/docs/audio.md
deleted file mode 100644
index 30817012..00000000
--- a/chapter31/docs/audio.md
+++ /dev/null
@@ -1,62 +0,0 @@
-# Optional background audio
-
-`sys.audio` uses [miniaudio](https://github.com/mackron/miniaudio) through an
-optional native C backend. Playback runs on its own thread; the game keeps
-processing input and drawing. No Python, CMake, codec packages, or sound files
-are needed. Default builds/tests never download miniaudio or open a device.
-
-From `chapter31`:
-
-```sh
-make libs CTAGS= # Once while online, or use make init.
-make audio CTAGS=
-make run-graphical-tictactoe CTAGS=
-```
-
-The last command builds both optional backends and runs the game. Accepted
-moves get a quiet 70ms sine boop. A player win gets a 480ms rising C-E-G
-celebration; a CPU win reverses the notes. Invalid input and occupied squares
-are silent. Replay stops any previous cue. Win/loss cues replace the ordinary
-move boop; draws use the ordinary boop.
-
-For direct execution in PowerShell, alongside `SIMPLE_MINIFB`:
-
-```powershell
-$env:SIMPLE_MINIAUDIO = (Resolve-Path build/release/x86_64_v2_win64/simple_miniaudio.dll).Path
-.\build\examples\x86_64_v2_win64\TicTacToeGraphical.exe
-```
-
-Linux uses `libsimple_miniaudio.so` in the corresponding release directory.
-`SIMPLE_MINIAUDIO` must name the full backend path. Unset it or set it to `off`
-for silent play. An unavailable audio device returns `ERROR` and the game
-continues. Audio and graphics can be configured independently.
-
-| Operation | Meaning |
-| --- | --- |
-| `open()` | Open output and generate built-in sounds; `OK` (0) or `ERROR` (-1). Repeated open is safe. |
-| `boop()`, `win()`, `lose()` | Play a built-in cue; same as `play(BOOP/WIN/LOSE)`. |
-| `load(samples)` | Copy `i16[~]` mono PCM at `RATE` (48000Hz); return handle or `ERROR`. |
-| `play(handle)` | Start/restart, replacing the current sound. Return `OK` or `ERROR`. |
-| `stop()` | Stop playback; safe before open/after close. |
-| `playing()` | Whether samples remain to submit; final device buffering may remain. |
-| `close()` | Join the audio thread and free device/buffers; safe to repeat. |
-
-All calls belong on the main/game thread. Load custom sounds at startup:
-there are 28 custom slots, each up to ten seconds, retained until close.
-Custom handles must be reloaded after close/reopen. Signed samples range
-from -32768 to 32767; quiet effects should use much smaller amplitudes.
-Native code copies the array and never retains a Simple heap pointer or calls
-Simple from the audio thread. Playback itself neither allocates nor waits for
-the sound duration. This first interface plays one sound at a time.
-
-`audio.mk` pins miniaudio 0.11.23, cached under `lib/miniaudio-0.11.23/` by
-`make libs` (or `init`; `lib` remains a setup alias). Only these explicit setup
-targets can download dependencies. All builds, runs, and tests use local
-copies, surviving `make clean`; missing cache entries fail promptly with setup
-instructions. Windows uses the existing MinGW-w64 compiler;
-Linux uses GCC and system pthread/math/dl libraries. No audio development
-headers need installing. The upstream header includes its public-domain and
-MIT-0 license options, copied beside the backend as `miniaudio-LICENSE`.
-`make test-audio CTAGS=` builds the backend checks from the local cache
-and runs a real audio thread with miniaudio's silent null
-device; normal tests exercise the loader and game without hardware.
diff --git a/chapter31/docs/construction-groups.md b/chapter31/docs/construction-groups.md
deleted file mode 100644
index 197a6082..00000000
--- a/chapter31/docs/construction-groups.md
+++ /dev/null
@@ -1,241 +0,0 @@
-# Construction: field types and incomplete references
-
-Instance constructors use ordinary field Loads and Stores. There are two checks:
-whether a field has a value, and whether an object reference is usable outside
-construction. Neither requires a collection of constructor-group identities.
-
-## Field initialization
-
-New produces private `TypeMem` containing the object's `TypeStruct`, with
-`TypeScalar.BOT` for fresh fields. Defaults emit ordinary Stores: zero for an
-ordinary integer, null for a nullable pointer, no Store for a required field.
-An assignment strongly updates its field in private memory. Phi meets the
-incoming memories; a missing live arm survives because `BOT.meet(7) == BOT`.
-An initialized unknown integer has `TypeInteger.BOT`, not `TypeScalar.BOT`.
-Arrays retain their language-level zero filling.
-
-One `#selfMem` binding carries this memory through scopes and returns. A Load
-checks its incoming field type. Constructor completion checks the merged Return
-memory; the explicit constructor receives the declaration initializer's merged
-result, including early exits. There is no backwards initialization query,
-per-field parser state, or store-all instance exit.
-
-The existing Iter/Opto passes propagate these types; TypeCheck reports errors.
-There is no extra construction type solve or retained source-use list. An
-initialized field carried unchanged around a loop needs the optimistic SCCP
-solution. Numeric fields in loop memory widen as scalar loop values do.
-Arithmetic, conversions, and numeric Stores preserve Scalar.BOT, so a live bad
-read cannot disappear merely because it is multiplied by zero. Genuinely unused
-reads may be removed by DCE.
-
-The allocator's ConstructNode retains the constructor's final private memory
-for its completion check. TypeCheck gathers these nodes during its existing
-error walk and removes checked boundaries before lowering. The pass removal
-exposes known failures; see [the late-check notes](deferred-construction.md).
-
-Internal construction memory parameters use actual allocation/initializer call
-edges; the hypothetical external caller does not supply their memory. They
-retain their memory family when there are no live callers. Function-valued
-fields retain their declared signatures in private summaries, avoiding repeated
-unfolding of a constructor whose returned memory contains its own function field.
-Class singleton initialization keeps its older store-at-exit implementation.
-
-## Partial references and readable fields
-
-`self` and incoming `C ^arg` parameters are incomplete references. `C? ^arg`
-also accepts null. Ordinary functions and constructors accept the qualifier on
-struct parameters; arrays cannot be qualified this way.
-
-- An allocation result is incomplete if any actual argument is incomplete.
-- With only completed arguments, including null, the result is complete.
-- An incomplete reference may be stored into self or passed to a `^` parameter.
-- Ordinary calls and stores into other objects require completed references.
-- A borrowed partial can read fields its incoming type proves initialized.
- It cannot write fields, even non-finals. Exact local aliases of self retain
- the original constructor's access to its current private memory.
-- An object-reference field read through a partial is conservatively
- incomplete, with no initialized-field guarantees for its referent. There is
- no inference of initialized-field requirements on `^` arguments.
- Arrays are already initialized and cannot receive
- incomplete elements, so an initialized array field can be used normally.
-
-For example:
-
-```simple
-struct Child {
- Test.Parent? parent;
- new Child = { Test.Parent? ^par -> parent = par; };
-};
-struct Parent {
- Child child;
- int~ payload;
- new Parent = { int n ->
- child = new Child(self); // Incomplete result: self is incomplete.
- // Retention does not authorize reading parent.payload through child.
- payload = n;
- };
-};
-val parent = new Parent(arg);
-val local = new Child(parent); // Complete argument, complete result.
-return local.parent==parent; // Lookup is allowed.
-```
-
-Here `Test` names the source unit. After the root Parent constructor completes,
-the entire cycle is usable: all members have initialized their own fields, and
-none could expose an incomplete reference to ordinary code during construction.
-The Child constructor still treats its `^par` as incomplete when the actual
-argument is complete. This public constructor also has unknown callers, whose
-partial arguments promise no initialized fields, so `par.payload` is unreadable.
-
-## Forward field views
-
-At a use of self, `InitViewNode` combines the pointer with that program point's
-private memory. Its TypeMemPtr contains declared types for initialized fields
-and Scalar.BOT for missing fields. The node retains the declaration separately
-from the incoming flow shape, so an exact self alias captured before a Store
-can receive a fresh view afterward. Earlier calls retain their earlier views.
-
-For example, a private helper can read `x` while `y` is still unset:
-
-```simple
-struct _C {
- int~ x;
- int~ y;
- new _C = { int n -> x=n; y=_read(self); };
-};
-val _read = { _C ^p -> return p.x; };
-return new _C(arg).y;
-```
-
-Parm meets the incoming shapes using the normal type flow. If any live caller
-lacks `x`, Scalar.BOT survives and the Load reports the missing initialization.
-Unknown callers supply an empty field promise. Parsing must also start borrowed
-parameters at that bound: otherwise early folding of `p.x*0` could hide a bad
-read before SCCP. The hidden constructor receiver retains its declaration;
-its private memory supplies its read checks and precise field updates.
-
-Values still come from normal memory. Before a call borrowing self, EscapeNode
-borrow slices carry the current constructor Stores onto the ordinary call
-memory edge. These slices are aliasable and do not publish the private identity
-or its fields into the global escape sets. No hidden partial-memory arguments,
-field bitsets, additional passes, or recursive flow queries are introduced.
-
-InitView folds before TypeCheck when its input already has the same type and
-retains a structural partial view. Nested partial-only Construct wrappers also
-collapse. A Parm's current partial type alone is insufficient: inlining may
-later substitute a complete actual argument, which must not grant the borrowed
-parameter permission to write or publish that object. The completion form of
-Construct already folds once its memory proves initialization and its result
-type matches its input.
-
-TypeCheck checks the consumers and erases remaining InitViews along with the
-checked Construct boundaries in its existing walk. A surviving field view is
-not necessarily erroneous: a reader may need only the initialized subset.
-Construct remains necessary for
-final-field completion and for the partial qualifier of each source `new`.
-Alias Phis and nested reference loads are conservative; they do not acquire
-the original constructor's write permission. This prototype adds no general
-ban on overlapping allocations of the same class: only the owning receiver
-uses private memory, while borrowed reads use aliasable memory.
-
-## Aliases and loops
-
-Incomplete is a property of a value, not just the current contents of a parser
-Var. Consider `while (n--) { use(p); p = self; }`: the backedge introduces an
-incomplete value after `use(p)` has been parsed. `TypeMemPtr._partial` carries
-that restriction through ordinary forward typing. It is an independent
-two-point lattice: meet ORs the restriction and dual complements it. Copies,
-conversions, Stores, and Phis preserve it; a merge is incomplete if any live
-input is incomplete. A `^` formal stays incomplete even when its known callers
-are complete. The receiver's private memory identifies the own-self exception;
-another incomplete pointer of the same class has no such permission.
-
-A small `ConstructNode` wraps each source `new`. Its runtime value is the
-allocator result; its type adds the OR of that call's actual argument qualifiers.
-This distinguishes `new Child(self)` from `new Child(null)` even when both call
-the same constructor. Looking only at the shared callee Return would lose this
-distinction. The node disappears after TypeCheck, before lowering.
-
-A completed receiver gives a completed view of its pointer fields. Construction
-may retain incomplete references but cannot publish them, so reaching the root
-`new` boundary with complete arguments makes the entire reachable cycle usable.
-There is no group identity or traversal to mark members complete. Conversely,
-object-reference fields read through incomplete self remain conservative, even
-if the particular stored reference was complete.
-
-The existing optimistic SCCP solve also handles qualifier cycles. For
-`p = null; while (n--) p = new Link(p);`, no input introduces incompleteness,
-so `p` stays complete and a subsequent field read is allowed. A backedge carrying
-self instead makes the Phi and its uses incomplete.
-
-`Construction` selects private self memory during parsing; it retains no
-source-use lists or flow facts and performs no recursive Load/Phi/Call query. The old
-root and allocation bitsets are gone. There are no field-requirement sets,
-hidden `^` memory arguments, or runtime group objects.
-
-`PartialReadTest` exercises field reads, missing fields, forwarding, merged
-callers, loops, exact aliases, constructor retention, and borrowed write and
-publication restrictions. `ConstructionGroupTest` exercises cycles, complete/null arguments, prohibited
-lookups/publication, aliases, branch merges, complete and incomplete loop
-backedges, and declared restrictions with only complete callers, including an
-uninlined constructor through machine encoding. `ConstructorCompletionTest`,
-`FinalConstructionTest`, and `BoundaryTest` exercise field-memory semantics.
-The former inferred-requirement litmus tests are preserved, explicitly deferred,
-in `ConstructionRequirementsTest`. Separate compilation of `^` functions is
-still deliberately unsupported. The pointer qualifier has an object-file
-representation, but importing and checking the full construction contract is
-outside this experiment. Rebuild chapter 29 object files after the type-format
-change.
-
-## Deferred field-aware contracts (2026-11-07)
-
-Decision: do not implement inferred contracts now. Cliff considers the required
-infrastructure too large for the feature alone; revisit when a general
-backwards/liveness flow is justified, potentially for memory management.
-The later forward-field-view prototype above does not implement this contract
-discovery proposal. Separate compilation of `^` interfaces remains rejected.
-
-The intended extension would let functions and constructors receive partially
-initialized objects, read initialized fields, retain partial references with
-their restrictions, and write non-final fields. Only the original constructor
-would retain permission to initialize/reassign its own final fields; passing a
-pointer must not pass that permission. Final-field reads during construction
-would not establish value stability against later writes by that constructor.
-
-The proposed contract representation uses normal types, not a separate field
-bitset. For a function reading only `P.pi`, its unknown-caller default would be
-schematically `Partial{pi:declared-pi-type, name:TypeScalar.BOT}`. Scalar.BOT
-means no initialization guarantee, not a requirement that the caller leave the
-field unset. Required fields receive their declared types, covering every legal
-external caller. MEET with actual arguments preserves those guarantees only
-when the callers satisfy them; extra initialized fields supplied by locals do
-not strengthen the body beyond the external contract. TypeStruct/Field already
-meet field contents, and nested/cyclic types can represent nested contracts.
-TOP is not the missing-initialization marker.
-
-Cliff proposed discovering conservative, context-insensitive requirements after
-Iter and before SCCP. Freeze the resulting default argument types on functions;
-SCCP consumes them without refining the contracts. Reads on branches SCCP later
-eliminates may still impose requirements, as may reads following assignments.
-That rejection of some valid programs is acceptable for an opt-in `^` feature.
-Combine compatible requirement shapes with JOIN; combine possible caller states
-with MEET. Keep the contract distinct from the merged Parm type, and check each
-actual argument against it for a call-site diagnostic such as
-"foo requires Partial.pi to be initialized". Serialize contracts with declaration
-metadata so checking imported calls does not require loading bodies.
-
-The complication is discovering and propagating those contracts. Local SSA
-aliases share values; Phi demands reach every input. A demand on a loaded field
-becomes a nested receiver requirement. Calls substitute actual arguments for
-formals, and recursive forwarding needs a convergent propagation rule. Cyclic
-types represent recursive requirements but do not by themselves prevent a
-discovery algorithm from unfolding progressively deeper paths. Indirect calls
-need contracts available through their callable interfaces; returns need usable
-guarantees without retroactively strengthening an exported contract for a client.
-Stored references and helper writes also require a coherent account of private
-construction memory and object identity; that discussion was deliberately left
-unfinished. None of this requires H-M or bidirectional type inference, but it
-does require a substantial backwards demand analysis to handle well.
-
-The ignored ConstructionRequirementsTest retains useful litmus cases, not an
-approved implementation plan. Do not restart this work without a new request.
diff --git a/chapter31/docs/deferred-construction.md b/chapter31/docs/deferred-construction.md
deleted file mode 100644
index 104ab9e9..00000000
--- a/chapter31/docs/deferred-construction.md
+++ /dev/null
@@ -1,385 +0,0 @@
-# Deferring construction checks: experiment
-
-The [escape-flow continuation](escape-flow.md) supersedes the frozen-public
-fallback and remaining recursive-test failures described later in these notes.
-All four recursive examples now pass their original printed-IR expectations.
-The older audit below records the evidence that led to this change.
-
-The extra construction pass is removed from the working implementation.
-`Construction.check()`, its retained source-use lists, `Iter.types()`, and the
-separate constructor-Return walk are gone. Errors now belong to the existing
-TypeCheck walk; ConstructNode retains final private memory for completion checks.
-No additional whole-graph pass was added. Constructor rejection tests remain active.
-
-## Constant folding
-
-`TypeScalar.BOT` is not an initialized integer. Arithmetic, comparisons,
-negation, numeric conversions, and typed Stores must preserve it rather than
-manufacturing an integer or floating-point result. In particular, `x*0` and
-`x==x` cannot become constants while `x` has this type. An initialized unknown
-integer still permits those folds.
-
-The scan found and changed these related cases:
-
-- Multiplication by zero now folds in `compute`, after checking numeric inputs.
- Integer strength reduction also waits for integer operands; an unfinished
- loop Phi could eventually become a float.
-- Same-input comparisons fold in `compute`. Floating comparisons keep NaN
- semantics; `x==x` is not necessarily true. The integer range implementation
- of `!=` also had the equality answers reversed.
-- Arithmetic pushed through Phis uses each copied operation's `compute`,
- including floating-point constants, instead of an unchecked integer cast.
-- Known array length offsets and element shifts fold in
- `ConFldOffNode.compute`, rather than its `idealize`.
-- `Not`, unary minus, conversions, and Stores preserve unknown initialization.
- `RoundF32` already passed that type through.
-
-This does not ban creating constant *operands* in rewrites such as `x*8` to
-`x<<3`. Memory forwarding still has cases that return a stored constant or an
-array's zero-filled element; these were inspected but not rewritten into a new
-memory analysis. `Load.idealize` retains a `Scalar.BOT` load.
-
-The changes exposed a rejected-Phi-fold worklist cycle. Factoring
-`Phi(bool & 7, integer & bool)` widens the result from `bool` to `[0-7]` and
-must fail. Building and then killing the candidate woke the same dependencies
-forever. The trial now computes its types before registering use edges.
-
-## Preserving the constructor body through optimization
-
-This regression must reject a live incomplete lookup:
-
-```simple
-struct Child {
- Test.Parent? parent;
- new Child = { Test.Parent? ^par -> parent = par; };
-};
-struct Parent {
- Child child;
- int~ payload;
- new Parent = { ->
- child = new Child(self);
- payload = child.parent == null;
- };
-};
-return new Parent().payload;
-```
-
-`child` is incomplete because its constructor received incomplete `self`.
-Reading `child.parent` must therefore fail. The read supplies the final result;
-this is not a discarded local or dead-code issue.
-
-The decisive failure was private-memory Parm typing. During Iter, inlining
-removed a real caller while the function still had its unknown-caller edge.
-The special case returned MemTop anyway. That erased the memory merge, Store,
-and the bad Load feeding it, before TypeCheck could report the error.
-
-Parms now use their normal merge. Hidden initializer/constructor helpers have
-only actual allocator callers; the source-visible constructor binding denotes
-the allocator. Public allocators still receive unknown callers, so unused public
-constructor bodies remain checked. This also avoids poisoning a helper's private
-memory with a fictitious external default.
-
-Inlining presents a second issue: a complete actual pointer must not grant
-permission to read a restricted formal. A partial-only ConstructNode gives
-self and ^ parameters their body view independently of Parm typing. It remains
-until TypeCheck. Load's alias search recognizes that this view preserves the
-address, while compute/err continue to see the qualified pointer.
-
-A smaller regression reads an unwritten field through a self cycle:
-
-```simple
-struct C {
- C next = self;
- int~ x;
- new C = { -> x = next.x; };
-};
-return new C().x;
-```
-
-Both examples now reject at TypeCheck. A positive regression initializes x to
-7, increments it in the constructor, and checks that the result folds to 8.
-
-The broader run exposed a function-lifetime bug during SCCP: unlinking calls
-could delete a body subsequently rediscovered from a type-level function
-reference. Returns are kept during the existing reset walk and released once
-call edges have been rebuilt. No additional graph walk is needed.
-
-Class-init dependency discovery also skips a CLInit whose receiver has not
-resolved to a class. A Scalar.BOT receiver is left for its Load's TypeCheck
-error, rather than dereferencing a null class name.
-
-The trial successfully uses the existing passes to prove a chain built from
-`null` complete. It also rejects direct `par.payload`, `par.payload*0`, and
-`int x = par.payload; value = x*0` after the arithmetic/conversion repairs.
-
-Genuinely unused reads are allowed to disappear under late-check semantics.
-Rejection tests must keep the read live. `testUnusedIncompleteReadCanDie` checks
-that an unused `par.payload` read is eliminated and the program returns 5.
-
-## Optimization differences and register allocation
-
-`Chapter18Test.testFcn9` exposed an independent escape bug. StopCU treated the
-class initializer's synthetic self as an object already held by an external
-caller. Its broad function-valued field type exposed the local x function even
-though the initializer never returned and x had no callers after inlining.
-Skipping that synthetic argument restores the empty escape set for x and the
-expected `return Top;`. Actual public-call arguments still escape normally.
-
-That correction exposed `Chapter18Test.testFcn8`: a Store computed from TOP
-memory interpreted its optimistic singleton bit as established private memory.
-It widened a function value to the declared signature, then narrowed its FIDX
-set when memory resolved. Store now returns TOP while its memory is TOP, so
-SCCP remains monotone.
-
-The String differences have a different cause. In Chapter19, the private
-_hashCodeString body dies; the surviving functions are the initializer,
-allocator, equals, and public hashCode. Its golden string now omits the two dead
-private-helper MemTop Returns and matches the current addition order.
-`Add.spine_cmp` breaks this tie by node ID. Strength reduction creates the Sub
-in IterPostOpto, after the byte Load (Sub#594 versus Load#504 in one traced copy),
-so the Sub sorts to the left. This is node ordering, not a lost value type.
-
-In the Chapter20/21 fixtures, _hashCodeString really escapes through the implicit
-return, and hashCode contains an inlined copy. Before the allocator repair, both loops needed an extra x86
-register copy with the new addition operand order. A disposable probe
-swapped only `((hash<<5)-hash) + byte` to `byte + ((hash<<5)-hash)` after Unlink:
-no types or live functions changed, but the weighted split score fell from 37
-to 21. Each hash body fell from 17 to 9; the allocator stayed at 3.
-
-Reconstructing the earlier source by reversing the saved construction-pass
-removal patch reproduces the expected 29. Its standalone _hashCodeString costs
-17, inlined hashCode costs 9, and allocator costs 3. Before the allocator repair,
-these costs were 17, 17, and 3. Both versions contain two hash loops; no inlining decision changed.
-Current code emits two fewer functions, the dead initializer/constructor helpers,
-which contributed zero. Thus the entire increase is one loop-weighted register
-copy in the inlined hashCode body, not another retained function or stack spill.
-
-With the old operand order, the byte Load can write the loop's hash register
-and Add accumulates the shifted/subtracted value into it. With the new order,
-Add's destructive input is the Sub result. Its two-address tie plus the Phi
-backedge joins the shift/Sub/Add chain to the old hash live range, which overlaps
-the shifted value at the subtraction. `RegAlloc.splitSelfConflict` inserts a
-`use/self/two` copy before Add. The existing commute heuristic in `splitByLoop`
-is not reached: self conflicts take an earlier splitting path. Commuting Add
-before splitting is the concrete optimization opportunity.
-
-The allocator now does this in `splitSelfConflict`, using the existing failed-
-range traversal and scratch list. It commutes two-address operators when the
-RHS has one use and belongs to a different live range, then omits the copy for
-the tie it broke. An allocator-generated Split is excluded: its single use can
-hide a longer-lived value, and commuting onto it can undo an earlier repair.
-The existing coloring retry rebuilds live ranges. There is no new whole-IR pass
-or analysis structure. The machine's `commutes()` hook covers Add, Mul, Xor,
-And, and Or (and commutative floating instructions).
-
-The String score is now 21: each hash body costs 9 and the allocator costs 3.
-The three x86 expectations are updated to 21. A single regression exercises
-all five integer operators in both machine operand orders, checks register
-constraints, and encodes the results. Existing testFlags2 guards against the
-Split-operand regression.
-
-## Incremental Iter setup
-
-Iter no longer resets and requeues the whole graph after parsing. `Node.init()`
-queues initialized nodes, and Calls queue themselves so Iter can link targets
-loaded after the call was parsed. Iter seeds its new global escape summary,
-then drains the worklist. Import loading still resets the newly loaded nodes
-and repairs affected neighbors.
-
-Removing the sweep also exposed an unused receiver left behind when field
-lookup switches from an instance to its class. That path now releases the keep
-and kills the receiver if unused.
-
-FldOffNode's base is data in slot 1. Slot 0 is reserved for control; putting a
-data parameter there made inliner body discovery exclude an unresolved offset.
-The regression `CallEndTest.testUnresolvedOffsetInInlineBody` checks that the
-offset belongs to the function body even before its type resolves.
-
-## Type upgrades in Opto setup
-
-ParseAll still closes the named types and freezes the public interface after
-loading all units. It no longer walks the IR. Opto installs those closed types
-and resolves forward references during its existing reset walk. Setup runs no
-peepholes against the partly reset graph: resolved FRefs propagate their input
-type in SCCP and disappear during subsequent peepholes. Construction identities
-also wait until this setup has installed complete field declarations.
-
-That walk retains Returns while call edges are rebuilt, gathers unresolved
-numeric modes, and records dependencies for cleanup after SCCP. Type upgrades
-also register cleanup dependencies, even if the eventual value type is unchanged.
-Old Iter types are snapshots for change detection, not upper bounds after
-recursive declarations have been closed. SCCP still asserts monotone falling
-types and a complete worklist within its own solve.
-
-The move exposed assumptions formerly hidden by early upgrades. Resolving an
-already known class name must retain its known fields instead of replacing them
-with an empty placeholder. A Load must not forward a stored pointer whose open
-shape is weaker than the Load's computed type. Escape must retain escapes from
-the actual private value before narrowing it to its declared field type, so
-selecting a Store out of a MemMerge does not introduce new escapes.
-
-An unknown return or memory effect carries FULL escape sets. StopCU and
-GlobalEscape preserve that bound: narrowing it to public names would omit
-private objects and callbacks that a subsequent load-forwarding rewrite can
-reveal. Both summaries recompute from their inputs without retaining previous
-escape sets. Refining a value removes possibilities; it never adds escapes
-outside the old bound. IterPeeps has no special summary handling, and its
-worklist assertion requires every node's type to lift, including queued nodes.
-`testUnknownEscapesRefineToPrivateValues` checks both escape sinks;
-`testPrivateRecursiveReturn` covers cyclic private objects and field loads.
-
-The ordinary dependency mechanism also covers signature refinement and lazy
-imports. FunNode depends on its Return when refining its signature. Calls
-depend on their target FunNode; while a target is absent, they depend on Start
-and retry when a linker mapping is installed. Loading bodies and adding call
-edges still use `Iter.repair` for graph changes, not for value refinement.
-
-SCCP's Start linking honors FULL for private targets too. Incoming arguments
-are not themselves outgoing escapes; Stores, Returns, and external-call
-arguments describe those effects. Constant singleton field slices carry the
-stored value's escapes, not unrelated bulk-memory escapes frozen at the time
-of folding. This preserves precision for local recursive callbacks.
-
-As bounds sharpen after SCCP, FunNode removes unknown callers even if concrete
-callers remain. Called initializers retain their Return through StopCU because
-CLInit has no Return edge. Removing an uncalled function queues the affected
-Stops, and compilation-unit wrappers retain distinct identities even when
-empty. These are worklist notifications and ownership rules, not extra passes.
-
-### Remaining precision issue with FULL escapes
-
-The monotone bounds expose a feedback problem in the existing grand cycle.
-In `Chapter12Test.testPrivateRecursiveReturn`, SCCP sees BOTTOM for the final
-load chain and therefore FULL escapes. These feed through Start's memory into
-the function memory results. Post-SCCP forwarding resolves the return to `_B`,
-but that memory cycle remains at MemBot and keeps private constructors callable
-by unknown callers. This is conservative, but loses the previous dead-function
-elimination. It does not justify narrowing BOTTOM to public names or adding
-the IterPeeps widening repair back.
-
-For this example, the root Return goes from `[Ctrl, MemBot, Bot]` after Opto to
-`[Ctrl, MemBot, *_B]` after TypeCheck; Stop's memory remains MemBot. The remaining
-design question is how to avoid this feedback while retaining conservative
-bounds and the existing pass budget. The current experiment leaves the printed
-IR expectations unchanged so they continue to expose this loss of precision.
-
-The source-validity audit separates these cases from Chapter10 `testIfOrNull`.
-That test originally returned the nullable pointer itself. A historical edit
-changed it to `return bar.a;` without adding TypeCheck, leaving a real null
-error hidden behind a printed-IR assertion. It now again returns `bar`, runs
-through TypeCheck, and passes with `return Phi(Region,null,Test._Bar);`.
-
-All four remaining programs pass TypeCheck. The Chapter12 recursive-object
-tests have one pending bad Load after Opto; forwarding eliminates every Load
-and resolves the result to `17`, `_B`, or `_R`, while escape memory stays MemBot.
-
-The two Chapter17b forward-type tests now pass their original IR expectations
-and explicitly run TypeCheck. Their undeclared `B` is an opaque external type,
-not an arbitrary unknown local value. EscapeNode uses the frozen public
-interface as its fallback for that type, preserving escapes already present
-in its private and public memory inputs. This applies to both the actual private
-value and the declared field bound: in `testForward1`, the private array element
-type is already `B?`. Bounding only FIDXs is insufficient; FULL aliases expose
-private class fields, which then expose their constructor FIDXs.
-
-CodeGen caches the fallback when ParseAll freezes the public interface. It
-returns FULL until Opto's existing reset walk installs the closed types into
-the IR. Only then does an open `_fref` reliably denote an external object.
-Ordinary open local structs, `TypeScalar.BOT`, and abstract pointers still
-require FULL. No new pass or IterPeeps hook is involved.
-
-### Escape-bound audit
-
-All Chapter29 `escapesFrom`, `XInt.FULL`, and `TypeMem.BOT` uses were reviewed,
-including the equivalent `escapes` helper and indirect `makePrivate` uses.
-The following remaining sites warrant work; they have not been narrowed here:
-
-* **StoreNode's three `escapesFrom(val)` paths.** The singleton constant,
- private instance, and ordinary aliasing paths still treat an opaque external
- value as FULL. A concrete example is:
-
- ```simple
- struct _A { B? !b; new _A = { B? p -> b=p; }; };
- val wrap = { B? b -> return new _A(b); };
- return wrap;
- ```
-
- This passes TypeCheck, but the surviving Stores of `b` have FULL FIDX and
- alias sets and keep an extra `_A` allocator. Do not mechanically substitute
- the public default: singleton slices deliberately discard unrelated incoming
- memory escapes. A narrower opaque bound must retain private values previously
- given to external code, without freezing unrelated transient escapes into
- singleton constants. Ordinary aliasing Stores already retain incoming sets.
-
-* **StopCU return values, CallNode external arguments, and SummaryNode arguments.**
- These use `escapes`, which currently duplicates the unbounded `escapesFrom`.
- `val identity = { B? b -> return b; }; return identity;` passes TypeCheck but
- gives StopCU MemBot. Likewise,
- `val send = { B? b -> { B? -> int } retain = "C"; return retain(b); }; return send;`
- gives the native CallEnd MemBot. These are concrete instances of the same
- opaque-type precision loss. A future change can share the bounded helper,
- while retaining incoming/returned memory, explicit private arguments, and
- imported-summary effects. StopCU's public function seed and `escapesAliases`
- class seed describe known declarations; GlobalEscape's `escapes` calls merely
- union already computed TypeMem sets.
-
-* **CLInitNode's possible-initialization result.** Even a known initializer
- yields TypeMem.BOT until its ready flag is true; only the initialized flag's
- slice is precise. This loses both memory-content and escape precision.
- CLInit has an analysis call edge but no Return edge supplying callee effects.
- Improving it needs a dependency on the initializer's effects, including
- recursive dependencies. The public interface alone is not a safe cap: that
- initializer can publish private callbacks. Its unresolved-flag BOT fallback
- is also conservative, but normally disappears when the receiver resolves.
-
-* **CallEndNode's unknown or unlinked target result.** Both return TypeMem.BOT.
- The unlinked case covers invalid calls and transient missing edges; SCCP links
- valid finite targets before computing CallEnd. Truly unknown targets can be
- local private functions as well as external functions, so a public-only cap
- would be wrong. Native calls already use CallNode's argument/memory effects.
- Any refinement must distinguish target provenance and retain explicit private
- arguments; it is not the same small fix as an opaque external object.
-
-The other broad defaults appear justified:
-
-* TypeMem's generic BOTTOM/scalar/pointer cases and TypeStruct's unknown scalar
- fields must include private callbacks that later value refinement can reveal.
- Private-memory declarations/Phis use `makePrivate(BOTTOM)` for the same reason.
- MemMerge's `makePrivate(struct)` describes actual fields, not an external
- opaque object.
-* Parser/function memory declarations, initial node types, TypeTuple.STATE,
- and low-family error fallbacks in Store, MemMerge, BulkMemPhi, Start, and
- TypeTuple need worst-case memory. CallNode and SummaryNode likewise cannot
- promise bounded effects when their inputs are still arbitrary low values.
-* Iter's import reset gives newly loaded nonconstant memory FULL before repairing
- affected neighbors. Saved types belong to another caller context; constants
- retain their own computed types. This is a safe pessimistic seed, though it
- can contribute to the existing memory-cycle precision problem.
-* TypeFunPtr's FULL signatures and TypeRPC.BOT describe unknown function/return
- targets. Serialization/remapping preserves the FULL sentinel; type gathering
- exercises it; LoopNode's `isa(TypeMem.BOT)` is a type-family check. These do
- not independently manufacture an escape effect.
-
-Ignoring assertions, the remaining whole-node walks through TypeCheck are
-Opto's setup/reset and TypeCheck's error scan. Class-init checking separately
-scans function control flow and runs SCC over the resulting dependency graph.
-
-## Validation
-
-Chapter29's latest run tested 594 active cases with assertions: 590 passed and
-four printed-IR comparisons failed. `make -k tests` ran raw0 (400/404), raw1
-(38), standalone (13), system (29), and fuzzer (1); the aggregate group (109)
-was run separately because Make skips it after a prerequisite failure.
-The remaining failures retain extra private constructors: Chapter12 `testCoRecur`,
-`testCoRecur2`, `testCoRecur3`, and `testPrivateRecursiveReturn`. Both Chapter17b
-forward tests pass unchanged goldens. TypeTest.testOpaqueExternalEscapes checks
-both fallback sets, preservation of prior private escapes, and FULL for ordinary
-unknowns. System, spill, import, callback, and constructor tests pass. The only
-golden changed during the earlier source-validity audit belongs to the restored
-`return bar;` source; none were changed to accept extra functions.
-
-The offset regression fails with the old slot-0 layout. Constructor and
-boundary tests pass, including both missed rejections and the prior NPE.
-Printed-IR expectations omit the dead private-helper MemTop Returns; no
-rejection expectations were relaxed. The three String spill checks now expect
-21 on x86, with the same live functions and inlining decisions.
diff --git a/chapter31/docs/drawing.md b/chapter31/docs/drawing.md
deleted file mode 100644
index 3fec1f12..00000000
--- a/chapter31/docs/drawing.md
+++ /dev/null
@@ -1,84 +0,0 @@
-# Drawing in Simple
-
-`sys.draw` draws into an ordinary `u32[]`. It has no native dependencies and
-does not open a window. `sys.gfx` presents the resulting pixels using the
-optional [MiniFB backend](graphics.md).
-
-```simple
-val canvas = new sys.draw.Canvas(600,780);
-u32 orange = 0xe47b57;
-canvas.clear(sys.draw.WHITE);
-canvas.fillRect(20,20,180,80,orange);
-canvas.rect(20,20,180,80,3,sys.draw.BLACK);
-canvas.circle(300,200,48,8,sys.draw.BLUE);
-canvas.fillCircle(420,200,20,sys.draw.GREEN);
-canvas.line(40,320,250,440,12,orange);
-canvas.text(40,500,"YOUR TURN",4,sys.draw.BLACK);
-// After sys.gfx.open succeeds:
-sys.gfx.present(canvas.pixels);
-```
-
-## Small raster API
-
-Coordinates start at the upper left; x increases rightward and y downward.
-Drawing methods return the canvas for chaining. Everything is opaque RGB;
-there is no blending, antialiasing, transform stack, or native drawing state.
-Coordinates accept `i64` so ordinary widened arithmetic can be passed directly.
-Circle radii and circle stroke widths are `int`. Use screen-sized coordinates,
-extents, and stroke widths.
-
-| Operation | Behavior |
-| --- | --- |
-| `rgb(r,g,b)` | Clamp components to 0–255 and pack RGB. `BLACK`, `WHITE`, `RED`, `GREEN`, and `BLUE` are available too. |
-| `new Canvas(width,height)` | Allocate a zero-filled pixel array. Dimensions must be positive and their product must fit a signed 32-bit index; invalid sizes exit with status 1. Allocation can still fail for lack of memory. |
-| `clear(color)` | Fill the entire canvas. |
-| `pixel(x,y,color)` | Set one pixel; ignore points outside the canvas. |
-| `fillRect(x,y,w,h,color)` | Fill a half-open rectangle: x through x+w-1, y through y+h-1. |
-| `rect(x,y,w,h,thickness,color)` | Draw an inward outline. A sufficiently wide outline fills the rectangle. |
-| `fillCircle(cx,cy,radius,color)` | Fill a circle; radius zero draws its center pixel. |
-| `circle(cx,cy,radius,thickness,color)` | Draw an inward circular outline. |
-| `line(x0,y0,x1,y1,thickness,color)` | Draw a round-ended segment. A zero-length segment draws a round dot. Thickness is its geometric diameter, sampled at integer pixel centers. |
-| `text(x,y,string,scale,color)` | Draw a 3×5 bitmap font, with one column between characters. Upper/lowercase ASCII letters, digits, spaces, and basic punctuation are supported. Newline advances six scaled pixels. Unknown characters use `?`. |
-
-Shapes clip to the canvas. Nonpositive rectangle extents, stroke widths, or
-text scale do nothing; negative circle radii do nothing. Line and circle
-coverage scans only the clipped bounding box, which is sufficient for small
-turn-based games. This is a starting raster library rather than a fast animated
-renderer. The pixel array remains available for direct drawing and inspection.
-
-Packed colors use hexadecimal literals (`0xRRGGBB`); `rgb(r,g,b)` remains handy
-for computed components. The font masks use leading-zero octal, with five
-digits after the prefix: each digit is one three-pixel row, top to bottom.
-For example, `A` is `025755`: rows `010`, `101`, `111`, `101`, `101`.
-
-## Graphical tic-tac-toe
-
-From `chapter31`:
-
-```sh
-make run-graphical-tictactoe CTAGS=
-```
-
-Click an empty square or press **1–9**, numbered left-to-right, top-to-bottom.
-You are X; the CPU is O. It wins when possible, blocks your immediate win,
-then prefers the center, corners, and edges. The result stays visible with
-the winning line highlighted. Press **R** or **Space** to start a new game,
-or **Q**/**Escape** to quit. Restart is also available during a game.
-
-Held buttons and keys do not take repeated turns. Moving the pointer highlights
-empty cells. The canvas is redrawn only after a move, restart, or hover change;
-polling still processes window events and waits between polls.
-
-`make graphical-tictactoe CTAGS=` builds without opening a window or requiring
-MiniFB. Its output is `build/examples/x86_64_v2_win64/TicTacToeGraphical.exe`
-on Windows or `build/examples/x86_64_v2_SystemV/TicTacToeGraphical` on Linux.
-The explicit backend path follows [the pixel-window instructions](graphics.md).
-Passing any argument performs a five-poll, self-closing smoke test.
-
-The original `make tictactoe` still builds the terminal game.
-The graphical game also uses optional [background audio](audio.md): a soft
-boop for accepted moves, rising tones for a player win, and falling tones for
-a CPU win. Bad input is silent. The run target builds/configures both backends.
-`make test CLASS=DrawTest CTAGS=` checks raster pixels and complete game turns
-without a display. `make tests_nographics CTAGS=` runs the ordinary suite with
-the backend disabled.
diff --git a/chapter31/docs/escape-flow.md b/chapter31/docs/escape-flow.md
deleted file mode 100644
index 8ad49f15..00000000
--- a/chapter31/docs/escape-flow.md
+++ /dev/null
@@ -1,147 +0,0 @@
-# Outside-world escape flow
-
-The `escape-flow` branch developed this design in Chapter29 and backported it
-to Chapters 28a/28b. Chapter28a uses `LocalIds` and its existing initializer
-root/lowering protocol; Chapter28b adds saved summaries and cofinite identity
-remapping. Neither port imports Chapter29's deferred-construction model.
-
-## The cycle
-
-The outside world's access to local objects and functions is a value in the
-Start/Stop cycle. Public declarations are not that value. The frozen public
-interface inventory has been removed; public-method and public-alias tests
-check the converged outside escape sets directly.
-
-At Opto setup, the outer Start receives a constant foreign-identity seed:
-
-```
-foreign identities = FULL minus identities owned by this compilation
-outside identities = foreign identities union discovered local escapes
-```
-
-Known native function and storage identities are foreign too. The infinite
-tail permits future foreign functions even when no local callback has escaped.
-The finite exclusions include registered imported identities, including bodies
-represented by summaries. This scans identity tables, not the IR. Opto's
-existing reset/worklist solve discovers the local escapes.
-
-StartCU includes the shared outside state. Infinite FIDX sets must retain their
-exclusions: `Opto.linkStart` checks each local function's membership rather than
-treating every cofinite set as FULL. Serialization remaps a cofinite set by
-remapping its finite exclusions and complementing again.
-
-Before Opto, outside queries remain pessimistic. During SCCP, a consumer can
-read the foreign seed before Start has run: otherwise a temporary finite set
-can turn a generic foreign callback into an unrelated local function with the
-same arity. No previous escape result is accumulated to repair value flow.
-
-## Consumers and dependencies
-
-* Memory and callback defaults for unknown callers use Start's memory
- projection. Parm applies its declared callback signature to the escaping
- FIDX set. Defaults whose values do not depend on escapes remain constants.
-* Unknown/native CallEnd results use the outside state and the current call's
- exposed arguments. Callback results are bounded by their declared signature
- and the outside FIDX set. Explicit linked Return effects are retained.
-* CallEnd registers a direct dependency on Start. Depending only on Call is
- insufficient: Call can stay CONTROL while the outside set changes. This
- first implementation uses `addDepForwards`; it does not change CallEnd's
- input layout or introduce a synthetic Fun/Return pair.
-* Infinite calls use the outside continuation. Escaped local functions remain
- callable through Start, and their effects return through Stop. Attaching
- every same-arity body to an infinite call is incorrect: argument/result
- families may differ despite the equal arity.
-* Outgoing Call argument exposure is independent of CallEnd, including a call
- that never returns. The shared fixed point also permits immediate callback
- round trips and reentrant calls.
-* Opaque external values in Escape, Store, Return, and imported-summary paths
- use the current outside/input-memory bound. Explicit private values and
- already accumulated escapes remain included. Arbitrary local BOTTOM values
- still require FULL.
-* Function-valued Loads use their memory input's FIDX bound, joined with the
- field declaration. They do not independently manufacture an escape set.
-
-CLInit was another unconditional producer of FULL. During Opto it now depends
-on the known initializer's Return and merges those effects with incoming
-memory. It waits for live memory before publishing effects. Lowering computes
-the replacement CallEnd's linked type before exposing its projections, so a
-temporary unlinked MemBot cannot widen the already analyzed caller.
-
-## Why the recursive tests needed local precision too
-
-All four former Chapter12 printed-IR failures pass their original expectations.
-The problem was not solely an outside-call default:
-
-1. Convert widened a non-null pointer to a nullable declaration until its later
- identity rewrite. It now preserves non-nullness in compute. Preserving the
- entire source shape conditionally failed the existing monotonicity test;
- shape and access still follow the declaration.
-2. A Load could wait until post-SCCP Store forwarding to recover that non-null
- pointer. In the meantime the next dereference produced BOTTOM, which fed
- FULL around the memory cycle and revived private constructors.
-3. Forwarded addresses, resolved field aliases, and already-bypassed CLInit
- projections were also waiting for graph rewrites.
-
-Load's existing forwarding search now supplies pointer value facts during
-compute, without constructing or rewriting nodes. It can recognize a stored
-address through a valid pointer conversion or a proven forwarded Load, use a
-resolved named field before layout, and follow an existing CLInit bypass.
-The same dependency mechanism reruns the search when its evidence changes.
-Nullable/incomplete access checks still precede this sharpening; arbitrary
-memory Phis and unknown stores remain barriers. This adds local queries, not a
-new whole-program pass, analysis map, or second IR.
-
-## Hidden class receivers
-
-A class function's hidden `#self` defaults to its owning class singleton.
-Seeding that input with TypePtr.PTR used to give FULL escapes when forwarded
-to an unknown callback. For example:
-
-```simple
-val _hidden_noInline = { int n -> return n+2; };
-val apply_noInline = { {int->int} f,int n -> return f(n); };
-return apply_noInline;
-```
-
-`FunNode.defaultArg` now supplies the Test class singleton for this receiver,
-both during parsing and when Opto reconnects unknown callers. The callback
-parameter still reads Start dynamically. The printed-IR regression verifies
-that only `<clinit>` and `apply_noInline` escape; `_hidden_noInline` stays private.
-
-The function signature retains TypePtr.PTR in this slot. The backends use it
-to identify the hidden ABI argument, and callback annotations must not bind
-the receiver to the class where the annotation appears. Explicit calls still
-supply their actual receiver; instance methods keep their declared object
-type. This sharpens the default input, not every abstract pointer: a local
-merge of a private object and private callback can also have an abstract
-pointer type, so capping arbitrary TypePtr values at outside escapes is unsound.
-
-## Remaining design question
-
-Late imported identities also deserve further precision work: identities not
-registered when Opto starts lie in the foreign tail. Existing import tests
-exercise correctness, but this can remain conservative when bodies arrive
-later. This limitation is not repaired by resetting the whole IR.
-
-## Validation
-
-The combined `make -k tests CHAPTERS="chapter28a chapter28b chapter29" CTAGS=`
-run passes with assertions: 538 active tests in Chapter28a, 578 in Chapter28b,
-and 601 in Chapter29. Shared printer and ISA checks pass too. The log is saved
-under ignored `build/escape-backport-final.log`.
-
-`EscapeFlowTest` covers opaque wrappers with three worklist seeds, foreign
-callback parameters, private callbacks passed to and returned from native code,
-and a CallEnd dependency that responds when only Start's escape set changes.
-It also checks that public allocators escape while their private-memory helpers
-do not. Class-init tests cover unknown callback cycles; saved-library tests in
-28b/29 verify private-function exclusions survive identity remapping.
-The existing suites cover nonreturning native calls, class-init cycles,
-constructor rejection, serialization, imported callbacks, and three backends.
-The four recursive-class examples also pass a separate 16-case worklist-seed
-check. Backport IR expectations now retain public allocator Returns instead of
-private-memory helper Returns. The String allocation/encoding/export fixtures
-in 28a/28b/29 now declare `_hashCodeString` before the public `hashCode` wrapper,
-so the implicit return exposes the wrapper. Their measured spill expectations
-are 12/8/6 (x86/RISC-V/ARM); native x86 export expects 12. The reordered fixture
-also measures 8 on RISC-V before the backport, versus the old order's 6.
diff --git a/chapter31/docs/examples/Breakout.smp b/chapter31/docs/examples/Breakout.smp
new file mode 100644
index 00000000..d60894ac
--- /dev/null
+++ b/chapter31/docs/examples/Breakout.smp
@@ -0,0 +1,369 @@
+// Clear 24 x 8 bricks. Arrows or mouse move; Space/click serves; P pauses;
+// R restarts; Q/Escape exits. Any argument runs ten frames as a smoke test.
+u32 WIDTH = 1008, HEIGHT = 760, COLS = 24, ROWS = 8;
+int LEFT = 24, RIGHT = 984, TOP = 84, BOTTOM = 718;
+int BRICK_TOP = 152, BRICK_DX = 40, BRICK_DY = 22, BRICK_W = 36, BRICK_H = 18;
+int RADIUS = 5, PADDLE_HALF = 56, PADDLE_Y = 674;
+int READY = 0, PLAY = 1, WON = 2, LOST = 3;
+int KEY_LEFT = 263, KEY_RIGHT = 262; // MiniFB key codes; gfx.LEFT is a mouse button.
+i64 STEP_ms = 8, FRAME_ms = 16;
+u32 BACKGROUND = 0x0b1220, WHITE = 0xeef7ff, MUTED = 0x8aabc4, CYAN = 0x4ce0ef;
+val COLORS = new u32[~]{0xff5268,0xff8050,0xffb548,0xffdb58,
+ 0x9bdd58,0x45d8b0,0x49b9f5,0x8d94ff};
+val DIGITS = new u8[~][~]{"0","1","2","3","4","5","6","7","8","9"};
+
+struct Game {
+ u8[] bricks = new u8[COLS*ROWS]{int i -> 1;};
+ int score = 0, remaining = COLS*ROWS, lives = 3, depth = 1, phase = READY;
+ bool boosted = false, backWall = false, paused = false;
+ f64 x = 504.0, y = 663.0, dx = 0.4, dy = -0.916515138991168;
+
+ // Fixed 8 ms simulation, split further to travel at most two pixels per step.
+ // Even at maximum boosted speed a ball cannot tunnel through an 18 px brick.
+ val _tick = { int direction ->
+ if( paused || phase == WON || phase == LOST ) return 0;
+ _paddle(paddle+direction*6.4);
+ if( phase == READY ) { x = paddle; y = PADDLE_Y-RADIUS-6; return 0; }
+ f64 seconds = 0.008; // 8ms
+ while( seconds > 0.000000001 && phase == PLAY ) {
+ f64 dt = 2.0/speed;
+ if( dt > seconds ) dt = seconds;
+ seconds -= dt;
+ f64 oldX = x, oldY = y;
+ x += dx*speed*dt;
+ y += dy*speed*dt;
+ if( x < LEFT+RADIUS && dx < 0.0 ) {
+ x = 2.0*(LEFT+RADIUS)-x; dx = -dx; _cue(1);
+ }
+ if( x > RIGHT-RADIUS && dx > 0.0 ) {
+ x = 2.0*(RIGHT-RADIUS)-x; dx = -dx; _cue(1);
+ }
+ if( y < TOP+RADIUS && dy < 0.0 ) {
+ y = 2.0*(TOP+RADIUS)-y; dy = -dy;
+ backWall = true; _cue(1);
+ }
+ if( dy > 0.0 && oldY <= PADDLE_Y-RADIUS && y >= PADDLE_Y-RADIUS &&
+ paddle-PADDLE_HALF-RADIUS <= x <= paddle+PADDLE_HALF+RADIUS ) _rebound();
+ if( y > BOTTOM+RADIUS ) {
+ _lostBall();
+ break;
+ }
+ // Map the center into the grid of radius-expanded brick boxes.
+ // Their overlap is smaller than one cell: at most 2 x 2 candidates.
+ if( x <= LEFT+2 -RADIUS || x >= LEFT+2 +(COLS-1)*BRICK_DX+BRICK_W+RADIUS ||
+ y <= BRICK_TOP-RADIUS || y >= BRICK_TOP+(ROWS-1)*BRICK_DY+BRICK_H+RADIUS )
+ continue;
+ int col = (x-(LEFT+2 -RADIUS))/BRICK_DX;
+ int row = (y-(BRICK_TOP-RADIUS))/BRICK_DY;
+ bool hit = false;
+ for( int r = row > 0 ? row-1 : 0; r <= row && r < ROWS && !hit; r++ )
+ for( int c = col > 0 ? col-1 : 0; c <= col && c < COLS; c++ ) {
+ int i = r*COLS+c;
+ if( bricks[i] == 0 ) continue;
+ f64 left = LEFT+2 +c*BRICK_DX-RADIUS;
+ f64 top = BRICK_TOP+r*BRICK_DY-RADIUS;
+ f64 right = left+BRICK_W+2*RADIUS;
+ f64 bottom= top +BRICK_H+2*RADIUS;
+ if( left < x < right && top < y < bottom ) {
+ bool back = false;
+ // Resolve the face crossed this step, using the previous center.
+ // Vertical faces win a simultaneous corner contact.
+ if( oldY <= top && dy > 0.0 ) {
+ y = top; dy = -dy; back = true;
+ } else if( oldY >= bottom && dy < 0.0 ) {
+ y = bottom; dy = -dy;
+ } else if( oldX <= left && dx > 0.0 ) {
+ x = left; dx = -dx;
+ } else if( oldX >= right && dx < 0.0 ) {
+ x = right; dx = -dx;
+ } else continue; // Missed all bricks
+ _brick(i,back);
+ hit = true;
+ break;
+ }
+ }
+ }
+ return 0;
+ };
+
+
+ // Several sound things might happen in this event, pick one
+ int sound = 0; // Increasing priority: wall, paddle, brick, boost, miss, win.
+ val _cue = { int snd -> if( snd > sound ) sound = snd; };
+
+ // Ball speed is a fraction of deepest brick hit, plus backwall boost
+ f64 speed;
+ val _speed = { -> speed = (320.0+35.0*(depth-1))*(boosted ? 1.65 : 1.0); };
+
+ // Clamp paddle to wall sides
+ f64 paddle;
+ val _paddle = { f64 x ->
+ paddle = x < LEFT +PADDLE_HALF ? LEFT +PADDLE_HALF :
+ x > RIGHT-PADDLE_HALF ? RIGHT-PADDLE_HALF :
+ x;
+ };
+
+ // Hit the paddle
+ val _rebound = { ->
+ // Where along the paddle did you hit?
+ f64 offset = (x-paddle)/PADDLE_HALF;
+ if( offset < -1.0 ) offset = -1.0;
+ if( offset > 1.0 ) offset = 1.0;
+ dx = 0.88*offset;
+ // A near-center hit still drifts sideways instead of repeating forever.
+ if( -0.12 < dx < 0.12 ) dx = dx < 0.0 ? -0.12 : 0.12;
+ dy = -_sqrt(1.0-dx*dx); // Bounce upwards speed
+ y = PADDLE_Y-RADIUS; // Reset ball hit to top of paddle
+ backWall = false; // Did not hit back wall
+ _cue(2); // Paddle bounce sound
+ };
+
+ // Hit a brick?
+ int soundDepth; // Which brick depth for the boop
+ val _brick = { int index, bool back ->
+ if( bricks[index] == 0 ) return 0; // No brick to hit!
+ bricks[index] = 0; // Clear brick
+ int row = ROWS-index/COLS; // Get brick row
+ score += row; // Score by row
+ remaining--; // Fewer bricks to iwn
+ if( row > depth ) depth = row; // Max depth seen
+ // Brick-hit sound
+ if( sound <= 3 ) { _cue(3); soundDepth = row; }
+ if( back && backWall && !boosted ) { _cue(3); boosted = true; }
+ if( remaining == 0 ) { _cue(6); phase = WON; }
+ _speed();
+ return 0;
+ };
+
+ // Missed ball with paddle
+ val _lostBall = { ->
+ lives--;
+ phase = lives == 0 ? LOST : READY;
+ backWall = false;
+ depth = 1;
+ boosted = false;
+ _speed();
+ x = paddle; y = PADDLE_Y-RADIUS-6;
+ _cue(5);
+ };
+
+ // Reset for another round
+ val _reset = { ->
+ for( int i = 0; i < bricks#; i++ ) bricks[i] = 1;
+ score = 0;
+ remaining = COLS*ROWS;
+ lives = 3;
+ depth = 1;
+ phase = READY;
+ boosted = false;
+ backWall = false;
+ paused = false;
+ sound = 0;
+ soundDepth = 1;
+ paddle = 504.0;
+ x = paddle;
+ y = PADDLE_Y-RADIUS-6;
+ _speed();
+ };
+
+ // --------------------------------
+ // Drawing code
+ val _hud = { !sys.draw.Canvas c ->
+ c.text(24,22,"BREAKOUT",5,WHITE);
+ c.text(264,20,"SCORE",2,MUTED);
+ _number(c,264,40,score,3,4,WHITE);
+ c.text(424,20,"BRICKS",2,MUTED);
+ _number(c,424,40,remaining,3,4,WHITE);
+ c.text(584,20,"BALLS",2,MUTED);
+ for( int i = 0; i < lives; i++ ) c.fillCircle(590+23*i,50,5,CYAN);
+ c.text(714,20,"SPEED",2,MUTED);
+ int ispeed = speed;
+ _number(c,714,40,ispeed,3,4,boosted ? COLORS[0] : WHITE);
+ c.text(838,40,boosted ? "BOOST!" : "NORMAL",3,boosted ? COLORS[0] : MUTED);
+ };
+
+
+ val _bricks = { !sys.draw.Canvas c ->
+ c.fillRect(LEFT-4,TOP-4,RIGHT-LEFT+8,4,MUTED);
+ c.fillRect(LEFT-4,TOP,4,BOTTOM-TOP,0x29435a);
+ c.fillRect(RIGHT,TOP,4,BOTTOM-TOP,0x29435a);
+ c.text(376,108,boosted ? "BACK WALL BOOST ACTIVE" : "BREAK THROUGH FOR A BOOST",2,boosted ? COLORS[0] : MUTED);
+ for( int i = 0; i < bricks#; i++ ) {
+ if( bricks[i] == 0 ) continue;
+ int row = i/COLS;
+ i64 x = LEFT+2+(i%COLS)*BRICK_DX, y = BRICK_TOP+row*BRICK_DY;
+ c.fillRect(x,y,BRICK_W,BRICK_H,COLORS[row]);
+ c.fillRect(x,y,BRICK_W,2,WHITE);
+ }
+ };
+
+ val _overlay = { !sys.draw.Canvas c ->
+ if( phase != PLAY || paused ) {
+ c.fillRect(246,422,516,108,0x17263a).rect(246,422,516,108,2,0x29435a);
+ u8[~] title = paused ? "PAUSED" : phase == WON ? "WALL CLEARED!" : phase == LOST ? "GAME OVER" : "READY?";
+ c.text(504-(title#*4-1)*4/2,442,title,4,WHITE);
+ u8[~] help = paused ? "P TO CONTINUE" : phase == WON || phase == LOST ? "R TO PLAY AGAIN" : "SPACE OR CLICK TO SERVE";
+ c.text(504-(help#*4-1)*2/2,490,help,2,CYAN);
+ }
+ return 0;
+ };
+
+ // With this Canvas, we draw into the blank canvas, then "present". The
+ // underlying graphics lib copies the bits, and we are then free to clear
+ // and draw again while the old bits continue to be presented.
+ val _draw = { !sys.draw.Canvas c ->
+ c.clear(BACKGROUND);
+ _hud(c);
+ _bricks(c);
+ i64 paddle = paddle, ballX = x, ballY = y;
+ int glowRadius = RADIUS+3;
+ c.fillRect(paddle-PADDLE_HALF,PADDLE_Y,2*PADDLE_HALF,12,CYAN);
+ c.fillRect(paddle-PADDLE_HALF+4,PADDLE_Y+2,2*PADDLE_HALF-8,2,WHITE);
+ c.fillCircle(ballX,ballY,glowRadius,boosted ? 0x672a42 : 0x224b61);
+ c.fillCircle(ballX,ballY,RADIUS,boosted ? COLORS[0] : WHITE);
+ _overlay(c);
+ c.text(24,738,"ARROWS / MOUSE: MOVE SPACE / CLICK: SERVE P: PAUSE R: RESTART Q / ESC: QUIT",2,MUTED);
+ };
+
+ // Served and still holding serve key
+ bool serveHeld;
+ // Paused and still holding pause key
+ bool pauseHeld;
+ // Restart and still holding restart key
+ bool restartHeld;
+ // Last mouse position; track moving mouse
+ int lastMouse;
+
+ // Read and act on the controls
+ val _input = { sys.draw.Canvas c ->
+ val gfx = sys.gfx;
+ bool serve = gfx.key(' ') || gfx.button(gfx.LEFT);
+ bool pause = gfx.key('P');
+ bool restart= gfx.key('R');
+
+ // Keyboard direction and mouse position
+ int direction = (gfx.key(KEY_RIGHT) ? 1 : 0)-(gfx.key(KEY_LEFT) ? 1 : 0);
+ int mouse = c.localX(gfx.mouseX());
+
+ // Restart requested
+ restartHeld = debounce( restart, restartHeld, { -> _reset(); sys.audio.stop(); } );
+
+ // Playing or ready to play game?
+ if( phase == READY || phase == PLAY ) {
+ // Flip pause state
+ pauseHeld = debounce( pause, pauseHeld, { -> paused = !paused; } );
+
+ // If no key and mouse moved, set paddle to mouse
+ if( mouse >= 0 && mouse != lastMouse && direction == 0 && !paused ) {
+ _paddle(mouse*1.0); // Set paddle to mouse
+ // If READY and not PLAY, ball tracks paddle directly
+ if( phase == READY ) x = paddle;
+ }
+ lastMouse = mouse;
+
+ }
+
+ // Serve requested
+ serveHeld = debounce( serve, serveHeld, _serve );
+
+ // Return key direction, so the tick tracking can slide paddle smoothly
+ return direction;
+ };
+
+ val debounce = { bool b, bool bHeld, { int } action ->
+ if( b && !bHeld ) // Action requested and repeating
+ action(); // Do action
+ b; // Dont action again, until 'b' is released
+ };
+
+
+ // Serve the ball; give it a nominal direction and speed
+ val _serve = { ->
+ if( phase == READY && !paused ) {
+ phase = PLAY;
+ dx = 0.4;
+ dy = -_sqrt(1.0-dx*dx);
+ }
+ return 0;
+ };
+};
+
+// Fixed-width decimal labels avoid allocating new strings on every frame.
+val _number = { !sys.draw.Canvas c, i64 x, i64 y, int value, int digits, int scale, u32 color ->
+ for( int i = 0; i < digits; i++ ) {
+ c.text(x+(digits-1-i)*4*scale,y,DIGITS[value%10],scale,color);
+ value /= 10;
+ }
+};
+
+// Short, fading triangle waves; the array initializer builds PCM once at startup.
+val _tone = { int period ->
+ val samples = new i16[~2400]{int i ->
+ int phase = i%period;
+ int triangle = phase < period/2 ? phase : period-phase;
+ return (triangle*4-period)*6000/period*(2400-i)/2400;
+ };
+ int handle = sys.audio.load(samples);
+ return handle < 0 ? sys.audio.BOOP : handle;
+};
+
+
+// Fast low accuracy sqrt
+val _sqrt = { f64 n ->
+ f64 r = 1.0;
+ for( int i = 0; i < 8; i++ ) r = (r+n/r)*0.5;
+ return r;
+};
+
+val main = { u8[~][] args ->
+ // Shortcuts
+ val gfx = sys.gfx, audio = sys.audio;
+
+ // Open a window
+ if( gfx.open("Simple Breakout",WIDTH,HEIGHT) != gfx.OK ) return 1;
+
+ // Audio setup; pre-specify a series of sounds
+ audio.open(); // Optional: a missing audio backend leaves play silent.
+ val sounds = new int[~]{0,_tone(120),_tone(80),audio.BOOP,audio.WIN,audio.LOSE,audio.WIN};
+ // Bottom to top: roughly 333..800 Hz, below the old 1000 Hz brick tone.
+ val brickSounds = new int[~ROWS]{int i -> int period = 144-i*12; _tone(period);};
+
+ // Setup drawing board
+ val c = new sys.draw.Canvas(WIDTH,HEIGHT);
+
+ // Setup game contents
+ val g = new Game;
+ g._reset();
+
+ //
+ int frames = 0, status = gfx.OK;
+ i64 last_ms = sys.time.monotonic(), pending_ms = 0, frame_ms = last_ms;
+
+ while( status == gfx.OK ) {
+ if( gfx.key('Q') || gfx.key(gfx.ESCAPE) ) break;
+ // Physics stays in base coordinates; only drawing and input scale.
+ if( c.resize(gfx.width(),gfx.height()) ) {
+ g.lastMouse = c.localX(gfx.mouseX());
+ frame_ms = 0;
+ }
+ int direction = g._input(c);
+ i64 now_ms = sys.time.monotonic(), elapsed_ms = now_ms-last_ms;
+ last_ms = now_ms;
+ // Drop long stalls instead of teleporting the ball after a window drag.
+ pending_ms += elapsed_ms < 0 ? 0 : elapsed_ms > 64 ? 64 : elapsed_ms;
+ while( pending_ms >= STEP_ms ) { g._tick(direction); pending_ms -= STEP_ms; }
+ if( g.sound != 0 ) {
+ audio.play(g.sound == 3 ? brickSounds[g.soundDepth-1] : sounds[g.sound]);
+ g.sound = 0;
+ }
+ if( now_ms >= frame_ms ) {
+ g._draw(c);
+ status = gfx.presentSize(c.pixels,c.width,c.height);
+ frame_ms = now_ms+FRAME_ms;
+ if( args# > 1 && ++frames == 10 ) break;
+ }
+ if( status == gfx.OK ) status = gfx.wait(STEP_ms-pending_ms);
+ }
+ audio.close(); gfx.close();
+ return status == gfx.ERROR ? 1 : 0;
+};
diff --git a/chapter31/docs/examples/Clock.smp b/chapter31/docs/examples/Clock.smp
new file mode 100644
index 00000000..fb50f84e
--- /dev/null
+++ b/chapter31/docs/examples/Clock.smp
@@ -0,0 +1,128 @@
+// Local clocks; click the button or press Space to switch. Q/Escape exits.
+// Any argument runs ten frames, exercising both faces for smoke tests.
+u32 GREEN = 0x62ff70, DIM = 0x123d20, BACKGROUND = 0x020b05;
+
+val main = { u8[~][] args ->
+ val gfx = sys.gfx;
+ val time = sys.time;
+ // The main Canvas
+ val screen = new sys.draw.Canvas(720,540);
+ if( gfx.open("Simple digital and analog clocks",screen.width,screen.height) != gfx.OK ) return 1;
+
+ // Button to flip clock style
+ val button = new sys.draw.Button(220,454,280,52,"ANALOG CLOCK");
+ val timers = new sys.time.Timers();
+ u32 frame_id = timers.every(33);
+ if( frame_id == 0 ) { gfx.close(); return 1; }
+
+ bool analog = false, held = false;
+ int frames = 0, status = gfx.OK;
+
+ // Main event loop
+ while( status == gfx.OK ) {
+ bool resized = screen.resize(gfx.width(),gfx.height());
+ // Did the user press space bar?
+ bool space = gfx.key(' ');
+ // Did the left mouse button go down?
+ bool down = gfx.button(gfx.LEFT);
+ // ANd did it go down over this button?
+ bool click = button.update(screen.localX(gfx.mouseX()),screen.localY(gfx.mouseY()),down);
+ // If clicked, flip the clock mode
+ if( click || (space && !held) ) analog = !analog;
+ held = space;
+ if( gfx.key('Q') ) break;
+ // Change button label
+ button.label = analog ? "DIGITAL CLOCK" : "ANALOG CLOCK";
+ // If the next timer event is the every-33-msec event
+ if( timers.poll(time.monotonic()) == frame_id || resized ) {
+ // Draw the clock screen and button
+ _draw(screen,time.now(),analog);
+ button.draw(screen,3,GREEN,BACKGROUND,DIM);
+ // Presne the canvas on screen
+ status = gfx.presentSize(screen.pixels,screen.width,screen.height);
+ // Testing only: show 5 frames, flip to analog, show 5 more and exit
+ if( args# > 1 ) {
+ frames++;
+ if( frames == 5 ) analog = true;
+ if( frames == 10 ) break;
+ }
+ }
+ if( status != gfx.OK ) break;
+ // Stall until next timer event
+ status = gfx.wait(time.remaining(timers.nextDeadline(),time.monotonic()));
+ }
+ gfx.close();
+ return status == gfx.ERROR ? 1 : 0;
+};
+
+val _draw = { !sys.draw.Canvas screen, i64 wall_ms, i64 analog ->
+ val d = sys.time.local(wall_ms);
+ screen.clear(BACKGROUND);
+ screen.text(266,24,"SIMPLE CLOCK",4,GREEN);
+ if( analog ) _analog(screen,d.hour,d.minute,d.second,d.millisecond);
+ else _digital(screen,d.hour,d.minute,d.second);
+ screen.text(298,412,"%(sys.time.formatLocal(wall_ms,sys.time.DATE))",4,GREEN);
+ screen.text(249,520,"SPACE SWITCH Q OR ESC QUIT",2,GREEN);
+};
+
+// a..g bits: top, upper-right, lower-right, bottom, lower-left, upper-left,
+// middle. Faint unlit bars retain the old LED figure-eight silhouette.
+val _digitFont = new u8[~]{
+ // 0 1 2 3 4 5 6 7 8 9
+ 0x3f, 0x06, 0x5b, 0x4f, 0x66, 0x6d, 0x7d, 0x07, 0x7f, 0x6f
+};
+val _digitBars = new u8[~]{
+ // x0 y0 x1 y1
+ 14, 0, 58, 0, // a: top
+ 68, 12, 68, 60, // b: upper-right
+ 68, 84, 68, 132, // c: lower-right
+ 14, 144, 58, 144, // d: bottom
+ 4, 84, 4, 132, // e: lower-left
+ 4, 12, 4, 60, // f: upper-left
+ 14, 72, 58, 72 // g: middle
+};
+val _digit = { !sys.draw.Canvas c, int x, int y, i64 digit ->
+ int bits = 0 <= digit < _digitFont# ? _digitFont[digit] : 0;
+ for( int i = 0; i < 7; i++ ) {
+ u32 color = (bits&(1<<i)) != 0 ? GREEN : DIM;
+ int bar = i*4;
+ c.line(x+_digitBars[bar ],y+_digitBars[bar+1],
+ x+_digitBars[bar+2],y+_digitBars[bar+3],10,color);
+ }
+};
+
+val _digital = { !sys.draw.Canvas c, int hour, int minute, int second ->
+ _digit(c, 68,166, hour/10); _digit(c,154,166, hour%10);
+ _digit(c,284,166,minute/10); _digit(c,370,166,minute%10);
+ _digit(c,500,166,second/10); _digit(c,586,166,second%10);
+ for( int i = 0; i < 2; i++ ) {
+ c.fillCircle(254+i*216,214,6,GREEN);
+ c.fillCircle(254+i*216,262,6,GREEN);
+ }
+ c.text(272,352,"LOCAL TIME 24H",3,GREEN);
+};
+val _hand = { !sys.draw.Canvas c, f64 turn, int length, int thickness, u32 color ->
+ f64 angle = turn*2*sys.math.PI;
+ int x = 360+sys.math.sin(angle)*length, y = 232-sys.math.cos(angle)*length;
+ c.line(360,232,x,y,thickness,color);
+};
+val _analog = { !sys.draw.Canvas c, int hour, int minute, int second, int millisecond ->
+ c.circle(360,232,154,3,GREEN);
+ for( int i = 0; i < 60; i++ ) {
+ f64 angle = i/60.0*2*sys.math.PI;
+ bool major = i%5 == 0;
+ int inner = major ? 133 : 143;
+ f64 sine = sys.math.sin(angle), cosine = sys.math.cos(angle);
+ int x0 = 360+sine*inner, y0 = 232-cosine*inner;
+ int x1 = 360+sine* 149 , y1 = 232-cosine* 149 ;
+ c.line(x0,y0,x1,y1,major ? 3 : 1,GREEN);
+ }
+ c.text(349,100,"12",2,GREEN); c.text(484,227,"3",2,GREEN);
+ c.text(357,354, "6",2,GREEN); c.text(230,227,"9",2,GREEN);
+ f64 seconds = second+millisecond/1000.0;
+ f64 minutes = minute+seconds/60.0;
+ _hand(c,(hour%12+minutes/60.0)/12.0,78,8,GREEN);
+ _hand(c,minutes/60.0,112,5,GREEN);
+ _hand(c,seconds/60.0,128,2,0xc3ffcb);
+ c.fillCircle(360,232,6,GREEN);
+};
diff --git a/chapter31/docs/examples/Dijkstra.smp b/chapter31/docs/examples/Dijkstra.smp
index 768bdd08..6591b310 100644
--- a/chapter31/docs/examples/Dijkstra.smp
+++ b/chapter31/docs/examples/Dijkstra.smp
@@ -3,20 +3,17 @@
// https://sampleprograms.io/projects/dijkstra/
val shortestPath = { !sys.aryi64 matrix, int nodes, int src, int dst ->
- i64 infinity = (1 << 63)-1;
- var dist = new i64[nodes];
+ i64 infinity = sys.integer.MAX_I64;
var visited = new sys.adt.bitset();
- // All nodes are infinitely far from each other
- for( int i=0; i<nodes; i++ ) dist[i] = infinity;
- // Starting point is zero far from starting point
- dist[src] = 0;
+ // All nodes are infinitely far from each other, except the starting point
+ var dist = new i64[nodes]{ int i -> i == src ? 0 : infinity; };
i64 result = -1;
int count = 0;
while( count < nodes && result < 0 ) {
int nearest = -1;
i64 best = infinity;
- for( int node=0; node<nodes; node++ )
+ for( int node = 0; node < nodes; node++ )
if( !visited.get(node) && dist[node] < best ) {
nearest = node;
best = dist[node];
@@ -25,8 +22,8 @@ val shortestPath = { !sys.aryi64 matrix, int nodes, int src, int dst ->
else {
if( nearest == dst ) return best;
visited.set(nearest);
- for( int node=0; node<nodes; node++ ) {
- u32 index=nearest*nodes + node;
+ for( int node = 0; node < nodes; node++ ) {
+ u32 index = nearest*nodes + node;
i64 weight = matrix.get(index);
if( weight > 0 && !visited.get(node) && best+weight < dist[node] )
dist[node] = best+weight;
@@ -50,7 +47,7 @@ val main = { u8[~][] args ->
if( !matrix ) return usage();
if( !matrix.len ) return usage();
// All numbers are positive
- for( u32 i=0; i<matrix.len; i++ )
+ for( u32 i = 0; i < matrix.len; i++ )
if( matrix.get(i) < 0 ) return usage();
// Matrix is square
int nodes = 0;
@@ -64,7 +61,7 @@ val main = { u8[~][] args ->
if( src < 0 || src >= nodes || dst < 0 || dst >= nodes )
return usage(); // Source and destination land within the graph
- int source=src, destination=dst;
+ int source = src, destination = dst;
i64 cost = shortestPath(matrix,nodes,source,destination);
if( cost >= 0 ) {
new sys.aryu8().num(cost).add('\n').write(1);
diff --git a/chapter31/docs/examples/Graphics.smp b/chapter31/docs/examples/Graphics.smp
index 7ba5c6e7..1878e97d 100644
--- a/chapter31/docs/examples/Graphics.smp
+++ b/chapter31/docs/examples/Graphics.smp
@@ -2,13 +2,22 @@
// Pass any argument for a short, self-closing test; otherwise close or press Esc.
val main = { u8[~][] args ->
if( sys.gfx.open("Simple pixels",320,240) != sys.gfx.OK ) return 1;
- val pixels = new u32[320*240];
- for( int y=0; y<240; y++ )
- for( int x=0; x<320; x++ )
- pixels[y*320+x] = (x*255/319 << 16) | (y*255/239 << 8) | 64;
- int result = sys.gfx.present(pixels);
+ val c = new sys.draw.Canvas(320,240);
+ int result = sys.gfx.OK;
+ bool dirty = true;
int frames = 0;
while( result == sys.gfx.OK ) {
+ if( c.resize(sys.gfx.width(),sys.gfx.height()) ) dirty = true;
+ if( dirty ) {
+ // The gradient fills the window, including non-4:3 shapes.
+ int dx = c.width > 1 ? c.width-1 : 1, dy = c.height > 1 ? c.height-1 : 1;
+ for( int y = 0; y < c.height; y++ )
+ for( int x = 0; x < c.width; x++ )
+ c.pixels[y*c.width+x] = (x*255/dx << 16) | (y*255/dy << 8) | 64;
+ result = sys.gfx.presentSize(c.pixels,c.width,c.height);
+ if( result != sys.gfx.OK ) break;
+ dirty = false;
+ }
result = sys.gfx.poll(true);
if( args# > 1 && ++frames == 5 ) break;
}
diff --git a/chapter31/docs/examples/README.md b/chapter31/docs/examples/README.md
index a1d81be2..05dcf6cb 100644
--- a/chapter31/docs/examples/README.md
+++ b/chapter31/docs/examples/README.md
@@ -2,18 +2,53 @@
These programs live beside the documentation so readers can find and run them.
Their non-graphical native regression tests run as part of `make tests`.
+All four graphical demos support window resizing. Clock, Tic-tac-toe, and
+Breakout scale their base layouts uniformly and center them in the window;
+mouse input follows the same transform. Breakout keeps its physics in base
+coordinates, so resizing preserves the current game and ball speed. The pixel
+gradient fills the entire window at its new resolution.
The optional [pixel-window example](Graphics.smp) uses MiniFB; see
-[graphics setup](../graphics.md). `make run-graphics` opens it explicitly.
+[graphics setup](../../src/main/smp/sys/gfx.md). `make run-graphics` opens it explicitly.
The [graphical tic-tac-toe](TicTacToeGraphical.smp) uses the Simple
-[drawing library](../drawing.md). Run it with
-`make run-graphical-tictactoe CTAGS=`; click a cell or press 1–9, R/Space to
+[drawing library](../../src/main/smp/sys/draw/README.md). Run it with
+`make run-graphical-tictactoe`; click a cell or press 1–9, R/Space to
replay, and Q/Escape to quit. The terminal game below remains available.
-Optional [background audio](../audio.md) supplies soft move and win/loss cues.
+Optional [background audio](../../src/main/smp/sys/audio.md) supplies soft move and win/loss cues.
+
+The [digital and analog clock](Clock.smp) demonstrates the [time library](../../src/main/smp/sys/time/README.md),
+green seven-segment digits, smooth clock hands, and a reusable software button.
+Run `make run-clock`; click the button or press Space to switch faces,
+and Q/Escape to exit. Both faces show system-local time.
+`make clock-example` builds it without starting a window.
+
+The [Breakout game](Breakout.smp) has 24 columns and 8 rows, with colors and
+point values by depth: 1 at the bottom through 8 at the top, 864 points total.
+Clear the wall before losing all three balls. Mouse movement or the arrow keys
+move the paddle; Space/left click serves, P pauses, R restarts, Q/Escape exits.
+Run `make run-breakout` or build only with `make breakout`.
+The familiar paddle, serve, and limited-ball rules follow
+[Atari's Breakout instructions](https://atari.com/pages/breakout).
+
+The deepest row reached with the current ball sets the base speed: 320 pixels/second plus 35 for
+each additional depth. After touching the back wall, hitting the top of a brick
+activates a **one-time 1.65x speed boost**; side/front hits do not. Returning to
+the paddle disarms that trip's back-wall opportunity. Losing a ball resets depth
+and boost, so each new ball starts at 320 pixels/second and can earn its own
+back-wall boost. Edge hits on the paddle give a wider
+rebound than center hits. Clear all bricks to win; no new wall replaces them.
+
+Physics uses fixed 8 ms ticks with movement split into steps of at most two
+pixels, including at boosted speed. Rendering runs roughly every 16 ms. The
+brick and sound tables demonstrate array initializers; the short bounce tones
+use read-only PCM arrays made by index functions. Brick boops rise in pitch with
+row depth, from about 333 Hz at the bottom to 800 Hz at the top. Audio is optional. Native
+tests in `BreakoutTest` exercise collisions, scoring, lives, pause, paddle angles,
+the boost, and clearing the whole wall without a display or audio device.
From `chapter31`, build the tic-tac-toe executable (without starting it):
```sh
-make lib tictactoe CTAGS=
+make lib tictactoe
```
Run the Windows build from PowerShell:
@@ -22,9 +57,15 @@ Run the Windows build from PowerShell:
.\build\examples\x86_64_v2_win64\TicTacToe.exe
```
-Or from Cygwin:
+Or from Command Prompt (`cmd.exe`):
-```sh
+```bat
+.\build\examples\x86_64_v2_win64\TicTacToe.exe
+```
+
+Or from Bash (Cygwin, using the Windows build):
+
+```bash
./build/examples/x86_64_v2_win64/TicTacToe.exe
```
@@ -36,7 +77,7 @@ directory in WSL. Separate Java and native output directories let the Windows
and Linux builds coexist:
```sh
-make lib tictactoe CLZDIR=build/classes-linux CTAGS=
+make lib tictactoe CLZDIR=build/classes-linux
./build/examples/x86_64_v2_SystemV/TicTacToe
```
diff --git a/chapter31/docs/examples/TicTacToe.smp b/chapter31/docs/examples/TicTacToe.smp
index a710e440..ee4e3182 100644
--- a/chapter31/docs/examples/TicTacToe.smp
+++ b/chapter31/docs/examples/TicTacToe.smp
@@ -3,8 +3,7 @@ val main = { u8[~][] args ->
sys.io.p("Tic-tac-toe!\nYou are X; the CPU is O. You go first.\n");
sys.io.p("Press a square's number (no Enter needed), or q/Esc to quit.\n");
sys.io.p("Squares:\n 1 | 2 | 3 \n---+---+---\n 4 | 5 | 6 \n---+---+---\n 7 | 8 | 9 \n\n");
- val board = new u8[9];
- for( int i=0; i<board#; i++ ) board[i]=' ';
+ val board = new u8[9]{ int i -> ' '; }; // Initialize the board
// Draw empty board
_draw(board);
@@ -22,7 +21,7 @@ val main = { u8[~][] args ->
// Compute CPU move
int reply = _cpu(board);
// Set CPU choice; print board
- board[reply]='O';
+ board[reply] = 'O';
sys.io.p("CPU plays %(reply+1).\n");
_draw(board);
// A winner?
@@ -62,37 +61,37 @@ val _validMove = { u8[~] board ->
// Return the winning mark, or zero.
val _winner = { u8[~] board ->
- for( int i=0; i<3; i++ ) {
+ for( int i = 0; i < 3; i++ ) {
int row = i*3;
- if( board[row]!=' ' && board[row]==board[row+1] && board[row]==board[row+2] )
+ if( board[row] != ' ' && board[row] == board[row+1] && board[row] == board[row+2] )
return board[row];
- if( board[i]!=' ' && board[i]==board[i+3] && board[i]==board[i+6] )
+ if( board[i] != ' ' && board[i] == board[i+3] && board[i] == board[i+6] )
return board[i];
}
- if( board[4]!=' ' ) {
- if( board[0]==board[4] && board[4]==board[8] ) return board[4];
- if( board[2]==board[4] && board[4]==board[6] ) return board[4];
+ if( board[4] != ' ' ) {
+ if( board[0] == board[4] && board[4] == board[8] ) return board[4];
+ if( board[2] == board[4] && board[4] == board[6] ) return board[4];
}
return 0;
};
val _finished = { u8[~] board ->
int winner = _winner(board);
- if( winner=='X' ) { sys.io.p("You win!\n"); return true; }
- if( winner=='O' ) { sys.io.p("CPU wins!\n"); return true; }
- for( int i=0; i<board#; i++ )
- if( board[i]==' ' ) return false;
+ if( winner == 'X' ) { sys.io.p("You win!\n"); return true; }
+ if( winner == 'O' ) { sys.io.p("CPU wins!\n"); return true; }
+ for( int i = 0; i < board#; i++ )
+ if( board[i] == ' ' ) return false;
sys.io.p("It's a draw!\n");
return true;
};
// Try each empty square, restoring it before returning.
val _threat = { u8[] board, u8 mark ->
- for( int i=0; i<board#; i++ ) {
- if( board[i]==' ' ) {
- board[i]=mark;
- bool wins = _winner(board)==mark;
- board[i]=' '; // Restore board
+ for( int i = 0; i < board#; i++ ) {
+ if( board[i] == ' ' ) {
+ board[i] = mark;
+ bool wins = _winner(board) == mark;
+ board[i] = ' '; // Restore board
if( wins ) return i;
}
}
@@ -104,30 +103,30 @@ val _threat = { u8[] board, u8 mark ->
val _cpu = { u8[] board ->
// If O can win, do so
int win = _threat(board,'O');
- if( win>=0 ) return win;
+ if( win >= 0 ) return win;
// If X will win next move, block
int block = _threat(board,'X');
- if( block>=0 ) return block;
+ if( block >= 0 ) return block;
// If center is open, take it
- if( board[4]==' ' ) return 4;
+ if( board[4] == ' ' ) return 4;
// If a corner is open, take it
- for( int i=0; i<board#; i+=2 )
- if( board[i]==' ' ) return i;
+ for( int i = 0; i < board#; i += 2 )
+ if( board[i] == ' ' ) return i;
// Take whatever is available
- for( int i=0; i<board#; i++ )
- if( board[i]==' ' ) return i;
+ for( int i = 0; i < board#; i++ )
+ if( board[i] == ' ' ) return i;
return -1;
};
val _draw = { u8[~] board ->
val out = new sys.aryu8();
- for( int row=0; row<3; row++ ) {
- for( int col=0; col<3; col++ ) {
+ for( int row = 0; row < 3; row++ ) {
+ for( int col = 0; col < 3; col++ ) {
out.add(' ').add(board[row*3+col]).add(' ');
- if( col<2 ) out.add('|');
+ if( col < 2 ) out.add('|');
}
out.add('\n');
- if( row<2 ) out.addAry("---+---+---\n");
+ if( row < 2 ) out.addAry("---+---+---\n");
}
out.write(sys.libc.STDOUT);
};
diff --git a/chapter31/docs/examples/TicTacToeGraphical.smp b/chapter31/docs/examples/TicTacToeGraphical.smp
index b4f8bcf4..72ee6522 100644
--- a/chapter31/docs/examples/TicTacToeGraphical.smp
+++ b/chapter31/docs/examples/TicTacToeGraphical.smp
@@ -9,101 +9,103 @@ val main = { u8[~][] args ->
if( sys.gfx.open("Simple tic-tac-toe",screen.width,screen.height) != sys.gfx.OK ) return 1;
sys.audio.open(); // Audio is optional; failure leaves the game silent.
_draw(screen,board,-1);
- int result = sys.gfx.present(screen.pixels);
+ int result = sys.gfx.presentSize(screen.pixels,screen.width,screen.height);
bool mouseHeld = false, keyHeld = false, replayHeld = false;
int hover = -1, frames = 0;
- while( result==sys.gfx.OK ) {
- result = sys.gfx.poll(true);
- if( result!=sys.gfx.OK ) break;
+
+ while( result == sys.gfx.OK ) {
+ result = sys.gfx.wait(17);
+ if( result != sys.gfx.OK ) break;
if( sys.gfx.key('Q') ) break;
bool down = sys.gfx.button(sys.gfx.LEFT);
bool replay = sys.gfx.key('R') || sys.gfx.key(' ');
- int square = _square(sys.gfx.mouseX(),sys.gfx.mouseY());
- bool dirty = square!=hover;
+ bool resized = screen.resize(sys.gfx.width(),sys.gfx.height());
+ int square = _square(screen.localX(sys.gfx.mouseX()),screen.localY(sys.gfx.mouseY()));
+ bool dirty = resized || square != hover;
hover = square;
- if( replay && !replayHeld ) { sys.audio.stop(); _reset(board); dirty=true; }
+ if( replay && !replayHeld ) { sys.audio.stop(); _reset(board); dirty = true; }
bool digit = false;
int choice = down && !mouseHeld ? square : -1;
- for( int i=0; i<9; i++ ) {
+ for( int i = 0; i < 9; i++ ) {
int key = '1'+i;
if( sys.gfx.key(key) ) {
digit = true;
- if( !keyHeld ) choice=i;
+ if( !keyHeld ) choice = i;
}
}
if( !(replay && !replayHeld) && _move(board,choice) ) {
sys.audio.play(_sound(board));
- dirty=true;
+ dirty = true;
}
mouseHeld = down;
keyHeld = digit;
replayHeld = replay;
if( dirty ) {
_draw(screen,board,hover);
- result = sys.gfx.present(screen.pixels);
+ result = sys.gfx.presentSize(screen.pixels,screen.width,screen.height);
}
- if( args#>1 && ++frames==5 ) break;
+ if( args# > 1 && ++frames == 5 ) break;
}
sys.audio.close();
sys.gfx.close();
- return result==sys.gfx.ERROR ? 1 : 0;
+ return result == sys.gfx.ERROR ? 1 : 0;
};
// Called only for an accepted move; invalid input never requests a sound.
val _sound = { u8[~] board ->
int winner = _winner(board);
- return winner=='X' ? sys.audio.WIN : winner=='O' ? sys.audio.LOSE : sys.audio.BOOP;
+ return winner == 'X' ? sys.audio.WIN : winner == 'O' ? sys.audio.LOSE : sys.audio.BOOP;
};
val _reset = { u8[] board ->
- for( int i=0; i<9; i++ ) board[i]=' ';
+ for( int i = 0; i < 9; i++ ) board[i] = ' ';
};
val _square = { int x, int y ->
- if( x<48 || x>=552 || y<168 || y>=672 ) return -1;
+ if( x < 48 || x >= 552 || y < 168 || y >= 672 ) return -1;
return (y-168)/168*3+(x-48)/168;
};
// One player turn followed by one CPU turn. Invalid/finished moves do nothing.
val _move = { u8[] board, int square ->
- if( square<0 || square>=9 || board[square]!=' ' || _finished(board) ) return false;
+ if( square < 0 || square >= 9 || board[square] != ' ' || _finished(board) ) return false;
board[square] = 'X';
if( !_finished(board) ) {
int reply = _cpu(board);
- if( reply>=0 ) board[reply]='O';
+ if( reply >= 0 ) board[reply] = 'O';
}
return true;
};
val _finished = { u8[~] board ->
if( _winner(board) ) return true;
- for( int i=0; i<9; i++ ) if( board[i]==' ' ) return false;
+ for( int i = 0; i < 9; i++ ) if( board[i] == ' ' ) return false;
return true;
};
val _winningLine = { u8[~] board ->
- for( int i=0; i<3; i++ ) {
+ for( int i = 0; i < 3; i++ ) {
int row = i*3;
- if( board[row]!=' ' && board[row]==board[row+1] && board[row]==board[row+2] ) return i;
- if( board[i]!=' ' && board[i]==board[i+3] && board[i]==board[i+6] ) return 3+i;
+ if( board[row] != ' ' && board[row] == board[row+1] && board[row] == board[row+2] ) return i;
+ if( board[i] != ' ' && board[i] == board[i+3] && board[i] == board[i+6] ) return 3+i;
}
- if( board[4]!=' ' ) {
- if( board[0]==board[4] && board[4]==board[8] ) return 6;
- if( board[2]==board[4] && board[4]==board[6] ) return 7;
+ if( board[4] != ' ' ) {
+ if( board[0] == board[4] && board[4] == board[8] ) return 6;
+ if( board[2] == board[4] && board[4] == board[6] ) return 7;
}
return -1;
};
// Return the winning mark, or zero.
val _winner = { u8[~] board ->
int line = _winningLine(board);
- return line<0 ? 0 : line<3 ? board[line*3] : line<6 ? board[line-3] : board[4];
+ return line < 0 ? 0 : line < 3 ? board[line*3] : line < 6 ? board[line-3] : board[4];
};
// Try each empty square, restoring it before returning.
val _threat = { u8[] board, u8 mark ->
- for( int i=0; i<9; i++ )
- if( board[i]==' ' ) {
+ for( int i = 0; i < 9; i++ )
+ if( board[i] == ' ' ) {
board[i] = mark;
- bool wins = _winner(board)==mark;
+ bool wins = _winner(board) == mark;
board[i] = ' '; // Restore board
if( wins ) return i;
}
@@ -114,16 +116,16 @@ val _threat = { u8[] board, u8 mark ->
val _cpu = { u8[] board ->
// If O can win, do so
int win = _threat(board,'O');
- if( win>=0 ) return win;
+ if( win >= 0 ) return win;
// If X will win next move, block
int block = _threat(board,'X');
- if( block>=0 ) return block;
+ if( block >= 0 ) return block;
// If center is open, take it
- if( board[4]==' ' ) return 4;
+ if( board[4] == ' ' ) return 4;
// If a corner is open, take it
- for( int i=0; i<9; i+=2 ) if( board[i]==' ' ) return i;
+ for( int i = 0; i < 9; i += 2 ) if( board[i] == ' ' ) return i;
// Take whatever is available
- for( int i=0; i<9; i++ ) if( board[i]==' ' ) return i;
+ for( int i = 0; i < 9; i++ ) if( board[i] == ' ' ) return i;
return -1;
};
@@ -135,31 +137,31 @@ val _draw = { !sys.draw.Canvas screen, u8[~] board, int hover ->
screen.clear(background);
screen.text(48,34,"TIC TAC TOE",6,paper);
screen.fillRect(48,90,504,3,ink);
- screen.text(48,116,finished ? (winner=='X' ? "YOU WIN!" : winner=='O' ? "CPU WINS" : "DRAW") : "YOUR TURN",4,accent);
+ screen.text(48,116,finished ? (winner == 'X' ? "YOU WIN!" : winner == 'O' ? "CPU WINS" : "DRAW") : "YOUR TURN",4,accent);
screen.line(428,112,450,134,5,cross).line(450,112,428,134,5,cross);
screen.circle(496,123,13,5,0x70c9bf);
screen.text(428,145,"YOU",2,0xa2b9b7);
screen.text(484,145,"CPU",2,0xa2b9b7);
screen.fillRect(48,168,504,504,paper);
- if( !finished && hover>=0 && hover<9 && board[hover]==' ' )
- screen.fillRect(48+(hover-hover/3*3)*168,168+hover/3*168,168,168,0xd9e8de);
- for( int i=1; i<3; i++ ) {
+ if( !finished && hover >= 0 && hover < 9 && board[hover] == ' ' )
+ screen.fillRect(48+(hover%3)*168,168+hover/3*168,168,168,0xd9e8de);
+ for( int i = 1; i < 3; i++ ) {
screen.fillRect(48+i*168-3,168,6,504,ink);
screen.fillRect(48,168+i*168-3,504,6,ink);
}
- for( int i=0; i<9; i++ ) {
- int cx = 132+(i-i/3*3)*168, cy = 252+i/3*168;
- if( board[i]=='X' )
+ for( int i = 0; i < 9; i++ ) {
+ int cx = 132+(i%3)*168, cy = 252+i/3*168;
+ if( board[i] == 'X' )
screen.line(cx-38,cy-38,cx+38,cy+38,12,cross).line(cx+38,cy-38,cx-38,cy+38,12,cross);
- else if( board[i]=='O' ) screen.circle(cx,cy,48,11,ring);
- else screen.text(cx-6,cy-10,i==0 ? "1" : i==1 ? "2" : i==2 ? "3" :
- i==3 ? "4" : i==4 ? "5" : i==5 ? "6" : i==6 ? "7" : i==7 ? "8" : "9",4,0x95a59e);
+ else if( board[i] == 'O' ) screen.circle(cx,cy,48,11,ring);
+ else screen.text(cx-6,cy-10,i == 0 ? "1" : i == 1 ? "2" : i == 2 ? "3" :
+ i == 3 ? "4" : i == 4 ? "5" : i == 5 ? "6" : i == 6 ? "7" : i == 7 ? "8" : "9",4,0x95a59e);
}
int line = _winningLine(board);
- if( line>=0 ) {
- int first = line<3 ? line*3 : line<6 ? line-3 : line==6 ? 0 : 2;
- int last = line<3 ? first+2 : line<6 ? first+6 : line==6 ? 8 : 6;
- screen.line(132+(first-first/3*3)*168,252+first/3*168,132+(last-last/3*3)*168,252+last/3*168,5,0xeab64e);
+ if( line >= 0 ) {
+ int first = line < 3 ? line*3 : line < 6 ? line-3 : line == 6 ? 0 : 2;
+ int last = line < 3 ? first+2 : line < 6 ? first+6 : line == 6 ? 8 : 6;
+ screen.line(132+(first%3)*168,252+first/3*168,132+(last%3)*168,252+last/3*168,5,0xeab64e);
}
screen.text(48,704,"CLICK A SQUARE OR PRESS 1-9",3,paper);
screen.text(48,738,"R OR SPACE REPLAY Q OR ESC QUIT",3,0xa2b9b7);
diff --git a/chapter31/docs/graphics.md b/chapter31/docs/graphics.md
deleted file mode 100644
index 2394a401..00000000
--- a/chapter31/docs/graphics.md
+++ /dev/null
@@ -1,119 +0,0 @@
-# Optional graphics
-
-Simple owns the pixel array and drawing code. [MiniFB](https://github.com/emoon/minifb)
-provides a window, input, and pixel presentation. The first interface is
-`sys.gfx`: one fixed-size window, operated on the main thread. The
-[Graphics example](examples/Graphics.smp) draws a color gradient in Simple.
-The [drawing library and graphical tic-tac-toe](drawing.md) build on this pixel
-interface. `make run-graphical-tictactoe CTAGS=` builds the optional backend and
-opens the game; `make graphical-tictactoe CTAGS=` only builds its executable.
-The game run target also builds optional [background audio](audio.md).
-
-## Default: no graphics dependency
-
-From `chapter31`, the usual `make release`, `make tests`, and `make tictactoe`
-need no MiniFB, graphics headers, OpenGL, CMake, or running display. Nothing
-downloads dependencies unless you explicitly request `make libs` or `make init`
-(`make lib` remains a setup alias). Build and run targets never use the network.
-
-`make tests_nographics CTAGS=` runs the entire ordinary suite with
-`SIMPLE_MINIFB=off`. This includes the missing-backend tests, which never open
-windows. It excludes the interactive `run-graphics` target.
-
-The runtime contains a small loader using the OS dynamic-library facilities.
-It does nothing until `sys.gfx.open`. Without a configured backend, `open`
-prints a diagnostic to stderr and returns `sys.gfx.ERROR` (-1). Programs can
-return a nonzero status or fall back to text; the library does not terminate
-the process. Non-graphics programs ignore even a broken graphics configuration.
-
-## Build the optional backend
-
-From `chapter31`:
-
-```sh
-make libs CTAGS= # Once while online; fills the persistent lib/ cache.
-make graphics graphics-example CTAGS=
-make run-graphics CTAGS=
-```
-
-`libs` downloads the revision pinned in [graphics.mk](../graphics.mk) into
-ignored `lib/minifb-<revision>.tar.gz` and extracts it under `lib/`.
-`graphics` builds only its C framebuffer backend from these local sources. Windows
-uses the MinGW-w64 GCC compiler (`x86_64-w64-mingw32-gcc`) and GDI; the rest of
-Simple still uses the existing Cygwin GCC. Linux uses GCC and X11 (`libx11-dev`
-on Ubuntu), including XWayland on a Wayland desktop. OpenGL, the C++ callback
-wrappers, and upstream example programs are omitted. Native Wayland and macOS
-builds are not provided here yet.
-
-Outputs:
-
-| Platform | Backend | Example |
-| --- | --- | --- |
-| Windows | `build/release/x86_64_v2_win64/simple_minifb.dll` | `build/examples/x86_64_v2_win64/Graphics.exe` |
-| Linux | `build/release/x86_64_v2_SystemV/libsimple_minifb.so` | `build/examples/x86_64_v2_SystemV/Graphics` |
-
-`MiniFB-LICENSE` is copied alongside the backend; include it when distributing
-the library. MiniFB sources remain outside the tracked Simple sources.
-The cache survives `make clean`. Editing a makefile or rebuilding a backend
-does not fetch or check GitHub. Missing dependencies fail promptly with
-instructions to run `make libs` while online.
-
-`graphics-example` alone builds the executable without requiring MiniFB. It
-also demonstrates the diagnostic and exit status 1 when graphics is absent.
-`run-graphics` builds both, sets the backend path, and opens a window. Close it
-or release Escape to exit. Passing any argument to the executable makes it
-close after five polling iterations, for a quick smoke test.
-
-To run directly from PowerShell:
-
-```powershell
-$env:SIMPLE_MINIFB = (Resolve-Path build/release/x86_64_v2_win64/simple_minifb.dll).Path
-.\build\examples\x86_64_v2_win64\Graphics.exe
-```
-
-From Cygwin bash:
-
-```sh
-export SIMPLE_MINIFB="$PWD/build/release/x86_64_v2_win64/simple_minifb.dll"
-./build/examples/x86_64_v2_win64/Graphics.exe
-```
-
-For WSL, from the repository root:
-
-```sh
-wsl -d Ubuntu-24.04 -- bash -lc 'cd chapter31 && make graphics graphics-example CLZDIR=build/classes-linux CTAGS='
-```
-
-Inside WSL, set `SIMPLE_MINIFB` to the full path of the Linux `.so`, then run
-the Linux example with a working X11 display. For an automated virtual display:
-
-```sh
-SIMPLE_MINIFB="$PWD/build/release/x86_64_v2_SystemV/libsimple_minifb.so" \
- xvfb-run -a build/examples/x86_64_v2_SystemV/Graphics smoke
-```
-
-The backend path is explicit: a DLL installed elsewhere or a different working
-directory cannot silently select the wrong version. `SIMPLE_MINIFB=off` disables
-graphics; an absent, unloadable, or incompatible backend produces a diagnostic.
-A backend that loads but cannot create a window also reports an error cleanly.
-
-## Initial interface
-
-| Operation | Meaning |
-| --- | --- |
-| `open(title,width,height)` | Open one window; returns `OK` or `ERROR`. |
-| `present(pixels)` | Present a `u32[~]` of exactly `width*height` pixels, packed `0x00RRGGBB`. |
-| `poll(wait)` | Process input; `true` waits about 17ms first to avoid a busy loop. |
-| `mouseX()`, `mouseY()` | Current mouse position, origin at upper left. |
-| `button(LEFT)`, `key(code)` | Current pressed state; printable keys use uppercase ASCII. |
-| `close()` | Release native window and pixel storage; safe to repeat. |
-
-`present` and `poll` return `OK` (0), `CLOSED` (1, normal close/Escape), or
-`ERROR` (-1). Stop polling after either terminal result and call `close`.
-The initial input API samples held state; it is not a queue of every transition.
-
-MiniFB retains its last framebuffer for repaint events. The adapter copies the
-Simple array into native-owned storage before presenting; it never retains a
-Simple heap pointer. Framebuffer allocation, the copy, and window/input calls
-are the only native work here. Drawing primitives and the games can be built
-in Simple on top of this boundary.