summaryrefslogtreecommitdiff
path: root/chapter33/docs
diff options
context:
space:
mode:
authorCliff Click <cliffc@acm.org>2026-11-23 16:45:54 -0800
committerCliff Click <cliffc@acm.org>2026-11-23 16:45:54 -0800
commitc7b2a8edc93a313728c59353dd7df5ff3abf26b7 (patch)
tree2ecb0ab0cb1a1aaa62d77b2e1b844dcac35f4365 /chapter33/docs
parent96f150b05516bc254c4035821c0119db1ecce301 (diff)
downloadSimple-c7b2a8edc93a313728c59353dd7df5ff3abf26b7.tar.gz
Simple-c7b2a8edc93a313728c59353dd7df5ff3abf26b7.zip
Next round auto-mem analysis done
Diffstat (limited to 'chapter33/docs')
-rw-r--r--chapter33/docs/33-grammar.md10
-rw-r--r--chapter33/docs/ArrayDeleteSurvey.java107
-rw-r--r--chapter33/docs/array-delete-survey.md141
-rw-r--r--chapter33/docs/growing-array-rewrites.md13
-rw-r--r--chapter33/docs/growing-arrays-survey.md24
5 files changed, 277 insertions, 18 deletions
diff --git a/chapter33/docs/33-grammar.md b/chapter33/docs/33-grammar.md
index 7e9ef8cd..a336d2f5 100644
--- a/chapter33/docs/33-grammar.md
+++ b/chapter33/docs/33-grammar.md
@@ -85,14 +85,16 @@ bindingModifier : '!' | '~' ;
initializer : assignment ;
// The prefix qualifies the named struct reference, not an enclosing array.
-// Each [] / [~] suffix qualifies its own array layer. ? requires a reference.
+// Each [] / [~] / [^] suffix qualifies its own array layer. ? requires a reference.
type
: functionType
| primitiveType typeSuffix*
| accessModifier? typeName typeSuffix*
;
accessModifier : '!' | '~' ;
-typeSuffix : '?' | '[]' | '[~]' ;
+typeSuffix : '?' | '[]' | '[~]' | '[^]' ;
+// [^] permits checked .del(); it is not a promise of uniqueness.
+// .del() uses ordinary member/call syntax. Runtime recycling is not implemented.
typeName : IDENTIFIER ('.' IDENTIFIER)* ;
primitiveType
@@ -187,9 +189,9 @@ argumentList : assignment (',' assignment)* ','? ;
// Allocation invokes the declared constructor; inline initializer blocks from
// earlier chapters are replaced by constructor arguments.
newExpression
- : 'new' type ('[' '~'? assignment ']' arrayInitializer? | arrayInitializer | callSuffix)?
+ : 'new' type ('[' ('~' | '^')? assignment ']' arrayInitializer? | arrayInitializer | callSuffix)?
;
-// With no explicit length, type must end in [] or [~] and the initializer is a list.
+// With no explicit length, type ends in [], [~], or [^]; the initializer is a list.
arrayInitializer
: '{' (assignment (',' assignment)* ','?)? '}'
| '{' ('int' | 'i32' | 'i64' | 'u32') IDENTIFIER '->' statement* '}'
diff --git a/chapter33/docs/ArrayDeleteSurvey.java b/chapter33/docs/ArrayDeleteSurvey.java
new file mode 100644
index 00000000..7e549048
--- /dev/null
+++ b/chapter33/docs/ArrayDeleteSurvey.java
@@ -0,0 +1,107 @@
+import com.seaofnodes.simple.codegen.*;
+import com.seaofnodes.simple.parser.Parser;
+import com.seaofnodes.simple.type.TypeInteger;
+import com.seaofnodes.simple.util.SB;
+import java.nio.file.*;
+import java.util.ArrayDeque;
+
+/** Compile-only source migrations. Originals are never changed. Run from chapter33. */
+public class ArrayDeleteSurvey {
+ private static String change(String src, String from, String to) {
+ if( !src.contains(from) ) throw new IllegalArgumentException("Survey source changed: "+from);
+ return src.replace(from,to);
+ }
+
+ private static String migrate(String name, String src) {
+ switch(name) {
+ case "aryu8":
+ src=change(src,"u8[] !buf;","u8[^] !buf;");
+ src=change(src,"new u8[1]","new u8[^1]");
+ src=change(src,"u8[] !buf2 = new u8[newlen];","val old = buf;\n u8[^] !buf2 = new u8[^newlen];");
+ return change(src,"buf = buf2;","buf = buf2;\n old.del();");
+ case "aryi64":
+ src=change(src,"i64[] !buf;","i64[^] !buf;");
+ src=change(src,"i64[] b ->","i64[^] b ->");
+ src=change(src,"new i64[","new i64[^");
+ src=change(src,"i64[] !buf2 =","val old = buf;\n i64[^] !buf2 =");
+ return change(src,"buf = buf2;","buf = buf2;\n old.del();");
+ case "bitset":
+ src=change(src,"i64[] !_bits;","i64[^] !_bits;");
+ src=change(src,"new i64[","new i64[^");
+ src=change(src,"var bits =","val old = _bits;\n var bits =");
+ return change(src,"_bits = bits;","_bits = bits;\n old.del();");
+ case "Timers":
+ src=change(src,"u32[]","u32[^]");
+ src=change(src,"i64[]","i64[^]");
+ src=change(src,"new u32[","new u32[^");
+ src=change(src,"new i64[","new i64[^");
+ src=change(src,"val ids =","val oldIds = _ids, oldDue = _due_ms, oldPeriod = _period_ms;\n val ids =");
+ return change(src,"_period_ms = periods_ms;","_period_ms = periods_ms;\n oldIds.del(); oldDue.del(); oldPeriod.del();");
+ case "Canvas":
+ src=change(src,"u32[] !pixels;","u32[^] !pixels;");
+ src=change(src,"new u32[","new u32[^");
+ return change(src,"pixels = new u32[^capacity];",
+ "val old = pixels;\n pixels = new u32[^capacity];\n old.del();");
+ default: throw new IllegalArgumentException(name);
+ }
+ }
+
+ private static void copyTree(Path src, Path dst) throws Exception {
+ ArrayDeque<Path> work=new ArrayDeque<>();
+ work.push(src);
+ while( !work.isEmpty() ) {
+ Path path=work.pop(), target=dst.resolve(src.relativize(path));
+ if( Files.isDirectory(path) ) {
+ Files.createDirectories(target);
+ try( DirectoryStream<Path> children=Files.newDirectoryStream(path) ) {
+ for( Path child : children ) work.push(child);
+ }
+ } else Files.copy(path,target);
+ }
+ }
+
+ private static String clean(String s) { return s.replace('\t',' ').replace('\n',' ').replace('\r',' '); }
+
+ public static void main(String[] args) throws Exception {
+ Path build=Path.of("build/array-delete-survey");
+ Files.createDirectories(build);
+ Path run=Files.createTempDirectory(build,"run-");
+ SB report=new SB().p("case\tfunction\tstatus\tdetail\n");
+ String[] names={"aryu8","aryi64","bitset","Timers","Canvas"};
+ String[] files={"sys/aryu8.smp","sys/aryi64.smp","sys/adt/bitset.smp","sys/time/Timers.smp","sys/draw/Canvas.smp"};
+ for( int i=0; i<names.length; i++ ) {
+ String name=names[i];
+ Path out=run.resolve(name), src=out.resolve("src");
+ copyTree(Path.of("src/main/smp"),src);
+ Path file=src.resolve(files[i]);
+ Files.writeString(file,migrate(name,Files.readString(file)));
+ CodeGen code=new CodeGen(src.toString(),out.resolve("objects").toString(),null,"sys",null,456,true,TypeInteger.BOT);
+ try {
+ code.driver(CodeGen.Phase.Allocation);
+ if( Boolean.getBoolean("simple.delete.graph") ) {
+ Files.writeString(out.resolve("graph.txt"),code.toString());
+ Files.writeString(out.resolve("allocation.txt"),code._allocation.toString());
+ }
+ for( ArrayDelete deletion : code._allocation._deletes ) {
+ String status=deletion._reject!=null ? "REJECT" : deletion._unique!=null ? "NEEDS UNIQUE ENTRY" : "PASS";
+ report.p(name).p('\t').p(deletion._call.fun()._name).p('\t').p(status).p('\t').p(clean(deletion.toString())).p('\n');
+ }
+ if( code._allocation._deletes.isEmpty() ) throw new IllegalStateException("No deletion sites found");
+ code.driver(CodeGen.Phase.TypeCheck);
+ System.out.println(name+": TypeCheck PASS");
+ } catch( Parser.ParseException e ) {
+ Files.writeString(out.resolve("rejection.txt"),e.diagnostic());
+ report.p(name).p("\t<TypeCheck>\tREJECT\t").p(clean(e.getMessage())).p('\n');
+ System.out.println(name+": REJECT at "+code._phase+": "+e.getMessage());
+ } catch( Throwable e ) {
+ SB stack=new SB().p(e.toString()).p('\n');
+ for( StackTraceElement frame : e.getStackTrace() ) stack.p(frame.toString()).p('\n');
+ Files.writeString(out.resolve("crash.txt"),stack.toString());
+ report.p(name).p("\t<compiler>\tCRASH\t").p(clean(e.toString())).p('\n');
+ System.out.println(name+": CRASH at "+code._phase+": "+e);
+ }
+ }
+ Files.writeString(run.resolve("results.tsv"),report.toString());
+ System.out.println("Results: "+run.resolve("results.tsv"));
+ }
+}
diff --git a/chapter33/docs/array-delete-survey.md b/chapter33/docs/array-delete-survey.md
new file mode 100644
index 00000000..82303acb
--- /dev/null
+++ b/chapter33/docs/array-delete-survey.md
@@ -0,0 +1,141 @@
+# Deletable-array source survey
+
+2026-11-23. Five production resize implementations, seven source deletion sites.
+The compiler now accepts `E[^]`, `new E[^N]`, and `.del()` and requires an ownership
+proof at TypeCheck. Runtime recycling remains unimplemented.
+
+| Source | Local deletion check | Full TypeCheck |
+|---|---|---|
+| [aryu8._grow](../src/main/smp/sys/aryu8.smp) | Grow/add/append, string/integer formatting, and `aryi64.str` compose | Reject: native boundaries in file input, floating formatting, and calendar formatting |
+| [aryi64._grow](../src/main/smp/sys/aryi64.smp) | Initializer and repeated `add` calls compose | Pass, including `parseAryI64` |
+| [bitset._grow](../src/main/smp/sys/adt/bitset.smp) | Contract propagates through `set` and `tset` | Pass |
+| [Timers._add](../src/main/smp/sys/time/Timers.smp) | Consuming recursion not supported | Reject |
+| [Canvas.resize](../src/main/smp/sys/draw/Canvas.smp) | Consuming `self.pixels` contract inferred | Pass |
+
+No compiler crashes remain in the final sweep. Initially four cases asserted on
+an array `.del` field offset: the receiver became an array only after parsing.
+Deferred member resolution now folds that load to the intrinsic. The added
+generic receiver signature also exposed an abstract-pointer type-upgrade bug;
+abstract struct bounds now remain bounds instead of being looked up as classes.
+
+The source-level poster children in Chapter33Test pass: local arrays, replacement
+of a locally constructed owner's buffer, borrowing helpers, list/generator
+initializers, and serialized/imported deletion bodies. Saved aliases and
+double deletion reject. Extracting an element reference does not retain its
+backing array. Incoming ownership becomes a checked function requirement; callers
+must discharge it or propagate it in their own contract. A library can therefore
+pass TypeCheck while retaining requirements for future callers.
+
+## What the failures tell us
+
+Known native `_exit` calls now retain normal call control but return `TypeMem.TOP`
+memory and `TypeScalar.TOP` values. The machine call remains; mixed or unknown
+targets remain conservative. This removes `_exit` from the merged memory effects
+without adding an exceptional CFG edge.
+
+The earlier reduced case's redundant `Test.$init` guard is handled: loads recover
+the initialized flag through whole-memory parameters when every live incoming
+path proves it. Variable-sized `[^]` allocations are planned as buddy storage.
+
+Its replacement, `testArrayDeleteAryu8IntegerInit`, reads `sys.integer.MAX_U32`
+directly and imports the release library, isolating remote initialization from
+`ary.capacity` and `ary.copy`. The saved summary now records the function's own
+written aliases, reference-write flag, and escaping identities. Incoming memory
+and unrelated functions' escapes are not part of that contract. Effects compose
+through calls, including recursive and nonreturning paths. The initializer has
+no reference writes. The local proof produces a consuming requirement, and the
+fresh-wrapper caller discharges it; the test now passes TypeCheck.
+
+This removes `sys.ary.capacity` and `sys.integer` as blockers in the production
+sweep. Allocation contracts now survive serialization too: `ary.copy` returns
+its `dst` argument, allocates no storage, and writes no references. The deletion
+checker follows returned argument aliases, allowing this copy while still
+rejecting uses of an old array through a returned alias after deletion.
+`testArrayDeleteAryu8Copy` exercises the actual imported contract without loading
+the copy implementation; its fresh-wrapper caller now passes too. Caller checks
+use the buffer's entry identity: saved aliases reject, but a reload of the
+replaced field is valid. Requirements survive forwarding and serialization.
+
+The repeated-checkpoint restriction is now removed. `testArrayConsumeGrowLoop`
+passes, as do nested loops, breaks, fresh allocation/deletion per iteration, and
+loops calling an imported forwarder. The backedge check rejects saved array
+references and verifies the callee preserves an exclusive owning field. A helper
+that publishes an alias of its replacement cannot satisfy that proof.
+Copies of the replacement crossing the backedge are conservatively rejected,
+even when the next iteration could use and discard them before its next grow.
+
+The two-grow example now passes (`testArrayConsumeTwoGrows`). The checker follows
+memory SSA; it substitutes each call's field stores and returned origins at that
+call's memory output. A proven unique outgoing field provides a new ownership
+version, even on a no-growth path. Loop heads provide iteration-entry versions,
+so several grows per iteration do not confuse prior and current buffers. The
+initializer-specific proof was replaced by this general call substitution.
+
+String formatting needs both a writable builder and a borrowed input array.
+Its unique-buffer requirement excludes an alias in that input parameter; callers
+check their actual arguments. Passing the builder's own buffer rejects. Distinct
+wrapper parameters are still allowed to alias, so their field paths cannot gain
+this disjointness assumption merely by having different names.
+
+## Checkpoint for design review
+
+The latest sweep passes the complete `aryi64`, `bitset`, and `Canvas` migrations.
+Within the `aryu8` migration, `_grow`, `add`, `addAry`, `num`, padding, string and
+integer formatting, `aryi64.str`, and elapsed-time formatting pass their checks.
+The remaining failures are:
+
+| Boundary | Current rejection |
+|---|---|
+| `sys.io.read` | Native `read` has no usable pointer-memory effect contract |
+| Floating formatting | `simple_text_float` returns storage with unknown origin |
+| Calendar formatting | `sys.time.local` carries unmodeled native effects |
+| Timers | Recursive consuming groups lack allocation/ownership contracts |
+
+The storage graph is still flow-insensitive. It supplies conservative may-stores
+and the proof of unique outgoing fields; the deletion checker applies those
+facts in memory order. Arbitrary callee overwrites do not yet prove an alias was
+cleared. Other conservative limits remain: replacement aliases carried across
+iterations, cyclic reference queries, multiple incoming ownership paths, and
+array-element ownership slots requiring index proofs. These are useful targets
+for the architecture review rather than more library-specific exceptions.
+
+IR format 8 records whether raw/native/initialization effects are absent from
+the field graph. Such summaries remain opaque to ownership composition, also
+after serialization. Tests cover unsafe saved aliases, helper retention, actual
+argument aliasing, multiple grows per iteration, imported forwarders, and an
+imported raw-address store. The headless test suite passes. No compiler crashes
+occurred in the sweep. Runtime recycling remains unimplemented.
+
+## Reproducing the sweep
+
+[ArrayDeleteSurvey.java](ArrayDeleteSurvey.java) copies `src/main/smp` into a fresh
+directory under `build/array-delete-survey`, changes one library per case, then
+compiles the whole source `sys`. It does not alter production files or run Simple
+code. Each migration marks backing arrays and their allocations `[^]`, saves the
+old references, publishes replacements, and calls `.del()` on the old buffers.
+For aryi64 it also changes the owning constructor parameter and its factory's
+initial allocation; arbitrary caller arrays cannot simply acquire the capability.
+
+From chapter33, compile the runner:
+
+```text
+javac -cp build/classes/main -d build/array-delete-survey docs/ArrayDeleteSurvey.java
+```
+
+PowerShell or cmd:
+
+```text
+java -ea -Xss16m -Xmx2g -XX:ActiveProcessorCount=2 -cp "build/classes/main;build/array-delete-survey" ArrayDeleteSurvey
+```
+
+Bash on Unix:
+
+```sh
+java -ea -Xss16m -Xmx2g -XX:ActiveProcessorCount=2 -cp 'build/classes/main:build/array-delete-survey' ArrayDeleteSurvey
+```
+
+The runner prints the output directory. It contains migrated sources, a
+`results.tsv` with every deletion result, and source diagnostics for rejected
+compilations. Java exceptions/assertions are recorded separately as crashes.
+Adding `-Dsimple.delete.graph=true` also saves the IR and allocation dump for each
+case. Quote that option in PowerShell.
diff --git a/chapter33/docs/growing-array-rewrites.md b/chapter33/docs/growing-array-rewrites.md
index 4bb0d141..cd9257d3 100644
--- a/chapter33/docs/growing-array-rewrites.md
+++ b/chapter33/docs/growing-array-rewrites.md
@@ -244,12 +244,13 @@ Both examples have a natural end of growth, so neither needs `finish(buf)` or
while growth is allowed. Scope exit does not guess the number of bytes a native
call wrote: `io.read` must explicitly set the final length from `used`.
-For a non-moving implementation, the returned storage must already be in an
-area that survives the callee, or its owning storage group must transfer to the
-result's destination. Ordinary callee-local RSP storage cannot simply survive a
-return. A chunk-chain handle can transfer ownership of storage, but a chain of
-nonadjacent chunks is not one contiguous `u8[]`. Neither syntax example resolves
-that placement choice by itself.
+The agreed placement is a parallel growable data stack, separate from the control
+stack. Its top is hidden call state; the updated top returns with the finished
+array. The caller's owning lifetime eventually restores the saved data-stack
+mark. A contiguous reserved address range lets the array grow without moving,
+subject to a checked capacity limit. This resolves the result destination without
+a final copy or relocating return addresses and spills. Actual lowering is still
+pending; retained inner results can still block an outer builder's growth.
Growing a non-moving array preserves existing interior references. Trimming is
different: references into the removed tail must be gone before that storage is
diff --git a/chapter33/docs/growing-arrays-survey.md b/chapter33/docs/growing-arrays-survey.md
index f8f7e2b1..13fd93d0 100644
--- a/chapter33/docs/growing-arrays-survey.md
+++ b/chapter33/docs/growing-arrays-survey.md
@@ -96,13 +96,13 @@ For Timers the programmer can choose either representation:
Agreed allocator direction: growable containers use power-of-two backing arrays
and deleted backing arrays are recycled through a buddy allocator. Resize obtains
a larger chunk, copies the used elements, publishes the replacement, and calls
-`delete(old)` to retire the old backing allocation. This moving representation
+`old.del()` to retire the old backing allocation. This moving representation
does not promise stable
direct interior references through resize. Container/index handles and copied
primitive/reference values remain useful interfaces.
Agreed safety rule: a deletable array has a different type from an ordinary
-array; its spelling is still undecided. It disallows interior references and
+array; its provisional modifier is `^`. It disallows interior references and
requires unique access and no escaping aliases. Deletion consumes the owning
access, with no outstanding borrows or other usable aliases surviving it.
The compiler checks this rule; it is not an unchecked promise by the library.
@@ -124,6 +124,14 @@ class-slot post-delete guarantees. The agreed uniqueness rule excludes those
stale accesses, allowing the buddy allocator to recycle the whole block.
Moving the length field out of the allocation is therefore not needed for this
safety argument; it remains a separate, useful layout optimization.
+The same buddy allocator can serve every element type and keep metadata inside
+freed blocks. Automatic deletion on a proven last-reference overwrite is deferred;
+the first interface uses explicit `.del()`. The
+[first ownership experiment](../README.md#array-deletion-first-ownership-checks)
+now accepts source `E[^]` and `.del()` and checks local aliases and field kills.
+The [migration survey](array-delete-survey.md) records which real resize bodies
+pass these local checks and which proof obligations remain. The runtime
+intrinsic is not implemented yet.
`text.begin()` currently returns a newly created builder. For the proposed
scope-owned growing array, interpolation should establish that storage in the
@@ -157,12 +165,12 @@ the normal allocation analysis rejects the program. There is no separate
interpolation allocation rule. Helpers growing a caller's destination likewise
use the general call-frame placement rules.
-Finished growth does not solve the return destination. `io.read`, parsed number
-arrays, formatted strings, and BrainFuck results can finish before returning,
-but the caller still does not know their size in advance. A chunk-backed lifetime
-group with a fixed-size handle is a candidate for the previously deferred result
-storage decision. An explicit copy/destination remains another option. We should
-not silently introduce returning a still-growing stack-tail array.
+The agreed return destination is now a separate growable data stack. `io.read`,
+parsed number arrays, formatted strings, and BrainFuck results finish growth
+before returning; their bytes survive the callee's control frame. The hidden
+data-stack top is updated on return, and the owning lifetime later restores its
+mark. This supplies contiguous non-moving storage without a final copy; lowering
+and the calling convention remain implementation work.
## Aliases and future inline elements