summaryrefslogtreecommitdiff
path: root/chapter31/src/test
diff options
context:
space:
mode:
authorCliff Click <cliffc@acm.org>2026-11-15 11:20:40 -0800
committerCliff Click <cliffc@acm.org>2026-11-15 11:20:40 -0800
commitf0a6c6757a795b8e186de0076836a87acef59fa7 (patch)
treeef45c1b58093420bbd2de6647274139e46539bfe /chapter31/src/test
parent7e66b7ae6b00a2e1652db32f01f0bf480508ef05 (diff)
downloadSimple-f0a6c6757a795b8e186de0076836a87acef59fa7.tar.gz
Simple-f0a6c6757a795b8e186de0076836a87acef59fa7.zip
Graphics now allow resizemain
Reorganize docs. Fix bugs X86 LOad+cmp scheduling. Math intrinsics
Diffstat (limited to 'chapter31/src/test')
-rw-r--r--chapter31/src/test/java/com/seaofnodes/simple/ArithNodeTest.java1
-rw-r--r--chapter31/src/test/java/com/seaofnodes/simple/BreakoutTest.java2
-rw-r--r--chapter31/src/test/java/com/seaofnodes/simple/DrawTest.java61
-rw-r--r--chapter31/src/test/java/com/seaofnodes/simple/Eval2.java3
-rw-r--r--chapter31/src/test/java/com/seaofnodes/simple/GraphicsTest.java58
-rw-r--r--chapter31/src/test/java/com/seaofnodes/simple/MathTest.java79
-rw-r--r--chapter31/src/test/java/com/seaofnodes/simple/ModTest.java201
-rw-r--r--chapter31/src/test/java/com/seaofnodes/simple/SchedulingTest.java47
-rw-r--r--chapter31/src/test/java/com/seaofnodes/simple/StreamIOTest.java2
-rw-r--r--chapter31/src/test/java/com/seaofnodes/simple/StringFormatTest.java5
-rw-r--r--chapter31/src/test/java/com/seaofnodes/simple/TestC.java2
11 files changed, 436 insertions, 25 deletions
diff --git a/chapter31/src/test/java/com/seaofnodes/simple/ArithNodeTest.java b/chapter31/src/test/java/com/seaofnodes/simple/ArithNodeTest.java
index b29c9706..2299bd17 100644
--- a/chapter31/src/test/java/com/seaofnodes/simple/ArithNodeTest.java
+++ b/chapter31/src/test/java/com/seaofnodes/simple/ArithNodeTest.java
@@ -85,6 +85,7 @@ public class ArithNodeTest {
ops.add(new SubNode(lhs,rhs,mode));
ops.add(new MulNode(lhs,rhs,mode));
ops.add(new DivNode(lhs,rhs,mode));
+ ops.add(new ModNode(lhs,rhs,mode));
}
ops.add(new AndNode(null,lhs,rhs));
ops.add(new OrNode(null,lhs,rhs));
diff --git a/chapter31/src/test/java/com/seaofnodes/simple/BreakoutTest.java b/chapter31/src/test/java/com/seaofnodes/simple/BreakoutTest.java
index 7f3e56d4..f374d397 100644
--- a/chapter31/src/test/java/com/seaofnodes/simple/BreakoutTest.java
+++ b/chapter31/src/test/java/com/seaofnodes/simple/BreakoutTest.java
@@ -191,7 +191,7 @@ public class BreakoutTest {
g._serve();
// Drive through every brick's front, bottom row first.
for( int i=COLS*ROWS-1; i>=0; i-- ) {
- g.x=LEFT+20.0+(i-i/COLS*COLS)*BRICK_DX;
+ g.x=LEFT+20.0+(i%COLS)*BRICK_DX;
g.y=BRICK_TOP+1.0+(i/COLS)*BRICK_DY+BRICK_H+RADIUS;
g.dx=0.0; g.dy=-1.0;
g._tick(0);
diff --git a/chapter31/src/test/java/com/seaofnodes/simple/DrawTest.java b/chapter31/src/test/java/com/seaofnodes/simple/DrawTest.java
index 1ca161cf..2af3b03e 100644
--- a/chapter31/src/test/java/com/seaofnodes/simple/DrawTest.java
+++ b/chapter31/src/test/java/com/seaofnodes/simple/DrawTest.java
@@ -3,19 +3,51 @@ package com.seaofnodes.simple;
import java.nio.file.Files;
import java.nio.file.Path;
import org.junit.Test;
-import com.seaofnodes.simple.codegen.CodeGen;
-import com.seaofnodes.simple.type.TypeInteger;
-import com.seaofnodes.simple.util.Ary;
-import static org.junit.Assert.*;
// Native raster and game checks; no backend or display is needed.
public class DrawTest {
+ @Test public void resizedLayoutAndInput() throws Exception {
+ String game=Files.readString(Path.of("docs/examples/TicTacToeGraphical.smp"))
+ .replace("val main =","val _windowMain =");
+ TestC.runSYS(game+"""
+ val main={ ->
+ val c=new sys.draw.Canvas(600,780);
+ val original=c.pixels;
+ val board=new u8[9]; _reset(board);
+ // Half size with horizontal margins: board remains square.
+ if( !c.resize(500,390) || c.scale!=0.5 || c.offsetX!=100 || c.offsetY!=0 ) return 1;
+ if( c.pixels!=original ) return 13;
+ _draw(c,board,4);
+ if( c.pixels[84*500+124]!=0x35535a || c.pixels[0]!=0x142e36 ) return 2;
+ if( _square(c.localX(250),c.localY(210))!=4 || c.localX(99)!=-1 ) return 3;
+ if( c.localX(400)!=-1 || c.localY(390)!=-1 ) return 4;
+ // Noninteger scale, taller aspect ratio, and scaled button hit box.
+ val b=new sys.draw.Button(48,168,168,168,"GO");
+ if( !c.resize(750,1100) || c.scale!=1.25 || c.offsetY!=62 ) return 5;
+ val grown=c.pixels;
+ if( b.update(c.localX(100),c.localY(300),true) ) return 6;
+ if( !b.update(c.localX(100),c.localY(300),false) ) return 7;
+ c.clear(0).fillCircle(300,400,40,9).text(48,34,"GO",3,7);
+ if( c.pixels[562*750+425]!=9 || c.pixels[612*750+375]!=9 ) return 8;
+ if( c.pixels[562*750+426]!=0 || c.pixels[613*750+375]!=0 ) return 9;
+ // Minimize and repeated sizes retain the last usable buffer.
+ if( c.resize(0,0) || c.resize(750,1100) || c.width!=750 ) return 10;
+ if( !c.resize(1,1) ) return 11;
+ _draw(c,board,4);
+ if( !c.resize(600,780) || c.scale!=1.0 || c.offsetX!=0 || c.offsetY!=0 ) return 12;
+ if( c.pixels!=grown ) return 14;
+ return 0;
+ };
+ ""","drawResize","",-1);
+ }
+
@Test public void nativeClockCoordinates() throws Exception {
String clock=Files.readString(Path.of("docs/examples/Clock.smp"))
.replace("val main =","val _windowMain =");
StringBuilder source=new StringBuilder(clock+"""
val _check_noInline={ f64 turn, int expectedX, int expectedY ->
- int x=360+_sin(turn)*128, y=232-_sin(turn+0.25)*128;
+ f64 angle=turn*2*sys.math.PI;
+ int x=360+sys.math.sin(angle)*128, y=232-sys.math.cos(angle)*128;
if( x<expectedX-1 || x>expectedX+1 || y<expectedY-1 || y>expectedY+1 ) {
sys.io.p("turn %f(turn): %(x),%(y) expected %(expectedX),%(expectedY)\\n");
return 1;
@@ -26,7 +58,7 @@ public class DrawTest {
""");
for(int i=0;i<=60;i++) {
double turn=i/60.0;
- int x=(int)(360+clockSine(turn)*128), y=(int)(232-clockSine(turn+0.25)*128);
+ int x=(int)(360+Math.sin(turn*2*Math.PI)*128), y=(int)(232-Math.cos(turn*2*Math.PI)*128);
source.append("if(_check_noInline(").append(turn).append(',').append(x).append(',').append(y)
.append(")!=0) return 1;");
}
@@ -34,14 +66,6 @@ public class DrawTest {
TestC.runSYS(source.toString(),"clockCoordinates","",-1);
}
- private static double clockSine(double turn) {
- turn-=(long)turn;
- boolean negative=turn>0.5;
- double x=(negative ? turn-0.5 : turn)*6.283185307179586;
- double product=x*(3.141592653589793-x);
- return (negative ? -16.0 : 16.0)*product/(49.34802200544679-4*product);
- }
-
@Test public void nativeAnalogSweep() throws Exception {
String clock=Files.readString(Path.of("docs/examples/Clock.smp"))
.replace("val main =","val _windowMain =");
@@ -69,7 +93,7 @@ public class DrawTest {
""");
for(int millis:new int[]{0,500,7500,15000,30000,45000,59500}) {
double turn=millis/60000.0;
- int x=(int)(360+clockSine(turn)*128), y=(int)(232-clockSine(turn+0.25)*128);
+ int x=(int)(360+Math.sin(turn*2*Math.PI)*128), y=(int)(232-Math.cos(turn*2*Math.PI)*128);
source.append("if(_renderCheck_noInline(").append(millis/1000).append(',').append(millis%1000)
.append(',').append(x).append(',').append(y).append(")!=0) return 1;");
}
@@ -103,7 +127,7 @@ public class DrawTest {
@Test public void clockFacesWithoutWindow() throws Exception {
String clock=Files.readString(Path.of("docs/examples/Clock.smp"))
.replace("val main =","val _windowMain =");
- CodeGen code=new CodeGen(null,null,new Ary<>(new String[]{TestC.RELEASE_SYS_DIR}),"ClockRaster",clock+"""
+ TestC.runSYS(clock+"""
val main={ ->
val c=new sys.draw.Canvas(720,540);
_digit(c,10,10,8);
@@ -114,12 +138,9 @@ public class DrawTest {
if( c.pixels[214*720+254]!=GREEN || c.pixels[262*720+470]!=GREEN ) return 3;
c.clear(BACKGROUND); _analog(c,3,0,0,0);
if( c.pixels[232*720+430]!=GREEN || c.pixels[160*720+360]!=0xc3ffcb || c.pixels[232*720+360]!=GREEN ) return 4;
- if( _sin(0.25)<0.999 || _sin(0.75)>-0.999 || _sin(1.0)!=0.0 ) return 5;
return 0;
};
- return main();
- """,126L,true,TypeInteger.BOT).driver(CodeGen.Phase.TypeCheck);
- assertEquals("0",Eval2.eval(code,0,3000000));
+ ""","clockRaster","",-1);
}
@Test public void rectanglesAndColors() throws Exception {
diff --git a/chapter31/src/test/java/com/seaofnodes/simple/Eval2.java b/chapter31/src/test/java/com/seaofnodes/simple/Eval2.java
index eef05f93..d6d97ef1 100644
--- a/chapter31/src/test/java/com/seaofnodes/simple/Eval2.java
+++ b/chapter31/src/test/java/com/seaofnodes/simple/Eval2.java
@@ -313,6 +313,9 @@ public abstract class Eval2 {
case DivNode div -> div.mode()==1
? (Object)(x(div.in(2))==0 ? 0L : x(div.in(1)) / x(div.in(2)))
: (Object)((d(div.in(2))==0 ? 0D : d(div.in(1))) / d(div.in(2)));
+ case ModNode mod -> mod.mode()==1
+ ? (Object)(x(mod.in(2))==0 ? 0L : x(mod.in(1)) % x(mod.in(2)))
+ : (Object)(d(mod.in(1)) % d(mod.in(2)));
case EscapeNode esc -> esc(esc);
case FunPtrNode fptr -> con(fptr._con);
case LoadNode ld -> load(ld);
diff --git a/chapter31/src/test/java/com/seaofnodes/simple/GraphicsTest.java b/chapter31/src/test/java/com/seaofnodes/simple/GraphicsTest.java
index 110a6a38..3b4b9e31 100644
--- a/chapter31/src/test/java/com/seaofnodes/simple/GraphicsTest.java
+++ b/chapter31/src/test/java/com/seaofnodes/simple/GraphicsTest.java
@@ -32,6 +32,7 @@ public class GraphicsTest {
private static String run(String exe, String backend, int exit, Path cwd) throws Exception {
ProcessBuilder pb = new ProcessBuilder(Path.of(exe).toAbsolutePath().toString()).redirectErrorStream(true);
+ pb.environment().put("SIMPLE_MINIAUDIO","off");
if (cwd!=null) pb.directory(cwd.toFile());
if( backend == null ) pb.environment().remove("SIMPLE_MINIFB");
else pb.environment().put("SIMPLE_MINIFB",backend);
@@ -68,9 +69,12 @@ public class GraphicsTest {
static int32_t poll_events(int32_t n) { return 0; }
static int32_t position(void) { return 0; }
static int32_t wait_events(int64_t n) { return 0; }
+ static uint32_t size(void) { return 0; }
+ static int32_t present_size(const uint32_t *p,uint32_t n,uint32_t w,uint32_t h) { return 0; }
static void close_window(void) {}
static const struct simple_graphics_api api={SIMPLE_GRAPHICS_VERSION,
- open_window,present,poll_events,position,position,poll_events,poll_events,close_window,wait_events};
+ open_window,present,poll_events,position,position,poll_events,poll_events,close_window,wait_events,
+ size,size,present_size};
const struct simple_graphics_api *simple_minifb_api(void) { return &api; }
""");
Path mock=root.resolve(name);
@@ -150,9 +154,15 @@ public class GraphicsTest {
(k=='R' && (frames==8 || frames==9));
}
static int32_t wait_events(int64_t ms) { usleep(ms*1000); return 0; }
+ static uint32_t width(void) { return 1008; }
+ static uint32_t height(void) { return 760; }
+ static int32_t present_size(const uint32_t *p,uint32_t n,uint32_t w,uint32_t h) {
+ return w==1008 && h==760 ? present(p,n) : -1;
+ }
static void close_window(void) {}
static const struct simple_graphics_api api={SIMPLE_GRAPHICS_VERSION,
- open_window,present,poll_events,mouse_x,mouse_y,poll_events,key,close_window,wait_events};
+ open_window,present,poll_events,mouse_x,mouse_y,poll_events,key,close_window,wait_events,
+ width,height,present_size};
const struct simple_graphics_api *simple_minifb_api(void) { return &api; }
""");
TestC.exec(30,"gcc","-shared","-fPIC","-Isrc/main/c",source.toString(),"-o",library.toString());
@@ -174,6 +184,50 @@ public class GraphicsTest {
assertTrue(output,output.contains("cannot load MiniFB backend"));
}
+ @Test public void demosResizeWithoutDisplay() throws Exception {
+ Path source=Path.of("build/objs/graphics_resize.c");
+ Path library=Path.of("build/objs/graphics_resize"+(TestC.OS.startsWith("Windows") ? ".dll" : ".so"));
+ Files.writeString(source,"""
+ #include "simple_graphics.h"
+ #include <stdio.h>
+ #include <unistd.h>
+ static unsigned step, seen, base_w, base_h;
+ static uint32_t width(void) {
+ return step==1 ? base_w/2 : step==2 ? base_w+123 : step==3 ? 1 : step==4 ? 0 : base_w;
+ }
+ static uint32_t height(void) {
+ return step==1 ? base_h/2 : step==2 ? base_h/2+17 : step==3 ? 1 : step==4 ? 0 : base_h;
+ }
+ static int32_t open_window(const char *s,uint32_t w,uint32_t h) {
+ base_w=w; base_h=h; return 0;
+ }
+ static int32_t present_size(const uint32_t *p,uint32_t n,uint32_t w,uint32_t h) {
+ if(!p || n!=(uint64_t)w*h || (step!=4 && (w!=width() || h!=height()))) return -1;
+ seen |= 1u<<step;
+ return 0;
+ }
+ static int32_t present(const uint32_t *p,uint32_t n) { return -1; }
+ static int32_t wait_events(int64_t ms) {
+ usleep(35000);
+ if(++step<6) return 0;
+ // Minimized windows need not repaint; every usable size must.
+ if((seen & 46)!=46) { printf("missing resize frames: %u\\n",seen); return -1; }
+ puts("resize passed"); return 1;
+ }
+ static int32_t poll_events(int32_t n) { return wait_events(n); }
+ static int32_t position(void) { return 0; }
+ static int32_t key(int32_t n) { return 0; }
+ static void close_window(void) {}
+ static const struct simple_graphics_api api={SIMPLE_GRAPHICS_VERSION,
+ open_window,present,poll_events,position,position,key,key,close_window,wait_events,
+ width,height,present_size};
+ const struct simple_graphics_api *simple_minifb_api(void) { return &api; }
+ """);
+ TestC.exec(30,"gcc","-shared","-fPIC","-Isrc/main/c",source.toString(),"-o",library.toString());
+ for(String exe:new String[]{graphics,clock,game,breakout})
+ assertTrue(exe,run(exe,library.toAbsolutePath().toString(),0).contains("resize passed"));
+ }
+
@Test public void textIgnoresGraphicsConfiguration() throws Exception {
assertEquals("text still works\n",run(text,"off",0));
assertEquals("text still works\n",run(text,"no-such-backend",0));
diff --git a/chapter31/src/test/java/com/seaofnodes/simple/MathTest.java b/chapter31/src/test/java/com/seaofnodes/simple/MathTest.java
new file mode 100644
index 00000000..e19341b7
--- /dev/null
+++ b/chapter31/src/test/java/com/seaofnodes/simple/MathTest.java
@@ -0,0 +1,79 @@
+package com.seaofnodes.simple;
+
+import com.seaofnodes.simple.codegen.CodeGen;
+import com.seaofnodes.simple.codegen.RegAllocTestSupport.CheckedCodeGen;
+import com.seaofnodes.simple.type.TypeInteger;
+import org.junit.Test;
+
+public class MathTest {
+ @Test public void nativeValues() throws Exception {
+ TestC.runSYS("""
+ val near={ f64 x, f64 y -> x==x && x-y<1e-12 && y-x<1e-12; };
+ val main={ ->
+ val angles=new f64[~]{-sys.math.PI/2,0.0,sys.math.PI/6,sys.math.PI/2};
+ val sines=new f64[~]{-1.0,0.0,0.5,1.0};
+ val cosines=new f64[~]{0.0,1.0,0.8660254037844386,0.0};
+ for(int i=0;i<angles#;i++) {
+ if(!near(sys.math.sin(angles[i]),sines[i])) return 1;
+ if(!near(sys.math.cos(angles[i]),cosines[i])) return 2;
+ }
+ if(!near(sys.math.exp(1.0),sys.math.E)) return 3;
+ if(!near(sys.math.log(sys.math.E),1.0)) return 4;
+ if(!near(sys.math.sqrt(2.0),1.4142135623730951)) return 5;
+ if(!near(sys.math.log(sys.math.exp(-3.5)),-3.5)) return 6;
+ if(sys.math.sqrt(9.0)!=3.0) return 7;
+ if(sys.math.exp(0.0)!=1.0 || sys.math.log(1.0)!=0.0) return 8;
+ return 0;
+ };
+ ""","mathValues","",-1);
+ }
+
+ @Test public void nativeSpecialValues() throws Exception {
+ TestC.runSYS("""
+ val nan={ f64 x -> x!=x; };
+ val main={ ->
+ f64 inf=sys.math.f64FromBits(0x7ff0000000000000);
+ f64 qnan=sys.math.f64FromBits(0x7ff8000000000001);
+ if(!nan(sys.math.sin(inf)) || !nan(sys.math.cos(inf))) return 1;
+ if(!nan(sys.math.log(-1.0)) || !nan(sys.math.sqrt(-1.0))) return 2;
+ if(sys.math.log(0.0)!=-inf || sys.math.log(inf)!=inf) return 3;
+ if(sys.math.exp(inf)!=inf || sys.math.exp(-inf)!=0.0) return 4;
+ if(sys.math.sqrt(inf)!=inf) return 5;
+ if(sys.math.f64Bits(sys.math.sin(-0.0))!=sys.integer.MIN_I64) return 6;
+ if(sys.math.f64Bits(sys.math.sqrt(-0.0))!=sys.integer.MIN_I64) return 7;
+ if(sys.math.cos(-0.0)!=1.0) return 8;
+ if(!nan(sys.math.sin(qnan)) || !nan(sys.math.cos(qnan))) return 9;
+ if(!nan(sys.math.exp(qnan)) || !nan(sys.math.log(qnan)) ||
+ !nan(sys.math.sqrt(qnan))) return 10;
+ if(sys.math.exp(1000.0)!=inf || sys.math.exp(-1000.0)!=0.0) return 11;
+ return 0;
+ };
+ ""","mathSpecial","",-1);
+ }
+
+ @Test public void indirectBindings() throws Exception {
+ TestC.runSYS("""
+ val apply_noInline={ { f64 -> f64 } f, f64 x -> f(x); };
+ val main={ ->
+ if(apply_noInline(sys.math.sin,0.0)!=0.0) return 1;
+ if(apply_noInline(sys.math.cos,0.0)!=1.0) return 2;
+ if(apply_noInline(sys.math.exp,0.0)!=1.0) return 3;
+ if(apply_noInline(sys.math.log,1.0)!=0.0) return 4;
+ if(apply_noInline(sys.math.sqrt,9.0)!=3.0) return 5;
+ return 0;
+ };
+ ""","mathIndirect","",-1);
+ }
+
+ @Test public void allBackends() {
+ // Load just math from source so each backend selects its own C ABI.
+ String source="""
+ f64 x=arg;
+ return math.sin(x)+math.cos(x)+math.exp(x)+
+ math.log(x)+math.sqrt(x);
+ """;
+ for(String cpu:new String[]{"x86_64_v2","arm","riscv"})
+ new CheckedCodeGen("src/main/smp/sys",null,null,"MathCalls",source,126,true,TypeInteger.BOT)
+ .driver(CodeGen.Phase.Encoding,cpu,"SystemV");
+ }
+}
diff --git a/chapter31/src/test/java/com/seaofnodes/simple/ModTest.java b/chapter31/src/test/java/com/seaofnodes/simple/ModTest.java
new file mode 100644
index 00000000..7f79599d
--- /dev/null
+++ b/chapter31/src/test/java/com/seaofnodes/simple/ModTest.java
@@ -0,0 +1,201 @@
+package com.seaofnodes.simple;
+
+import com.seaofnodes.simple.codegen.CodeGen;
+import com.seaofnodes.simple.codegen.RegAllocTestSupport.CheckedCodeGen;
+import com.seaofnodes.simple.node.*;
+import com.seaofnodes.isa.eval.EvalArm64;
+import com.seaofnodes.isa.eval.EvalRisc5;
+import com.seaofnodes.simple.type.TypeInteger;
+import com.seaofnodes.simple.util.Ary;
+import java.nio.file.Files;
+import java.nio.file.Path;
+import org.junit.Test;
+import static org.junit.Assert.*;
+
+public class ModTest {
+ private static String literal(long x) {
+ return x==Long.MIN_VALUE ? "(-9223372036854775807-1)" : Long.toString(x);
+ }
+ @Test public void integers() {
+ long[] values={Long.MIN_VALUE,-17,-1,0,1,17,Long.MAX_VALUE};
+ long[] divisors={Long.MIN_VALUE,-5,-1,0,1,5,Long.MAX_VALUE};
+ for( long y : divisors ) {
+ for( long x : values ) {
+ CodeGen code=new CodeGen("return arg%"+literal(y)+";");
+ String expected=Long.toString(y==0 ? 0 : x%y);
+ try {
+ assertEquals(x+"%"+y,expected,Eval2.eval(code,x));
+ assertEquals(expected,Eval2.eval(new CodeGen("return "+literal(x)+"%"+literal(y)+";"),0));
+ } catch(Throwable e) { throw new AssertionError(x+"%"+y,e); }
+ }
+ }
+ }
+ @Test public void precedenceAndIdentifiers() {
+ assertEquals("6",Eval2.eval(new CodeGen("return 20%6*3;"),0));
+ assertEquals("2",Eval2.eval(new CodeGen("return 20/3%4;"),0));
+ assertEquals("21",Eval2.eval(new CodeGen("int mod=20; return mod+7%3;"),0));
+ }
+ @Test public void compoundAssignment() {
+ assertEquals("-2",Eval2.eval(new CodeGen("int x=arg; x %= 5; return x;"),-17));
+ assertEquals("0",Eval2.eval(new CodeGen("int x=17; x %= arg; return x;"),0));
+ assertEquals("1.5",Eval2.eval(new CodeGen("f64 x=7.5; x %= 2; return x;"),0));
+ assertEquals("21",Eval2.eval(new CodeGen("""
+ val a=new int[1]; a[0]=17;
+ int i=0; a[i++] %= 5;
+ return a[0]*10+i;
+ """),0));
+ }
+ @Test public void floats() {
+ for( double y : new double[]{-5.5,-1.0,0.0,1.0,5.5} ) {
+ CodeGen code=new CodeGen("return (arg+0.0)%"+y+";");
+ for( long x : new long[]{-17,-1,0,1,17} )
+ assertEquals(Double.isNaN(x%y) ? "Double.NaN" : Double.toString(x%y),Eval2.eval(code,x));
+ }
+ assertEquals("-0.0",Eval2.eval(new CodeGen("return -10.0%5.0;"),0));
+ assertEquals("1.5",Eval2.eval(new CodeGen("return 7.5%2;"),0));
+ }
+ @Test public void zeroAndDeadBranches() {
+ assertEquals("0",Eval2.eval(new CodeGen("return 1%arg;"),0));
+ assertEquals("0",Eval2.eval(new CodeGen("return 1%0;"),0));
+ CodeGen discarded=new CodeGen("1%arg; return 42;").driver(CodeGen.Phase.TypeCheck);
+ assertNull(discarded._stop.walk(n -> n instanceof ModNode || n instanceof CallNode ? n : null));
+ assertEquals("42",Eval2.eval(discarded,0));
+ CodeGen common=new CodeGen("return (arg%7)-(arg%7);").driver(CodeGen.Phase.TypeCheck);
+ assertNull(common._stop.walk(n -> n instanceof ModNode || n instanceof CallNode ? n : null));
+ assertEquals("0",Eval2.eval(common,17));
+ assertEquals("42",Eval2.eval(new CodeGen("if(arg) return 1%0; return 42;"),0));
+ assertEquals("42",Eval2.eval(new CodeGen("if(false) return 1%0; return 42;"),0));
+ }
+ @Test public void operandEffects() {
+ assertEquals("709",Eval2.eval(new CodeGen("""
+ int x=7;
+ int r=x++%++x;
+ return r*100+x;
+ """),0));
+ assertEquals("42",Eval2.eval(new CodeGen("""
+ val a=new int[1];
+ val next={ int[] a -> a[0]++; return a[0]+10; };
+ int r=next(a)%next(a);
+ return r*2+a[0]*10;
+ """),0));
+ }
+ @Test public void loopsAndRecursiveModes() {
+ String source="""
+ int sum=0;
+ for(int i=0;i<arg;i++) sum=sum+(i+1)%5;
+ return sum;
+ """;
+ assertEquals("40",Eval2.eval(new CodeGen(source),20));
+ assertEquals("41",Eval2.eval(new CodeGen(source),21));
+ assertEquals("1.5",Eval2.eval(new CodeGen("""
+ val f={ i64 n -> n==0 ? 7.5 : f(n-1)%2; };
+ return f(arg);
+ """),3));
+ }
+ @Test public void typeErrors() {
+ for( String source : new String[]{"return \"abc\"%2;", "return 2%new int[1];"} ) {
+ try {
+ new CodeGen(source).driver(CodeGen.Phase.TypeCheck);
+ fail("% needs numeric operands: "+source);
+ } catch(RuntimeException expected) {
+ assertTrue(expected.getMessage(),expected.getMessage().startsWith("Cannot"));
+ }
+ }
+ }
+ @Test public void allBackends() {
+ for( String cpu : new String[]{"x86_64_v2","arm","riscv"} )
+ new CheckedCodeGen("return arg%7 + (arg+0.5)%2.5;")
+ .driver(CodeGen.Phase.Encoding,cpu,"SystemV");
+ }
+ @Test public void nativeRemainders() throws Exception {
+ TestC.runSYS("""
+ val rem_noInline={ i64 x,i64 y -> x%y; };
+ val frem_noInline={ f64 x,f64 y -> x%y; };
+ val mixed_noInline={ f64 x,f64 y,i64 i -> x*13+(x%y)+y*17+i; };
+ val main={ ->
+ if(rem_noInline(-17,5)!=-2) return 1;
+ if(rem_noInline(17,-5)!=2) return 2;
+ if(rem_noInline(sys.integer.MIN_I64,-1)!=0) return 3;
+ if(rem_noInline(sys.integer.MIN_I64,3)!=-2) return 4;
+ if(frem_noInline(-7.5,2.0)!=-1.5) return 5;
+ if(sys.math.f64Bits(frem_noInline(-10.0,5.0))!=sys.integer.MIN_I64) return 6;
+ sys.libc.set_errno(123);
+ f64 nan=frem_noInline(1.0,0.0);
+ if(nan==nan) return 7;
+ if(sys.libc.errno()!=123) return 8;
+ if(mixed_noInline(7.5,2.0,31)!=164.0) return 9;
+ return 0;
+ };
+ ""","modNative","",-1);
+ }
+ @Test public void importedRemainders() throws Exception {
+ Path dir=Files.createTempDirectory(Path.of("build/objs"),"mod-import-");
+ new CodeGen(null,dir.toString(),null,"Remainders","val rem_noInline={ i64 x -> x%7; };",126,true,TypeInteger.BOT)
+ .driver(TestC.CPU_PORT,TestC.CALL_CONVENTION,false,false);
+ var paths=new Ary<>(new String[]{dir.toString()});
+ CodeGen client=new CodeGen(null,dir.toString(),paths,"Client","return Remainders.rem_noInline(arg);",126,true,TypeInteger.BOT);
+ assertEquals("-3",Eval2.eval(client,-17));
+ }
+ @Test public void nativeDivisionAndRemainderEdges() throws Exception {
+ TestC.runSYS(integerEdges(),"modDivEdges","",-1);
+ }
+ @Test public void emulatedDivisionAndRemainderEdges() throws Exception {
+ long[] values={Long.MIN_VALUE,Long.MIN_VALUE+1,-17,-1,0,1,17,Long.MAX_VALUE};
+ for( String op : new String[]{"%","/"} ) {
+ String source="val main={ i64 x,i64 y -> x "+op+" y; };";
+ EvalArm64 image=TestArm64.build("main",source,0,-1,false);
+ for( long x : values ) for( long y : values ) {
+ EvalArm64 arm=new EvalArm64(image._buf,1<<16);
+ arm._pc=image._pc;
+ arm.regs[0]=x; arm.regs[1]=y;
+ assertEquals(0,arm.step(1000));
+ assertEquals(x+" "+op+" "+y,y==0 ? 0 : op.equals("%") ? x%y : x/y,arm.regs[0]);
+ }
+ // The shared RISC-V emulator's DIV/REM still operate on 32-bit values.
+ EvalRisc5 rimage=TestRisc5.build(source,"main",0,-1,false);
+ for( long x : new long[]{-17,-1,0,1,17} ) for( long y : new long[]{-17,-1,0,1,17} ) {
+ EvalRisc5 riscv=new EvalRisc5(rimage._buf,1<<16);
+ riscv._pc=rimage._pc;
+ riscv.regs[10]=x; riscv.regs[11]=y;
+ assertEquals(0,riscv.step(1000));
+ assertEquals(x+" "+op+" "+y,y==0 ? 0 : op.equals("%") ? x%y : x/y,riscv.regs[10]);
+ }
+ }
+ }
+ private static String integerEdges() {
+ return integerEdges(new long[]{Long.MIN_VALUE,Long.MIN_VALUE+1,-17,-5,-1,0,1,5,17,Long.MAX_VALUE});
+ }
+ private static String integerEdges(long[] values) {
+ StringBuilder source=new StringBuilder("""
+ val rem_noInline={ i64 x,i64 y -> x%y; };
+ val div_noInline={ i64 x,i64 y -> x/y; };
+ val main={ ->
+ """);
+ int failure=1;
+ for( long x : values )
+ for( long y : values ) {
+ source.append("if(rem_noInline(").append(literal(x)).append(',').append(literal(y))
+ .append(")!=").append(literal(y==0 ? 0 : x%y)).append(") return ").append(failure++).append(';');
+ source.append("if(div_noInline(").append(literal(x)).append(',').append(literal(y))
+ .append(")!=").append(literal(y==0 ? 0 : x/y)).append(") return ").append(failure++).append(';');
+ }
+ return source.append("return 0; };").toString();
+ }
+ @Test public void nativeFloatingEdges() throws Exception {
+ double[][] cases={{Double.MAX_VALUE,0.1},{-Double.MAX_VALUE,0.1},
+ {Double.MIN_VALUE,1.0},{1.0,Double.POSITIVE_INFINITY},
+ {-0.0,Double.NEGATIVE_INFINITY},{-5.0,2.5},
+ {Double.POSITIVE_INFINITY,1.0},{Double.NaN,2.0},{2.0,Double.NaN},{1.0,-0.0}};
+ StringBuilder source=new StringBuilder("val rem_noInline={ f64 x,f64 y -> x%y; }; val main={ -> ");
+ for( int i=0; i<cases.length; i++ ) {
+ double x=cases[i][0],y=cases[i][1],r=x%y;
+ source.append("f64 r").append(i).append("=rem_noInline(sys.math.f64FromBits(")
+ .append(literal(Double.doubleToRawLongBits(x))).append("),sys.math.f64FromBits(")
+ .append(literal(Double.doubleToRawLongBits(y))).append(")); if(");
+ if( Double.isNaN(r) ) source.append('r').append(i).append("==r").append(i);
+ else source.append("sys.math.f64Bits(r").append(i).append(")!=").append(literal(Double.doubleToRawLongBits(r)));
+ source.append(") return ").append(i+1).append(";");
+ }
+ TestC.runSYS(source.append("return 0; };").toString(),"modFloatEdges","",-1);
+ }
+}
diff --git a/chapter31/src/test/java/com/seaofnodes/simple/SchedulingTest.java b/chapter31/src/test/java/com/seaofnodes/simple/SchedulingTest.java
new file mode 100644
index 00000000..16e12b0f
--- /dev/null
+++ b/chapter31/src/test/java/com/seaofnodes/simple/SchedulingTest.java
@@ -0,0 +1,47 @@
+package com.seaofnodes.simple;
+
+import org.junit.Test;
+
+public class SchedulingTest {
+ @Test public void nativeFoldedLoadsWithLaterOperands() throws Exception {
+ TestC.runSYS("""
+ val compare_noInline={ i64[] a, int flag ->
+ i64 x=a[0];
+ i64 y=flag ? a[1] : a[2];
+ return x==y;
+ };
+ val add_noInline={ i64[] a, int flag ->
+ i64 x=a[0];
+ i64 y=flag ? a[1] : a[2];
+ return x+y;
+ };
+ val main={ ->
+ val a=new i64[3]; a[0]=17; a[1]=17; a[2]=23;
+ if(!compare_noInline(a,1) || compare_noInline(a,0)) return 1;
+ if(add_noInline(a,1)!=34 || add_noInline(a,0)!=40) return 2;
+ return 0;
+ };
+ ""","scheduleLaterOperands","",-1);
+ }
+
+ @Test public void nativeLoadsAcrossWrites() throws Exception {
+ TestC.runSYS("""
+ val change_noInline={ i64[] a -> a[0]=a[1]; return a[0]; };
+ val compare_noInline={ i64[] a ->
+ i64 x=a[0];
+ return x==change_noInline(a);
+ };
+ val add_noInline={ i64[] a ->
+ i64 x=a[0];
+ return x+change_noInline(a);
+ };
+ val main={ ->
+ val a=new i64[2]; a[0]=17; a[1]=23;
+ if(compare_noInline(a)) return 1;
+ a[0]=17; a[1]=29;
+ if(add_noInline(a)!=46) return 2;
+ return 0;
+ };
+ ""","scheduleAcrossWrites","",-1);
+ }
+}
diff --git a/chapter31/src/test/java/com/seaofnodes/simple/StreamIOTest.java b/chapter31/src/test/java/com/seaofnodes/simple/StreamIOTest.java
index 7b459e75..79b95c03 100644
--- a/chapter31/src/test/java/com/seaofnodes/simple/StreamIOTest.java
+++ b/chapter31/src/test/java/com/seaofnodes/simple/StreamIOTest.java
@@ -88,7 +88,7 @@ public class StreamIOTest extends TestC {
val bytes=sys.io.read(700);
if(!bytes) return 1;
if(bytes#!=24593) return 2;
- for(u32 i=0; i<bytes#; i++) if(bytes[i]!=i-(i/251)*251) return 3;
+ for(u32 i=0; i<bytes#; i++) if(bytes[i]!=i%251) return 3;
test_io_mode(1,0);
if(sys.io.write(701,bytes)!=bytes# || test_io_count()!=bytes#) return 4;
if(test_io_status()) return 5;
diff --git a/chapter31/src/test/java/com/seaofnodes/simple/StringFormatTest.java b/chapter31/src/test/java/com/seaofnodes/simple/StringFormatTest.java
index 05e801dc..59b62709 100644
--- a/chapter31/src/test/java/com/seaofnodes/simple/StringFormatTest.java
+++ b/chapter31/src/test/java/com/seaofnodes/simple/StringFormatTest.java
@@ -25,6 +25,11 @@ public class StringFormatTest extends TestC {
"+00017|0x00002a|abc |1.25|A|false\n");
}
+ @Test public void testRemainderInInterpolation() throws Exception {
+ prints("int mod=17; sys.io.p(\"%(mod%5)|%02d(mod%5)|%%|\\%|%(mod %= 5)|%(mod)\");",
+ "2|02|%|%|2|2");
+ }
+
@Test public void testIntegerLimits() throws Exception {
prints("i64 lo=-9223372036854775807-1; sys.io.p(\"%(lo)|%(9223372036854775807)|%u(-1)|%X(-1)\");",
"-9223372036854775808|9223372036854775807|18446744073709551615|FFFFFFFFFFFFFFFF");
diff --git a/chapter31/src/test/java/com/seaofnodes/simple/TestC.java b/chapter31/src/test/java/com/seaofnodes/simple/TestC.java
index 63bb98da..9654382c 100644
--- a/chapter31/src/test/java/com/seaofnodes/simple/TestC.java
+++ b/chapter31/src/test/java/com/seaofnodes/simple/TestC.java
@@ -203,7 +203,7 @@ public abstract class TestC {
params.add(runtimeObject("simple_args"));
}
params.addAll(new String[] {
- "-lm", // Picks up 'sqrt' for newtonFloat tests to compare
+ "-lm", // sys.math functions, floating remainder, and C test drivers
"-g", // debug symbols
"-o", // name the output file
exe, // name the output file