summaryrefslogtreecommitdiff
path: root/chapter31/src/main
diff options
context:
space:
mode:
Diffstat (limited to 'chapter31/src/main')
-rw-r--r--chapter31/src/main/c/simple_crt.c23
-rw-r--r--chapter31/src/main/c/simple_graphics.c8
-rw-r--r--chapter31/src/main/c/simple_graphics.h5
-rw-r--r--chapter31/src/main/c/simple_minifb.c39
-rw-r--r--chapter31/src/main/java/com/seaofnodes/simple/codegen/CodeGen.java6
-rw-r--r--chapter31/src/main/java/com/seaofnodes/simple/codegen/ElfWriter.java15
-rw-r--r--chapter31/src/main/java/com/seaofnodes/simple/codegen/GlobalCodeMotion.java10
-rw-r--r--chapter31/src/main/java/com/seaofnodes/simple/codegen/IterPeeps.java4
-rw-r--r--chapter31/src/main/java/com/seaofnodes/simple/codegen/ListScheduler.java2
-rw-r--r--chapter31/src/main/java/com/seaofnodes/simple/codegen/ParseAll.java5
-rw-r--r--chapter31/src/main/java/com/seaofnodes/simple/codegen/RegAlloc.java14
-rw-r--r--chapter31/src/main/java/com/seaofnodes/simple/codegen/Serialize.java6
-rw-r--r--chapter31/src/main/java/com/seaofnodes/simple/codegen/StaticData.java10
-rw-r--r--chapter31/src/main/java/com/seaofnodes/simple/codegen/TypeCheck.java6
-rw-r--r--chapter31/src/main/java/com/seaofnodes/simple/node/ArrayInitNode.java70
-rw-r--r--chapter31/src/main/java/com/seaofnodes/simple/node/BulkMemPhiNode.java24
-rw-r--r--chapter31/src/main/java/com/seaofnodes/simple/node/CallEndNode.java4
-rw-r--r--chapter31/src/main/java/com/seaofnodes/simple/node/CallNode.java12
-rw-r--r--chapter31/src/main/java/com/seaofnodes/simple/node/EscapeNode.java6
-rw-r--r--chapter31/src/main/java/com/seaofnodes/simple/node/Intrinsic.java119
-rw-r--r--chapter31/src/main/java/com/seaofnodes/simple/node/LoadNode.java10
-rw-r--r--chapter31/src/main/java/com/seaofnodes/simple/node/MemOpNode.java3
-rw-r--r--chapter31/src/main/java/com/seaofnodes/simple/node/ModFNode.java49
-rw-r--r--chapter31/src/main/java/com/seaofnodes/simple/node/ModNode.java16
-rw-r--r--chapter31/src/main/java/com/seaofnodes/simple/node/Node.java5
-rw-r--r--chapter31/src/main/java/com/seaofnodes/simple/node/StoreNode.java4
-rw-r--r--chapter31/src/main/java/com/seaofnodes/simple/node/cpus/arm/BitCastARM.java23
-rw-r--r--chapter31/src/main/java/com/seaofnodes/simple/node/cpus/arm/ModARM.java29
-rw-r--r--chapter31/src/main/java/com/seaofnodes/simple/node/cpus/arm/arm.java4
-rw-r--r--chapter31/src/main/java/com/seaofnodes/simple/node/cpus/riscv/BitCastRISC.java23
-rw-r--r--chapter31/src/main/java/com/seaofnodes/simple/node/cpus/riscv/DivRISC.java17
-rw-r--r--chapter31/src/main/java/com/seaofnodes/simple/node/cpus/riscv/SplitRISC.java2
-rw-r--r--chapter31/src/main/java/com/seaofnodes/simple/node/cpus/riscv/riscv.java2
-rw-r--r--chapter31/src/main/java/com/seaofnodes/simple/node/cpus/x86_64_v2/BitCastX86.java23
-rw-r--r--chapter31/src/main/java/com/seaofnodes/simple/node/cpus/x86_64_v2/CmpX86.java7
-rw-r--r--chapter31/src/main/java/com/seaofnodes/simple/node/cpus/x86_64_v2/DivX86.java36
-rw-r--r--chapter31/src/main/java/com/seaofnodes/simple/node/cpus/x86_64_v2/MemOpX86.java6
-rw-r--r--chapter31/src/main/java/com/seaofnodes/simple/node/cpus/x86_64_v2/NegFX86.java25
-rw-r--r--chapter31/src/main/java/com/seaofnodes/simple/node/cpus/x86_64_v2/StoreX86.java3
-rw-r--r--chapter31/src/main/java/com/seaofnodes/simple/node/cpus/x86_64_v2/x86_64_v2.java34
-rw-r--r--chapter31/src/main/java/com/seaofnodes/simple/parser/Allocations.java17
-rw-r--r--chapter31/src/main/java/com/seaofnodes/simple/parser/ArrayInitializers.java187
-rw-r--r--chapter31/src/main/java/com/seaofnodes/simple/parser/Construction.java3
-rw-r--r--chapter31/src/main/java/com/seaofnodes/simple/parser/Conversions.java2
-rw-r--r--chapter31/src/main/java/com/seaofnodes/simple/parser/Declarations.java4
-rw-r--r--chapter31/src/main/java/com/seaofnodes/simple/parser/Expressions.java4
-rw-r--r--chapter31/src/main/java/com/seaofnodes/simple/parser/Functions.java64
-rw-r--r--chapter31/src/main/java/com/seaofnodes/simple/parser/Lexer.java4
-rw-r--r--chapter31/src/main/java/com/seaofnodes/simple/parser/MethodAccess.java130
-rw-r--r--chapter31/src/main/java/com/seaofnodes/simple/parser/Parser.java12
-rw-r--r--chapter31/src/main/java/com/seaofnodes/simple/parser/README.md13
-rw-r--r--chapter31/src/main/java/com/seaofnodes/simple/parser/References.java13
-rw-r--r--chapter31/src/main/java/com/seaofnodes/simple/parser/Statements.java1
-rw-r--r--chapter31/src/main/java/com/seaofnodes/simple/parser/Types.java11
-rw-r--r--chapter31/src/main/java/com/seaofnodes/simple/parser/Var.java5
-rw-r--r--chapter31/src/main/java/com/seaofnodes/simple/print/ASMPrinter.java11
-rw-r--r--chapter31/src/main/java/com/seaofnodes/simple/type/Type.java2
-rw-r--r--chapter31/src/main/java/com/seaofnodes/simple/type/TypeConAry.java147
-rw-r--r--chapter31/src/main/java/com/seaofnodes/simple/type/TypeConAryB.java20
-rw-r--r--chapter31/src/main/java/com/seaofnodes/simple/type/TypeConAryI.java16
-rw-r--r--chapter31/src/main/java/com/seaofnodes/simple/type/TypeFloat.java8
-rw-r--r--chapter31/src/main/java/com/seaofnodes/simple/type/TypeStruct.java11
-rw-r--r--chapter31/src/main/smp/sys.smp1
-rw-r--r--chapter31/src/main/smp/sys/adt/bitset.smp4
-rw-r--r--chapter31/src/main/smp/sys/ary.smp4
-rw-r--r--chapter31/src/main/smp/sys/aryi64.smp6
-rw-r--r--chapter31/src/main/smp/sys/aryu8.smp13
-rw-r--r--chapter31/src/main/smp/sys/audio.md84
-rw-r--r--chapter31/src/main/smp/sys/audio.smp1
-rw-r--r--chapter31/src/main/smp/sys/draw.smp7
-rw-r--r--chapter31/src/main/smp/sys/draw/Button.smp38
-rw-r--r--chapter31/src/main/smp/sys/draw/Canvas.smp228
-rw-r--r--chapter31/src/main/smp/sys/draw/README.md124
-rw-r--r--chapter31/src/main/smp/sys/gfx.md154
-rw-r--r--chapter31/src/main/smp/sys/gfx.smp19
-rw-r--r--chapter31/src/main/smp/sys/libc.smp8
-rw-r--r--chapter31/src/main/smp/sys/math.smp27
-rw-r--r--chapter31/src/main/smp/sys/rt/simple_args.smp2
-rw-r--r--chapter31/src/main/smp/sys/text.smp79
-rw-r--r--chapter31/src/main/smp/sys/time.smp170
-rw-r--r--chapter31/src/main/smp/sys/time/README.md133
-rw-r--r--chapter31/src/main/smp/sys/time/Timers.smp40
82 files changed, 2070 insertions, 466 deletions
diff --git a/chapter31/src/main/c/simple_crt.c b/chapter31/src/main/c/simple_crt.c
index 438ae5f9..e50042c2 100644
--- a/chapter31/src/main/c/simple_crt.c
+++ b/chapter31/src/main/c/simple_crt.c
@@ -3,9 +3,32 @@
#include <stdlib.h>
#include <string.h>
#include <errno.h>
+#include <math.h>
#include <termios.h>
#include <unistd.h>
+// Fixed-semantics compiler intrinsics. Keep these definitions for indirect
+// calls; direct calls may inline to representation-preserving register moves.
+int64_t simple_f64_bits(double value) {
+ int64_t bits;
+ memcpy(&bits, &value, sizeof(bits));
+ return bits;
+}
+double simple_f64_from_bits(int64_t bits) {
+ double value;
+ memcpy(&value, &bits, sizeof(value));
+ return value;
+}
+
+// Floating remainder's machine instruction uses this memory-preserving helper.
+double simple_f64_mod(double x, double y) {
+ // fmod can set errno for NaN-producing inputs; arithmetic leaves it alone.
+ int saved_errno = errno;
+ double result = fmod(x, y);
+ errno = saved_errno;
+ return result;
+}
+
// errno may be thread-local or a macro calling a platform accessor.
int32_t simple_errno(void) { return errno; }
int32_t simple_set_errno(int32_t error) { errno = error; return -1; }
diff --git a/chapter31/src/main/c/simple_graphics.c b/chapter31/src/main/c/simple_graphics.c
index 40d66ba9..a35c28a6 100644
--- a/chapter31/src/main/c/simple_graphics.c
+++ b/chapter31/src/main/c/simple_graphics.c
@@ -74,7 +74,8 @@ static int load_graphics(void) {
if (!candidate || candidate->version != SIMPLE_GRAPHICS_VERSION ||
!candidate->open || !candidate->present || !candidate->poll ||
!candidate->mouse_x || !candidate->mouse_y || !candidate->button ||
- !candidate->key || !candidate->close || !candidate->wait) {
+ !candidate->key || !candidate->close || !candidate->wait ||
+ !candidate->width || !candidate->height || !candidate->present_size) {
fprintf(stderr, "Simple graphics: incompatible MiniFB backend '%s'. Rebuild with make graphics.\n", path);
dlclose(library);
library = NULL;
@@ -93,6 +94,11 @@ int32_t simple_gfx_open(const char *title, uint32_t width, uint32_t height) {
int32_t simple_gfx_present(const uint32_t *pixels, uint32_t count) {
return api ? api->present(pixels, count) : -1;
}
+int32_t simple_gfx_present_size(const uint32_t *pixels, uint32_t count, uint32_t width, uint32_t height) {
+ return api ? api->present_size(pixels, count, width, height) : -1;
+}
+uint32_t simple_gfx_width(void) { return api ? api->width() : 0; }
+uint32_t simple_gfx_height(void) { return api ? api->height() : 0; }
int32_t simple_gfx_poll(int32_t wait) { return api ? api->poll(wait) : -1; }
int32_t simple_gfx_mouse_x(void) { return api ? api->mouse_x() : 0; }
int32_t simple_gfx_mouse_y(void) { return api ? api->mouse_y() : 0; }
diff --git a/chapter31/src/main/c/simple_graphics.h b/chapter31/src/main/c/simple_graphics.h
index 370256be..d19cac46 100644
--- a/chapter31/src/main/c/simple_graphics.h
+++ b/chapter31/src/main/c/simple_graphics.h
@@ -15,6 +15,9 @@ struct simple_graphics_api {
int32_t (*key)(int32_t);
void (*close)(void);
int32_t (*wait)(int64_t);
+ uint32_t (*width)(void);
+ uint32_t (*height)(void);
+ int32_t (*present_size)(const uint32_t *, uint32_t, uint32_t, uint32_t);
};
-#define SIMPLE_GRAPHICS_VERSION 2
+#define SIMPLE_GRAPHICS_VERSION 3
#endif
diff --git a/chapter31/src/main/c/simple_minifb.c b/chapter31/src/main/c/simple_minifb.c
index 2117f0d2..86f110c3 100644
--- a/chapter31/src/main/c/simple_minifb.c
+++ b/chapter31/src/main/c/simple_minifb.c
@@ -14,11 +14,19 @@
#include "x11/WindowData_X11.h"
#endif
-// One fixed-size window for now. No Simple pointer survives a native call:
+// One resizable window. No Simple pointer survives a native call:
// MiniFB retains its last draw buffer for OS repaint events, so copy it here.
static struct mfb_window *window;
static uint32_t *frame;
static uint32_t width, height;
+static size_t capacity;
+
+static uint32_t window_width(void) { return window ? mfb_get_window_width(window) : 0; }
+static uint32_t window_height(void) { return window ? mfb_get_window_height(window) : 0; }
+
+static void resize_window(struct mfb_window *w, int x, int y) {
+ if (x > 0 && y > 0) mfb_set_viewport(w, 0, 0, (unsigned)x, (unsigned)y);
+}
// The C-only build never installs the upstream C++ callback wrappers.
void release_cpp_stub(struct mfb_window *unused) { (void)unused; }
@@ -31,6 +39,7 @@ static void close_window(void) {
}
free(frame);
frame = NULL;
+ capacity = 0;
}
static int32_t open_window(const char *title, uint32_t w, uint32_t h) {
@@ -44,7 +53,8 @@ static int32_t open_window(const char *title, uint32_t w, uint32_t h) {
fprintf(stderr, "Simple graphics: cannot allocate the display buffer.\n");
return -1;
}
- window = mfb_open(title, w, h);
+ capacity = (size_t)w * h;
+ window = mfb_open_ex(title, w, h, MFB_WF_RESIZABLE);
if (!window) {
fprintf(stderr, "Simple graphics: MiniFB could not open a window (is a graphical display available?).\n");
close_window();
@@ -52,6 +62,7 @@ static int32_t open_window(const char *title, uint32_t w, uint32_t h) {
}
width = w;
height = h;
+ mfb_set_resize_callback(window, resize_window);
return 0;
}
@@ -67,14 +78,29 @@ static int32_t status(mfb_update_state state) {
return -1;
}
-static int32_t present(const uint32_t *pixels, uint32_t count) {
+static int32_t present_size(const uint32_t *pixels, uint32_t count, uint32_t w, uint32_t h) {
if (!window) return 1;
- if (!pixels || count != (uint64_t)width * height) {
+ if (!pixels || !w || !h || w > UINT32_MAX / 4 ||
+ count != (uint64_t)w * h || (uint64_t)w * h > SIZE_MAX / 4) {
fprintf(stderr, "Simple graphics: pixel array length must equal width * height.\n");
return -1;
}
+ if (count > capacity) {
+ uint32_t *larger = realloc(frame, (size_t)count * sizeof(*frame));
+ if (!larger) {
+ fprintf(stderr, "Simple graphics: cannot resize the display buffer.\n");
+ return -1;
+ }
+ frame = larger;
+ capacity = count;
+ }
memcpy(frame, pixels, (size_t)count * sizeof(*frame));
- return status(mfb_update_ex(window, frame, width, height));
+ return status(mfb_update_ex(window, frame, w, h));
+}
+
+// Compatibility for clients drawing at their original resolution.
+static int32_t present(const uint32_t *pixels, uint32_t count) {
+ return present_size(pixels, count, width, height);
}
static int32_t wait_events(int64_t timeout) {
@@ -109,7 +135,8 @@ static int32_t key(int32_t k) {
static const struct simple_graphics_api api = {
SIMPLE_GRAPHICS_VERSION, open_window, present, poll_events,
- mouse_x, mouse_y, button, key, close_window, wait_events
+ mouse_x, mouse_y, button, key, close_window, wait_events,
+ window_width, window_height, present_size
};
#ifdef _WIN32
__declspec(dllexport)
diff --git a/chapter31/src/main/java/com/seaofnodes/simple/codegen/CodeGen.java b/chapter31/src/main/java/com/seaofnodes/simple/codegen/CodeGen.java
index b4c93e1e..8618b47b 100644
--- a/chapter31/src/main/java/com/seaofnodes/simple/codegen/CodeGen.java
+++ b/chapter31/src/main/java/com/seaofnodes/simple/codegen/CodeGen.java
@@ -786,7 +786,11 @@ public class CodeGen {
public boolean _asmLittle=true;
public String asm() { return asm(new SB()).toString(); }
SB asm(SB sb) {
- ASMPrinter.print(sb,this);
+ if( _encodings.isEmpty() ) ASMPrinter.print(sb,this);
+ else for( var entry : _encodings.entrySet() ) {
+ sb.p("\n=== Compilation unit: ").p(entry.getKey()._cname).p(" ===\n");
+ ASMPrinter.print(sb,this,entry.getValue());
+ }
return sb;
}
diff --git a/chapter31/src/main/java/com/seaofnodes/simple/codegen/ElfWriter.java b/chapter31/src/main/java/com/seaofnodes/simple/codegen/ElfWriter.java
index fcf5c287..c5b25be0 100644
--- a/chapter31/src/main/java/com/seaofnodes/simple/codegen/ElfWriter.java
+++ b/chapter31/src/main/java/com/seaofnodes/simple/codegen/ElfWriter.java
@@ -318,11 +318,15 @@ public class ElfWriter {
_strtab = new StringSection();
// place all the symbols
+ Encoding enc = _code._encoding;
int nlocals = 1/*null*/+9/*number of sections*/+1/*Simple section*/;
+ int debugLocals=0;
+ for( StaticData.ObjectData obj : enc._data.objects.values() )
+ if( !obj.external ) debugLocals+=obj.debugNames.size();
+ nlocals+=debugLocals;
SymbolSection symbols = new SymbolSection(nlocals);
// we've already constructed these entire sections in the encoding phase
- Encoding enc = _code._encoding;
// Append ELF-only thunks to a copy. Export must not change instruction
// offsets or the image used by the in-memory linker and emulators.
BAOS textBits = new BAOS(enc._bits.toByteArray(),enc._bits.size());
@@ -402,10 +406,17 @@ public class ElfWriter {
SimpleSection simple = new SimpleSection(_code._serial);
// Write the local section header symbols
- assert nlocals == 1+_sections._len;
+ assert nlocals == 1+_sections._len+debugLocals;
symbols.symbol("",0,0,0); // Null symbol at index 0
for( Section s : _sections )
symbols.symbol(s._name, s._index, SYM_BIND_LOCAL, SYM_TYPE_SECTION, 0, s.size());
+ // Local aliases describe the pooled object without changing linkage.
+ // Several source constants may name the same bytes.
+ for( StaticData.ObjectData obj : enc._data.objects.values() )
+ if( !obj.external )
+ for( String name : obj.debugNames )
+ symbols.symbol(name,obj.readOnly ? rodata._index : rwdata._index,
+ SYM_BIND_LOCAL,SYM_TYPE_OBJECT,obj.offset,obj.size);
int size = 64; // ELF header size
// size of all section data
diff --git a/chapter31/src/main/java/com/seaofnodes/simple/codegen/GlobalCodeMotion.java b/chapter31/src/main/java/com/seaofnodes/simple/codegen/GlobalCodeMotion.java
index 86cb2e98..83c0677d 100644
--- a/chapter31/src/main/java/com/seaofnodes/simple/codegen/GlobalCodeMotion.java
+++ b/chapter31/src/main/java/com/seaofnodes/simple/codegen/GlobalCodeMotion.java
@@ -141,10 +141,11 @@ public abstract class GlobalCodeMotion {
if( def!=null && !(def instanceof PhiNode) )
_schedEarly(def,code,start);
- // An existing edge 0 already supplies control (or a Phi/Proj binding).
- if( n.in(0)==null ) {
+ // A memory op's control is a lower bound, not a complete early schedule:
+ // instruction selection may have folded in an operand defined later.
+ if( n.in(0)==null || n instanceof MemOpNode ) {
// Schedule at deepest input
- CFGNode early = start; // Maximally early, lowest idepth
+ CFGNode early = n.in(0) instanceof CFGNode ctrl ? ctrl : start;
for( int i=1; i<n.nIns(); i++ )
if( n.in(i)!=null && n.in(i).cfg0().idepth() > early.idepth() )
early = n.in(i).cfg0(); // Latest/deepest input
@@ -251,6 +252,9 @@ public abstract class GlobalCodeMotion {
if( use != null )
lca = use_block(n,use, late).domLCA(lca,null);
+ assert lca!=null && early.dominates(lca,null) :
+ "Early schedule must dominate uses of "+n.getClass().getSimpleName()+"#"+n._nid;
+
// Loads may need anti-dependencies, raising their LCA
if( n instanceof MemOpNode load && load._isLoad )
lca = find_anti_dep(lca,load,early,late,anti, antideps);
diff --git a/chapter31/src/main/java/com/seaofnodes/simple/codegen/IterPeeps.java b/chapter31/src/main/java/com/seaofnodes/simple/codegen/IterPeeps.java
index 985cd4d2..f4acb729 100644
--- a/chapter31/src/main/java/com/seaofnodes/simple/codegen/IterPeeps.java
+++ b/chapter31/src/main/java/com/seaofnodes/simple/codegen/IterPeeps.java
@@ -65,8 +65,10 @@ public class IterPeeps {
* Iterate peepholes and inlining to a fixed point
*/
public void iterate( CodeGen code ) {
+ assert !CodeGen.expensiveAssert(0) || (progressOnList(code, _work) && schedulableUses(code));
boolean didInline = false;
Ary<Node> defer = new Ary<>(Node.class);
+
while( true ) {
// Clean up everything that does not grow the code
iteratePeeps(code);
@@ -97,8 +99,6 @@ public class IterPeeps {
// Run all the code-reduction and type-lifting peeps as possible
private void iteratePeeps( CodeGen code ) {
- assert !CodeGen.expensiveAssert(0) || (progressOnList(code, _work) && schedulableUses(code));
-
Node n;
while( (n = _work.pop()) != null ) {
if( n.isDead() ) continue;
diff --git a/chapter31/src/main/java/com/seaofnodes/simple/codegen/ListScheduler.java b/chapter31/src/main/java/com/seaofnodes/simple/codegen/ListScheduler.java
index c3b603e5..f90d8d4e 100644
--- a/chapter31/src/main/java/com/seaofnodes/simple/codegen/ListScheduler.java
+++ b/chapter31/src/main/java/com/seaofnodes/simple/codegen/ListScheduler.java
@@ -49,7 +49,7 @@ public abstract class ListScheduler {
else
computeSingleRDef(bb,n);
- if( n instanceof NewNode || n instanceof CallNode )
+ if( n instanceof NewNode || n instanceof CallNode || n instanceof ModFNode )
bb.fun()._hasCalls = true;
return this;
}
diff --git a/chapter31/src/main/java/com/seaofnodes/simple/codegen/ParseAll.java b/chapter31/src/main/java/com/seaofnodes/simple/codegen/ParseAll.java
index 3306ff8f..882a0f8a 100644
--- a/chapter31/src/main/java/com/seaofnodes/simple/codegen/ParseAll.java
+++ b/chapter31/src/main/java/com/seaofnodes/simple/codegen/ParseAll.java
@@ -150,7 +150,8 @@ public abstract class ParseAll {
}
private static void addRequiredTypes(CodeGen code, CompUnit cunit) {
- for( String typeName : code.P._requiredTypes ) {
+ for( var required : code.P._requiredTypes.entrySet() ) {
+ String typeName = required.getKey();
// A forward use can have been resolved later in this source file.
if( Parser.TYPES.get(typeName) instanceof TypeStruct ts && !ts._fref ) continue;
try {
@@ -158,7 +159,7 @@ public abstract class ParseAll {
if( xcunit != null )
cunit.addDep(xcunit);
else
- assert false : "expected to find required type";
+ throw Parser.error("Unknown type '"+typeName+"'",required.getValue());
} catch( IOException ioe ) {
throw new RuntimeException(ioe);
}
diff --git a/chapter31/src/main/java/com/seaofnodes/simple/codegen/RegAlloc.java b/chapter31/src/main/java/com/seaofnodes/simple/codegen/RegAlloc.java
index 3991cd48..303fd355 100644
--- a/chapter31/src/main/java/com/seaofnodes/simple/codegen/RegAlloc.java
+++ b/chapter31/src/main/java/com/seaofnodes/simple/codegen/RegAlloc.java
@@ -184,6 +184,7 @@ public class RegAlloc {
if( bb instanceof CallEndMach cend ) cend.cacheRegs(_code);
for( Node n : bb._outputs )
if( n instanceof NewNode nnn ) nnn.cacheRegs(_code);
+ else if( n instanceof ModFNode mod ) mod.cacheRegs(_code);
}
// Expensive assert: useful when chasing cross-function allocator edges.
//assert verifyFunctionLocalEdges();
@@ -215,7 +216,7 @@ public class RegAlloc {
_deferredLoopSelf.clear();
for( byte round=0; !graphColor(round); round++ ) {
split(round);
- if( round >= 7 ) {
+ if( round >= 10 ) {
FunNode fun = _cfg.at(0).fun();
throw new IllegalStateException("Register allocation failed after eight rounds in "+
(fun==null ? "<root>" : fun.label()));
@@ -680,7 +681,14 @@ public class RegAlloc {
if( cfg==def.cfg0() && def.nOuts()==1 && !singleReg )
return;
}
- makeSplit(def,kind,round,lrg,umask).insertBefore(n, i);
+ // If isolating a loop Phi's uses did not relieve pressure, cloning its
+ // constant input again cannot help: it still forces the Phi into a GPR.
+ // A real transfer on this retry lets the Phi live on the stack.
+ Node split = n instanceof PhiNode phi && phi.region() instanceof LoopNode &&
+ lrg._machUse instanceof SplitNode prior && prior._round<round &&
+ !lrg._mask.isEmpty() && def instanceof MachNode mach && mach.isClone()
+ ? makeSplit(kind,round,lrg) : makeSplit(def,kind,round,lrg,umask);
+ split.insertBefore(n, i);
// Keep the def-side transfer: a kill between the two copies may be
// exactly why this range split. Coalescing can join them when safe.
}
@@ -742,6 +750,8 @@ public class RegAlloc {
// Raise frame size by max stack args passed to New
if( n instanceof NewNode nnn )
maxReg = Math.max(maxReg,nnn._xslot);
+ if( n instanceof ModFNode mod )
+ maxReg = Math.max(maxReg,mod._xslot);
if( !(n instanceof SplitNode ) ) continue;
int defreg = lrg(n )._reg;
diff --git a/chapter31/src/main/java/com/seaofnodes/simple/codegen/Serialize.java b/chapter31/src/main/java/com/seaofnodes/simple/codegen/Serialize.java
index 79bebe1f..b168c4af 100644
--- a/chapter31/src/main/java/com/seaofnodes/simple/codegen/Serialize.java
+++ b/chapter31/src/main/java/com/seaofnodes/simple/codegen/Serialize.java
@@ -448,7 +448,11 @@ public class Serialize {
// TYPES names the mutable array declaration. Read-only arrays in
// imported signatures keep their own types, but must not replace that
// declaration: closeOver looks up its mutable variant by name.
- if( ts.isAry() ) ts = ts.replace(ts.field("[]").makeFrom(false));
+ if( ts.isConAry() ) {
+ TypeConAry ary=(TypeConAry)ts.field("[]")._t;
+ ts=TypeStruct.makeAry(ts._name,TypeInteger.U32,ts.field("#")._alias,
+ ary.storageType(),ts.field("[]")._alias,false);
+ } else if( ts.isAry() ) ts = ts.replace(ts.field("[]").makeFrom(false));
Parser.TYPES.put(ts._name,ts);
}
diff --git a/chapter31/src/main/java/com/seaofnodes/simple/codegen/StaticData.java b/chapter31/src/main/java/com/seaofnodes/simple/codegen/StaticData.java
index 5d1a519b..3d3a40dd 100644
--- a/chapter31/src/main/java/com/seaofnodes/simple/codegen/StaticData.java
+++ b/chapter31/src/main/java/com/seaofnodes/simple/codegen/StaticData.java
@@ -14,7 +14,10 @@ public final class StaticData {
public final String symbol;
public final boolean readOnly, external;
public final int alignment, size;
+ // Source names are aliases, not part of the object's pooling identity.
+ final TreeSet<String> debugNames = new TreeSet<>();
public int offset;
+ public String label() { return debugNames.isEmpty() ? symbol : String.join(", ",debugNames); }
ObjectData(Type t, String name, boolean ro, boolean ext) {
type=t; symbol=name; readOnly=ro; external=ext;
alignment=t.alignment();
@@ -73,7 +76,12 @@ public final class StaticData {
// Register before following fields: class objects may refer to each other.
if( !obj.external && t instanceof TypeStruct ts )
for( Field f : ts._fields )
- if( !f._extern && f._t.isConstant() ) target(f._t);
+ if( !f._extern && f._t.isConstant() ) {
+ target(f._t);
+ if( clz && f._final && f._t instanceof TypeMemPtr ptr &&
+ pointerConstant(ptr) && !isClass(ptr._obj) )
+ object(ptr._obj).debugNames.add(ts._name.substring(TypeStruct.CLZ.length())+"."+f._fname);
+ }
return obj;
}
diff --git a/chapter31/src/main/java/com/seaofnodes/simple/codegen/TypeCheck.java b/chapter31/src/main/java/com/seaofnodes/simple/codegen/TypeCheck.java
index a86cd18a..418edaf6 100644
--- a/chapter31/src/main/java/com/seaofnodes/simple/codegen/TypeCheck.java
+++ b/chapter31/src/main/java/com/seaofnodes/simple/codegen/TypeCheck.java
@@ -21,12 +21,14 @@ abstract class TypeCheck {
Ary<Node> errs = new Ary<>(Node.class);
Ary<ConstructNode> constructs = new Ary<>(ConstructNode.class);
Ary<InitViewNode> views = new Ary<>(InitViewNode.class);
+ Ary<ArrayInitNode> arrays = new Ary<>(ArrayInitNode.class);
code._stop.walk( n -> {
if( n.err() != null )
errs.add(n);
if( n instanceof CLInitNode ) code.add(n);
if( n instanceof ConstructNode con ) constructs.add(con);
if( n instanceof InitViewNode view ) views.add(view);
+ if( n instanceof ArrayInitNode array ) arrays.add(array);
return null;
});
@@ -57,13 +59,15 @@ abstract class TypeCheck {
if( !con.isDead() ) con.subsume(con.in(1));
for( InitViewNode view : views )
if( !view.isDead() ) view.subsume(view.in(1));
+ for( ArrayInitNode array : arrays )
+ if( !array.isDead() ) array.subsume(array.in(2));
}
private static int errorRank(Node n) {
// Bad memory access originates the error. Missing construction fields
// in turn explain generic-scalar arithmetic further downstream.
if( n instanceof MemOpNode && noBottomInputs(n) ) return 0;
- if( n instanceof ConstructNode ) return 1;
+ if( n instanceof ConstructNode || n instanceof ArrayInitNode ) return 1;
return noBottomInputs(n) ? 2 : 3;
}
diff --git a/chapter31/src/main/java/com/seaofnodes/simple/node/ArrayInitNode.java b/chapter31/src/main/java/com/seaofnodes/simple/node/ArrayInitNode.java
new file mode 100644
index 00000000..c6ae90ea
--- /dev/null
+++ b/chapter31/src/main/java/com/seaofnodes/simple/node/ArrayInitNode.java
@@ -0,0 +1,70 @@
+package com.seaofnodes.simple.node;
+
+import com.seaofnodes.print.ExprPrinter;
+import com.seaofnodes.simple.parser.Lexer;
+import com.seaofnodes.simple.parser.Parser;
+import com.seaofnodes.simple.type.*;
+import com.seaofnodes.simple.util.Ary;
+
+/** Source checks for array construction and its yielded elements. Erased by
+ * TypeCheck before serialization and scheduling. */
+public final class ArrayInitNode extends Node {
+ private final int _count; // List size, -1 for a generator, -2 for a yielded element.
+ private final Lexer _loc;
+ public ArrayInitNode(Node ctrl, Node mem, Node ptr, Node len, int count, Lexer loc, Ary<Node> values) {
+ super(ctrl,mem,ptr,len);
+ _count=count; _loc=loc;
+ for( Node value : values ) addDef(value);
+ }
+ public ArrayInitNode(Node ctrl, Node value, Lexer loc) {
+ super(ctrl,null,value);
+ _count=-2; _loc=loc;
+ }
+ @Override public String label() { return "ArrayInit"; }
+ @Override protected ExprPrinter<Node> _print1(ExprPrinter<Node> p) { return p.p("arrayInit(").n(in(2)).p(")"); }
+ @Override public Type compute() {
+ if( in(0)._type != Type.CONTROL ) return Type.TOP;
+ Type ptr = in(2)._type;
+ if( _count < 0 ) return ptr;
+ // A list is strict in all its inputs. Wait for every input before
+ // choosing a constant payload or falling to the ordinary array type.
+ // Otherwise one SCCP worklist order can return PtrTop (or an array)
+ // before another unresolved input sends the result back up to Top.
+ if( ptr.isHigh() || in(3)._type.isHigh() ) return Type.TOP;
+ for( int i = 4; i < nIns(); i++ )
+ if( in(i)._type.isHigh() ) return Type.TOP;
+ if( !(ptr instanceof TypeMemPtr tmp) ) return ptr;
+ Field body = tmp._obj.field("[]");
+ if( body == null || !body._final || !(body._t instanceof TypeInteger storage) ) return ptr;
+ if( !(in(3)._type instanceof TypeInteger length) || !length.isConstant() || length.value() != _count ) return ptr;
+ long[] values = new long[_count];
+ for( int i = 0; i < _count; i++ ) {
+ Type value = in(i+4)._type;
+ if( !(value instanceof TypeInteger integer) || !integer.isConstant() ) return ptr;
+ values[i] = integer.value();
+ }
+ TypeConAry contents = TypeConAry.make(storage,values);
+ TypeStruct array = TypeStruct.makeAry(tmp._obj._name,tmp._obj.field("#")._alias,body._alias,contents);
+ // The surrounding ReadOnlyNode supplies the public view. Keep this
+ // node's access flags consistent when its contents cease to be constant.
+ return TypeMemPtr.make((byte)2,array,true).withAccess(tmp._ro);
+ }
+ @Override public Node idealize() { return null; }
+ @Override public Parser.ParseException err() {
+ if( in(0)._type==Type.XCONTROL ) return null;
+ if( _count==-2 )
+ return TypeMemPtr.mayBePartial(in(2)._type)
+ ? Parser.error("Array initializer requires fully initialized elements",_loc) : null;
+ if( !(in(3)._type instanceof TypeInteger len) )
+ return Parser.error("Array length must be an integer",_loc);
+ if( len.isConstant() && (len.value()<0 || len.value()>TypeInteger.U32._max) )
+ return Parser.error("Array length is outside the u32 range",_loc);
+ if( _count>=0 && (!len.isConstant() || len.value()!=_count) )
+ return Parser.error("Array initializer has "+_count+" elements; length must equal that constant",_loc);
+ for( int i=4; i<nIns(); i++ )
+ if( TypeMemPtr.mayBePartial(in(i)._type) )
+ return Parser.error("Array initializer requires fully initialized elements",_loc);
+ return null;
+ }
+ @Override public boolean eq(Node n) { return this==n; }
+}
diff --git a/chapter31/src/main/java/com/seaofnodes/simple/node/BulkMemPhiNode.java b/chapter31/src/main/java/com/seaofnodes/simple/node/BulkMemPhiNode.java
index 130b631c..b49163e7 100644
--- a/chapter31/src/main/java/com/seaofnodes/simple/node/BulkMemPhiNode.java
+++ b/chapter31/src/main/java/com/seaofnodes/simple/node/BulkMemPhiNode.java
@@ -261,15 +261,35 @@ public class BulkMemPhiNode extends PhiNode {
mphi = new MemPhiNode(ScopeNode.memName(alias),alias);
mphi.addDef(region());
// Due to cycles, must set before calling peephole
- // Splitting preserves the bulk Phi's established escape bound. Starting
- // at BOT would temporarily invent escapes when the new slice is merged.
+ // An escaped slice must preserve the bulk Phi's established bound.
+ // An unescaped slice was excluded from that summary: include the
+ // facts hidden in predecessor slices before wiring any cyclic Phis.
TypeMem old = (TypeMem)_type;
+ if( !XInt.bit(old._escAs,alias) )
+ old = (TypeMem)old.meet(sliceBound(this,alias,new BitSet()));
mphi.setType(TypeMem.make(alias,old._t,old._one,old._clz,false,old._escFs,old._escAs));
for( int i=1; i<nIns(); i++ )
mphi.addDef(CodeGen.CODE.add(preciseInput(in(i),alias)));
return CodeGen.CODE.add(mphi);
}
+ // A bulk summary ignores unescaped slots in MemMerge inputs. Follow the
+ // same slots that splitting will expose, including across loop backedges.
+ // A visited cycle contributes TOP; its incoming definitions supply the bound.
+ private static TypeMem sliceBound(Node mem, int alias, BitSet visit) {
+ if( visit.get(mem._nid) ) return TypeMem.TOP;
+ visit.set(mem._nid);
+ if( mem instanceof MemMergeNode merge )
+ return sliceBound(merge.alias(alias),alias,visit);
+ if( mem instanceof BulkMemPhiNode bulk ) {
+ TypeMem bound = TypeMem.TOP;
+ for( int i = 1; i < bulk.nIns(); i++ )
+ bound = (TypeMem)bound.meet(sliceBound(bulk.in(i),alias,visit));
+ return bound;
+ }
+ return mem._type instanceof TypeMem bound ? bound : TypeMem.BOT;
+ }
+
MemPhiNode _findPhi(int alias) {
for( Node use : region().outs() )
if( use instanceof MemPhiNode mphi && mphi._alias==alias )
diff --git a/chapter31/src/main/java/com/seaofnodes/simple/node/CallEndNode.java b/chapter31/src/main/java/com/seaofnodes/simple/node/CallEndNode.java
index b5156c2d..108dd024 100644
--- a/chapter31/src/main/java/com/seaofnodes/simple/node/CallEndNode.java
+++ b/chapter31/src/main/java/com/seaofnodes/simple/node/CallEndNode.java
@@ -85,6 +85,8 @@ public class CallEndNode extends CFGNode implements MultiNode {
return ftype.isHigh() ? TypeTuple.STATE.dual() : TypeTuple.STATE;
// Mid-fold, just take the inlined callee's return.
if( _folding ) return in(1)._type;
+ TypeTuple intrinsic=Intrinsic.compute(call,this);
+ if( intrinsic!=null ) return intrinsic;
// The outside continuation reads Start directly: Call can remain
// CONTROL while its possible returned identities change.
@@ -135,6 +137,8 @@ public class CallEndNode extends CFGNode implements MultiNode {
}
public byte maybeInline() {
+ byte intrinsic=Intrinsic.tryInline(this);
+ if( intrinsic>0 ) return intrinsic;
byte inline = inlineCandidate(false);
if( CodeGen.CODE._midAssert )
return inline;
diff --git a/chapter31/src/main/java/com/seaofnodes/simple/node/CallNode.java b/chapter31/src/main/java/com/seaofnodes/simple/node/CallNode.java
index ac5e4eee..9e9c5224 100644
--- a/chapter31/src/main/java/com/seaofnodes/simple/node/CallNode.java
+++ b/chapter31/src/main/java/com/seaofnodes/simple/node/CallNode.java
@@ -97,6 +97,7 @@ public class CallNode extends CFGNode {
if( _type!=Type.CONTROL ) return TypeMem.BOT;
if( !(fptr()._type instanceof TypeFunPtr) )
return fptr()._type.isHigh() ? TypeMem.START : TypeMem.BOT;
+ if( Intrinsic.pure(this) ) return TypeMem.START;
if( !external() ) return TypeMem.START;
Type input = dep.addDepForwards(mem())._type;
TypeMem escaped = input instanceof TypeMem m ? m : input.isHigh() ? TypeMem.TOP : TypeMem.BOT;
@@ -241,6 +242,8 @@ public class CallNode extends CFGNode {
return Parser.error("Expected a function, but found " + fptr()._type, _loc);
if( !tfp.notNull() )
return Parser.error( "Might be null calling "+tfp, _loc);
+ Parser.ParseException intrinsic=Intrinsic.err(this);
+ if( intrinsic!=null ) return intrinsic;
if( nargs() != tfp.nargs() )
return Parser.error( "Expecting "+(tfp.nargs()-1)+" arguments, but found "+(nargs()-1), _loc);
@@ -253,6 +256,15 @@ public class CallNode extends CFGNode {
// Constructors return private memory and carry hidden self and
// selfMem arguments ahead of the source-level arguments.
int argno = i - (tfp.ret() instanceof TypeMem ? 2 : 0);
+ // Access qualifiers are not shown by the structural type dump.
+ // Report the differing permission instead of two huge shapes.
+ if( arg(i+2)._type instanceof TypeMemPtr actual && actual._ro &&
+ tfp.arg(i) instanceof TypeMemPtr formal && !formal._ro ) {
+ String who = i == 0 ? name() == null ? "Receiver" : "Receiver for method '"+name()+"'"
+ : "Argument #"+argno;
+ return Parser.error(who+" is read-only "+actual._obj.str()+
+ "; expected writable "+formal._obj.str(),_loc);
+ }
return Parser.error( "Argument #" + argno + " isa " + arg(i+2)._type + ", but must be a " + tfp.arg(i), _loc );
}
diff --git a/chapter31/src/main/java/com/seaofnodes/simple/node/EscapeNode.java b/chapter31/src/main/java/com/seaofnodes/simple/node/EscapeNode.java
index 57340609..a8a6151c 100644
--- a/chapter31/src/main/java/com/seaofnodes/simple/node/EscapeNode.java
+++ b/chapter31/src/main/java/com/seaofnodes/simple/node/EscapeNode.java
@@ -64,6 +64,10 @@ public class EscapeNode extends TypeNode {
@Override
public Type compute() {
+ // A static constant array has no private heap writes to publish.
+ // This depends on its type, regardless of which node produced it.
+ if( self()!=null && self()._type instanceof TypeMemPtr ptr &&
+ ptr.isConstant() && ptr._obj.isConAry() ) return pub()._type;
if( priv()._type.isHigh() ) return TypeMem.TOP;
if( pub ()._type.isHigh() ) return TypeMem.TOP;
TypeMem mpriv = (TypeMem)priv()._type;
@@ -100,6 +104,8 @@ public class EscapeNode extends TypeNode {
}
@Override public Node idealize() {
+ if( self()._type instanceof TypeMemPtr ptr && ptr.isConstant() && ptr._obj.isConAry() )
+ return pub();
// Sharpen private memory input
if( priv() instanceof MemMergeNode mmm ) {
setDef(2,mmm.alias(fld()._alias));
diff --git a/chapter31/src/main/java/com/seaofnodes/simple/node/Intrinsic.java b/chapter31/src/main/java/com/seaofnodes/simple/node/Intrinsic.java
new file mode 100644
index 00000000..82626507
--- /dev/null
+++ b/chapter31/src/main/java/com/seaofnodes/simple/node/Intrinsic.java
@@ -0,0 +1,119 @@
+package com.seaofnodes.simple.node;
+
+import com.seaofnodes.simple.codegen.CodeGen;
+import com.seaofnodes.simple.parser.Parser;
+import com.seaofnodes.simple.type.*;
+
+// Fixed-semantics C functions. Recognition, effects and expansion live here;
+// Call/CallEnd only delegate. These symbols also have ordinary C definitions
+// for calls whose target is not known at compile time.
+public final class Intrinsic {
+ private Intrinsic() {}
+
+ private enum Op {
+ F64_BITS("simple_f64_bits",TypeFloat.F64,TypeInteger.BOT,true),
+ F64_FROM_BITS("simple_f64_from_bits",TypeInteger.BOT,TypeFloat.F64,true);
+
+ final String symbol;
+ final Type arg, ret;
+ final boolean pure;
+ Op(String symbol, Type arg, Type ret, boolean pure) {
+ this.symbol=symbol; this.arg=arg; this.ret=ret; this.pure=pure;
+ }
+ boolean signature(TypeFunPtr fp) {
+ // Slot zero is the implicit receiver, omitted by the C ABI.
+ return fp.nargs()==2 && fp.arg(1)==arg && fp.ret()==ret;
+ }
+ Expansion expand(CallNode call) {
+ Node value=switch(this) {
+ case F64_BITS -> new F64BitsNode(call.arg(3)).peephole();
+ case F64_FROM_BITS -> new F64FromBitsNode(call.arg(3)).peephole();
+ };
+ return new Expansion(call.ctrl(),call.mem(),value);
+ }
+ }
+
+ private static Op lookup(CallNode call) {
+ if( !(call.fptr()._type instanceof TypeFunPtr fp) || !fp.notNull() || !fp.isConstant() ) return null;
+ String symbol=CodeGen.CODE.externFunc(fp.fidx());
+ if( symbol==null ) return null; // A Simple function with this name is ordinary code.
+ for( Op op : Op.values() ) if( op.symbol.equals(symbol) ) return op;
+ return null;
+ }
+
+ public static Parser.ParseException err(CallNode call) {
+ Op op=lookup(call);
+ return op==null || op.signature(call.tfp()) ? null : Parser.error(
+ "Intrinsic '"+op.symbol+"' requires { "+op.arg.str()+" -> "+op.ret.str()+" }",call._loc);
+ }
+
+ // Both initial operations are pure and expose no references. Future atomic
+ // operations need their own memory/escape semantics, not this passthrough.
+ public static boolean pure(CallNode call) {
+ Op op=lookup(call);
+ return op!=null && op.pure && op.signature(call.tfp());
+ }
+
+ public static TypeTuple compute(CallNode call, Node dep) {
+ if( !pure(call) ) return null;
+ return TypeTuple.make(Type.CONTROL,dep.addDep(call.mem())._type,call.tfp().ret());
+ }
+
+ // An expansion replaces the complete call state, even for a pure value op.
+ private record Expansion(Node control, Node memory, Node value) {
+ void replace(CallEndNode end) {
+ Node[] state={control,memory,value};
+ for( Node n : state ) n.keep();
+ end.keep();
+ for( Node use : end._outputs.asAry() ) {
+ if( use==null ) continue; // Our temporary keep.
+ assert use instanceof Proj;
+ use.subsume(state[((Proj)use).idx()]);
+ }
+ end.unkill();
+ for( Node n : state ) n.unkill();
+ CodeGen.CODE.invalidateIDepthCaches();
+ }
+ }
+
+ // Same cheap-inlining worklist as ordinary functions, but no body/Return,
+ // cloning, size heuristic, or import loading is needed.
+ public static byte tryInline(CallEndNode end) {
+ if( end.folding() || !(end.in(0) instanceof CallNode call) ) return 0;
+ Op op=lookup(call);
+ if( op==null || !op.signature(call.tfp()) || call.nargs()!=call.tfp().nargs() ||
+ !end.goodArgs(call,call.tfp()) ) return 0;
+ if( !CodeGen.CODE._midAssert ) op.expand(call).replace(end);
+ return 1;
+ }
+
+ public abstract static class BitCastNode extends Node {
+ BitCastNode(Node value) { super(null,value); }
+ public abstract boolean toBits();
+ @Override public Type compute() {
+ Type input=in(1)._type;
+ Type result=toBits() ? TypeInteger.BOT : TypeFloat.F64;
+ if( input.isHigh() ) return result.dual();
+ if( toBits() && input instanceof TypeFloat f && f.isConstant() )
+ return TypeInteger.constant(Double.doubleToRawLongBits(f.value()));
+ if( !toBits() && input instanceof TypeInteger i && i.isConstant() )
+ return TypeFloat.constant(Double.longBitsToDouble(i.value()));
+ return result;
+ }
+ @Override public Node idealize() {
+ return in(1) instanceof BitCastNode cast && cast.toBits()!=toBits() ? cast.in(1) : null;
+ }
+ }
+ public static final class F64BitsNode extends BitCastNode {
+ public F64BitsNode(Node value) { super(value); }
+ @Override public boolean toBits() { return true; }
+ @Override public Tag serialTag() { return Tag.F64Bits; }
+ @Override protected String format() { return "f64Bits(%1)"; }
+ }
+ public static final class F64FromBitsNode extends BitCastNode {
+ public F64FromBitsNode(Node value) { super(value); }
+ @Override public boolean toBits() { return false; }
+ @Override public Tag serialTag() { return Tag.F64FromBits; }
+ @Override protected String format() { return "f64FromBits(%1)"; }
+ }
+}
diff --git a/chapter31/src/main/java/com/seaofnodes/simple/node/LoadNode.java b/chapter31/src/main/java/com/seaofnodes/simple/node/LoadNode.java
index 35db4c2f..14efa315 100644
--- a/chapter31/src/main/java/com/seaofnodes/simple/node/LoadNode.java
+++ b/chapter31/src/main/java/com/seaofnodes/simple/node/LoadNode.java
@@ -98,7 +98,15 @@ public class LoadNode extends MemOpNode {
t = mem._alias==_alias ? mem._t : actual==null ? TypeScalar.BOT : actual._t;
} else if( mem._alias==_alias )
t = t.join(mem._t);
- if( !mem._one ) t = mem.outside(t);
+ // A final method's identity comes from its declaration, not from an
+ // unknown outside writer. It remains callable on a local object even
+ // when that function has never escaped to outside code.
+ if( !mem._one ) {
+ Type declared = Parser.TYPES.get(tmp._obj._name);
+ Field field = declared instanceof TypeStruct obj ? obj.field(_name) : null;
+ if( !(field != null && field._final && field._t instanceof TypeFunPtr fun && fun.isConstant()) )
+ t = mem.outside(t);
+ }
// Store forwarding is also a value fact during SCCP. Waiting for the
// later rewrite can turn a known non-null stored pointer into a
// nullable declaration, then BOTTOM at the next dereference.
diff --git a/chapter31/src/main/java/com/seaofnodes/simple/node/MemOpNode.java b/chapter31/src/main/java/com/seaofnodes/simple/node/MemOpNode.java
index 35183380..bce11b50 100644
--- a/chapter31/src/main/java/com/seaofnodes/simple/node/MemOpNode.java
+++ b/chapter31/src/main/java/com/seaofnodes/simple/node/MemOpNode.java
@@ -94,7 +94,8 @@ public abstract class MemOpNode extends TypeNode {
if( !(ptr()._type instanceof TypeMemPtr tmp) )
return Type.BOTTOM;
Field fld = tmp._obj.field(_name);
- return fld == null || fld._t == null ? Type.BOTTOM : fld._t;
+ return fld == null || fld._t == null ? Type.BOTTOM :
+ fld._t instanceof TypeConAry ary ? ary.storageType() : fld._t;
}
@Override protected ExprPrinter<Node> _print1(ExprPrinter<Node> p) { return _printMach(p); }
diff --git a/chapter31/src/main/java/com/seaofnodes/simple/node/ModFNode.java b/chapter31/src/main/java/com/seaofnodes/simple/node/ModFNode.java
new file mode 100644
index 00000000..17d7e36c
--- /dev/null
+++ b/chapter31/src/main/java/com/seaofnodes/simple/node/ModFNode.java
@@ -0,0 +1,49 @@
+package com.seaofnodes.simple.node;
+
+import com.seaofnodes.isa.Arm64;
+import com.seaofnodes.isa.RiscV;
+import com.seaofnodes.isa.X86;
+import com.seaofnodes.simple.codegen.*;
+import com.seaofnodes.simple.node.cpus.arm.arm;
+import com.seaofnodes.simple.node.cpus.riscv.riscv;
+import com.seaofnodes.simple.type.*;
+import com.seaofnodes.simple.util.SB;
+
+/** Floating remainder has no SSE/ARM/RISC-V instruction: emit a helper call. */
+public class ModFNode extends MachConcreteNode implements MachNode {
+ private RegMask _lhs, _rhs, _ret, _kills;
+ public int _xslot;
+ public ModFNode(ModNode mod) { super(mod); }
+ @Override public String op() { return "modf"; }
+ public void cacheRegs(CodeGen code) {
+ TypeFunPtr sig=TypeFunPtr.make(false,new Type[]{TypeFloat.F64,TypeFloat.F64},TypeFloat.F64);
+ _lhs=code._mach.callArgMask(sig,2,0,code._cCallingConv);
+ _rhs=code._mach.callArgMask(sig,3,0,code._cCallingConv);
+ _ret=code._mach.retMask(sig);
+ RegMaskRW kills=code._cCallerSave.copy();
+ if( code._mach instanceof arm ) kills.set(arm.FLAGS);
+ int base=code._mach.regs().length+cfg0().fun()._maxArgSlot;
+ _xslot=base+code._mach.maxArgSlot(sig,code._cCallingConv);
+ for( int i=base; i<_xslot; i++ ) kills.set(i);
+ _kills=kills;
+ }
+ @Override public RegMask regmap(int i) { return i==1 ? _lhs : i==2 ? _rhs : null; }
+ @Override public RegMask outregmap() { return _ret; }
+ @Override public RegMask killmap() { return _kills; }
+ @Override public void encoding(Encoding enc) {
+ enc.external(this,"simple_f64_mod");
+ switch( machine().name() ) {
+ case "x86_64_v2" -> X86.call(enc);
+ case "arm" -> enc.add4(Arm64.b(Arm64.OP_CALL,0));
+ case "riscv" -> {
+ enc.add4(RiscV.u_type(RiscV.OP_AUIPC,riscv.T0,0));
+ enc.add4(RiscV.i_type(RiscV.OP_JALR,riscv.RPC,0,riscv.T0,0));
+ }
+ default -> throw new IllegalStateException(machine().name());
+ }
+ }
+ @Override public void asm(CodeGen code, SB sb) {
+ sb.p(code.reg(this)).p(" = ").p(code.reg(in(1))).p(" % ").p(code.reg(in(2)));
+ }
+ @Override public String comment() { return "call simple_f64_mod"; }
+}
diff --git a/chapter31/src/main/java/com/seaofnodes/simple/node/ModNode.java b/chapter31/src/main/java/com/seaofnodes/simple/node/ModNode.java
new file mode 100644
index 00000000..7c1a9238
--- /dev/null
+++ b/chapter31/src/main/java/com/seaofnodes/simple/node/ModNode.java
@@ -0,0 +1,16 @@
+package com.seaofnodes.simple.node;
+
+import com.seaofnodes.simple.type.TypeInteger;
+
+public class ModNode extends ArithNode {
+ public ModNode(Node lhs, Node rhs) { super(null,lhs,rhs); }
+ public ModNode(Node lhs, Node rhs, byte mode) { super(null,lhs,rhs,mode); }
+ @Override public Tag serialTag() { return Tag.Mod; }
+ @Override public String op() { return "%"; }
+ @Override boolean allowFloat() { return true; }
+
+ @Override long doOp(long x, long y) { return y==0 ? 0 : x%y; }
+ @Override double doOp(double x, double y) { return x%y; }
+ @Override TypeInteger doOp(TypeInteger x, TypeInteger y) { return TypeInteger.BOT; }
+ @Override Node copy(Node lhs, Node rhs) { return new ModNode(lhs,rhs,_mode); }
+}
diff --git a/chapter31/src/main/java/com/seaofnodes/simple/node/Node.java b/chapter31/src/main/java/com/seaofnodes/simple/node/Node.java
index 2815dfba..ad4f47e0 100644
--- a/chapter31/src/main/java/com/seaofnodes/simple/node/Node.java
+++ b/chapter31/src/main/java/com/seaofnodes/simple/node/Node.java
@@ -77,7 +77,7 @@ public abstract class Node extends BaseNode<Node> implements Cloneable {
New,Never,Not,Or,Parm,Phi,Proj,PtrToInt,
ReadOnly,Return,Region,RoundF32,
Sar,Shl,Shr,Start,StartCU,StopCU,Stop,Store,Sub,
- ToInteger,ToFloat,XCtrl,Xor;
+ ToInteger,ToFloat,XCtrl,Xor,F64Bits,F64FromBits,Mod;
public static final Tag[] VALS = values();
public Node make( BAOS bais, String[] strs, Type[] types, GlobalBits fileAliases, GlobalBits aliases ) {
return switch(this) {
@@ -103,6 +103,8 @@ public abstract class Node extends BaseNode<Node> implements Cloneable {
case Sub -> new SubNode(null,null,(byte)bais.packed1());
case ToFloat-> new ToFloatNode(null);
case ToInteger-> new ToIntegerNode(null);
+ case F64Bits-> new Intrinsic.F64BitsNode(null);
+ case F64FromBits-> new Intrinsic.F64FromBitsNode(null);
case XCtrl -> new XCtrlNode();
case Xor -> { int mode=bais.packed1(); assert mode==1; yield new XorNode(null,null,null); }
@@ -115,6 +117,7 @@ public abstract class Node extends BaseNode<Node> implements Cloneable {
case Call -> CallNode.make(bais,strs);
case CallEnd-> CallEndNode.make(bais ,types);
case CLInit -> new CLInitNode(bais,strs);
+ case Mod -> new ModNode(null,null,(byte)bais.packed1());
case CProj -> CProjNode.make(bais,strs);
case Con -> ConstantNode.make(bais ,types);
case Escape-> EscapeNode.make(bais ,types);
diff --git a/chapter31/src/main/java/com/seaofnodes/simple/node/StoreNode.java b/chapter31/src/main/java/com/seaofnodes/simple/node/StoreNode.java
index 010d5f61..204e0c4b 100644
--- a/chapter31/src/main/java/com/seaofnodes/simple/node/StoreNode.java
+++ b/chapter31/src/main/java/com/seaofnodes/simple/node/StoreNode.java
@@ -243,6 +243,10 @@ public class StoreNode extends MemOpNode {
private byte storageType() {
if( !(ptr()._type instanceof TypeMemPtr tmp) )
return 0;
+ // Completing a forward declaration changes TYPES without changing
+ // this Store's inputs. Wait for the pointer's type upgrade, which
+ // queues its users, before consulting the completed declaration.
+ if( tmp._obj._fref ) return 0;
TypeStruct obj = (TypeStruct)Parser.TYPES.get(tmp._obj._name);
Field fld = obj.field(_name);
if( fld == null || fld._t == null )
diff --git a/chapter31/src/main/java/com/seaofnodes/simple/node/cpus/arm/BitCastARM.java b/chapter31/src/main/java/com/seaofnodes/simple/node/cpus/arm/BitCastARM.java
new file mode 100644
index 00000000..ec57b3f8
--- /dev/null
+++ b/chapter31/src/main/java/com/seaofnodes/simple/node/cpus/arm/BitCastARM.java
@@ -0,0 +1,23 @@
+package com.seaofnodes.simple.node.cpus.arm;
+
+import com.seaofnodes.isa.Arm64;
+import com.seaofnodes.simple.codegen.*;
+import com.seaofnodes.simple.node.*;
+import com.seaofnodes.simple.util.SB;
+
+// A representation move, with no arithmetic, rounding, or flag changes.
+public class BitCastARM extends MachConcreteNode implements MachNode {
+ private final boolean _toBits;
+ BitCastARM(Intrinsic.BitCastNode cast) { super(cast); _toBits=cast.toBits(); }
+ @Override public String op() { return _toBits ? "f64bits" : "f64frombits"; }
+ @Override public RegMask regmap(int i) { assert i==1; return _toBits ? arm.DMASK : arm.RMASK; }
+ @Override public RegMask outregmap() { return _toBits ? arm.WMASK : arm.DMASK; }
+ @Override public void encoding(Encoding enc) {
+ enc.add4(Arm64.f_mov_general(Arm64.OP_FMOV,0b01,0,_toBits ? 0b110 : 0b111,
+ enc.reg(in(1))-(_toBits ? arm.D_OFFSET : 0),
+ enc.reg(this)-(_toBits ? 0 : arm.D_OFFSET)));
+ }
+ @Override public void asm(CodeGen code, SB sb) {
+ sb.p(code.reg(this)).p(" = bits ").p(code.reg(in(1)));
+ }
+}
diff --git a/chapter31/src/main/java/com/seaofnodes/simple/node/cpus/arm/ModARM.java b/chapter31/src/main/java/com/seaofnodes/simple/node/cpus/arm/ModARM.java
new file mode 100644
index 00000000..bd29ba3f
--- /dev/null
+++ b/chapter31/src/main/java/com/seaofnodes/simple/node/cpus/arm/ModARM.java
@@ -0,0 +1,29 @@
+package com.seaofnodes.simple.node.cpus.arm;
+
+import com.seaofnodes.isa.Arm64;
+import com.seaofnodes.simple.codegen.*;
+import com.seaofnodes.simple.node.*;
+import com.seaofnodes.simple.util.SB;
+
+public class ModARM extends MachConcreteNode implements MachNode {
+ private static final RegMask REGS=new RegMask(arm.WR_BITS & ~(1L<<arm.X16));
+ ModARM(Node mod) { super(mod); }
+ @Override public String op() { return "mod"; }
+ @Override public RegMask regmap(int i) { return REGS; }
+ @Override public RegMask outregmap() { return REGS; }
+ @Override public RegMask killmap() { return new RegMask(1L<<arm.X16,1L); }
+ @Override public void encoding(Encoding enc) {
+ int lhs=enc.reg(in(1)), rhs=enc.reg(in(2)), dst=enc.reg(this);
+ enc.add4(Arm64.imm_inst(Arm64.OPI_CMP,0,rhs,31)); // CMP rhs,0
+ enc.add4(Arm64.b_cond(Arm64.OP_BRANCH,20,Arm64.COND.EQ));
+ enc.add4(Arm64.madd(Arm64.OP_DIV,rhs,3,lhs,arm.X16)); // SDIV x16,lhs,rhs
+ enc.add4(Arm64.madd(Arm64.OP_MUL,rhs,31,arm.X16,arm.X16)); // MUL x16,x16,rhs
+ enc.add4(Arm64.r_reg(Arm64.OP_SUB,0,arm.X16,0,lhs,dst)); // SUB dst,lhs,x16
+ enc.add4(Arm64.b(Arm64.OP_UJMP,8));
+ enc.add4(Arm64.mov(Arm64.OP_MOVZ,0,0,dst));
+ }
+ @Override public void asm(CodeGen code, SB sb) {
+ sb.p(code.reg(this)).p(" = ").p(code.reg(in(1))).p(" % ").p(code.reg(in(2)));
+ }
+ @Override public String comment() { return "SDIV/MUL/SUB; kill x16, flags; zero guarded"; }
+}
diff --git a/chapter31/src/main/java/com/seaofnodes/simple/node/cpus/arm/arm.java b/chapter31/src/main/java/com/seaofnodes/simple/node/cpus/arm/arm.java
index ee7b0fc3..55a9cdb0 100644
--- a/chapter31/src/main/java/com/seaofnodes/simple/node/cpus/arm/arm.java
+++ b/chapter31/src/main/java/com/seaofnodes/simple/node/cpus/arm/arm.java
@@ -28,7 +28,7 @@ public class arm extends Machine {
public static final int D16 = 48, D17 = 49, D18 = 50, D19 = 51, D20 = 52, D21 = 53, D22 = 54, D23 = 55;
public static final int D24 = 56, D25 = 57, D26 = 58, D27 = 59, D28 = 60, D29 = 61, D30 = 62, D31 = 63;
- static final int FLAGS = 64;
+ public static final int FLAGS = 64;
static final int MAX_REG = 65;
public static final int D_OFFSET = 32;
@@ -318,6 +318,7 @@ public class arm extends Machine {
case CProjNode c -> new CProjNode(c);
case ConstantNode con-> con(con);
case DivNode div -> div.mode()==2 ? new DivFARM(div) : new DivARM(div);
+ case ModNode mod -> mod.mode()==2 ? new ModFNode(mod) : new ModARM(mod);
case EscapeNode esc -> new EscapeNode(esc);
case FunNode fun -> new FunARM(fun);
case FunPtrNode fptr -> fptr(fptr);
@@ -350,6 +351,7 @@ public class arm extends Machine {
case StoreNode st -> st(st);
case SubNode sub -> sub.mode()==2 ? new SubFARM(sub) : sub(sub);
case ToFloatNode tfn -> new I2F8ARM(tfn);
+ case Intrinsic.BitCastNode cast -> new BitCastARM(cast);
case ToIntegerNode cvt -> new F8ToIARM(cvt);
case XorNode xor -> xor(xor);
diff --git a/chapter31/src/main/java/com/seaofnodes/simple/node/cpus/riscv/BitCastRISC.java b/chapter31/src/main/java/com/seaofnodes/simple/node/cpus/riscv/BitCastRISC.java
new file mode 100644
index 00000000..141ff7d5
--- /dev/null
+++ b/chapter31/src/main/java/com/seaofnodes/simple/node/cpus/riscv/BitCastRISC.java
@@ -0,0 +1,23 @@
+package com.seaofnodes.simple.node.cpus.riscv;
+
+import com.seaofnodes.isa.RiscV;
+import com.seaofnodes.simple.codegen.*;
+import com.seaofnodes.simple.node.*;
+import com.seaofnodes.simple.util.SB;
+
+// A representation move, with no arithmetic, rounding, or flag changes.
+public class BitCastRISC extends MachConcreteNode implements MachNode {
+ private final boolean _toBits;
+ BitCastRISC(Intrinsic.BitCastNode cast) { super(cast); _toBits=cast.toBits(); }
+ @Override public String op() { return _toBits ? "f64bits" : "f64frombits"; }
+ @Override public RegMask regmap(int i) { assert i==1; return _toBits ? riscv.FMASK : riscv.RMASK; }
+ @Override public RegMask outregmap() { return _toBits ? riscv.WMASK : riscv.FMASK; }
+ @Override public void encoding(Encoding enc) {
+ enc.add4(RiscV.r_type(RiscV.OP_FP,
+ enc.reg(this)-(_toBits ? 0 : riscv.F_OFFSET),0,
+ enc.reg(in(1))-(_toBits ? riscv.F_OFFSET : 0),0,_toBits ? 0b1110001 : 0b1111001));
+ }
+ @Override public void asm(CodeGen code, SB sb) {
+ sb.p(code.reg(this)).p(" = bits ").p(code.reg(in(1)));
+ }
+}
diff --git a/chapter31/src/main/java/com/seaofnodes/simple/node/cpus/riscv/DivRISC.java b/chapter31/src/main/java/com/seaofnodes/simple/node/cpus/riscv/DivRISC.java
index 515ffa47..691979ec 100644
--- a/chapter31/src/main/java/com/seaofnodes/simple/node/cpus/riscv/DivRISC.java
+++ b/chapter31/src/main/java/com/seaofnodes/simple/node/cpus/riscv/DivRISC.java
@@ -1,17 +1,26 @@
package com.seaofnodes.simple.node.cpus.riscv;
+import com.seaofnodes.isa.RiscV;
import com.seaofnodes.simple.util.SB;
import com.seaofnodes.simple.codegen.*;
import com.seaofnodes.simple.node.*;
public class DivRISC extends MachConcreteNode implements MachNode{
- public DivRISC(Node div) {super(div);}
- @Override public String op() { return "div"; }
+ private final boolean _mod;
+ public DivRISC(Node div) {super(div); _mod=div instanceof ModNode;}
+ @Override public String op() { return _mod ? "mod" : "div"; }
@Override public RegMask regmap(int i) { return riscv.RMASK; }
@Override public RegMask outregmap() { return riscv.WMASK; }
- @Override public void encoding( Encoding enc ) { riscv.r_type(enc,this,4,1); }
+ @Override public void encoding( Encoding enc ) {
+ // RISC-V returns -1 for DIV by zero, and the dividend for REM by zero.
+ // Both ideal operations instead return zero.
+ enc.add4(RiscV.b_type(RiscV.OP_BRANCH,1,enc.reg(in(2)),(short)riscv.ZERO,12));
+ enc.add4(RiscV.i_type(RiscV.OP_IMM,enc.reg(this),0,riscv.ZERO,0));
+ enc.add4(RiscV.j_type(RiscV.OP_JAL,riscv.ZERO,8));
+ riscv.r_type(enc,this,_mod ? 6 : 4,1);
+ }
@Override public void asm(CodeGen code, SB sb) {
- sb.p(code.reg(this)).p(" = ").p(code.reg(in(1))).p(" / ").p(code.reg(in(2)));
+ sb.p(code.reg(this)).p(" = ").p(code.reg(in(1))).p(_mod ? " % " : " / ").p(code.reg(in(2)));
}
}
diff --git a/chapter31/src/main/java/com/seaofnodes/simple/node/cpus/riscv/SplitRISC.java b/chapter31/src/main/java/com/seaofnodes/simple/node/cpus/riscv/SplitRISC.java
index d455337b..de754393 100644
--- a/chapter31/src/main/java/com/seaofnodes/simple/node/cpus/riscv/SplitRISC.java
+++ b/chapter31/src/main/java/com/seaofnodes/simple/node/cpus/riscv/SplitRISC.java
@@ -47,7 +47,7 @@ public class SplitRISC extends SplitNode {
// FPR->FPR
src -= riscv.F_OFFSET;
dst -= riscv.F_OFFSET;
- enc.add4(RiscV.r_type(RiscV.OP_FP, dst, 0b000, src, src, 0b0010101)); // dst = FMIN(src,src)
+ enc.add4(RiscV.r_type(RiscV.OP_FP, dst, 0b000, src, src, 0b0010001)); // FSGNJ.D preserves NaN bits.
} else if(!srcX && dstX) {
//GPR->FPR
// fmv.d.x
diff --git a/chapter31/src/main/java/com/seaofnodes/simple/node/cpus/riscv/riscv.java b/chapter31/src/main/java/com/seaofnodes/simple/node/cpus/riscv/riscv.java
index 378955a5..70585732 100644
--- a/chapter31/src/main/java/com/seaofnodes/simple/node/cpus/riscv/riscv.java
+++ b/chapter31/src/main/java/com/seaofnodes/simple/node/cpus/riscv/riscv.java
@@ -222,6 +222,7 @@ public class riscv extends Machine {
case CProjNode c -> new CProjNode(c);
case ConstantNode con -> con(con);
case DivNode div -> div.mode()==2 ? new DivFRISC(div) : new DivRISC(div);
+ case ModNode mod -> mod.mode()==2 ? new ModFNode(mod) : new DivRISC(mod);
case EscapeNode esc -> new EscapeNode(esc);
case FunNode fun -> new FunRISC(fun);
case FunPtrNode fptr -> fptr(fptr);
@@ -254,6 +255,7 @@ public class riscv extends Machine {
case StoreNode st -> st(st);
case SubNode sub -> sub.mode()==2 ? new SubFRISC(sub) : sub(sub);
case ToFloatNode tfn -> i2f8(tfn);
+ case Intrinsic.BitCastNode cast -> new BitCastRISC(cast);
case ToIntegerNode cvt -> new F8ToIRISC(cvt);
case XorNode xor -> xor(xor);
diff --git a/chapter31/src/main/java/com/seaofnodes/simple/node/cpus/x86_64_v2/BitCastX86.java b/chapter31/src/main/java/com/seaofnodes/simple/node/cpus/x86_64_v2/BitCastX86.java
new file mode 100644
index 00000000..bf550032
--- /dev/null
+++ b/chapter31/src/main/java/com/seaofnodes/simple/node/cpus/x86_64_v2/BitCastX86.java
@@ -0,0 +1,23 @@
+package com.seaofnodes.simple.node.cpus.x86_64_v2;
+
+import com.seaofnodes.isa.X86;
+import com.seaofnodes.simple.codegen.*;
+import com.seaofnodes.simple.node.*;
+import com.seaofnodes.simple.util.SB;
+
+// A representation move, with no arithmetic, rounding, or flag changes.
+public class BitCastX86 extends MachConcreteNode implements MachNode {
+ private final boolean _toBits;
+ BitCastX86(Intrinsic.BitCastNode cast) { super(cast); _toBits=cast.toBits(); }
+ @Override public String op() { return _toBits ? "f64bits" : "f64frombits"; }
+ @Override public RegMask regmap(int i) { assert i==1; return _toBits ? x86_64_v2.XMASK : x86_64_v2.RMASK; }
+ @Override public RegMask outregmap() { return _toBits ? x86_64_v2.WMASK : x86_64_v2.XMASK; }
+ @Override public void encoding(Encoding enc) {
+ X86.move(enc,!_toBits,_toBits,
+ enc.reg(this)-(_toBits ? 0 : x86_64_v2.XMM_OFFSET),
+ enc.reg(in(1))-(_toBits ? x86_64_v2.XMM_OFFSET : 0));
+ }
+ @Override public void asm(CodeGen code, SB sb) {
+ sb.p(code.reg(this)).p(" = bits ").p(code.reg(in(1)));
+ }
+}
diff --git a/chapter31/src/main/java/com/seaofnodes/simple/node/cpus/x86_64_v2/CmpX86.java b/chapter31/src/main/java/com/seaofnodes/simple/node/cpus/x86_64_v2/CmpX86.java
index 7faea17b..f8e652df 100644
--- a/chapter31/src/main/java/com/seaofnodes/simple/node/cpus/x86_64_v2/CmpX86.java
+++ b/chapter31/src/main/java/com/seaofnodes/simple/node/cpus/x86_64_v2/CmpX86.java
@@ -7,6 +7,12 @@ import com.seaofnodes.simple.util.SB;
public class CmpX86 extends MachConcreteNode implements MachNode {
CmpX86( Node add ) { super(add); }
+ private CmpX86(CmpX86 cmp) {
+ super((Node)null);
+ addDef(null);
+ addDef(cmp.in(1));
+ addDef(cmp.in(2));
+ }
@Override public String op() { return "cmp"; }
@Override public RegMask regmap(int i) { return x86_64_v2.RMASK; }
@Override public RegMask outregmap() { return x86_64_v2.FLAGS_MASK; }
@@ -16,6 +22,7 @@ public class CmpX86 extends MachConcreteNode implements MachNode {
// compared to some normal registers - and those normal registers might not
// be spilling!
@Override public boolean isClone() { return true; }
+ @Override public Node copy() { return new CmpX86(this); }
@Override public void encoding( Encoding enc ) {
X86.reg(enc,0x3B,enc.reg(in(1)),enc.reg(in(2)));
diff --git a/chapter31/src/main/java/com/seaofnodes/simple/node/cpus/x86_64_v2/DivX86.java b/chapter31/src/main/java/com/seaofnodes/simple/node/cpus/x86_64_v2/DivX86.java
index 9f375a80..7607913f 100644
--- a/chapter31/src/main/java/com/seaofnodes/simple/node/cpus/x86_64_v2/DivX86.java
+++ b/chapter31/src/main/java/com/seaofnodes/simple/node/cpus/x86_64_v2/DivX86.java
@@ -6,20 +6,42 @@ import com.seaofnodes.simple.node.*;
import com.seaofnodes.simple.util.SB;
public class DivX86 extends MachConcreteNode implements MachNode {
- DivX86( Node div ) { super(div); }
- @Override public String op() { return "div"; }
+ private final boolean _mod;
+ DivX86( Node div ) { super(div); _mod=div instanceof ModNode; }
+ @Override public String op() { return _mod ? "mod" : "div"; }
@Override public RegMask regmap(int i) {
return (i==1) ? x86_64_v2.RAX_MASK : x86_64_v2.DIV_MASK;
}
- @Override public RegMask outregmap() { return x86_64_v2.RAX_MASK; }
- @Override public RegMask killmap() { return x86_64_v2.RDX_MASK; }
+ @Override public RegMask outregmap() { return _mod ? x86_64_v2.RDX_MASK : x86_64_v2.RAX_MASK; }
+ @Override public RegMask killmap() {
+ return new RegMask((1L<<(_mod ? x86_64_v2.RAX : x86_64_v2.RDX)) | (1L<<x86_64_v2.FLAGS));
+ }
@Override public void encoding( Encoding enc ) {
- X86.divide(enc,enc.reg(in(2)));
+ int rhs=enc.reg(in(2)), dst=enc.reg(this);
+ // IDIV faults on zero and MIN_VALUE/-1. Handle both before issuing it.
+ X86.reg(enc,0x85,rhs,rhs); // TEST rhs,rhs
+ enc.add1(0x0F).add1(0x84);
+ int zero=enc._bits.size(); enc.add4(0); // JZ zero
+ X86.imm(enc,0x81,7,rhs,-1); // CMP rhs,-1
+ enc.add1(0x0F).add1(0x85);
+ int divide=enc._bits.size(); enc.add4(0); // JNE divide
+ if( _mod ) X86.reg(enc,0x33,dst,dst);
+ else X86.unary(enc,0xF7,3,dst); // NEG wraps MIN_VALUE, like ideal division.
+ enc.add1(0xE9);
+ int minusOne=enc._bits.size(); enc.add4(0); // JMP done
+ enc.patch4(divide,enc._bits.size()-divide-4);
+ X86.divide(enc,rhs);
+ enc.add1(0xE9);
+ int done=enc._bits.size(); enc.add4(0); // JMP done
+ enc.patch4(zero,enc._bits.size()-zero-4);
+ X86.reg(enc,0x33,dst,dst);
+ enc.patch4(minusOne,enc._bits.size()-minusOne-4);
+ enc.patch4(done,enc._bits.size()-done-4);
}
// General form: "div dst /= src"
@Override public void asm(CodeGen code, SB sb) {
- sb.p(code.reg(this)).p(" = ").p(code.reg(in(1))).p(" / ").p(code.reg(in(2)));
+ sb.p(code.reg(this)).p(" = ").p(code.reg(in(1))).p(_mod ? " % " : " / ").p(code.reg(in(2)));
}
- @Override public String comment() { return "kill rdx"; }
+ @Override public String comment() { return (_mod ? "kill rax" : "kill rdx")+", flags; zero and -1 guarded"; }
}
diff --git a/chapter31/src/main/java/com/seaofnodes/simple/node/cpus/x86_64_v2/MemOpX86.java b/chapter31/src/main/java/com/seaofnodes/simple/node/cpus/x86_64_v2/MemOpX86.java
index fcca7f8f..b0ecd685 100644
--- a/chapter31/src/main/java/com/seaofnodes/simple/node/cpus/x86_64_v2/MemOpX86.java
+++ b/chapter31/src/main/java/com/seaofnodes/simple/node/cpus/x86_64_v2/MemOpX86.java
@@ -67,9 +67,9 @@ public abstract class MemOpX86 extends MemOpNode implements MachNode {
if( i==1 ) return null; // Memory
if( i==2 ) return x86_64_v2.RMASK; // base in GPR
if( i==3 ) return x86_64_v2.RMASK; // index in GPR
- if( i==4 ) return _sz >= '4'
- ? x86_64_v2.MEM_MASK // value in GPR or XMM
- : x86_64_v2.RMASK; // Bytes and shorts in GPR only
+ // Integer arithmetic and comparisons require a GPR value operand.
+ // Only StoreX86 has alternate encodings that accept XMM values.
+ if( i==4 ) return x86_64_v2.RMASK;
return null; // Anti-dependence
}
diff --git a/chapter31/src/main/java/com/seaofnodes/simple/node/cpus/x86_64_v2/NegFX86.java b/chapter31/src/main/java/com/seaofnodes/simple/node/cpus/x86_64_v2/NegFX86.java
new file mode 100644
index 00000000..61662fd2
--- /dev/null
+++ b/chapter31/src/main/java/com/seaofnodes/simple/node/cpus/x86_64_v2/NegFX86.java
@@ -0,0 +1,25 @@
+package com.seaofnodes.simple.node.cpus.x86_64_v2;
+
+import com.seaofnodes.isa.X86;
+import com.seaofnodes.simple.codegen.*;
+import com.seaofnodes.simple.node.*;
+import com.seaofnodes.simple.type.TypeFloat;
+import com.seaofnodes.simple.util.SB;
+
+// Flip the sign bit, preserving signed zero, infinities, and NaN payloads.
+public class NegFX86 extends MachConcreteNode implements MachNode {
+ NegFX86(MinusNode neg) {
+ super(neg);
+ addDef(new FltX86(new ConstantNode(TypeFloat.constant(-0.0)),null));
+ }
+ @Override public String op() { return "negf"; }
+ @Override public RegMask regmap(int i) { assert i==1 || i==2; return x86_64_v2.XMASK; }
+ @Override public RegMask outregmap() { return x86_64_v2.XMASK; }
+ @Override public int twoAddress() { return 1; }
+ @Override public void encoding(Encoding enc) {
+ X86.sse(enc,0x66,0x0F57,false,enc.reg(this)-x86_64_v2.XMM_OFFSET,enc.reg(in(2))-x86_64_v2.XMM_OFFSET);
+ }
+ @Override public void asm(CodeGen code, SB sb) {
+ sb.p(code.reg(this)).p(" ^= ").p(code.reg(in(2))).p(" // sign bit");
+ }
+}
diff --git a/chapter31/src/main/java/com/seaofnodes/simple/node/cpus/x86_64_v2/StoreX86.java b/chapter31/src/main/java/com/seaofnodes/simple/node/cpus/x86_64_v2/StoreX86.java
index 9ffa25fc..8dfd31e7 100644
--- a/chapter31/src/main/java/com/seaofnodes/simple/node/cpus/x86_64_v2/StoreX86.java
+++ b/chapter31/src/main/java/com/seaofnodes/simple/node/cpus/x86_64_v2/StoreX86.java
@@ -25,6 +25,9 @@ public class StoreX86 extends MemOpX86 {
}
// Register mask allowed as a result. 0 for no register.
@Override public RegMask outregmap() { return null; }
+ @Override public RegMask regmap(int i) {
+ return i==4 && _sz>='4' ? x86_64_v2.MEM_MASK : super.regmap(i);
+ }
@Override public void encoding( Encoding enc ) {
short ptr=enc.reg(ptr()), idx=enc.reg(idx()), src=enc.reg(val());
if( src==-1 ) X86.storeImm(enc,Integer.numberOfTrailingZeros(_sz-'0'),_imm,ptr,idx,_off,_scale);
diff --git a/chapter31/src/main/java/com/seaofnodes/simple/node/cpus/x86_64_v2/x86_64_v2.java b/chapter31/src/main/java/com/seaofnodes/simple/node/cpus/x86_64_v2/x86_64_v2.java
index aed8ee4c..d4714953 100644
--- a/chapter31/src/main/java/com/seaofnodes/simple/node/cpus/x86_64_v2/x86_64_v2.java
+++ b/chapter31/src/main/java/com/seaofnodes/simple/node/cpus/x86_64_v2/x86_64_v2.java
@@ -4,6 +4,8 @@ import com.seaofnodes.simple.codegen.*;
import com.seaofnodes.simple.node.*;
import com.seaofnodes.simple.type.*;
import com.seaofnodes.simple.util.Utils;
+import com.seaofnodes.simple.util.Ary;
+import java.util.IdentityHashMap;
public class x86_64_v2 extends Machine {
public x86_64_v2( CodeGen code ) {}
@@ -294,6 +296,7 @@ public class x86_64_v2 extends Machine {
public Node instSelect(Node n) {
return switch (n) {
case AddNode add -> add(add);
+ case Intrinsic.BitCastNode cast -> new BitCastX86(cast);
case AndNode and -> and(and);
case BoolNode bool -> cmp(bool);
case CLInitNode init -> new CLInitNode(init);
@@ -304,16 +307,14 @@ public class x86_64_v2 extends Machine {
case GuardNode guard -> new GuardMach(guard);
case ConstantNode con -> con(con);
case DivNode div -> div.mode()==2 ? new DivFX86(div) : new DivX86(div);
+ case ModNode mod -> mod.mode()==2 ? new ModFNode(mod) : new DivX86(mod);
case EscapeNode esc -> new EscapeNode(esc);
case FunNode fun -> new FunX86(fun);
case FunPtrNode fptr -> fptr(fptr);
case IfNode iff -> jmp(iff);
case LoadNode ld -> ld(ld);
case MemMergeNode mem -> new MemMergeNode(mem);
- case MinusNode neg -> {
- if( neg.mode()==2 ) throw Utils.TODO();
- yield new NegX86(neg);
- }
+ case MinusNode neg -> neg.mode()==2 ? new NegFX86(neg) : new NegX86(neg);
case MulNode mul -> mul.mode()==2 ? new MulFX86(mul) : mul(mul);
case NewNode nnn -> new NewX86(nnn);
case NotNode not -> new NotX86(not);
@@ -356,7 +357,7 @@ public class x86_64_v2 extends Machine {
return new AddFX86(add);
Node lhs = add.in(1);
Node rhs = add.in(2);
- if( lhs instanceof LoadNode ld && ld.nOuts() == 1 && ld.declaredType().log_size() >= 3)
+ if( lhs instanceof LoadNode ld && ld.declaredType().log_size() >= 3 && canFoldLoad(ld,rhs) )
return new AddMemX86(add, address(ld), ld.ptr(), idx, off, scale, 0, rhs);
// Attempt a full LEA-style break down.
// Returns one of AddX86, AddIX86, LeaX86, or LHS
@@ -432,11 +433,11 @@ public class x86_64_v2 extends Machine {
// Since cmp does not record a BOP, SetX/Jmp need to know if the CMP is swapped.
// Vs memory
- if( lhs instanceof LoadNode ld && ld.nOuts() == 1 && rhs._type.isa(ld.declaredType()) )
+ if( lhs instanceof LoadNode ld && rhs._type.isa(ld.declaredType()) && canFoldLoad(ld,rhs) )
return new CmpMemX86(bool, address(ld), ld.ptr(), idx, off, scale, imm(rhs), val, false);
// Operands swap in the encoding directly, no need for Set/Jmp to swap `bop`
- if( rhs instanceof LoadNode ld && ld.nOuts() == 1 && lhs._type.isa(ld.declaredType()) &&
+ if( rhs instanceof LoadNode ld && lhs._type.isa(ld.declaredType()) && canFoldLoad(ld,lhs) &&
(!(lhs instanceof ConstantNode con && con._con instanceof TypeInteger ti && imm32(ti.value())) ||
bool.op()=="==" || bool.op()=="!=") )
return new CmpMemX86(bool, address(ld), ld.ptr(), idx, off, scale, imm(lhs), val, true );
@@ -453,6 +454,25 @@ public class x86_64_v2 extends Machine {
return new CmpX86(bool);
}
+ // The other operand must not depend on a writer which must follow this
+ // load. Fusing them would move the read across that write (or form a
+ // scheduling cycle). Control dependencies count too, including calls.
+ private static boolean canFoldLoad(LoadNode load, Node value) {
+ if( load.nOuts()!=1 ) return false;
+ Ary<Node> writers=load.antiDeps(new Ary<>(Node.class));
+ if( writers.isEmpty() ) return true;
+ var seen=new IdentityHashMap<Node,Boolean>();
+ Ary<Node> work=new Ary<>(Node.class);
+ work.push(value);
+ while( !work.isEmpty() ) {
+ Node n=work.pop();
+ if( seen.put(n,Boolean.TRUE)!=null ) continue;
+ if( writers.find(n)!=-1 ) return false;
+ for( Node def : n._inputs ) if( def!=null ) work.push(def);
+ }
+ return true;
+ }
+
private Node con( ConstantNode con ) {
if( !con._con.isConstant() )
return ConstantNode.raw(con); // Default unknown caller inputs
diff --git a/chapter31/src/main/java/com/seaofnodes/simple/parser/Allocations.java b/chapter31/src/main/java/com/seaofnodes/simple/parser/Allocations.java
index 861f95b6..64234045 100644
--- a/chapter31/src/main/java/com/seaofnodes/simple/parser/Allocations.java
+++ b/chapter31/src/main/java/com/seaofnodes/simple/parser/Allocations.java
@@ -25,11 +25,20 @@ final class Allocations {
}
// Parse ary[ length_expr ]
if( P.match("[") ) {
- if( !t.makeZero().isa(t) )
- throw Parser.error("Cannot allocate a non-nullable, since arrays are always zero/null filled",site);
+ boolean readonly = P.match("~");
+ if( P.match("]") ) {
+ P.require("{");
+ return P.arrays.parse(t,readonly,null,site);
+ }
Node len = P.expressions.parseAssignment().keep();
P.require("]");
+ if( P.match("{") ) return P.arrays.parse(t,readonly,len,site);
+ if( !t.makeZero().isa(t) )
+ throw Parser.error("Cannot allocate a non-nullable, since arrays are always zero/null filled",site);
+ if( readonly ) return new ReadOnlyNode(allocArray(P.types.typeAry(t,true),len)).peephole();
return allocArray(P.types.typeAry(t,false),len);
+ } else if( t instanceof TypeMemPtr ary && ary._obj.isAry() && P.match("{") ) {
+ return P.arrays.parse(ary._obj.field("[]")._t,ary._ro,null,site);
} else {
if( !(t instanceof TypeMemPtr tmp) )
throw Parser.error("Cannot allocate a "+t.str(),site);
@@ -101,8 +110,6 @@ final class Allocations {
// TODO: Needs runtime check.
Node st = P.peep(new StoreNode(null, "#", 1, TypeInteger.U32, null, smem, self, ConFldOffNode.make(ts,"#"), len.unkeep(), true));
- // TODO: Allow add-on "constructor" to init the array elements
-
Node prior = P.mem();
Node esc = P.peep(new EscapeNode(lenFld,self,st,prior));
P.mem(P.mergeAlias(prior,lenFld._alias,esc));
@@ -117,7 +124,7 @@ final class Allocations {
TypeStruct ts = P.types.typeAry(TypeInteger.U8,true);
int lenAlias = ts.field("#" )._alias;
int elemAlias = ts.field("[]")._alias;
- TypeConAryB body = TypeConAryB.make(s);
+ TypeConAry body = TypeConAry.make(s);
TypeInteger slen = TypeInteger.constant(s.length);
// Make a TMP, not-null (byte)2, singleton (true) (requires text
// strings are hash-interned), with a TypeStruct having a constant
diff --git a/chapter31/src/main/java/com/seaofnodes/simple/parser/ArrayInitializers.java b/chapter31/src/main/java/com/seaofnodes/simple/parser/ArrayInitializers.java
new file mode 100644
index 00000000..079853cd
--- /dev/null
+++ b/chapter31/src/main/java/com/seaofnodes/simple/parser/ArrayInitializers.java
@@ -0,0 +1,187 @@
+package com.seaofnodes.simple.parser;
+
+import com.seaofnodes.simple.node.*;
+import com.seaofnodes.simple.node.ScopeNode.Kind;
+import com.seaofnodes.simple.type.*;
+import com.seaofnodes.simple.util.Ary;
+
+/** Array construction keeps the destination private until all elements exist.
+ * A generator is a scoped, immediately executed loop body, not an escaping closure. */
+final class ArrayInitializers {
+ private final Parser P;
+ Frame _frame;
+
+ static final class Frame {
+ final Kind.Block _kind;
+ final int _depth;
+ final Var _value;
+ ScopeNode _returns;
+ Frame(Kind.Block kind, int depth, Var value) {
+ _kind=kind; _depth=depth; _value=value;
+ }
+ }
+
+ ArrayInitializers(Parser P) { this.P=P; }
+
+ // Opening brace consumed; an absent length means a list with inferred size.
+ Node parse(Type elem, boolean readonly, Node len, Lexer site) {
+ int pos=P.pos();
+ Type indexType=P.types.parseType();
+ String index=indexType==null ? null : P._lexer.matchId();
+ boolean generator=index!=null && P.match("->");
+ if( !generator ) P.pos(pos);
+ if( generator && Parser.KEYWORDS.contains(index) )
+ throw Parser.error("Expected an array index name",site);
+ if( generator && (indexType!=TypeInteger.BOT && indexType!=TypeInteger.I32 && indexType!=TypeInteger.U32) )
+ throw Parser.error("Array generator index must be int, i64, or u32",site);
+ if( generator && len==null )
+ throw Parser.error("Array generator requires a length",site);
+
+ Ary<Node> values=new Ary<>(Node.class);
+ if( !generator ) {
+ if( !P.peek('}') ) do {
+ values.add(P.conversions.convertExpr(P.expressions.parseAssignment(),elem).keep());
+ } while( P.match(",") && !P.peek('}') );
+ P.require("}");
+ if( len==null ) len=P.con(values.size()).keep();
+ }
+
+ TypeStruct ts=P.types.typeAry(elem,readonly);
+ Field body=ts.field("[]"), length=ts.field("#");
+ Node size=new AddNode(ConFldOffNode.make(ts,"[]"),
+ new ShlNode(null,len,P.con(ts.aryScale())).peephole()).peephole();
+ NewNode alloc=new NewNode(ts,P.ctrl(),size).init();
+ Node self=new ProjNode(alloc,0,ts.str()).init().keep();
+ Node mem=new ProjNode(alloc,1,"#arrayMem").init().keep();
+ Node slen=new StoreNode(site,"#",length._alias,TypeInteger.U32,null,mem,self,
+ ConFldOffNode.make(ts,"#"),len,true).peephole().keep();
+
+ if( generator ) {
+ mem=generator(ts,self,mem,len,index,indexType,site);
+ } else {
+ for( int i=0; i<values.size(); i++ ) {
+ Node st=store(ts,self,mem,P.con(i),values.at(i),site).keep();
+ mem.unkeep();
+ mem=st;
+ }
+ }
+
+ Node result=new ArrayInitNode(P.ctrl(),mem,self,len,
+ generator ? -1 : values.size(),site,values).peephole().keep();
+ Node prior=P.mem();
+ P.mem(P.mergeAlias(prior,length._alias,new EscapeNode(length,result,slen.unkeep(),prior).peephole()));
+ prior=P.mem();
+ P.mem(P.mergeAlias(prior,body._alias,new EscapeNode(body,result,mem,prior).peephole()));
+ mem.unkeep(); self.unkeep(); len.unkeep();
+ for( Node value : values ) value.unkeep();
+ result.unkeep();
+ return readonly ? new ReadOnlyNode(result).peephole() : result;
+ }
+
+ private Node store(TypeStruct ts, Node self, Node mem, Node idx, Node value, Lexer site) {
+ Field fld=ts.field("[]");
+ Node off=new AddNode(ConFldOffNode.make(ts,"[]"),
+ new ShlNode(null,idx,P.con(ts.aryScale())).peephole()).peephole();
+ return new StoreNode(site,"[]",fld._alias,fld._t,P.ctrl(),mem,self,off,value,true).peephole();
+ }
+
+ private Var define(String name, Type type, boolean fin, Node value, Lexer site) {
+ if( !P._scope.define(name,type,fin,value,site) ) throw Parser.error("Duplicate name '"+name+"'",site);
+ return P._scope.lookup(name);
+ }
+
+ private Node read(Var var) { return P._scope.in(P._scope.update(var,null)); }
+
+ private Node generator(TypeStruct ts, Node self, Node mem, Node len, String name,
+ Type indexType, Lexer site) {
+ Frame outer=_frame;
+ ScopeNode oldBreak=P.statements._breakScope, oldContinue=P.statements._continueScope;
+ P.statements._breakScope=P.statements._continueScope=null;
+ Kind.Block kind=new Kind.Block();
+ P._scope.push(kind);
+ // The counter stays wide even when the source index is a narrow int.
+ // The private memory and result slots cannot be named in source.
+ Var counter=define("$arrayIndex",TypeInteger.BOT,false,P.con(0),site);
+ Var memory=define("$arrayMem",TypeMem.makePrivate(Type.BOTTOM),false,mem.unkeep(),site);
+ Var result=define("$arrayValue",ts.field("[]")._t,false,P.con(Type.TOP),site);
+ _frame=new Frame(kind,P._scope.depth(),result);
+
+ P.ctrl(new LoopNode(site,null,P.ctrl()).peephole());
+ ScopeNode head=P._scope.keep();
+ P._xScopes.push(P._scope=P._scope.dup(true));
+ Node idx=read(counter).keep();
+ Node pred=new BoolNode.LT(idx,len).peephole().keep();
+ Node iff=new IfNode(P.ctrl(),pred).peephole().keep();
+ CFGNode yes=new CProjNode(iff,0,"True").peephole().keep();
+ CFGNode no=(CFGNode)new CProjNode(iff.unkeep(),1,"False").peephole();
+ P.ctrl(no);
+ ScopeNode exit=P._scope.dup();
+ P._xScopes.push(exit);
+ exit.addGuards(no,pred,true);
+ P.ctrl(yes.unkeep());
+ P._scope.addGuards(yes,pred.unkeep(),false);
+
+ P._scope.push(new Kind.Block());
+ define(name,indexType,true,new ConvertNode(indexType,idx).peephole(),site);
+ Node last=P._code.ZERO;
+ while( !P.peek('}') && !P._lexer.isEOF() ) {
+ P._code.add(last);
+ last=P.statements.parseStatement();
+ }
+ P.require("}");
+ if( P.ctrl()._type!=Type.XCONTROL ) addReturn(last);
+ P._scope.pop();
+ if( _frame._returns!=null ) {
+ P._scope.kill();
+ P._scope=_frame._returns;
+ }
+ Node value=read(result);
+ // The loop starts with the whole private array memory. Keep that shape
+ // on the backedge too: mixing it with an element slice yields BOTTOM,
+ // which would falsely publish every function when the array escapes.
+ Node prior=read(memory).keep();
+ Node st=store(ts,self,prior,idx,value,site);
+ P._scope.update(memory,P.mergeAlias(prior.unkeep(),ts.field("[]")._alias,st));
+ P._scope.update(counter,new AddNode(idx.unkeep(),P.con(1)).peephole());
+ P._scope.removeGuards(yes);
+ head.balanceLoopFRefs(P._scope);
+ exit.balanceLoopFRefs(P._scope);
+ head.endLoop(P._scope,exit);
+ head.unkeep().kill();
+ P._xScopes.pop();
+ P._xScopes.pop();
+ if( !P._xScopes.isEmpty() ) { P._xScopes.pop(); P._xScopes.push(exit); }
+ P._scope=exit;
+ Node done=read(memory).keep();
+ P._scope.pop();
+ _frame=outer;
+ P.statements._breakScope=oldBreak;
+ P.statements._continueScope=oldContinue;
+ return done;
+ }
+
+ Node addReturn(Node expr) {
+ Node value=P.conversions.convertExpr(expr,_frame._value.type());
+ value=new ArrayInitNode(P.ctrl(),value,P.loc()).peephole().keep();
+ P.mem(); // Materialize lazy memory before cloning a return path.
+ ScopeNode cur=P._scope.dup();
+ // Saved paths share Var records with the active scope. Drop locals
+ // without promoting them, then copy forward references explicitly.
+ while( cur.depth()>_frame._depth ) cur._pop();
+ cur.balanceLoopFRefs(P._scope);
+ cur.update(_frame._value,value.unkeep());
+ if( _frame._returns==null ) _frame._returns=cur;
+ else {
+ _frame._returns.balanceLoopFRefs(cur);
+ cur.balanceLoopFRefs(_frame._returns);
+ _frame._returns.ctrl(_frame._returns.mergeScopes(cur,P.loc()).peephole());
+ }
+ P.ctrl(P._code.XCTRL);
+ return P._code.ZERO;
+ }
+
+ void checkAssignment(Var var, Lexer site) {
+ if( _frame!=null && var._idx<_frame._kind._lexSize )
+ throw Parser.error("Cannot assign captured local '"+var._name+"' in an array generator",site);
+ }
+}
diff --git a/chapter31/src/main/java/com/seaofnodes/simple/parser/Construction.java b/chapter31/src/main/java/com/seaofnodes/simple/parser/Construction.java
index 6dec8ac1..7797cae4 100644
--- a/chapter31/src/main/java/com/seaofnodes/simple/parser/Construction.java
+++ b/chapter31/src/main/java/com/seaofnodes/simple/parser/Construction.java
@@ -56,7 +56,8 @@ import com.seaofnodes.simple.util.Ary;
* binding denotes the allocator. Private-memory Parms therefore need no
* fictitious external default or constructor-specific transfer function.
* InitView and Construct are erased by the existing TypeCheck walk. There is
- * no extra construction pass; see docs/construction-groups.md.
+ * no extra construction pass; see chapter29/docs/construction-groups.md
+ * from the repository root, and chapter29/README.md for the introduction.
*/
final class Construction {
private final Parser P;
diff --git a/chapter31/src/main/java/com/seaofnodes/simple/parser/Conversions.java b/chapter31/src/main/java/com/seaofnodes/simple/parser/Conversions.java
index fa11311d..72247ca6 100644
--- a/chapter31/src/main/java/com/seaofnodes/simple/parser/Conversions.java
+++ b/chapter31/src/main/java/com/seaofnodes/simple/parser/Conversions.java
@@ -37,7 +37,7 @@ final class Conversions {
case TypeFloat tf -> TypeFloat.F64;
case TypeMemPtr tmp -> tmp.makeVar();
case TypeFunPtr tfp -> tfp;
- case TypeConAry<?> a -> a;
+ case TypeConAry a -> a;
case TypePtr ptr -> TypePtr.PTR;
case TypeScalar ts -> TypeScalar.BOT;
default -> t;
diff --git a/chapter31/src/main/java/com/seaofnodes/simple/parser/Declarations.java b/chapter31/src/main/java/com/seaofnodes/simple/parser/Declarations.java
index 13fa59b8..473a7c24 100644
--- a/chapter31/src/main/java/com/seaofnodes/simple/parser/Declarations.java
+++ b/chapter31/src/main/java/com/seaofnodes/simple/parser/Declarations.java
@@ -91,6 +91,10 @@ final class Declarations {
// expr is a constant function
if( t instanceof TypeFunPtr decl && expr._type instanceof TypeFunPtr tfp && tfp.isConstant() ) {
t = decl.makeFrom(tfp.fidx());
+ // The explicit signature specifies source parameters/return;
+ // the receiver of a method body is still inferred.
+ if( expr instanceof FunPtrNode && P.structs.inStructDeclaration() )
+ t = ((TypeFunPtr)t).makeFrom(tfp.arg(0),0);
FunNode fun = P._code.link(tfp);
if( fun != null )
fun.setName(name); // Assign debug name to Simple function
diff --git a/chapter31/src/main/java/com/seaofnodes/simple/parser/Expressions.java b/chapter31/src/main/java/com/seaofnodes/simple/parser/Expressions.java
index 6486aba8..ffc96f57 100644
--- a/chapter31/src/main/java/com/seaofnodes/simple/parser/Expressions.java
+++ b/chapter31/src/main/java/com/seaofnodes/simple/parser/Expressions.java
@@ -233,7 +233,7 @@ final class Expressions {
* Parse an multiplicativeExpr expression
*
* <pre>
- * multiplicativeExpr : unaryExpr (('*' | '/') unaryExpr)*
+ * multiplicativeExpr : unaryExpr (('*' | '/' | '%') unaryExpr)*
* </pre>
* @return a multiply expression {@link Node}, never {@code null}
*/
@@ -242,6 +242,7 @@ final class Expressions {
while( true ) {
if( P.match("*") ) lhs = new MulNode(lhs,null);
else if( P.match("/") ) lhs = new DivNode(lhs,null);
+ else if( P.match("%") ) lhs = new ModNode(lhs,null);
else break;
lhs.setDef(2,parseUnary());
lhs = P.peep(lhs);
@@ -341,6 +342,7 @@ final class Expressions {
case '-' -> new SubNode(lhs,rhs);
case '*' -> new MulNode(lhs,rhs);
case '/' -> new DivNode(lhs,rhs);
+ case '%' -> new ModNode(lhs,rhs);
case '|' -> new OrNode(null,lhs,rhs);
case '&' -> new AndNode(null,lhs,rhs);
case '^' -> new XorNode(P.loc(),lhs,rhs);
diff --git a/chapter31/src/main/java/com/seaofnodes/simple/parser/Functions.java b/chapter31/src/main/java/com/seaofnodes/simple/parser/Functions.java
index 5175acc6..84bd509e 100644
--- a/chapter31/src/main/java/com/seaofnodes/simple/parser/Functions.java
+++ b/chapter31/src/main/java/com/seaofnodes/simple/parser/Functions.java
@@ -14,6 +14,11 @@ final class Functions {
// Merge all function exits here.
ScopeNode _returnScope;
+ // Instance method headers are available immediately; their bodies need
+ // the complete field scope, just like explicitly declared constructors.
+ private record Method(FunPtrNode ptr, Lexer body, Lexer loc, BitSet finals, String[] ids) {}
+ private Ary<Method> _methods;
+
Functions(Parser P) { this.P = P; }
/**
@@ -29,6 +34,7 @@ final class Functions {
Ary<String> ids = new Ary<>(String.class);
BitSet finals = new BitSet();
Type self = P.types.implicitSelfType();
+ if( P.structs.inStructDeclaration() ) self = self.makeRO();
ts.push(self);
ids.push(self == TypePtr.PTR ? "#self" : "self");
@@ -38,10 +44,49 @@ final class Functions {
parameters(ts,ids,finals,false);
// Make a concrete function type, with a fidx
TypeFunPtr tfp = TypeFunPtr.make1((byte)2,true,ts.asAry(),Type.BOTTOM,P._code.fidx(P._ref._cname));
+ if( P.structs.inStructDeclaration() ) {
+ FunPtrNode ptr = (FunPtrNode)new FunPtrNode(tfp,P._code._start,null).peephole().keep();
+ _methods.push(new Method(ptr,P.loc(),loc,finals,ids.asAry()));
+ P._lexer.skipTo('{','}',"method body");
+ return ptr;
+ }
ReturnNode ret = parseFunctionBody(tfp,loc,finals,ids.asAry());
return new FunPtrNode(tfp,P._code._start,ret).peephole();
}
+ private void finishMethods() {
+ if( _methods == null ) return;
+ Ary<Method> methods = _methods;
+ Lexer after = P._lexer;
+ for( Method method : methods ) {
+ P._lexer = new Lexer(method.body());
+ TypeFunPtr sig = (TypeFunPtr)method.ptr()._con;
+ ReturnNode ret = parseFunctionBody(sig,method.loc(),method.finals(),method.ids());
+ method.ptr().setDef(1,ret);
+ P.require("}");
+ }
+ Ary<FunNode> functions = new Ary<>(FunNode.class);
+ for( Method method : methods ) functions.add(method.ptr().fun());
+ MethodAccess.infer(functions);
+ for( Method method : methods ) {
+ ReturnNode ret = method.ptr().ret();
+ TypeFunPtr sig = ret.fun().sig();
+ method.ptr().peephole();
+ // Declarations saw the header before its FunNode existed.
+ for( Var var : P._scope._vars )
+ if( var.type() instanceof TypeFunPtr tfp && tfp.isConstant() && tfp.fidx() == sig.fidx() ) {
+ ret.fun().setName(var._name);
+ var.refineType(var.type().join(method.ptr()._type));
+ TypeStruct self = P._scope.constructorSelf();
+ TypeStruct shape = (TypeStruct)Parser.TYPES.get(self._name);
+ Parser.TYPES.put(shape._name,shape.replace(shape.field(var._name).makeFrom(var.type())));
+ break;
+ }
+ method.ptr().unkeep();
+ }
+ P._lexer = after;
+ }
+
Node parseConstructor(String name, boolean explicit) {
P.require("{");
Ary<Type> ts = new Ary<>(Type.class);
@@ -198,9 +243,13 @@ final class Functions {
}
ReturnNode parseBody( String funName, TypeFunPtr sig, Lexer loc, BitSet finals, String[] ids) {
+ ArrayInitializers.Frame outerArray = P.arrays._frame;
+ P.arrays._frame = null;
Structs.Constructor outerCtor = P.structs._pendingCtor;
P.structs._pendingCtor = null;
boolean isInit = FunNode.isInit(funName);
+ Ary<Method> outerMethods = _methods;
+ _methods = FunNode.isInstance(funName) ? new Ary<>(Method.class) : null;
boolean isCtor = isInit || P.structs.isExplicitConstructorName(funName);
String typeName = isCtor ? ((TypeMemPtr)sig._sig[0])._obj._name : null;
@@ -233,7 +282,11 @@ final class Functions {
nvar = P.structs.updateSelfAsFieldsDiscovered( typeName, nvar );
}
- if( isInit ) P.structs.finishConstructor();
+ if( isInit ) {
+ finishMethods();
+ P.structs.finishConstructor();
+ }
+ _methods = outerMethods;
P.structs._pendingCtor = outerCtor;
ParmNode self = fun.parm(2);
@@ -275,6 +328,7 @@ final class Functions {
P.statements._breakScope = breakScope;
P._scope.pop();
P.construction._frame = outerConstruction;
+ P.arrays._frame = outerArray;
return ret;
}
@@ -300,8 +354,14 @@ final class Functions {
// All args, "as-if" called externally
for( int i = 0; i<ids.length; i++ ) {
Type t = sig.arg(i);
+ // Parse an implicit receiver with write access, then infer the
+ // public requirement from its uses once every method is present.
+ if( i == 0 && ids[0].equals("self") && !FunNode.isInit(funName) &&
+ !(sig.ret() instanceof TypeMem) && t instanceof TypeMemPtr ptr )
+ t = ptr.withAccess(false);
// Args take a default input if called from Start/external-world
- Node parm = new ParmNode(ids[i],i+2,t,fun,ConstantNode.seed(fun.defaultArg(i)).peephole()).peephole();
+ Type seed = i == 0 && t instanceof TypeMemPtr ? t : fun.defaultArg(i);
+ Node parm = new ParmNode(ids[i],i+2,t,fun,ConstantNode.seed(seed).peephole()).peephole();
if( t instanceof TypeMemPtr ptr && ptr._partial ) parm = new ConstructNode(parm).peephole();
P._scope.define(ids[i], t, (i==0 && ids[0]=="self") || (finals!=null && finals.get(i)), parm, loc);
}
diff --git a/chapter31/src/main/java/com/seaofnodes/simple/parser/Lexer.java b/chapter31/src/main/java/com/seaofnodes/simple/parser/Lexer.java
index 62dd054e..8633f2be 100644
--- a/chapter31/src/main/java/com/seaofnodes/simple/parser/Lexer.java
+++ b/chapter31/src/main/java/com/seaofnodes/simple/parser/Lexer.java
@@ -325,7 +325,7 @@ public class Lexer {
//
private boolean isPunctuation(char ch) {
- return "=;[]<>()+-/*&|^".indexOf(ch) != -1;
+ return "=;[]<>()+-/*%&|^".indexOf(ch) != -1;
}
private String parsePunctuation() {
@@ -350,7 +350,7 @@ public class Lexer {
if( match(">>=" ) ) return SAR;
if( _position+2 >= _input.length ) return 0;
char ch0 = (char)_input[_position];
- if( "+-/*&|^".indexOf(ch0) == -1 ) return 0;
+ if( "+-/*%&|^".indexOf(ch0) == -1 ) return 0;
char ch1 = (char)_input[_position+1];
if( ch1 == '=' ) { _position += 2; return ch0; }
if( isIdLetter((char)_input[_position+2]) ) return 0;
diff --git a/chapter31/src/main/java/com/seaofnodes/simple/parser/MethodAccess.java b/chapter31/src/main/java/com/seaofnodes/simple/parser/MethodAccess.java
new file mode 100644
index 00000000..099ba036
--- /dev/null
+++ b/chapter31/src/main/java/com/seaofnodes/simple/parser/MethodAccess.java
@@ -0,0 +1,130 @@
+package com.seaofnodes.simple.parser;
+
+import com.seaofnodes.simple.node.*;
+import com.seaofnodes.simple.codegen.CodeGen;
+import com.seaofnodes.simple.type.*;
+import com.seaofnodes.simple.util.Ary;
+import java.util.ArrayDeque;
+import java.util.HashMap;
+import java.util.HashSet;
+import java.util.Collections;
+import java.util.IdentityHashMap;
+import java.util.Set;
+
+/** Infer the access required through an instance method's receiver. */
+final class MethodAccess {
+ private final FunNode _fun;
+ private final Set<Node> _aliases = Collections.newSetFromMap(new IdentityHashMap<>());
+ private final Set<MethodAccess> _calls = new HashSet<>();
+ private boolean _writes;
+
+ private MethodAccess(FunNode fun) { _fun = fun; }
+
+ static void infer(Ary<FunNode> functions) {
+ HashMap<Integer,MethodAccess> methods = new HashMap<>();
+ for( FunNode fun : functions ) methods.put(fun.sig().fidx(),new MethodAccess(fun));
+ for( MethodAccess method : methods.values() ) method.scan(methods);
+ boolean changed;
+ do {
+ changed = false;
+ for( MethodAccess method : methods.values() )
+ if( !method._writes )
+ for( MethodAccess callee : method._calls )
+ if( callee._writes ) { method._writes = true; changed = true; break; }
+ } while( changed );
+ for( MethodAccess method : methods.values() ) method.finish();
+ }
+
+ private void scan(HashMap<Integer,MethodAccess> methods) {
+ if( _fun.parm(2) == null ) return; // Unused receiver.
+ ArrayDeque<Node> work = new ArrayDeque<>();
+ work.add(_fun.parm(2));
+ while( !work.isEmpty() ) {
+ Node value = work.remove();
+ if( !_aliases.add(value) ) continue;
+ for( Node use : value._outputs ) {
+ if( use == null || use instanceof ReadOnlyNode ) continue;
+ if( use instanceof StoreNode store ) {
+ if( store.ptr() == value || store.val() == value ) _writes = true;
+ } else if( use instanceof CallNode call ) {
+ for( int i = 2; i < call.nIns()-1; i++ )
+ if( call.in(i) == value ) call(call,i-2,methods);
+ } else if( use instanceof ReturnNode ret ) {
+ // Returning a writable alias must not grant write access
+ // to an object reached through a read-only receiver.
+ if( ret.expr() == value ) _writes = true;
+ } else if( use instanceof LoadNode load && load.ptr() == value ) {
+ Type type = type(load);
+ if( type instanceof TypeMemPtr ptr ) {
+ if( !ptr._ro ) work.add(load);
+ } else if( type == Type.BOTTOM || type == TypeScalar.BOT ) _writes = true;
+ } else if( use instanceof PhiNode || use instanceof GuardNode ) {
+ work.add(use);
+ } else if( use instanceof ConvertNode convert ) {
+ if( !(convert.dst() instanceof TypeMemPtr ptr && ptr._ro) ) _writes = true;
+ } else if( use instanceof BoolNode || use instanceof NotNode ||
+ use instanceof FldOffNode || use instanceof ScopeNode || use instanceof CLInitNode ) {
+ // Comparisons and field offsets do not expose write access.
+ } else {
+ // Includes raw-address casts and unrecognized escapes.
+ _writes = true;
+ }
+ }
+ }
+ }
+
+ private void call(CallNode call, int arg, HashMap<Integer,MethodAccess> methods) {
+ // Every member of this struct is now declared. An unresolved bare
+ // function name belongs to an outer scope, whose hidden slot is not self.
+ if( arg == 0 && call.fptr() instanceof FRefNode ) return;
+ Type type = type(call.fptr());
+ if( !(type instanceof TypeFunPtr sig) || arg >= sig.nargs() ) { _writes = true; return; }
+ if( arg == 0 && sig.arg(0) == TypePtr.PTR ) return;
+ if( arg == 0 ) {
+ if( XInt.isHigh(sig.fidxs()) ) { _writes = true; return; }
+ for( int fidx = XInt.next(sig.fidxs(),-1); fidx >= 0; fidx = XInt.next(sig.fidxs(),fidx) ) {
+ MethodAccess local = methods.get(fidx);
+ if( local != null ) _calls.add(local);
+ else {
+ FunNode target = CodeGen.CODE.link(fidx);
+ Type receiver = target == null ? sig.arg(0) : target.sig().arg(0);
+ if( !(receiver instanceof TypeMemPtr ptr && ptr._ro) ) _writes = true;
+ }
+ }
+ return;
+ }
+ if( !(sig.arg(arg) instanceof TypeMemPtr ptr && ptr._ro) ) _writes = true;
+ }
+
+ private static Type type(Node value) {
+ // Flow types can still be BOTTOM while the parser discovers fields.
+ if( value instanceof LoadNode load ) {
+ TypeStruct obj = load.off() instanceof ConFldOffNode off ? off._ts :
+ type(load.ptr()) instanceof TypeMemPtr ptr ? ptr._obj : null;
+ if( obj != null ) {
+ if( !obj.isAry() && Parser.TYPES.get(obj._name) instanceof TypeStruct latest ) obj = latest;
+ Field field = obj.field(load._name);
+ if( field != null ) return field._t;
+ }
+ }
+ return value._type;
+ }
+
+ private void finish() {
+ ParmNode self = _fun.parm(2);
+ if( self == null ) return;
+ TypeMemPtr receiver = ((TypeMemPtr)self._declaredType).withAccess(!_writes);
+ _fun.setSig(_fun.sig().makeFrom(receiver,0));
+ if( _writes ) return;
+ self._declaredType = receiver;
+ self.setDef(1,ConstantNode.seed(receiver).peephole());
+ // These parser-time assumptions are settled before Iter/SCCP. No
+ // writable alias escapes a method classified as read-only.
+ for( Node alias : _aliases )
+ if( alias._type instanceof TypeMemPtr ptr ) {
+ alias._type = ptr.makeRO();
+ CodeGen.CODE.add(alias);
+ CodeGen.CODE.addAll(alias._outputs);
+ }
+ }
+}
diff --git a/chapter31/src/main/java/com/seaofnodes/simple/parser/Parser.java b/chapter31/src/main/java/com/seaofnodes/simple/parser/Parser.java
index 0cf3c0e7..9c18385d 100644
--- a/chapter31/src/main/java/com/seaofnodes/simple/parser/Parser.java
+++ b/chapter31/src/main/java/com/seaofnodes/simple/parser/Parser.java
@@ -7,7 +7,7 @@ import com.seaofnodes.simple.type.*;
import com.seaofnodes.simple.util.Ary;
import java.util.HashMap;
import java.util.HashSet;
-import java.util.LinkedHashSet;
+import java.util.LinkedHashMap;
import java.util.Stack;
/** Source-unit entry point and shared cursor, scope, and IR utilities.
@@ -21,6 +21,7 @@ public class Parser {
final Functions functions = new Functions(this);
final Structs structs = new Structs(this);
final Allocations allocations = new Allocations(this);
+ final ArrayInitializers arrays = new ArrayInitializers(this);
final References references = new References(this);
final Conversions conversions = new Conversions(this);
final Construction construction = new Construction(this);
@@ -91,7 +92,7 @@ public class Parser {
public final Stack<ScopeNode> _xScopes = new Stack<>();
// Layouts needed by field accesses in this source file. Resolve after
// parsing, since a later local struct declaration can satisfy the use.
- public final LinkedHashSet<String> _requiredTypes = new LinkedHashSet<>();
+ public final LinkedHashMap<String,Lexer> _requiredTypes = new LinkedHashMap<>();
// Mapping from a type name to a Type. The string name matches
// `type.str()` call.
@@ -120,6 +121,11 @@ public class Parser {
public final Lexer _loc;
ParseException( String msg, Lexer loc ) { super(msg); _loc = loc==null ? null : new Lexer(loc); }
public String diagnostic() { return _loc==null ? getMessage() : _loc.diagnostic(getMessage()); }
+ // JUnit and uncaught-exception reporters use these entry points rather
+ // than the CLI's diagnostic(). Source errors should retain their source
+ // excerpt and caret there too. getMessage() stays stable for callers.
+ @Override public void printStackTrace(java.io.PrintStream out) { out.println(diagnostic()); }
+ @Override public void printStackTrace(java.io.PrintWriter out) { out.println(diagnostic()); }
}
public Parser(CodeGen code ) {
@@ -265,7 +271,7 @@ public class Parser {
// Field offset for an unknown type
public Node fldoff( Node n, String name ) {
if( n._type instanceof TypeMemPtr ptr && ptr._obj._fref )
- _requiredTypes.add(ptr._obj._name);
+ _requiredTypes.putIfAbsent(ptr._obj._name,loc());
return new FldOffNode(n,name,loc()).peephole();
}
public Node peep( Node n ) {
diff --git a/chapter31/src/main/java/com/seaofnodes/simple/parser/README.md b/chapter31/src/main/java/com/seaofnodes/simple/parser/README.md
index c70dcaba..e6281e50 100644
--- a/chapter31/src/main/java/com/seaofnodes/simple/parser/README.md
+++ b/chapter31/src/main/java/com/seaofnodes/simple/parser/README.md
@@ -14,6 +14,7 @@ productions to their entry points.
| `Declarations.java` | Bindings, initializers, mutability modifiers, and native declarations. |
| `Types.java` | Type syntax, qualified-name lookup, arrays, function types, and forward types. |
| `Functions.java` | Function expressions, parameters, arguments, calls, and function entry/return graphs. |
+| `MethodAccess.java` | Infers whether an instance method needs writable access through its receiver. |
| `Structs.java` | Struct and constructor declarations, field discovery, and initialization Stores. |
| `Construction.java` | Selects private self memory during parsing; its comment explains BOT fields, the TypeMemPtr qualifier, and checks deferred to TypeCheck. |
| `References.java` | Bare-name and field resolution, implicit receivers, assignments, and forward references. |
@@ -23,8 +24,16 @@ productions to their entry points.
| `Var.java` | Lexical binding metadata: name, type, scope slot, and mutability. |
Start with `Statements.parseStatement` or `Expressions.parseAssignment` to follow
-the grammar. Loop updates are parsed after their bodies, and declared constructor
-bodies after field discovery; `Lexer.skipTo` scans these deferred fragments.
+the grammar. Loop updates are parsed after their bodies. Instance method headers
+are parsed immediately, but their bodies and declared constructor bodies wait
+until all fields are known. Methods can therefore use fields declared later in
+the struct. `Lexer.skipTo` scans these deferred fragments.
+
+Method receivers accept read-only access unless the body needs writable access.
+The check follows aliases, child references, array elements, and calls between
+methods. Writing an independent argument does not require a writable receiver.
+Returning or storing a writable receiver alias also requires writable access;
+an explicit read-only view can be exposed without that requirement.
`Parser` keeps the short cursor, scope/memory, IR-building, and diagnostic helpers
used by these components. Independent helpers live with their data: class-object
diff --git a/chapter31/src/main/java/com/seaofnodes/simple/parser/References.java b/chapter31/src/main/java/com/seaofnodes/simple/parser/References.java
index 6335bad2..7724103e 100644
--- a/chapter31/src/main/java/com/seaofnodes/simple/parser/References.java
+++ b/chapter31/src/main/java/com/seaofnodes/simple/parser/References.java
@@ -120,6 +120,7 @@ final class References {
return P.expressions.parsePostfixMethod(P.construction.view(rvalue),P._scope.in(P._scope.update(P._scope.var(selfx),null)));
}
// Assign-update direct into Scope
+ P.arrays.checkAssignment(var,site);
if( var._final && !P._scope.canInit(var) )
throw Parser.error("Cannot reassign final '"+var._name+"'",site);
checkSharedFunction(var);
@@ -130,6 +131,7 @@ final class References {
}
void checkAssignment(Var def, Lexer site) {
+ if( fieldSelf(def)==null ) P.arrays.checkAssignment(def,site);
String name = def._name;
// A final field may receive its first value in its constructor.
if( P._scope.in(def._idx)._type!=Type.TOP && def._final &&
@@ -278,7 +280,7 @@ final class References {
// Check for assign-update, "ptr.fld += expr" or "ary[idx]++"
char ch = pre==0 ? P._lexer.matchOperAssign() : (char)pre;
if( ch!=0 ) {
- if( fld!=null && decl==Type.BOTTOM )
+ if( fld!=null && decl==Type.BOTTOM && !ts._fref )
throw Parser.error( "'" + ts._name + "' is not fully initialized, field '" + fld._fname + "' needs to be set in a constructor",site );
Node op = P.expressions.opAssign(ch,load, decl ).keep();
mem.keep();
@@ -306,10 +308,15 @@ final class References {
// Fields are lvalues in memory, including inside their initializer and
// explicit constructor. Scope slots retain declaration metadata only.
private Node fieldSelf(Var var) {
- int kx = P._scope.kindx(var), fx = P._scope.enclosingFuncOrDecl();
+ int kx = P._scope.kindx(var);
ScopeNode.Kind kind = P._scope._kinds.at(kx);
if( !(kind instanceof Kind.Func inst) || !FunNode.isInstance(inst._name) || var._idx<inst._lexSize+2 ) return null;
- if( kx==fx || kx+1==fx ) return defaultSelf();
+ // Nested functions have their own receiver parameter. Resolve fields
+ // through it even across intervening function and block scopes.
+ Node self = defaultSelf();
+ Type owner = P._scope.var(inst._lexSize).type();
+ if( self._type instanceof TypeMemPtr ptr && owner instanceof TypeMemPtr declared &&
+ ptr._obj._name.equals(declared._obj._name) ) return self;
return null;
}
diff --git a/chapter31/src/main/java/com/seaofnodes/simple/parser/Statements.java b/chapter31/src/main/java/com/seaofnodes/simple/parser/Statements.java
index 707202ab..0c2a25f7 100644
--- a/chapter31/src/main/java/com/seaofnodes/simple/parser/Statements.java
+++ b/chapter31/src/main/java/com/seaofnodes/simple/parser/Statements.java
@@ -78,6 +78,7 @@ final class Statements {
*/
private Node parseReturn() {
var expr = P.require(P.expressions.parseAssignment(), ";");
+ if( P.arrays._frame!=null ) return P.arrays.addReturn(expr);
return P.functions.addReturn(expr);
}
diff --git a/chapter31/src/main/java/com/seaofnodes/simple/parser/Types.java b/chapter31/src/main/java/com/seaofnodes/simple/parser/Types.java
index 827518fd..501924f0 100644
--- a/chapter31/src/main/java/com/seaofnodes/simple/parser/Types.java
+++ b/chapter31/src/main/java/com/seaofnodes/simple/parser/Types.java
@@ -37,6 +37,12 @@ final class Types {
if( t0==Type.BOTTOM || t0==Type.TOP ) return t0; // var/val
tname = typeName(tname).intern();
t0 = Parser.TYPES.get(tname);
+ // Bare forward types use the same file-relative name as `new`.
+ // A later sibling declaration must complete this very type.
+ if( t0 == null && tname.indexOf('.') == -1 ) {
+ tname = fullTypeName(tname);
+ t0 = Parser.TYPES.get(tname);
+ }
}
Type t1 = t0==null ? TypeStruct.forward(tname) : t0;
@@ -135,9 +141,8 @@ final class Types {
Type implicitSelfType() {
TypeStruct self = P._scope.constructorSelf();
- // Ordinary instance methods accept the declared object shape. The
- // constructor-only receiver starts at the low/default field values,
- // and is built explicitly by parseConstructor().
+ // Function types without a body must allow for writes. Function
+ // expressions can infer a weaker requirement in MethodAccess.
return self == null ? TypePtr.PTR : TypeMemPtr.make(self);
}
diff --git a/chapter31/src/main/java/com/seaofnodes/simple/parser/Var.java b/chapter31/src/main/java/com/seaofnodes/simple/parser/Var.java
index ddbb91d8..5361148f 100644
--- a/chapter31/src/main/java/com/seaofnodes/simple/parser/Var.java
+++ b/chapter31/src/main/java/com/seaofnodes/simple/parser/Var.java
@@ -33,6 +33,11 @@ public class Var {
public Type type() { return _type; }
public Type _type() { return _type; } // ScopeNode printer needs to have no side effects
+ void refineType(Type type) {
+ assert type.isa(_type) : _name+": "+_type+" -> "+type;
+ _type = type;
+ }
+
// Forward reference variables (not types) must be BOTTOM and
// distinct from inferred variables
public boolean isFRef() { return _fref; }
diff --git a/chapter31/src/main/java/com/seaofnodes/simple/print/ASMPrinter.java b/chapter31/src/main/java/com/seaofnodes/simple/print/ASMPrinter.java
index bdd887e6..e4d1659d 100644
--- a/chapter31/src/main/java/com/seaofnodes/simple/print/ASMPrinter.java
+++ b/chapter31/src/main/java/com/seaofnodes/simple/print/ASMPrinter.java
@@ -16,13 +16,16 @@ import java.util.Map;
public final class ASMPrinter extends AssemblyAdapter<Node> {
private final CodeGen _code;
private final Encoding _enc;
- private ASMPrinter(CodeGen code) {
+ private ASMPrinter(CodeGen code, Encoding enc) {
super(new IRPrinter());
_code=code;
- _enc=code._encoding;
+ _enc=enc;
}
public static SB print(SB sb, CodeGen code) {
- return sb.p(new com.seaofnodes.print.ASMPrinter<>(new ASMPrinter(code)).print());
+ return print(sb,code,code._encoding);
+ }
+ public static SB print(SB sb, CodeGen code, Encoding enc) {
+ return sb.p(new com.seaofnodes.print.ASMPrinter<>(new ASMPrinter(code,enc)).print());
}
@Override public ArrayList<Node> blocks() {
var blocks=new ArrayList<Node>();
@@ -89,7 +92,7 @@ public final class ASMPrinter extends AssemblyAdapter<Node> {
var data=new ArrayList<Data>();
for( var obj : _enc._data.entries() )
if( !obj.external && obj.readOnly==ro )
- data.add(new Data(obj,obj.symbol+": "+obj.type.str(),obj.alignment,obj.size));
+ data.add(new Data(obj,obj.label()+": "+obj.type.str(),obj.alignment,obj.size));
return data;
}
// Retain this diagnostic entry point for checking that pool printing never lays out types.
diff --git a/chapter31/src/main/java/com/seaofnodes/simple/type/Type.java b/chapter31/src/main/java/com/seaofnodes/simple/type/Type.java
index 0f655f49..2e228494 100644
--- a/chapter31/src/main/java/com/seaofnodes/simple/type/Type.java
+++ b/chapter31/src/main/java/com/seaofnodes/simple/type/Type.java
@@ -531,7 +531,7 @@ public class Type /*implements Cloneable*/ {
// tag-space except for the first tag-space which uses 1 tag for
// multiple Types instead of 1 Type having multiple tags. Has to
// be ordered to match _type enum.
- for( Type t : new Type[]{Type.XNIL,TypeScalar.BOT,TypePtr.PTR,TypeInteger.BOT,TypeFloat.F64,TypeConAryB.ABC,TypeRPC.BOT,TypeMemPtr.BOT,TypeFunPtr.BOT,TypeMem.BOT,Field.BOT,TypeStruct.BOT,TypeTuple.BOT} )
+ for( Type t : new Type[]{Type.XNIL,TypeScalar.BOT,TypePtr.PTR,TypeInteger.BOT,TypeFloat.F64,TypeConAry.ABC,TypeRPC.BOT,TypeMemPtr.BOT,TypeFunPtr.BOT,TypeMem.BOT,Field.BOT,TypeStruct.BOT,TypeTuple.BOT} )
TAGOFFS[t._type+1] = TAGOFFS[t._type] + t.TAGOFF();
assert TAGOFFS[TMAX] <= 255;
return TAGOFFS;
diff --git a/chapter31/src/main/java/com/seaofnodes/simple/type/TypeConAry.java b/chapter31/src/main/java/com/seaofnodes/simple/type/TypeConAry.java
index 9cb23e09..c10f09aa 100644
--- a/chapter31/src/main/java/com/seaofnodes/simple/type/TypeConAry.java
+++ b/chapter31/src/main/java/com/seaofnodes/simple/type/TypeConAry.java
@@ -1,33 +1,48 @@
package com.seaofnodes.simple.type;
import com.seaofnodes.simple.util.BAOS;
-import com.seaofnodes.simple.util.Utils;
import java.util.ArrayList;
+import java.util.Arrays;
import java.util.HashMap;
/**
- * Represents a constant array of primitives
+ * Constant integer contents with an explicit storage width and signedness.
*/
-public abstract class TypeConAry<A> extends TypeScalar {
+public final class TypeConAry extends TypeScalar {
boolean _any;
byte _widen;
- // One of byte or int array
- public final A _ary;
+ private final TypeInteger _storage;
+ private final long[] _ary;
- TypeConAry( boolean any, byte widen, A ary ) { super(TCONARY); _any = any; _widen = widen; _ary = ary; }
+ private TypeConAry(boolean any, byte widen, TypeInteger storage, long[] ary) {
+ super(TCONARY);
+ _any=any; _widen=widen; _storage=storage; _ary=ary;
+ }
+ static final TypeConAry ABC=make("abc");
+ static final TypeConAry ABCD=make("abcd");
public static void gather(ArrayList<Type> ts) {
- ts.add(TypeConAryB.make(""));
- ts.add(TypeConAryB.ABC);
- ts.add(TypeConAryB.ABCD);
- ts.add(TypeConAryI.I123);
+ ts.add(make(""));
+ ts.add(ABC);
+ ts.add(ABCD);
+ ts.add(make(TypeInteger.I32,new long[]{1,2,3}));
+ ts.add(make(TypeInteger.U16,new long[]{0,65535}));
+ ts.add(make(TypeInteger.BOT,new long[]{Long.MIN_VALUE,Long.MAX_VALUE}));
+ for( TypeInteger storage : STORAGE ) {
+ ts.add(make(storage,new long[0]));
+ ts.add(make(storage,new long[]{0,1}));
+ }
}
// Fresh, uninterned type sharing this array; xdual must not intern.
- abstract TypeConAry<A> _make(boolean any, byte widen);
+ private TypeConAry _make(boolean any, byte widen) {
+ return new TypeConAry(any,widen,_storage,_ary);
+ }
- @Override TypeConAry<A> xdual() { return _make( !_any, (byte)(3-_widen) ); }
+ @Override TypeConAry xdual() { return _make( !_any, (byte)(3-_widen) ); }
@Override Type xmeet(Type t) {
TypeConAry ary = (TypeConAry)t; // Invariant
+ if( len()==0 ) return emptyMeet(ary);
+ if( ary.len()==0 ) return ary.emptyMeet(this);
// Same base array but different?
if( _equals(ary) )
// Return array with larger widen
@@ -37,15 +52,7 @@ public abstract class TypeConAry<A> extends TypeScalar {
}
Type ymeet( TypeInteger ti ) {
- // Empty arrays have no observed elements: use the storage bounds.
- // Check both endpoints just as the loop checks a nonempty body;
- // retaining high integer inputs here preserves lattice duality.
- if( len()==0 ) {
- TypeInteger bound=emptyElem();
- if( !ti.isa(TypeInteger.make(bound._min,bound._min,ti._widen)) ||
- !ti.isa(TypeInteger.make(bound._max,bound._max,ti._widen)) )
- return ti.meet(bound);
- }
+ if( len()==0 ) return emptyMeet(ti);
// if i can isa *each* element, then maybe can keep.
// no good to i.isa(elem()) because fails the dual
for( int j=0; j<len(); j++ )
@@ -56,12 +63,21 @@ public abstract class TypeConAry<A> extends TypeScalar {
}
private boolean _equals(TypeConAry ary) {
- int len = len();
- if( len != ary.len() ) return false;
- for( int i=0; i<len; i++ )
- if( at8(i) != ary.at8(i) )
- return false;
- return true;
+ return _storage==ary._storage && (len()!=0 || _any==ary._any) && Arrays.equals(_ary,ary._ary);
+ }
+ @Override boolean eq(Type t) { return t instanceof TypeConAry ary && _widen==ary._widen && _equals(ary); }
+ @Override int hash() { return Arrays.hashCode(_ary)^_storage.hashCode()^(len()==0 && _any ? 1231 : 0); }
+ @Override public String str() {
+ boolean text=_storage==TypeInteger.U8;
+ for( long value : _ary )
+ if( value<32 || value>126 ) { text=false; break; }
+ if( !text ) {
+ String range=elem().str();
+ return range.startsWith("[") ? range : "["+range+"]";
+ }
+ byte[] bytes = new byte[len()];
+ for( int i=0; i<bytes.length; i++ ) bytes[i]=(byte)_ary[i];
+ return "[\""+new String(bytes)+"\"]";
}
@Override public boolean isHigh() { return this==TOP; }
@@ -70,8 +86,6 @@ public abstract class TypeConAry<A> extends TypeScalar {
// Meet-over-elements type
public Type elem() {
- if( _ary==null )
- return _any ? Type.TOP : BOTTOM;
int len = len();
long min = Long.MAX_VALUE;
if( len==0 ) return emptyElem();
@@ -83,23 +97,80 @@ public abstract class TypeConAry<A> extends TypeScalar {
return TypeInteger.make(min,max,_widen);
}
private TypeInteger emptyElem() {
- return log_size()==0 ? TypeInteger.make(0,255,_widen)
- : TypeInteger.make(Integer.MIN_VALUE,Integer.MAX_VALUE,_widen);
+ TypeInteger storage=storageType();
+ return _any ? TypeInteger.make(storage._min,storage._max,_widen)
+ : TypeInteger.make(storage._max,storage._min,_widen);
+ }
+ // Keep the empty payload distinct from its element bound. It sits just
+ // above the storage dual; its own dual sits just below the storage bound.
+ // This makes it a subtype of every constant array within those bounds,
+ // while preserving meet/join symmetry with ordinary integer ranges.
+ private Type emptyMeet(Type t) {
+ Type bound=emptyElem();
+ if( t.isa(bound) && (_any || t!=bound) ) return this;
+ return bound.meet(t);
}
- public abstract long at8(int idx);
- public abstract int len();
- @Override public abstract int log_size();
- public void write( BAOS baos ) { throw Utils.TODO("Should not reach here: abstract constant array cannot be written"); }
+ public TypeInteger storageType() { return _storage; }
+ public long at8(int idx) { return _ary[idx]; }
+ public int len() { return _ary.length; }
+ @Override public int log_size() { return _storage.log_size(); }
+ public void write( BAOS baos ) {
+ for( int i=0; i<len(); i++ ) {
+ long value=at8(i);
+ for( int b=0; b<(1<<log_size()); b++ ) baos.write((byte)(value >>> (8*b)));
+ }
+ }
+
+ /** Canonical contents, independent of the node which discovered them. */
+ public static TypeConAry make(TypeInteger storage, long[] values) {
+ long[] copy=values.clone();
+ int shift=64-(8<<storage.log_size());
+ for( int i=0; i<copy.length; i++ )
+ copy[i]=storage._min<0 ? (copy[i]<<shift)>>shift : copy[i]&storage._max;
+ return new TypeConAry(false,(byte)0,storage,copy).intern();
+ }
+ public static TypeConAry make(byte[] bytes) {
+ long[] values=new long[bytes.length];
+ for( int i=0; i<bytes.length; i++ ) values[i]=bytes[i]&255;
+ return new TypeConAry(false,(byte)0,TypeInteger.U8,values).intern();
+ }
+ public static TypeConAry make(String s) { return make(s.getBytes()); }
+
+ // Keep the existing byte-array tag and encoding. An impossible Java array
+ // length escapes to a typed payload, without renumbering later type tags.
+ private static final int TYPED = -1;
+ private static final TypeInteger[] STORAGE={TypeInteger.BOOL,TypeInteger.I8,TypeInteger.U8,
+ TypeInteger.I16,TypeInteger.U16,TypeInteger.I32,TypeInteger.U32,TypeInteger.BOT};
// Reserve tags for u8 array
@Override int TAGOFF() { return 1; }
@Override public void packed( BAOS baos, HashMap<String,Integer> strs ) {
- assert log_size()==0 && !_any;
baos.write(TAGOFFS[TCONARY]+0);
+ if( storageType()!=TypeInteger.U8 || _any || _widen!=0 ) {
+ baos.packed4(TYPED);
+ int kind=0;
+ while( kind<STORAGE.length && STORAGE[kind]!=storageType() ) kind++;
+ assert kind<STORAGE.length;
+ baos.packed1(kind);
+ baos.packed1((_any ? 4 : 0)|_widen);
+ }
baos.packed4(len());
- baos.write((byte[])_ary);
+ write(baos);
}
static TypeConAry packed( int tag, BAOS bais ) {
- return TypeConAryB.make(bais.read(new byte[bais.packed4()]));
+ int len=bais.packed4();
+ if( len!=TYPED ) return make(bais.read(new byte[len]));
+ TypeInteger storage=STORAGE[bais.packed1()];
+ int flags=bais.packed1();
+ long[] values=new long[bais.packed4()];
+ int size=1<<storage.log_size();
+ for( int i=0; i<values.length; i++ ) {
+ long value=0;
+ for( int b=0; b<size; b++ ) value|=(long)bais.read() << (8*b);
+ if( storage._min<0 && size<8 ) value=(value << (64-size*8)) >> (64-size*8);
+ values[i]=value;
+ }
+ TypeConAry ary=make(storage,values);
+ return flags==0 ? ary : ary._make((flags&4)!=0,(byte)(flags&3)).intern();
}
}
diff --git a/chapter31/src/main/java/com/seaofnodes/simple/type/TypeConAryB.java b/chapter31/src/main/java/com/seaofnodes/simple/type/TypeConAryB.java
deleted file mode 100644
index 84be5fb2..00000000
--- a/chapter31/src/main/java/com/seaofnodes/simple/type/TypeConAryB.java
+++ /dev/null
@@ -1,20 +0,0 @@
-package com.seaofnodes.simple.type;
-
-import com.seaofnodes.simple.util.BAOS;
-import java.util.Arrays;
-
-public class TypeConAryB extends TypeConAry<byte[]> {
- private TypeConAryB(boolean any, byte widen, byte[] bs) { super(any,widen,bs); }
- @Override TypeConAryB _make( boolean any, byte widen ) { return new TypeConAryB(any,widen,_ary); }
- public static TypeConAryB make( byte[] bs ) { return new TypeConAryB(false,(byte)0,bs).intern(); }
- public static TypeConAryB make( String s ) { return make(s.getBytes()); }
- static final TypeConAryB ABC = make("abc");
- static final TypeConAryB ABCD = make("abcd");
- @Override public long at8(int idx) { return _ary[idx]&255; }
- @Override public int len() { return _ary.length; }
- @Override public int log_size() { return 0; }
- @Override public String str() { return "[\""+new String(_ary)+"\"]"; }
- @Override boolean eq(Type t) { return t instanceof TypeConAryB ary && _widen==ary._widen && Arrays.equals(_ary,ary._ary); }
- @Override int hash() { return Arrays.hashCode(_ary); }
- @Override public void write( BAOS baos ) { baos.write(_ary); }
-}
diff --git a/chapter31/src/main/java/com/seaofnodes/simple/type/TypeConAryI.java b/chapter31/src/main/java/com/seaofnodes/simple/type/TypeConAryI.java
deleted file mode 100644
index b1b061de..00000000
--- a/chapter31/src/main/java/com/seaofnodes/simple/type/TypeConAryI.java
+++ /dev/null
@@ -1,16 +0,0 @@
-package com.seaofnodes.simple.type;
-
-import java.util.Arrays;
-
-public class TypeConAryI extends TypeConAry<int[]> {
- private TypeConAryI(boolean any, byte widen, int[] bs) { super(any,widen,bs); }
- public static TypeConAryI make( int[] bs ) { return new TypeConAryI(false,(byte)0,bs).intern(); }
- @Override TypeConAryI _make( boolean any, byte widen ) { return new TypeConAryI(any,widen,_ary); }
- static final TypeConAryI I123 = make(new int[]{1,2,3});
- @Override public long at8(int idx) { return _ary[idx]; }
- @Override public int len() { return _ary.length; }
- @Override public int log_size() { return 2; }
- @Override public String str() { return "[i32]"; }
- @Override boolean eq(Type t) { return t instanceof TypeConAryI ary && _widen==ary._widen && Arrays.equals(_ary,ary._ary); }
- @Override int hash() { return Arrays.hashCode(_ary); }
-}
diff --git a/chapter31/src/main/java/com/seaofnodes/simple/type/TypeFloat.java b/chapter31/src/main/java/com/seaofnodes/simple/type/TypeFloat.java
index d410e9cf..8d04fcbf 100644
--- a/chapter31/src/main/java/com/seaofnodes/simple/type/TypeFloat.java
+++ b/chapter31/src/main/java/com/seaofnodes/simple/type/TypeFloat.java
@@ -107,7 +107,7 @@ public class TypeFloat extends TypeScalar {
else {
assert isConstant();
baos.write(TAGOFFS[_type] + 2);
- baos.packed8(Double.doubleToLongBits(_con));
+ baos.packed8(Double.doubleToRawLongBits(_con));
}
}
@@ -121,12 +121,12 @@ public class TypeFloat extends TypeScalar {
}
@Override
- int hash() { return (int)(Double.hashCode(_con) ^ _sz ^ (1<<17)); }
+ int hash() { return Long.hashCode(Double.doubleToRawLongBits(_con)) ^ _sz ^ (1<<17); }
@Override
public boolean eq( Type t ) {
TypeFloat i = (TypeFloat)t; // Contract
- // Allow NaN to check for equality
- return _sz==i._sz && Double.doubleToLongBits(_con)==Double.doubleToLongBits(i._con);
+ // Representation conversions observe NaN signs/payloads and signed zero.
+ return _sz==i._sz && Double.doubleToRawLongBits(_con)==Double.doubleToRawLongBits(i._con);
}
}
diff --git a/chapter31/src/main/java/com/seaofnodes/simple/type/TypeStruct.java b/chapter31/src/main/java/com/seaofnodes/simple/type/TypeStruct.java
index 7c9758bd..11ba3cc4 100644
--- a/chapter31/src/main/java/com/seaofnodes/simple/type/TypeStruct.java
+++ b/chapter31/src/main/java/com/seaofnodes/simple/type/TypeStruct.java
@@ -146,8 +146,7 @@ public class TypeStruct extends Type {
Type len = TypeInteger.constant(con.len());
return make(name,false,
Field.make("#" ,len , lenAlias,true),
- Field.make("[]" ,con.elem(),bodyAlias,true),
- Field.make("[con]",con ,bodyAlias,true));
+ Field.make("[]" ,con ,bodyAlias,true));
}
public TypeStruct makeInit() {
@@ -190,6 +189,9 @@ public class TypeStruct extends Type {
}
@Override TypeStruct _close( String name, HashMap<String, Type> TYPES ) {
assert (name==null) != (TYPES==null); // One or the other
+ // Primitive constant contents are already closed. Looking up their
+ // shared array name would discard the length and payload on import.
+ if( isConAry() ) return this;
String namePlusFinal = isAry() ? (_name+(_fields[1]._final ? "~" : "!")).intern() : _name;
TypeStruct ts = (TypeStruct)VISIT.get(namePlusFinal);
if( ts!=null ) return ts;
@@ -251,7 +253,7 @@ public class TypeStruct extends Type {
public static final TypeStruct TEST= make("test",false,Field.TEST);
private static final TypeStruct ARY = makeAry("[]i64",TypeInteger.U32,-1,TypeInteger.BOT,-2,false);
private static final TypeStruct STR = makeAry("[]u8" ,TypeInteger.U32,-1,TypeInteger.U8 ,-4,false);
- private static final TypeStruct ABC = makeAry("[]u8",-1,-4,TypeConAryB.ABC);
+ private static final TypeStruct ABC = makeAry("[]u8",-1,-4,TypeConAry.ABC);
// Representative unresolved forms for the exhaustive lattice tests:
// bare forward ref, forward ref constrained by a field use, and definition.
private static final TypeStruct FREF0 = forward("%FREF");
@@ -462,6 +464,7 @@ public class TypeStruct extends Type {
@Override public int log_size() { throw Utils.TODO("Should not reach here: structs have no scalar log size"); }
@Override public int size() { return offset(_fields.length); }
@Override public int alignment() {
+ if( isAry() ) return Math.max(2,aryScale()); // The length is always u32.
int align = 0;
for( Field f : _fields )
if( !f._extern ) align = Math.max(align, f._t.alignment());
@@ -607,7 +610,7 @@ public class TypeStruct extends Type {
int align = _fields[1]._t.alignment();
_offs[1] = (4 + ((1<<align)-1)) & -(1<<align);
if( _fields[1]._t instanceof TypeConAry ary ) // Array length is well-defined for constants, not defined for runtime arrays
- _offs[2] = _offs[1]+ary.len();
+ _offs[2] = _offs[1]+(ary.len()<<ary.log_size());
} else {
int[] cnts = new int[5]; // Count of fields at log field size
diff --git a/chapter31/src/main/smp/sys.smp b/chapter31/src/main/smp/sys.smp
index f7889c05..58896f33 100644
--- a/chapter31/src/main/smp/sys.smp
+++ b/chapter31/src/main/smp/sys.smp
@@ -8,6 +8,7 @@ val aryi64 = aryi64; // Variable sized array of i64
val aryu8 = aryu8; // Variable sized array of u8
val char = char; // Character utilities
val integer = integer; // Integer bounds
+val math = math; // Math functions, constants, and float representations
val io = io; // IO library
val gfx = gfx; // Optional pixel window (MiniFB)
val draw = draw; // Software raster drawing in Simple
diff --git a/chapter31/src/main/smp/sys/adt/bitset.smp b/chapter31/src/main/smp/sys/adt/bitset.smp
index d02cd2fe..a51a63e1 100644
--- a/chapter31/src/main/smp/sys/adt/bitset.smp
+++ b/chapter31/src/main/smp/sys/adt/bitset.smp
@@ -20,7 +20,7 @@ struct bitset {
if( x < len ) return self;
while( x >= len ) len *= 2;
var bits = new i64[len];
- for( int i=0; i<_bits#; i++ )
+ for( int i = 0; i < _bits#; i++ )
bits[i] = _bits[i];
_bits = bits;
return self;
@@ -51,7 +51,7 @@ struct bitset {
};
val clear = { ->
- for( int i=0; i<_bits#; i++ ) _bits[i] = 0;
+ for( int i = 0; i < _bits#; i++ ) _bits[i] = 0;
return self;
};
};
diff --git a/chapter31/src/main/smp/sys/ary.smp b/chapter31/src/main/smp/sys/ary.smp
index 11ddb7a0..b94ffa8f 100644
--- a/chapter31/src/main/smp/sys/ary.smp
+++ b/chapter31/src/main/smp/sys/ary.smp
@@ -19,7 +19,7 @@ val copy = { u8[] dst, u32 doff, u8[~] src, u32 soff, u32 len ->
if( doff > dst# || soff > src# ) return dst;
if( len > dst# - doff ) len = dst# - doff;
if( len > src# - soff ) len = src# - soff;
- for( u32 i=0; i<len; i++ )
+ for( u32 i = 0; i < len; i++ )
dst[i+doff] = src[i+soff];
return dst;
};
@@ -33,7 +33,7 @@ val cmp = { u8[~] src1, u32 off1, u8[~] src2, u32 off2, u32 len ->
u32 len1 = len > left1 ? left1 : len;
u32 len2 = len > left2 ? left2 : len;
u32 max = len1 > len2 ? len2 : len1;
- for( u32 i=0; i<max; i++ )
+ for( u32 i = 0; i < max; i++ )
if( src1[off1+i] != src2[off2+i] )
return src1[off1+i] - src2[off2+i]; // Bytes determine compare
return len1 - len2; // Length determines compare
diff --git a/chapter31/src/main/smp/sys/aryi64.smp b/chapter31/src/main/smp/sys/aryi64.smp
index b9f1fbed..aba1b459 100644
--- a/chapter31/src/main/smp/sys/aryi64.smp
+++ b/chapter31/src/main/smp/sys/aryi64.smp
@@ -14,7 +14,7 @@ struct aryi64 {
u32 newlen = ary.capacity(buf#,len+len2);
if( !newlen ) libc._exit(1); // Length exceeds the array representation.
i64[] !buf2 = new i64[newlen];
- for( u32 i=0; i<len; i++ )
+ for( u32 i = 0; i < len; i++ )
buf2[i] = buf[i];
buf = buf2;
self;
@@ -32,7 +32,7 @@ struct aryi64 {
val str = { ->
// TODO: clunky default constructor syntax
var str = new aryu8().add('[');
- for( u32 i=0; i<len; i++ )
+ for( u32 i = 0; i < len; i++ )
str.num(buf[i]).add(',').add(' ');
if( len ) str.undo(2);
return str.add(']');
@@ -79,7 +79,7 @@ val copy = { i64[] dst, u32 doff, i64[~] src, u32 soff, u32 len ->
if( doff > dst# || soff > src# ) return dst;
if( len > dst# - doff ) len = dst# - doff;
if( len > src# - soff ) len = src# - soff;
- for( u32 i=0; i<len; i++ )
+ for( u32 i = 0; i < len; i++ )
dst[i+doff] = src[i+soff];
return dst;
};
diff --git a/chapter31/src/main/smp/sys/aryu8.smp b/chapter31/src/main/smp/sys/aryu8.smp
index 88574522..3f462898 100644
--- a/chapter31/src/main/smp/sys/aryu8.smp
+++ b/chapter31/src/main/smp/sys/aryu8.smp
@@ -27,7 +27,7 @@ struct aryu8 {
// Add all of a plain array to the aryu8
val addAry = { u8[~] xs ->
- u32 n=xs#;
+ u32 n = xs#;
_grow(n);
ary.copy(buf,len,xs,0,n);
len += n;
@@ -60,7 +60,7 @@ val atoi = { u8[~] str ->
while( x < str# && str[x] <= ' ' ) x++;
if( x == str# ) return 0;
bool neg = false;
- if( str[x]=='-' ) { neg=true; x++; }
+ if( str[x] == '-' ) { neg = true; x++; }
i64 n = 0;
while( x < str# && '0' <= str[x] <= '9' )
n = n*10 + str[x++]-'0';
@@ -69,10 +69,7 @@ val atoi = { u8[~] str ->
// Zero-terminate a string for libc, reserving one array element for the zero.
{ u8[~] -> u8[] } str0 = { u8[~] str ->
- if( str# == sys.integer.MAX_U32 ) libc._exit(1);
- u8[] !strz = new u8[str#+1];
- u32 len=str#;
- ary.copy(strz,0,str,0,len);
- strz[str#] = '\0';
- strz;
+ if( str# == sys.integer.MAX_U32 ) libc._exit(1);
+ // Copy, terminate and return
+ return new u8[str#+1]{i64 i -> i < str# ? str[i] : '\0'; };
};
diff --git a/chapter31/src/main/smp/sys/audio.md b/chapter31/src/main/smp/sys/audio.md
new file mode 100644
index 00000000..bb2ad77c
--- /dev/null
+++ b/chapter31/src/main/smp/sys/audio.md
@@ -0,0 +1,84 @@
+# Optional background audio
+
+[Chapter 31](../../../../README.md#graphics-and-sound) introduces the library.
+The Simple API is implemented in [audio.smp](audio.smp), with the native adapter
+in [simple_miniaudio.c](../../c/simple_miniaudio.c).
+
+`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 # Once while online
+make audio
+make run-graphical-tictactoe
+```
+
+The last command builds both optional backends and runs a tictactoe game with
+sounds. 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
+
+For direct execution from `chapter31`, configure both backends and launch the
+game using your shell.
+
+PowerShell:
+
+```powershell
+$env:SIMPLE_MINIFB = (Resolve-Path build/release/x86_64_v2_win64/simple_minifb.dll).Path
+$env:SIMPLE_MINIAUDIO = (Resolve-Path build/release/x86_64_v2_win64/simple_miniaudio.dll).Path
+.\build\examples\x86_64_v2_win64\TicTacToeGraphical.exe
+```
+
+Command Prompt (`cmd.exe`):
+
+```bat
+set "SIMPLE_MINIFB=%CD%\build\release\x86_64_v2_win64\simple_minifb.dll"
+set "SIMPLE_MINIAUDIO=%CD%\build\release\x86_64_v2_win64\simple_miniaudio.dll"
+.\build\examples\x86_64_v2_win64\TicTacToeGraphical.exe
+```
+
+Bash (Cygwin, using the Windows build):
+
+```bash
+export SIMPLE_MINIFB="$PWD/build/release/x86_64_v2_win64/simple_minifb.dll"
+export SIMPLE_MINIAUDIO="$PWD/build/release/x86_64_v2_win64/simple_miniaudio.dll"
+./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`
+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/src/main/smp/sys/audio.smp b/chapter31/src/main/smp/sys/audio.smp
index 89e6dfa9..5dbe63a3 100644
--- a/chapter31/src/main/smp/sys/audio.smp
+++ b/chapter31/src/main/smp/sys/audio.smp
@@ -1,4 +1,5 @@
// Optional background audio. All API calls belong on the game/main thread.
+// API and launch reference: audio.md beside this file.
int OK = 0;
int ERROR = -1;
int BOOP = 1;
diff --git a/chapter31/src/main/smp/sys/draw.smp b/chapter31/src/main/smp/sys/draw.smp
index 61b250d3..92bf04b7 100644
--- a/chapter31/src/main/smp/sys/draw.smp
+++ b/chapter31/src/main/smp/sys/draw.smp
@@ -1,4 +1,5 @@
// Software raster drawing. No window or native calls; pixels are packed RGB (0x00RRGGBB).
+// API reference: draw/README.md.
u32 BLACK = 0x000000;
u32 WHITE = 0xffffff;
u32 RED = 0xff0000;
@@ -7,9 +8,9 @@ u32 BLUE = 0x0000ff;
// Components are clamped to bytes rather than wrapping.
val rgb = { int r, int g, int b ->
- r = r<0 ? 0 : r>255 ? 255 : r;
- g = g<0 ? 0 : g>255 ? 255 : g;
- b = b<0 ? 0 : b>255 ? 255 : b;
+ r = r < 0 ? 0 : r > 255 ? 255 : r;
+ g = g < 0 ? 0 : g > 255 ? 255 : g;
+ b = b < 0 ? 0 : b > 255 ? 255 : b;
u32 color = (r<<16) | (g<<8) | b;
return color;
};
diff --git a/chapter31/src/main/smp/sys/draw/Button.smp b/chapter31/src/main/smp/sys/draw/Button.smp
index edf01119..c90ed2d3 100644
--- a/chapter31/src/main/smp/sys/draw/Button.smp
+++ b/chapter31/src/main/smp/sys/draw/Button.smp
@@ -3,36 +3,36 @@
struct Button {
int x, y, width, height;
u8[~] !label;
- bool !enabled=true, !hovered=false, !pressed=false;
- bool !_held=false, !_armed=false;
+ bool !enabled = true, !hovered = false, !pressed = false;
+ bool !_held = false, !_armed = false;
new Button = { int px, int py, int w, int h, u8[~] text ->
- x=px; y=py; width=w; height=h; label=text;
+ x = px; y = py; width = w; height = h; label = text;
};
val contains = { i64 px, i64 py ->
- if( width<=0 || height<=0 ) return false;
- i64 right=x, bottom=y; right+=width; bottom+=height;
- if( px<x || py<y || px>=right || py>=bottom ) return false;
+ if( width <= 0 || height <= 0 ) return false;
+ i64 right = x, bottom = y; right += width; bottom += height;
+ if( px < x || py < y || px >= right || py >= bottom ) return false;
return true;
};
val update = { i64 px, i64 py, bool down ->
- hovered=false;
- if( enabled ) hovered=contains(px,py);
- if( !enabled ) _armed=false;
- if( down && !_held ) _armed=hovered;
- var clicked=false;
- if( !down ) if( _held ) if( _armed ) if( hovered ) clicked=true;
- if( !down ) _armed=false;
- _held=down;
- pressed=false;
- if( down ) if( _armed ) if( hovered ) pressed=true;
+ hovered = false;
+ if( enabled ) hovered = contains(px,py);
+ if( !enabled ) _armed = false;
+ if( down && !_held ) _armed = hovered;
+ var clicked = false;
+ if( !down ) if( _held ) if( _armed ) if( hovered ) clicked = true;
+ if( !down ) _armed = false;
+ _held = down;
+ pressed = false;
+ if( down ) if( _armed ) if( hovered ) pressed = true;
return clicked;
};
val draw = { !sys.draw.Canvas screen, int scale, u32 foreground, u32 background, u32 active ->
screen.fillRect(x,y,width,height,enabled && (hovered || pressed) ? active : background);
screen.rect(x,y,width,height,2,enabled ? foreground : active);
- if( scale>0 ) {
- i64 textWidth=label#; textWidth=(textWidth*4-1)*scale;
- if( textWidth<=width-8 && 5*scale<=height-8 )
+ if( scale > 0 ) {
+ i64 textWidth = label#; textWidth = (textWidth*4-1)*scale;
+ if( textWidth <= width-8 && 5*scale <= height-8 )
screen.text(x+(width-textWidth)/2,y+(height-5*scale)/2+(pressed ? 1 : 0),
label,scale,enabled ? foreground : active);
}
diff --git a/chapter31/src/main/smp/sys/draw/Canvas.smp b/chapter31/src/main/smp/sys/draw/Canvas.smp
index c736e4e2..5ec7c9ef 100644
--- a/chapter31/src/main/smp/sys/draw/Canvas.smp
+++ b/chapter31/src/main/smp/sys/draw/Canvas.smp
@@ -1,44 +1,88 @@
struct Canvas {
- u32 width;
- u32 height;
- u32[] pixels;
+ u32 !width;
+ u32 !height;
+ u32[] !pixels;
+ // Layout coordinates are relative to the constructor's base size.
+ // A single float scale preserves circles and game geometry on resize.
+ u32 baseWidth, baseHeight;
+ f64 scale = 1.0;
+ int offsetX = 0, offsetY = 0;
- new Canvas = { int w, int h ->
+ new Canvas = { u32 w, u32 h ->
+ if( w > sys.integer.MAX_I32 || h > sys.integer.MAX_I32 ) libc._exit(1);
i64 count = w;
count *= h;
- if( w<=0 || h<=0 || count>sys.integer.MAX_I32 ) libc._exit(1);
+ if( w <= 0 || h <= 0 || count > sys.integer.MAX_I32 ) libc._exit(1);
width = w;
height = h;
+ baseWidth = w;
+ baseHeight = h;
pixels = new u32[count];
};
+ // Ignore minimized windows. Return true only when a redraw is needed.
+ val resize = { u32 w, u32 h ->
+ if( w == 0 || h == 0 || (w == width && h == height) ) return false;
+ if( w > sys.integer.MAX_I32 || h > sys.integer.MAX_I32 ) libc._exit(1);
+ i64 count = w; count *= h;
+ if( count > sys.integer.MAX_I32 ) libc._exit(1);
+ // Reuse storage while dragging. Geometric growth bounds total allocation
+ // even in the current runtime, which does not yet collect old arrays.
+ if( count > pixels# ) {
+ i64 capacity = pixels#*2;
+ if( capacity < count ) capacity = count;
+ if( capacity > sys.integer.MAX_I32 ) capacity = sys.integer.MAX_I32;
+ pixels = new u32[capacity];
+ }
+ width = w; height = h;
+ f64 sx = w*1.0/baseWidth, sy = h*1.0/baseHeight;
+ scale = sx < sy ? sx : sy;
+ offsetX = (w-baseWidth*scale)/2;
+ offsetY = (h-baseHeight*scale)/2;
+ return true;
+ };
+
+ // Inverse of the drawing transform. Margins are outside the layout;
+ // reject them before integer truncation can turn a small negative into 0.
+ val localX = { int x ->
+ if( x < offsetX || x >= offsetX+baseWidth*scale ) return -1;
+ int local = (x-offsetX)/scale;
+ return local;
+ };
+ val localY = { int y ->
+ if( y < offsetY || y >= offsetY+baseHeight*scale ) return -1;
+ int local = (y-offsetY)/scale;
+ return local;
+ };
+
val clear = { u32 color ->
- for( int i=0; i<pixels#; i++ ) pixels[i] = color;
+ i64 count = width; count *= height;
+ for( int i = 0; i < count; i++ ) pixels[i] = color;
return self;
};
val pixel = { i64 x, i64 y, u32 color ->
- if( 0<=x<width && 0<=y<height ) pixels[y*width+x] = color;
- return self;
+ return fillRect(x,y,1,1,color);
};
// Integer coordinates, top-left origin. Rectangle extents are half-open.
val fillRect = { i64 x, i64 y, i64 w, i64 h, u32 color ->
- if( w<=0 || h<=0 ) return self;
- i64 right = x; right += w;
- i64 bottom = y; bottom += h;
- if( right<=0 || bottom<=0 || x>=width || y>=height ) return self;
- int x0 = x<0 ? 0 : x, y0 = y<0 ? 0 : y;
- int x1 = right>width ? width : right, y1 = bottom>height ? height : bottom;
- for( int py=y0; py<y1; py++ )
- for( int px=x0; px<x1; px++ ) pixels[py*width+px] = color;
+ if( w <= 0 || h <= 0 ) return self;
+ i64 right = offsetX+(x+w)*scale;
+ i64 bottom = offsetY+(y+h)*scale;
+ x = offsetX+x*scale; y = offsetY+y*scale;
+ if( right <= 0 || bottom <= 0 || x >= width || y >= height ) return self;
+ int x0 = x < 0 ? 0 : x, y0 = y < 0 ? 0 : y;
+ int x1 = right > width ? width : right, y1 = bottom > height ? height : bottom;
+ for( int py = y0; py < y1; py++ )
+ for( int px = x0; px < x1; px++ ) pixels[py*width+px] = color;
return self;
};
// Outline stays inside the rectangle. Wide borders become a filled rect.
val rect = { i64 x, i64 y, i64 w, i64 h, i64 thickness, u32 color ->
- if( w<=0 || h<=0 || thickness<=0 ) return self;
- if( thickness>=w || thickness>=h || thickness>=w-thickness || thickness>=h-thickness )
+ if( w <= 0 || h <= 0 || thickness <= 0 ) return self;
+ if( thickness >= w || thickness >= h || thickness >= w-thickness || thickness >= h-thickness )
return fillRect(x,y,w,h,color);
fillRect(x,y,w,thickness,color);
fillRect(x,y+h-thickness,w,thickness,color);
@@ -54,23 +98,27 @@ struct Canvas {
return _circle(cx,cy,radius,thickness,false,color);
};
val _circle = { i64 cx, i64 cy, int radius, int thickness, bool filled, u32 color ->
- if( radius<0 || (!filled && thickness<=0) ) return self;
+ if( radius < 0 || (!filled && thickness <= 0) ) return self;
+ cx = offsetX+cx*scale; cy = offsetY+cy*scale;
+ radius *= scale;
+ thickness *= scale;
+ if( !filled && thickness < 1 ) thickness = 1;
i64 left = cx; left -= radius;
i64 top = cy; top -= radius;
i64 right = cx; right += radius;
i64 bottom = cy; bottom += radius;
- if( right<0 || bottom<0 || left>=width || top>=height ) return self;
- int x0 = left<0 ? 0 : left, y0 = top<0 ? 0 : top;
- int x1 = right>=width ? width-1 : right, y1 = bottom>=height ? height-1 : bottom;
+ if( right < 0 || bottom < 0 || left >= width || top >= height ) return self;
+ int x0 = left < 0 ? 0 : left, y0 = top < 0 ? 0 : top;
+ int x1 = right >= width ? width-1 : right, y1 = bottom >= height ? height-1 : bottom;
i64 outer2 = radius;
outer2 *= radius;
i64 inner = filled ? -1 : radius-thickness;
- for( int py=y0; py<=y1; py++ )
- for( int px=x0; px<=x1; px++ ) {
+ for( int py = y0; py <= y1; py++ )
+ for( int px = x0; px <= x1; px++ ) {
i64 dx = px; dx -= cx;
i64 dy = py; dy -= cy;
i64 d2 = dx*dx+dy*dy;
- if( d2<=outer2 && (inner<=0 || d2>inner*inner) ) pixels[py*width+px] = color;
+ if( d2 <= outer2 && (inner <= 0 || d2 > inner*inner) ) pixels[py*width+px] = color;
}
return self;
};
@@ -78,17 +126,21 @@ struct Canvas {
// Round caps; a zero-length segment is a dot. Only the clipped bounding
// box is scanned. Floating distances avoid overflowing coordinate squares.
val line = { i64 x0, i64 y0, i64 x1, i64 y1, i64 thickness, u32 color ->
- if( thickness<=0 ) return self;
+ if( thickness <= 0 ) return self;
+ x0 = offsetX+x0*scale; y0 = offsetY+y0*scale;
+ x1 = offsetX+x1*scale; y1 = offsetY+y1*scale;
+ thickness *= scale;
+ if( thickness < 1 ) thickness = 1;
i64 pad = thickness/2+1;
- i64 left = x0<x1 ? x0 : x1; left -= pad;
- i64 top = y0<y1 ? y0 : y1; top -= pad;
- i64 right = x0>x1 ? x0 : x1; right += pad;
- i64 bottom = y0>y1 ? y0 : y1; bottom += pad;
- if( right<0 || bottom<0 || left>=width || top>=height ) return self;
- int bx0 = left<0 ? 0 : left, by0 = top<0 ? 0 : top;
- int bx1 = right>=width ? width-1 : right, by1 = bottom>=height ? height-1 : bottom;
- for( int py=by0; py<=by1; py++ )
- for( int px=bx0; px<=bx1; px++ )
+ i64 left = x0 < x1 ? x0 : x1; left -= pad;
+ i64 top = y0 < y1 ? y0 : y1; top -= pad;
+ i64 right = x0 > x1 ? x0 : x1; right += pad;
+ i64 bottom = y0 > y1 ? y0 : y1; bottom += pad;
+ if( right < 0 || bottom < 0 || left >= width || top >= height ) return self;
+ int bx0 = left < 0 ? 0 : left, by0 = top < 0 ? 0 : top;
+ int bx1 = right >= width ? width-1 : right, by1 = bottom >= height ? height-1 : bottom;
+ for( int py = by0; py <= by1; py++ )
+ for( int px = bx0; px <= bx1; px++ )
if( _onLine(px,py,x0,y0,x1,y1,thickness) ) pixels[py*width+px] = color;
return self;
};
@@ -96,14 +148,14 @@ struct Canvas {
// Small 3x5 bitmap font for game labels. Lowercase maps to uppercase.
// Newline returns to x; unsupported characters draw a question mark.
val text = { i64 x, i64 y, u8[~] str, int scale, u32 color ->
- if( scale<=0 ) return self;
+ if( scale <= 0 ) return self;
i64 px = x, py = y;
- for( int i=0; i<str#; i++ ) {
+ for( int i = 0; i < str#; i++ ) {
u8 c = str[i];
- if( c=='\n' ) { px=x; py+=6*scale; continue; }
+ if( c == '\n' ) { px = x; py += 6*scale; continue; }
int bits = _glyph(c);
- for( int row=0; row<5; row++ )
- for( int col=0; col<3; col++ )
+ for( int row = 0; row < 5; row++ )
+ for( int col = 0; col < 3; col++ )
if( (bits >> (14-row*3-col)) & 1 )
fillRect(px+col*scale,py+row*scale,scale,scale,color);
px += 4*scale;
@@ -112,79 +164,25 @@ struct Canvas {
};
};
-// An old-school 3x5 font
+// An old-school 3x5 font, ASCII 32..127. Five octal row digits need u16.
+// Lowercase uses uppercase shapes; unsupported characters use '?'.
+val _glyphs = new u16[~96]{
+ 000000,022202,055000,057575,061202,051245,061202,022000, // space..'
+ 012221,042224,005250,002720,000024,000700,000002,011244, // (../
+ 075557,026227,061247,061216,055711,074616,034757,071222, // 0..7
+ 075757,075716,002020,002024,012421,007070,042124,061202, // 8..?
+ 061202,025755,065656,034443,065556,074647,074644,034553, // @..G
+ 055755,072227,011152,055655,044447,057755,057775,025552, // H..O
+ 065644,025573,065655,034216,072222,055557,055552,055775, // P..W
+ 055255,055222,071247,032223,044211,062226,025000,000007, // X.._
+ 042000,025755,065656,034443,065556,074647,074644,034553, // `..g
+ 055755,072227,011152,055655,044447,057755,057775,025552, // h..o
+ 065644,025573,065655,034216,072222,055557,055552,055775, // p..w
+ 055255,055222,071247,032423,022222,062126,003600,061202, // x..DEL
+};
+
val _glyph = { u8 c ->
- // Only space for upper-case letters in a 3x5 font
- if( 'a' <= c <= 'z' )
- c -= 'a'-'A';
- // Five octal digits: one 3-bit row per digit, top to bottom.
- if( c==' ' ) return 000000;
- if( c=='0' ) return 075557;
- if( c=='1' ) return 026227;
- if( c=='2' ) return 061247;
- if( c=='3' ) return 061216;
- if( c=='4' ) return 055711;
- if( c=='5' ) return 074616;
- if( c=='6' ) return 034757;
- if( c=='7' ) return 071222;
- if( c=='8' ) return 075757;
- if( c=='9' ) return 075716;
- if( c=='A' ) return 025755;
- if( c=='B' ) return 065656;
- if( c=='C' ) return 034443;
- if( c=='D' ) return 065556;
- if( c=='E' ) return 074647;
- if( c=='F' ) return 074644;
- if( c=='G' ) return 034553;
- if( c=='H' ) return 055755;
- if( c=='I' ) return 072227;
- if( c=='J' ) return 011152;
- if( c=='K' ) return 055655;
- if( c=='L' ) return 044447;
- if( c=='M' ) return 057755;
- if( c=='N' ) return 057775;
- if( c=='O' ) return 025552;
- if( c=='P' ) return 065644;
- if( c=='Q' ) return 025573;
- if( c=='R' ) return 065655;
- if( c=='S' ) return 034216;
- if( c=='T' ) return 072222;
- if( c=='U' ) return 055557;
- if( c=='V' ) return 055552;
- if( c=='W' ) return 055775;
- if( c=='X' ) return 055255;
- if( c=='Y' ) return 055222;
- if( c=='Z' ) return 071247;
- if( c=='-' ) return 000700;
- if( c=='.' ) return 000002;
- if( c==':' ) return 002020;
- if( c==',' ) return 000024;
- if( c==';' ) return 002024;
- if( c=='\'' ) return 022000;
- if( c=='"' ) return 055000;
- if( c=='`' ) return 042000;
- if( c=='/' ) return 011244;
- if( c=='\\' ) return 044211;
- if( c=='(' ) return 012221;
- if( c==')' ) return 042224;
- if( c=='[' ) return 032223;
- if( c==']' ) return 062226;
- if( c=='{' ) return 032423;
- if( c=='}' ) return 062126;
- if( c=='+' ) return 002720;
- if( c=='=' ) return 007070;
- if( c=='_' ) return 000007;
- if( c=='<' ) return 012421;
- if( c=='>' ) return 042124;
- if( c=='|' ) return 022222;
- if( c=='^' ) return 025000;
- if( c=='~' ) return 003600;
- if( c=='*' ) return 005250;
- if( c=='#' ) return 057575;
- if( c=='%' ) return 051245;
- if( c=='!' ) return 022202;
- if( c=='?' ) return 061202;
- return 061202;
+ return 32 <= c < 128 ? _glyphs[c-32] : 061202;
};
// Pixel coverage for a round-ended segment, separate from traversal.
@@ -194,10 +192,10 @@ val _onLine = { i64 px, i64 py, i64 x0, i64 y0, i64 x1, i64 y1, i64 thickness ->
f64 vx = px; vx -= x0;
f64 vy = py; vy -= y0;
f64 length2 = dx*dx+dy*dy;
- bool point = x0==x1 && y0==y1;
+ bool point = x0 == x1 && y0 == y1;
f64 t = point ? 0.0 : (vx*dx+vy*dy)/length2;
- t = t<0 ? 0.0 : t>1 ? 1.0 : t;
+ t = t < 0 ? 0.0 : t > 1 ? 1.0 : t;
f64 ex = vx-t*dx, ey = vy-t*dy;
f64 half = thickness/2.0;
- return ex*ex+ey*ey<=half*half;
+ return ex*ex+ey*ey <= half*half;
};
diff --git a/chapter31/src/main/smp/sys/draw/README.md b/chapter31/src/main/smp/sys/draw/README.md
new file mode 100644
index 00000000..7d3bf6c8
--- /dev/null
+++ b/chapter31/src/main/smp/sys/draw/README.md
@@ -0,0 +1,124 @@
+# Drawing in Simple
+
+[Chapter 31](../../../../../README.md#graphics-and-sound) introduces the library.
+The implementation is in [Canvas.smp](Canvas.smp), [Button.smp](Button.smp),
+and the [draw module](../draw.smp).
+
+`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](../gfx.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.presentSize(canvas.pixels,canvas.width,canvas.height);
+```
+
+## 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. |
+| `resize(width,height)` | Fit the original layout into new drawable dimensions; return whether they changed. Ignore zero dimensions. |
+| `localX(x)`, `localY(y)` | Convert drawable pixels to base coordinates for input; return -1 in the margins. |
+| `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.
+
+The constructor sets the layout's `baseWidth` and `baseHeight`. Resizing uses
+`scale = min(width/baseWidth, height/baseHeight)` in floating point and centers
+the result with `offsetX` and `offsetY`. Sizes, offsets, glyph cells, and stroke
+widths all use this transform; circles stay circular. Positive line and circle
+strokes retain at least one drawable pixel. Existing drawing coordinates remain
+in base units, while `width`, `height`, and direct pixel indexing use the actual
+framebuffer dimensions. `clear` fills the whole framebuffer, including margins.
+At very small sizes, details smaller than a pixel naturally disappear.
+
+Canvas reuses its pixel storage and grows its capacity geometrically when needed.
+Only the first `width*height` elements are active; use `gfx.presentSize` after
+resizing. This avoids allocating on every drag event, including repeated shrink
+and grow cycles. Use `localX`/`localY` before button or game hit tests so drawing
+and input share the same scale and centering.
+
+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`.
+The font includes all printable ASCII punctuation except `@`, `&`, and `$`,
+which use the question-mark fallback. Colons and slashes support clock and date
+labels; quotes, brackets, arithmetic signs, and other small symbols fit in 3×5.
+
+## Button widget
+
+`new sys.draw.Button(x,y,width,height,label)` creates a rectangular software
+button. It owns no window or native resources. Feed pointer coordinates and
+the held mouse-button state to `update(x,y,down)` once per event-loop iteration.
+It returns true once on release inside, provided the press began inside.
+Dragging in from outside does not activate it; releasing outside cancels.
+
+`hovered` and `pressed` expose visual state. Set `enabled=false` to cancel a
+pending press and disable activation; `label` can be changed at any time.
+`contains(x,y)` uses half-open bounds. `draw(canvas,scale,foreground,background,active)`
+paints the button and centers its 3x5 label when it fits. Colors belong to the
+caller. Keyboard shortcuts belong to the application; this small widget has
+no focus system. The [clock example](../../../../../docs/examples/Clock.smp) shows mouse activation
+and a Space shortcut in the same single-threaded loop.
+
+## Graphical tic-tac-toe
+
+From `chapter31`:
+
+```sh
+make run-graphical-tictactoe
+```
+
+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 after a move, restart, hover change, or resize;
+polling still processes window events and waits between polls.
+
+`make graphical-tictactoe` 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.
+Backend discovery and explicit overrides follow [the pixel-window instructions](../gfx.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` checks raster pixels and complete game turns
+without a display. `make tests_nographics` runs the ordinary suite with
+the backend disabled.
diff --git a/chapter31/src/main/smp/sys/gfx.md b/chapter31/src/main/smp/sys/gfx.md
new file mode 100644
index 00000000..931d985f
--- /dev/null
+++ b/chapter31/src/main/smp/sys/gfx.md
@@ -0,0 +1,154 @@
+# Optional graphics
+
+[Chapter 31](../../../../README.md#graphics-and-sound) introduces the library.
+The Simple API is implemented in [gfx.smp](gfx.smp), with the window adapter in
+[simple_minifb.c](../../c/simple_minifb.c).
+
+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 resizable window, operated on the main thread. The
+[Graphics example](../../../../docs/examples/Graphics.smp) draws a color gradient in Simple.
+The [drawing library and graphical tic-tac-toe](draw/README.md) build on this pixel
+interface. `make run-graphical-tictactoe` builds the optional backend and
+opens the game; `make graphical-tictactoe` 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` 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 an available 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 # Once while online; fills the persistent lib/ cache.
+make graphics graphics-example
+make run-graphics
+```
+
+`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 `chapter31` in 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 Command Prompt (`cmd.exe`):
+
+```bat
+set "SIMPLE_MINIFB=%CD%\build\release\x86_64_v2_win64\simple_minifb.dll"
+.\build\examples\x86_64_v2_win64\Graphics.exe
+```
+
+From Bash (Cygwin, using the Windows build):
+
+```bash
+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'
+```
+
+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
+```
+
+With no `SIMPLE_MINIFB` setting, the runtime searches beside the executable,
+then its `../../release/<ABI>` and `../release/<ABI>` directories. These cover
+the examples and test build layouts regardless of the current directory.
+It also checks the current directory, `build/release/<ABI>`, and
+`chapter31/build/release/<ABI>` relative to the current directory. Thus built
+examples such as `Clock.exe` can be launched directly without configuration.
+
+`SIMPLE_MINIFB` overrides discovery; an invalid explicit path reports an error
+without falling back. `SIMPLE_MINIFB=off` disables graphics for headless tests.
+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 the original `width*height` pixels, packed `0x00RRGGBB`. MiniFB stretches this buffer to the window. |
+| `width()`, `height()` | Current drawable dimensions after the last event dispatch; zero when no window exists. |
+| `presentSize(pixels,width,height)` | Present the first `width*height` elements of a buffer at an explicit resolution. Dimensions must be positive and fit the array. |
+| `poll(wait)` | Process input; `true` waits up to 17ms, waking for input. |
+| `wait(timeoutMs)` | Wait for input or timeout, then process events; 0 polls, -1 waits indefinitely. |
+| `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`, `poll`, and `wait` 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.
+
+Waits may return early; values below -1 are errors. Recheck the monotonic
+clock after waking. The [time library and animation example](time/README.md) combine
+this wait with cooperative timer deadlines. Backend API version 3 adds
+resizing and explicit framebuffer dimensions; rebuild older MiniFB adapters
+with `make graphics` from the cached sources.
+
+For drawing at the new resolution, call `canvas.resize(gfx.width(),gfx.height())`
+after processing events, redraw when it returns true, and use
+`gfx.presentSize(canvas.pixels,canvas.width,canvas.height)`. Explicit buffer
+dimensions remain valid if another resize arrives while presenting. Zero-sized
+resize notifications are ignored by Canvas so minimizing retains the last layout.
+Mouse coordinates are in drawable pixels; convert them with `canvas.localX`
+and `canvas.localY` for hit testing in the [base layout](draw/README.md).
+
+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.
diff --git a/chapter31/src/main/smp/sys/gfx.smp b/chapter31/src/main/smp/sys/gfx.smp
index ae203bd1..60505ac9 100644
--- a/chapter31/src/main/smp/sys/gfx.smp
+++ b/chapter31/src/main/smp/sys/gfx.smp
@@ -1,5 +1,6 @@
// Minimal pixel-window interface; drawing belongs in Simple.
-// One fixed-size window, main thread only. Pixel format is 0x00RRGGBB.
+// API and launch reference: gfx.md beside this file.
+// One resizable window, main thread only. Pixel format is 0x00RRGGBB.
// open/present/poll return OK, CLOSED (normal user close/Esc), or ERROR.
int OK = 0;
int CLOSED = 1;
@@ -9,6 +10,9 @@ int ESCAPE = 256;
{ i64 u32 u32 -> i32 } simple_gfx_open = "C";
{ i64 u32 -> i32 } simple_gfx_present = "C";
+{ i64 u32 u32 u32 -> i32 } simple_gfx_present_size = "C";
+{ u32 } simple_gfx_width = "C";
+{ u32 } simple_gfx_height = "C";
{ i32 -> i32 } simple_gfx_poll = "C";
{ i32 } simple_gfx_mouse_x = "C";
{ i32 } simple_gfx_mouse_y = "C";
@@ -31,6 +35,19 @@ val present = { u32[~] pixels ->
simple_gfx_present(ptr,pixels#);
};
+// Drawable size after the last event dispatch; zero when closed.
+val width = { -> simple_gfx_width(); };
+val height = { -> simple_gfx_height(); };
+// Explicit dimensions keep a resize arriving during presentation harmless.
+val presentSize = { u32[~] pixels, u32 width, u32 height ->
+ if( width == 0 || height == 0 || width > pixels# || height > pixels# ) return ERROR;
+ i64 count = width; count *= height;
+ if( count > pixels# ) return ERROR;
+ i64 ptr = pixels;
+ u32 size = count;
+ simple_gfx_present_size(ptr,size,width,height);
+};
+
// wait=true waits up to 17ms, waking early for input to avoid a busy loop.
val poll = { bool wait -> simple_gfx_poll(wait); };
val mouseX = { -> simple_gfx_mouse_x(); };
diff --git a/chapter31/src/main/smp/sys/libc.smp b/chapter31/src/main/smp/sys/libc.smp
index 7122bbd8..8e417461 100644
--- a/chapter31/src/main/smp/sys/libc.smp
+++ b/chapter31/src/main/smp/sys/libc.smp
@@ -53,9 +53,9 @@ i32 EOVERFLOW = "C";
// addr len prot flags fd off -> void*
{ i64 i64 i32 i32 i32 i32 -> i64 } mmap = "C";
// mmap flags
-i32 PROT_EXEC = 4;
-i32 PROT_READ = 1;
-i32 PROT_WRITE= 2;
-i32 PROT_NONE = 0;
+i32 PROT_EXEC = 4;
+i32 PROT_READ = 1;
+i32 PROT_WRITE = 2;
+i32 PROT_NONE = 0;
i32 MAP_PRIVATE = 2;
i32 MAP_ANON = 32;
diff --git a/chapter31/src/main/smp/sys/math.smp b/chapter31/src/main/smp/sys/math.smp
new file mode 100644
index 00000000..33bb0e5f
--- /dev/null
+++ b/chapter31/src/main/smp/sys/math.smp
@@ -0,0 +1,27 @@
+// Mathematical constants, rounded to the nearest f64 value.
+val PI = 3.141592653589793;
+val E = 2.718281828459045;
+
+// Native libm functions, all f64 -> f64. sin/cos take radians; exp is e^x,
+// log is the natural logarithm, and sqrt is the nonnegative square root.
+// These are ordinary C calls: results and domain/range errors (including
+// errno) follow the host libm. They are not folded or treated as pure intrinsics.
+// The standard linker already includes -lm.
+{ f64 -> f64 } sin = "C";
+{ f64 -> f64 } cos = "C";
+{ f64 -> f64 } exp = "C";
+{ f64 -> f64 } log = "C";
+{ f64 -> f64 } sqrt = "C";
+
+// Fixed-semantics C bindings recognized by the compiler's intrinsic inliner.
+// See chapter31/README.md, "Math support and intrinsics", for the compiler contract.
+// These preserve all 64 bits, including signed zero and NaN payloads.
+// They are NOT numeric conversions (ordinary typed assignments still are).
+{ f64 -> i64 } simple_f64_bits = "C";
+{ i64 -> f64 } simple_f64_from_bits = "C";
+val f64Bits = simple_f64_bits;
+val f64FromBits = simple_f64_from_bits;
+
+
+val max = { f64 x, f64 y -> return x > y ? x : y; };
+val min = { f64 x, f64 y -> return x < y ? x : y; };
diff --git a/chapter31/src/main/smp/sys/rt/simple_args.smp b/chapter31/src/main/smp/sys/rt/simple_args.smp
index f2890c1c..8bfcc1a7 100644
--- a/chapter31/src/main/smp/sys/rt/simple_args.smp
+++ b/chapter31/src/main/smp/sys/rt/simple_args.smp
@@ -11,7 +11,7 @@ val simple_args = { i64 argc, i64 argv ->
// Zero-filled reference arrays require nullable elements. Every slot is
// filled before returning; the native entry bridge publishes u8[~][].
val args = new u8[~]?[argc];
- for( i64 i=0; i<argc; i++ ) {
+ for( i64 i = 0; i < argc; i++ ) {
i64 src = simple_argv(argv,i);
i64 len = strlen(src);
if( len < 0 || len > _MAX_U32 ) return null;
diff --git a/chapter31/src/main/smp/sys/text.smp b/chapter31/src/main/smp/sys/text.smp
index a28edf6d..77dc2190 100644
--- a/chapter31/src/main/smp/sys/text.smp
+++ b/chapter31/src/main/smp/sys/text.smp
@@ -5,78 +5,75 @@
val begin = { -> new aryu8(); };
val end = { aryu8 b ->
- val bytes = new u8[b.len];
- ary.copy(bytes,0,b.buf,0,b.len);
- u8[~] result = bytes;
- result;
+ new u8[~b.len]{ i64 i -> b.buf[i]; };
};
val _pad = { !aryu8 b, i64 n, u8 c ->
- for( i64 i=0; i<n; i++ ) b.add(c);
+ for( i64 i = 0; i < n; i++ ) b.add(c);
b;
};
val string = { !aryu8 b, u8[~] s, i64 spec, i64 width, i64 precision ->
- i64 len=s#;
- if( precision>=0 && precision<len ) len=precision;
- i64 pad=width-len;
+ i64 len = s#;
+ if( precision >= 0 && precision < len ) len = precision;
+ i64 pad = width-len;
if( !(spec&256) ) _pad(b,pad,' ');
- for( i64 i=0; i<len; i++ ) b.add(s[i]);
+ for( i64 i = 0; i < len; i++ ) b.add(s[i]);
if( spec&256 ) _pad(b,pad,' ');
b;
};
val integer = { !aryu8 b, i64 value, i64 spec, i64 width, i64 precision ->
- i64 kind=spec&255;
- if( kind=='b' ) return string(b,value ? "true" : "false",spec,width,-1);
- if( kind=='c' ) {
+ i64 kind = spec&255;
+ if( kind == 'b' ) return string(b,value ? "true" : "false",spec,width,-1);
+ if( kind == 'c' ) {
if( !(spec&256) ) _pad(b,width-1,' ');
- u8 c=value;
+ u8 c = value;
b.add(c);
if( spec&256 ) _pad(b,width-1,' ');
return b;
}
- bool signed=kind==0 || kind=='d' || kind=='i';
- i64 base=kind=='o' ? 8 : (kind=='x' || kind=='X' ? 16 : 10);
- u8[~] alphabet=kind=='X' ? "0123456789ABCDEF" : "0123456789abcdef";
- val digits=new u8[22]; // Maximum: 22 octal digits for a 64-bit integer.
- i64 count=0, n=value;
+ bool signed = kind == 0 || kind == 'd' || kind == 'i';
+ i64 base = kind == 'o' ? 8 : (kind == 'x' || kind == 'X' ? 16 : 10);
+ u8[~] alphabet = kind == 'X' ? "0123456789ABCDEF" : "0123456789abcdef";
+ val digits = new u8[22]; // Maximum: 22 octal digits for a 64-bit integer.
+ i64 count = 0, n = value;
// Signed decimal stays nonpositive, including the minimum i64.
- if( signed && n>0 ) n=-n;
- if( n==0 && precision!=0 ) digits[count++]='0';
- while( n!=0 ) {
- i64 q=0, r=0;
- if( signed ) { q=n/base; r=q*base-n; }
+ if( signed && n > 0 ) n = -n;
+ if( n == 0 && precision != 0 ) digits[count++] = '0';
+ while( n != 0 ) {
+ i64 q = 0, r = 0;
+ if( signed ) { q = n/base; r = -(n%base); }
else {
// Unsigned division without a u64 type. Halving first makes
// the dividend nonnegative; the remainder needs at most one fix.
- q=((n>>>1)/base)*2;
- r=n-q*base;
- if( r>=base ) { q++; r-=base; }
+ q = ((n>>>1)/base)*2;
+ r = n-q*base;
+ if( r >= base ) { q++; r -= base; }
}
- digits[count++]=alphabet[r];
- n=q;
+ digits[count++] = alphabet[r];
+ n = q;
}
- u8[~] !prefix="";
+ u8[~] !prefix = "";
if( signed ) {
- if( value<0 ) prefix="-";
- else if( spec&512 ) prefix="+";
- else if( spec&1024 ) prefix=" ";
- } else if( (spec&2048) && value!=0 ) {
- if( kind=='x' ) prefix="0x";
- if( kind=='X' ) prefix="0X";
+ if( value < 0 ) prefix = "-";
+ else if( spec&512 ) prefix = "+";
+ else if( spec&1024 ) prefix = " ";
+ } else if( (spec&2048) && value != 0 ) {
+ if( kind == 'x' ) prefix = "0x";
+ if( kind == 'X' ) prefix = "0X";
}
- i64 zeros=precision>count ? precision-count : 0;
+ i64 zeros = precision > count ? precision-count : 0;
// Alternate octal always begins with a zero, including precision-zero 0.
- if( kind=='o' && (spec&2048) && zeros==0 && (count==0 || digits[count-1]!='0') ) zeros=1;
- i64 pad=width-prefix#-zeros-count;
- bool left=(spec&256)!=0;
- bool zero=(spec&4096)!=0 && precision<0 && !left;
+ if( kind == 'o' && (spec&2048) && zeros == 0 && (count == 0 || digits[count-1] != '0') ) zeros = 1;
+ i64 pad = width-prefix#-zeros-count;
+ bool left = (spec&256) != 0;
+ bool zero = (spec&4096) != 0 && precision < 0 && !left;
if( !left && !zero ) _pad(b,pad,' ');
b.addAry(prefix);
if( zero ) _pad(b,pad,'0');
_pad(b,zeros,'0');
- while( count>0 ) b.add(digits[--count]);
+ while( count > 0 ) b.add(digits[--count]);
if( left ) _pad(b,pad,' ');
b;
};
diff --git a/chapter31/src/main/smp/sys/time.smp b/chapter31/src/main/smp/sys/time.smp
index 1706990e..27378ffe 100644
--- a/chapter31/src/main/smp/sys/time.smp
+++ b/chapter31/src/main/smp/sys/time.smp
@@ -1,4 +1,5 @@
// Time utilities; get the current time (both nanos and millis), sleep, time zones.
+// API, formatting, and timer reference: time/README.md.
// Instants: bare i64 UTC Unix-epoch milliseconds. Durations: i64 milliseconds.
// Monotonic readings are a separate clock domain, for deadlines/elapsed time.
@@ -24,7 +25,7 @@ i64 MIN = -_DAYS_BEFORE_EPOCH*DAY; // 0001-01-01T00:00:00.000Z
i64 MAX = (_DAYS_BEFORE_YEAR_10000-_DAYS_BEFORE_EPOCH)*DAY-1; // 9999-12-31T23:59:59.999Z
// Access to the underlying LIBC functions
-int ISO=0, CLOCK12=1, CLOCK24=2, ELAPSED=3, DATE=4, CLOCK24_SECONDS=5;
+int ISO = 0, CLOCK12 = 1, CLOCK24 = 2, ELAPSED = 3, DATE = 4, CLOCK24_SECONDS = 5;
{ i64 } simple_time_now = "C";
{ i64 } simple_time_mono = "C";
{ i64 } simple_time_nano = "C";
@@ -40,7 +41,7 @@ val sleepUntil = { i64 deadline_ms -> simple_time_sleep(deadline_ms,1); };
// Signed duration conversions. Overflow returns -1; reverse conversions truncate
// toward zero. An exact duration day is 24 hours, independent of DST.
val _scale = { i64 n, i64 unit ->
- if( n>sys.integer.MAX_I64/unit || n<sys.integer.MIN_I64/unit ) return -1;
+ if( n > sys.integer.MAX_I64/unit || n < sys.integer.MIN_I64/unit ) return -1;
return n*unit;
};
val seconds = { i64 n -> _scale(n,SECOND); };
@@ -56,31 +57,30 @@ val toNanos = { i64 ms -> _scale(ms,NANOS_PER_MS); };
// Clamp to zero once due, and saturate for widely separated i64 readings.
val remaining = { i64 deadline_ms, i64 current_ms ->
- if( deadline_ms<=current_ms ) return 0;
- if( current_ms<0 && deadline_ms>sys.integer.MAX_I64+current_ms ) return sys.integer.MAX_I64;
+ if( deadline_ms <= current_ms ) return 0;
+ if( current_ms < 0 && deadline_ms > sys.integer.MAX_I64+current_ms ) return sys.integer.MAX_I64;
return deadline_ms-current_ms;
};
-val _mod = { i64 n, i64 unit -> n-n/unit*unit; };
-val leap = { int year -> _mod(year,4)==0 && (_mod(year,100)!=0 || _mod(year,400)==0); };
+val leap = { int year -> year%4 == 0 && (year%100 != 0 || year%400 == 0); };
val monthDays = { int year, int month ->
- if( month<1 || month>12 ) return 0;
- return month==2 ? (leap(year) ? 29 : 28) :
- month==4 || month==6 || month==9 || month==11 ? 30 : 31;
+ if( month < 1 || month > 12 ) return 0;
+ return month == 2 ? (leap(year) ? 29 : 28) :
+ month == 4 || month == 6 || month == 9 || month == 11 ? 30 : 31;
};
// Gregorian civil dates, expressed using 400-year eras; no per-year loops.
val _days = { i64 year, i64 month, i64 day ->
- year -= month<=2 ? 1 : 0;
- i64 era=year/400, y=year-era*400;
- i64 mp=month+(month>2 ? -3 : 9);
+ year -= month <= 2 ? 1 : 0;
+ i64 era = year/400, y = year%400;
+ i64 mp = month+(month > 2 ? -3 : 9);
return era*_DAYS_PER_ERA+y*365+y/4-y/100+(153*mp+2)/5+day-1-_MARCH_EPOCH_DAYS;
};
val valid = { int year, int month, int day, int hour, int minute, int second, int millisecond ->
- return year>=1 && year<=9999 && month>=1 && month<=12 && day>=1 && day<=monthDays(year,month) &&
- hour>=0 && hour<=23 && minute>=0 && minute<=59 && second>=0 && second<=59 &&
- millisecond>=0 && millisecond<=999;
+ return year >= 1 && year <= 9999 && month >= 1 && month <= 12 && day >= 1 && day <= monthDays(year,month) &&
+ hour >= 0 && hour <= 23 && minute >= 0 && minute <= 59 && second >= 0 && second <= 59 &&
+ millisecond >= 0 && millisecond <= 999;
};
val makeUTC = { int year, int month, int day, int hour, int minute, int second, int millisecond ->
@@ -89,41 +89,41 @@ val makeUTC = { int year, int month, int day, int hour, int minute, int second,
};
val utc = { i64 instant ->
- val d=DateTime.empty();
- if( instant<MIN || instant>MAX ) return d;
- i64 day=instant/DAY, rest=_mod(instant,DAY);
- if( rest<0 ) { rest+=DAY; day--; }
- i64 z=day+_MARCH_EPOCH_DAYS, era=z/_DAYS_PER_ERA, doe=z-era*_DAYS_PER_ERA;
- i64 y=(doe-doe/(_DAYS_PER_4_YEARS-1)+doe/_DAYS_PER_CENTURY-doe/(_DAYS_PER_ERA-1))/365;
- i64 doy=doe-(365*y+y/4-y/100), mp=(5*doy+2)/153;
- d.day=doy-(153*mp+2)/5+1;
- d.month=mp+(mp<10 ? 3 : -9);
- d.year=y+era*400+(d.month<=2 ? 1 : 0);
- d.hour=rest/HOUR; d.minute=_mod(rest/MINUTE,60);
- d.second=_mod(rest/SECOND,60); d.millisecond=_mod(rest,SECOND);
- d.weekday=_mod(day+4,7);
- if( d.weekday<0 ) d.weekday+=7;
+ val d = DateTime.empty();
+ if( instant < MIN || instant > MAX ) return d;
+ i64 day = instant/DAY, rest = instant%DAY;
+ if( rest < 0 ) { rest += DAY; day--; }
+ i64 z = day+_MARCH_EPOCH_DAYS, era = z/_DAYS_PER_ERA, doe = z%_DAYS_PER_ERA;
+ i64 y = (doe-doe/(_DAYS_PER_4_YEARS-1)+doe/_DAYS_PER_CENTURY-doe/(_DAYS_PER_ERA-1))/365;
+ i64 doy = doe-(365*y+y/4-y/100), mp = (5*doy+2)/153;
+ d.day = doy-(153*mp+2)/5+1;
+ d.month = mp+(mp < 10 ? 3 : -9);
+ d.year = y+era*400+(d.month <= 2 ? 1 : 0);
+ d.hour = rest/HOUR; d.minute = rest/MINUTE%60;
+ d.second = rest/SECOND%60; d.millisecond = rest%SECOND;
+ d.weekday = (day+4)%7;
+ if( d.weekday < 0 ) d.weekday += 7;
return d;
};
val local = { i64 instant ->
- val d=DateTime.empty();
- val f=new i64[10];
- i64 ptr=f;
- if( simple_time_local(instant,ptr)!=0 ) return d;
- d.year=f[0]; d.month=f[1]; d.day=f[2];
- d.hour=f[3]; d.minute=f[4]; d.second=f[5]; d.millisecond=f[6];
- d.weekday=f[7]; d.offsetSeconds=f[8]; d.daylight=f[9]!=0;
+ val d = DateTime.empty();
+ val f = new i64[10];
+ i64 ptr = f;
+ if( simple_time_local(instant,ptr) != 0 ) return d;
+ d.year = f[0]; d.month = f[1]; d.day = f[2];
+ d.hour = f[3]; d.minute = f[4]; d.second = f[5]; d.millisecond = f[6];
+ d.weekday = f[7]; d.offsetSeconds = f[8]; d.daylight = f[9] != 0;
return d;
};
val zoneName = { i64 instant ->
- val bytes=new u8[128];
- i64 ptr=bytes;
- int n=simple_time_zone(instant,ptr,bytes#);
- if( n<0 ) return "";
- val b=new aryu8();
- for( int i=0; i<n; i++ ) b.add(bytes[i]);
+ val bytes = new u8[128];
+ i64 ptr = bytes;
+ int n = simple_time_zone(instant,ptr,bytes#);
+ if( n < 0 ) return "";
+ val b = new aryu8();
+ for( int i = 0; i < n; i++ ) b.add(bytes[i]);
return text.end(b);
};
@@ -133,28 +133,28 @@ val _digits = { !aryu8 b, i64 n, int width ->
val _format = { i64 instant, int style, bool localZone ->
val d = localZone ? local(instant) : utc(instant);
- if( d.year==0 || style<0 || style>5 || style==3 ) return "<invalid time>";
+ if( d.year == 0 || style < 0 || style > 5 || style == 3 ) return "<invalid time>";
val b = new aryu8();
- if( style==4 ) {
- _digits(b,d.day,2).add('/'); _digits(b,d.month,2).add('/'); _digits(b,_mod(d.year,100),2);
+ if( style == 4 ) {
+ _digits(b,d.day,2).add('/'); _digits(b,d.month,2).add('/'); _digits(b,d.year%100,2);
} else {
- if( style==0 ) {
+ if( style == 0 ) {
_digits(b,d.year,4).add('-'); _digits(b,d.month,2).add('-'); _digits(b,d.day,2).add('T');
}
- int hour=d.hour;
- if( style==1 ) { hour=_mod(hour,12); if( hour==0 ) hour=12; }
- _digits(b,hour,style==1 ? 1 : 2).add(':'); _digits(b,d.minute,2);
- if( style==0 || style==5 ) { b.add(':'); _digits(b,d.second,2); }
- if( style==1 ) b.addAry(d.hour<12 ? "am" : "pm");
- if( style==0 ) {
+ int hour = d.hour;
+ if( style == 1 ) { hour = hour%12; if( hour == 0 ) hour = 12; }
+ _digits(b,hour,style == 1 ? 1 : 2).add(':'); _digits(b,d.minute,2);
+ if( style == 0 || style == 5 ) { b.add(':'); _digits(b,d.second,2); }
+ if( style == 1 ) b.addAry(d.hour < 12 ? "am" : "pm");
+ if( style == 0 ) {
b.add('.'); _digits(b,d.millisecond,3);
- if( d.offsetSeconds==0 ) b.add('Z');
+ if( d.offsetSeconds == 0 ) b.add('Z');
else {
- i64 offset=d.offsetSeconds;
- b.add(offset<0 ? '-' : '+');
- if( offset<0 ) offset=-offset;
- _digits(b,offset/3600,2).add(':'); _digits(b,_mod(offset/60,60),2);
- if( _mod(offset,60)!=0 ) { b.add(':'); _digits(b,_mod(offset,60),2); }
+ i64 offset = d.offsetSeconds;
+ b.add(offset < 0 ? '-' : '+');
+ if( offset < 0 ) offset = -offset;
+ _digits(b,offset/3600,2).add(':'); _digits(b,offset/60%60,2);
+ if( offset%60 != 0 ) { b.add(':'); _digits(b,offset%60,2); }
}
}
}
@@ -162,58 +162,58 @@ val _format = { i64 instant, int style, bool localZone ->
};
val elapsed = { i64 ms ->
- val b=new aryu8();
+ val b = new aryu8();
// Nonpositive arithmetic handles the minimum i64 without negating it.
- if( ms<0 ) b.add('-'); else ms=-ms;
+ if( ms < 0 ) b.add('-'); else ms = -ms;
_digits(b,-(ms/MINUTE),2).add(':');
- _digits(b,-_mod(ms/SECOND,60),2).add('.'); _digits(b,-_mod(ms,SECOND),3);
+ _digits(b,-(ms/SECOND%60),2).add('.'); _digits(b,-(ms%SECOND),3);
return text.end(b);
};
val format = { i64 instant, int style ->
- if( style==ELAPSED ) return elapsed(instant);
+ if( style == ELAPSED ) return elapsed(instant);
return _format(instant,style,false);
};
val formatLocal = { i64 instant, int style ->
- if( style==ELAPSED ) return elapsed(instant);
+ if( style == ELAPSED ) return elapsed(instant);
return _format(instant,style,true);
};
val _number = { u8[~] s, i64 at, int count ->
- if( at<0 || count<1 || at+count>s# ) return -1;
- int n=0;
- for( int i=0; i<count; i++ ) {
- int c=s[at+i];
- if( c<'0' || c>'9' ) return -1;
- n=n*10+c-'0';
+ if( at < 0 || count < 1 || at+count > s# ) return -1;
+ int n = 0;
+ for( int i = 0; i < count; i++ ) {
+ int c = s[at+i];
+ if( c < '0' || c > '9' ) return -1;
+ n = n*10+c-'0';
}
return n;
};
// Keep suffix validation separate from calendar construction.
val _parseZone = { u8[~] s, int at, i64 instant ->
- if( at<0 || at>=s# ) return -1;
- i64 offset=0;
- if( s[at]=='Z' ) { if( at+1!=s# ) return -1; }
+ if( at < 0 || at >= s# ) return -1;
+ i64 offset = 0;
+ if( s[at] == 'Z' ) { if( at+1 != s# ) return -1; }
else {
- int sign=s[at]=='+' ? 1 : s[at]=='-' ? -1 : 0;
- if( !sign || (s#!=at+6 && s#!=at+9) || s[at+3]!=':' ) return -1;
- int oh=_number(s,at+1,2), om=_number(s,at+4,2), os=0;
- if( s#==at+9 ) { if( s[at+6]!=':' ) return -1; os=_number(s,at+7,2); }
- if( oh<0 || oh>23 || om<0 || om>59 || os<0 || os>59 ) return -1;
- offset=sign*(oh*HOUR+om*MINUTE+os*SECOND);
+ int sign = s[at] == '+' ? 1 : s[at] == '-' ? -1 : 0;
+ if( !sign || (s# != at+6 && s# != at+9) || s[at+3] != ':' ) return -1;
+ int oh = _number(s,at+1,2), om = _number(s,at+4,2), os = 0;
+ if( s# == at+9 ) { if( s[at+6] != ':' ) return -1; os = _number(s,at+7,2); }
+ if( oh < 0 || oh > 23 || om < 0 || om > 59 || os < 0 || os > 59 ) return -1;
+ offset = sign*(oh*HOUR+om*MINUTE+os*SECOND);
}
- instant-=offset;
- return instant<MIN || instant>MAX ? -1 : instant;
+ instant -= offset;
+ return instant < MIN || instant > MAX ? -1 : instant;
};
// Strict ISO absolute instants only. -1 is reserved for failure (and therefore
// cannot distinguish the valid instant one millisecond before Unix epoch).
val parse = { u8[~] s ->
- if( s#<20 || s[4]!='-' || s[7]!='-' || s[10]!='T' || s[13]!=':' || s[16]!=':' ) return -1;
- int y=_number(s, 0,4), m =_number(s, 5,2), d =_number(s, 8,2);
- int h=_number(s,11,2), min=_number(s,14,2), sec=_number(s,17,2);
- bool fraction=s[19]=='.';
- int ms=fraction ? _number(s,20,3) : 0;
+ if( s# < 20 || s[4] != '-' || s[7] != '-' || s[10] != 'T' || s[13] != ':' || s[16] != ':' ) return -1;
+ int y = _number(s, 0,4), m = _number(s, 5,2), d = _number(s, 8,2);
+ int h = _number(s,11,2), min = _number(s,14,2), sec = _number(s,17,2);
+ bool fraction = s[19] == '.';
+ int ms = fraction ? _number(s,20,3) : 0;
if( !valid(y,m,d,h,min,sec,ms) ) return -1;
return _parseZone(s,fraction ? 23 : 19,makeUTC(y,m,d,h,min,sec,ms));
};
diff --git a/chapter31/src/main/smp/sys/time/README.md b/chapter31/src/main/smp/sys/time/README.md
new file mode 100644
index 00000000..baa920cb
--- /dev/null
+++ b/chapter31/src/main/smp/sys/time/README.md
@@ -0,0 +1,133 @@
+# Time and single-threaded animation
+
+[Chapter 31](../../../../../README.md#time-library) introduces the library.
+The implementation is in [time.smp](../time.smp), [DateTime.smp](DateTime.smp),
+and [Timers.smp](Timers.smp).
+
+`sys.time` uses bare `i64` values: absolute instants are milliseconds since
+the Unix epoch in UTC; durations are milliseconds. Monotonic readings belong
+to a separate clock domain. Never subtract a wall-clock reading from a
+monotonic deadline.
+
+## Clocks and waits
+
+| Call | Result |
+| --- | --- |
+| `time.now()` | Unix-epoch milliseconds; may jump when the system clock changes. |
+| `time.monotonic()` | Monotonic milliseconds for elapsed time and deadlines. |
+| `time.nanoTime()` | Monotonic nanoseconds, with the clock's available resolution. |
+| `time.sleep(duration_ms)` | Sleep for a nonnegative duration. |
+| `time.sleepUntil(deadline_ms)` | Wait for a monotonic millisecond deadline; returns immediately if past. |
+| `time.remaining(deadline_ms, current_ms)` | Nonnegative difference, saturating on overflow. |
+
+Clock errors return `-1`; sleeps return zero on success or `-1` on error,
+with `sys.libc.errno()` available. Interrupted sleeps resume rather than
+returning early. Wakeup times are approximate, and these calls do not wake a
+suspended laptop. Sleeping blocks the one Simple execution thread; use
+`gfx.wait` when window input must remain responsive.
+
+`seconds(n)`, `minutes(n)`, `hours(n)`, and `days(n)` convert signed counts
+to milliseconds. `toSeconds(ms)`, `toMinutes(ms)`, `toHours(ms)`, and
+`toDays(ms)` truncate toward zero. A duration day is exactly 24 hours,
+independent of daylight saving. `toNanos(ms)` and `fromNanos(ns)` convert
+between millisecond and nanosecond units. Multiplication overflow returns
+`-1`. Constants `SECOND`, `MINUTE`, `HOUR`, and `DAY` are also available,
+defined as `1000`, `60*SECOND`, `60*MINUTE`, and `24*HOUR` respectively.
+`NANOS_PER_MS` is `1000*1000`. Overflow checks use the shared
+`sys.integer.MIN_I64` and `MAX_I64` bounds; `MAX_I32` and `MAX_U32` in that
+module also describe the library's array and timer-ID limits.
+
+## String interpolation
+
+Time formatting is built into the existing string interpolation syntax:
+
+| Format | Example | Named style |
+| --- | --- | --- |
+| `%t(instant)` or `%tF(instant)` | `2026-11-12T00:34:05.123Z` | `time.ISO` |
+| `%tr(instant)` | `12:34am` | `time.CLOCK12` |
+| `%tR(instant)` | `00:34` | `time.CLOCK24` |
+| `%tT(instant)` | `00:34:05` | `time.CLOCK24_SECONDS` |
+| `%tD(instant)` | `12/11/26` | `time.DATE` |
+| `%tM(duration)` | `02:03.456` | `time.ELAPSED` |
+
+For example, `"UTC %tR(sys.time.now())"`. Width and left alignment work as
+for strings: `%30t(instant)` and `%-30t(instant)`. Precision and numeric flags
+are rejected. `%tM` formats a duration, with total minutes rather than wrapping
+at an hour; negative durations keep their sign.
+
+Interpolation uses UTC, making its output stable across machines.
+`time.format(instant, style)` is the equivalent library call;
+`time.formatLocal(instant, style)` uses the system's local zone. Local ISO
+output includes a numeric offset instead of `Z` when nonzero, retaining
+offset seconds for historical zones. Invalid calendar values/styles produce
+`<invalid time>`. The ISO form retains all millisecond bits within the supported
+calendar range; short formats intentionally omit information.
+
+## Calendar values and absolute parsing
+
+`time.utc(instant)` and `time.local(instant)` return a `DateTime` with fields
+`year`, `month`, `day`, `hour`, `minute`, `second`, `millisecond`, `weekday`
+(Sunday = 0), `offsetSeconds` (east of UTC), and `daylight`. A zero year means
+conversion failed. `time.zoneName(instant)` returns the local abbreviation or
+an empty string on error. Local conversion uses the operating system's zone
+rules, including DST at that instant; no time-zone database is downloaded.
+
+`time.makeUTC(year, month, day, hour, minute, second, millisecond)` validates
+and constructs an instant, returning `-1` on invalid fields. `time.valid(...)`,
+`time.leap(year)`, and `time.monthDays(year, month)` support calendar checks.
+Calendar conversion supports Gregorian years 1 through 9999, bounded by
+`time.MIN` and `time.MAX`, and rejects leap seconds.
+
+`time.parse(text)` accepts strict absolute ISO text:
+`YYYY-MM-DDTHH:mm:ss[.SSS]Z` or the same with an explicit `+HH:MM`/`-HH:MM`
+offset (optionally with `:SS`). Fractions have exactly three digits. No relative
+time parsing, implicit local zone, locale-dependent parsing, or named-zone
+conversion is provided. Offsets must have hours 00–23 and minutes/seconds 00–59.
+Invalid text or an out-of-range result returns `-1`. By design, this sentinel
+is indistinguishable from the valid instant `1969-12-31T23:59:59.999Z`;
+formatting and calendar conversion still support that instant.
+
+## Cooperative timers
+
+Create `val timers = new sys.time.Timers();` on the game thread:
+
+Timer IDs are `u32`, with `0` reserved for registration failure or no timer due.
+Deadlines, delays, and periods remain `i64` milliseconds; their parameter,
+field, and local names end in `_ms` to distinguish them from IDs.
+
+| Operation | Meaning |
+| --- | --- |
+| `after(delay_ms)` | Register a one-shot timer; return its positive `u32` ID, or `0`. |
+| `every(period_ms)` | Register a repeating timer; period must be positive. Returns a `u32` ID, or `0`. |
+| `afterAt(current_ms, delay_ms)`, `everyAt(current_ms, period_ms)` | Supply a monotonic reading explicitly, useful for deterministic tests. |
+| `cancel(id)` | Remove a timer; return whether it was present. |
+| `nextDeadline()` | Earliest monotonic deadline, or `-1` if empty. |
+| `poll(current_ms)` | Return the next due `u32` ID, or `0` if none. |
+
+Poll repeatedly to drain due timers. Deadlines order delivery, then registration
+ID breaks ties. Repeating timers advance from their previous deadline, skipping
+missed ticks to the first future deadline rather than drifting or replaying a
+backlog. Deadline overflow rejects registration or cancels a repeating timer.
+IDs are never reused within a collection; registration fails once all nonzero
+`u32` IDs have been issued.
+There are no callbacks or timer threads: the caller handles each returned ID.
+
+`gfx.wait(timeout_ms)` processes events after waiting for input or a timeout:
+zero polls, `-1` waits indefinitely, values below `-1` fail. It returns the same
+`OK`, `CLOSED`, or `ERROR` statuses as `gfx.poll`, and may wake early. Re-read the
+monotonic clock after each wake. This allows one thread to handle timers,
+input, simulation, and drawing without busy waiting.
+
+The [digital and analog clock example](../../../../../docs/examples/Clock.smp) combines these pieces. From
+the repository root, with graphics dependencies already cached:
+
+```sh
+make -C chapter31 clock-example # Build without opening a window.
+make -C chapter31 run-clock # Build the backend and run.
+```
+
+Click the button or press Space to switch between green seven-segment digits
+and an analog dial with smoothly moving hands. Both display system-local time;
+Q/Escape exits. Passing any argument directly to the executable closes it after
+ten frames, switching faces halfway through. Hands are computed from the current
+time, so delayed frames do not create a simulation catch-up backlog.
diff --git a/chapter31/src/main/smp/sys/time/Timers.smp b/chapter31/src/main/smp/sys/time/Timers.smp
index eca32d15..7cca2e9c 100644
--- a/chapter31/src/main/smp/sys/time/Timers.smp
+++ b/chapter31/src/main/smp/sys/time/Timers.smp
@@ -14,37 +14,37 @@ struct Timers {
// Add a new timer
{ i64 i64 i64 -> u32 } _add = { i64 current_ms, i64 delay_ms, i64 period_ms ->
- if( current_ms<0 || delay_ms<0 || current_ms>sys.integer.MAX_I64-delay_ms || _next==0 ) return 0;
+ if( current_ms < 0 || delay_ms < 0 || current_ms > sys.integer.MAX_I64-delay_ms || _next == 0 ) return 0;
// Ugly linear scan for an available slot
- int slot=0;
- while( slot<_ids# && _ids[slot]!=0 ) slot++;
+ int slot = 0;
+ while( slot < _ids# && _ids[slot] != 0 ) slot++;
// Double size for lots of timers
- if( slot==_ids# ) {
- if( _ids#>sys.integer.MAX_I32/2 ) return 0;
+ if( slot == _ids# ) {
+ if( _ids# > sys.integer.MAX_I32/2 ) return 0;
val ids = new u32[_ids#*2];
val due_ms = new i64[_ids#*2], periods_ms = new i64[_ids#*2];
- for( int i=0; i<_ids#; i++ ) { ids[i]=_ids[i]; due_ms[i]=_due_ms[i]; periods_ms[i]=_period_ms[i]; }
- _ids=ids; _due_ms=due_ms; _period_ms=periods_ms;
+ for( int i = 0; i < _ids#; i++ ) { ids[i] = _ids[i]; due_ms[i] = _due_ms[i]; periods_ms[i] = _period_ms[i]; }
+ _ids = ids; _due_ms = due_ms; _period_ms = periods_ms;
// Retry against the newly published arrays after growing.
return _add(current_ms,delay_ms,period_ms);
}
// Next available timer id
u32 id = _next;
- _next = id==sys.integer.MAX_U32 ? 0 : id+1;
- _ids[slot]=id; _due_ms[slot]=current_ms+delay_ms; _period_ms[slot]=period_ms;
+ _next = id == sys.integer.MAX_U32 ? 0 : id+1;
+ _ids[slot] = id; _due_ms[slot] = current_ms+delay_ms; _period_ms[slot] = period_ms;
return id;
};
// Explicit-clock versions make game logic and tests deterministic.
{ i64 i64 -> u32 } afterAt = { i64 current_ms, i64 delay_ms -> _add(current_ms,delay_ms,0); };
- { i64 i64 -> u32 } everyAt = { i64 current_ms, i64 period_ms -> period_ms<=0 ? 0 : _add(current_ms,period_ms,period_ms); };
+ { i64 i64 -> u32 } everyAt = { i64 current_ms, i64 period_ms -> period_ms <= 0 ? 0 : _add(current_ms,period_ms,period_ms); };
{ i64 -> u32 } after = { i64 delay_ms -> afterAt(time.monotonic(),delay_ms ); };
{ i64 -> u32 } every = { i64 period_ms -> everyAt(time.monotonic(),period_ms); };
// Remove a timer
val cancel = { u32 id ->
- if( id==0 ) return false;
- for( int i=0; i<_ids#; i++ ) if( _ids[i]==id ) { _ids[i]=0; return true; }
+ if( id == 0 ) return false;
+ for( int i = 0; i < _ids#; i++ ) if( _ids[i] == id ) { _ids[i] = 0; return true; }
return false;
};
@@ -52,8 +52,8 @@ struct Timers {
val nextDeadline = { ->
i64 next_ms = -1;
// Ugly linear scan again, but short
- for( int i=0; i<_ids#; i++ )
- if( _ids[i]!=0 && (next_ms<0 || _due_ms[i] < next_ms) ) next_ms = _due_ms[i];
+ for( int i = 0; i < _ids#; i++ )
+ if( _ids[i] != 0 && (next_ms < 0 || _due_ms[i] < next_ms) ) next_ms = _due_ms[i];
return next_ms;
};
@@ -63,16 +63,16 @@ struct Timers {
// Repeats skip missed ticks and retain their phase, avoiding bursts/drift.
{ i64 -> u32 } poll = { i64 current_ms ->
int slot = -1;
- for( int i=0; i<_ids#; i++ )
- if( _ids[i]!=0 && _due_ms[i]<=current_ms && (slot<0 || _due_ms[i]<_due_ms[slot] ||
- (_due_ms[i]==_due_ms[slot] && _ids[i]<_ids[slot])) ) slot=i;
- if( slot<0 ) return 0;
+ for( int i = 0; i < _ids#; i++ )
+ if( _ids[i] != 0 && _due_ms[i] <= current_ms && (slot < 0 || _due_ms[i] < _due_ms[slot] ||
+ (_due_ms[i] == _due_ms[slot] && _ids[i] < _ids[slot])) ) slot = i;
+ if( slot < 0 ) return 0;
u32 id = _ids[slot];
i64 period_ms = _period_ms[slot];
- if( period_ms==0 ) _ids[slot]=0;
+ if( period_ms == 0 ) _ids[slot] = 0;
else {
i64 steps = (current_ms-_due_ms[slot])/period_ms;
- if( steps>=(sys.integer.MAX_I64-_due_ms[slot])/period_ms ) _ids[slot]=0;
+ if( steps >= (sys.integer.MAX_I64-_due_ms[slot])/period_ms ) _ids[slot] = 0;
else _due_ms[slot] += (steps+1)*period_ms;
}
return id;