diff options
Diffstat (limited to 'chapter28b')
13 files changed, 304 insertions, 79 deletions
diff --git a/chapter28b/README.md b/chapter28b/README.md index 84e538ea..5d8cbdf9 100644 --- a/chapter28b/README.md +++ b/chapter28b/README.md @@ -120,7 +120,14 @@ those exclusions by owner and slot, then restores the complement. Treating this set as FULL would expose private library functions. Unknown callback arguments, results, and unloaded summaries use the evolving Start/Stop state; no frozen public-function list supplies their bounds. Hidden class receivers -default to the defining class singleton even after import. The +default to the defining class singleton even after import, following +[chapter 28a's receiver model](../chapter28a/README.md#globals-use-the-same-receiver-as-fields). +`SummaryNode` excludes that hidden receiver from its conservative argument-escape +scan: the caller supplies no class object through the ABI, and actual publication +of the callee's class fields is already represented by the saved summary state. +Instance receivers remain ordinary arguments and participate in that scan. +[ReceiverTest](src/test/java/com/seaofnodes/simple/ReceiverTest.java) checks a +callback forwarded by another compiled class with a different field value. The [escape-flow implementation notes](../chapter29/docs/escape-flow.md) explain the shared design and the identity-remapping checks in more detail. diff --git a/chapter28b/src/main/java/com/seaofnodes/simple/Parser.java b/chapter28b/src/main/java/com/seaofnodes/simple/Parser.java index cef7091a..0e8eb5a9 100644 --- a/chapter28b/src/main/java/com/seaofnodes/simple/Parser.java +++ b/chapter28b/src/main/java/com/seaofnodes/simple/Parser.java @@ -291,8 +291,16 @@ public class Parser { // All args, "as-if" called externally for( int i=0; i<ids.length; i++ ) { Type t = sig.arg(i); + // The body sees its owning class receiver. PTR remains in the + // signature as the ABI marker for a receiver with no machine slot. + if( i==0 && t==TypePtr.PTR ) { + TypeStruct clz = ((TypeMemPtr)fun.defaultArg(i))._obj; + // A file can add globals after its struct declaration closes. + // Keep this view open until SCCP installs the completed class. + t = TypeMemPtr.make((byte)2,TypeStruct.make(clz._name,true,clz._fields),true); + } // Args take a default input if called from Start/external-world - _scope.define(ids[i], t, (i==0 && ids[0]=="self") || (finals!=null && finals.get(i)), new ParmNode(ids[i],i+2,t,fun,ConstantNode.seed(fun.defaultArg(i)).peephole()).peephole(), loc); + _scope.define(ids[i], t, (i==0 && ids[0]=="self") || (finals!=null && finals.get(i)), new ParmNode(ids[i],i+2,t,fun,ConstantNode.seed(i==0 && t instanceof TypeMemPtr ? t : fun.defaultArg(i)).peephole()).peephole(), loc); } if( isCtor && !isInit ) { @@ -1085,6 +1093,10 @@ public class Parser { throw error("Cannot reassign final '"+name+"'"); checkSharedFunction(def); + // All fields use the same receiver-based lvalue path. + if( fieldSelf(def)!=null ) + { pos(old); return parseExpression(); } + // Parse assignment expression Node expr = parseAsgn(); @@ -1094,27 +1106,6 @@ public class Parser { // Update _scope.update(name,lift); - // Check for storing into an instance field instead of a local var - int kx = _scope.kindx(def); // Declaration scope - int fx = _scope.enclosingFunction(); // Enclosing function scope - Kind kk = _scope._kinds.at(kx); - Kind fk = _scope._kinds.at(fx); - // Access instance field from 'self' - if( kx+1 == fx && kk instanceof Kind.Func inst && FunNode.isInstance(inst._name) && - fk instanceof Kind.Func method && !inExplicitConstructor() ) { - // Named field offset on an unknown struct type - TypeMemPtr self = (TypeMemPtr)_scope.var(fk._lexSize).type(); - TypeStruct sobj = (TypeStruct)TYPES.get(self._obj._name); - Field fld = sobj.field(name); - int alias = fld._alias; - Node ptr = _scope.in(method._lexSize); - Node off = fldoff(ptr,name); - Node prior = mem().keep(); - Node st = new StoreNode(loc(), name, alias, decl, ctrl(), prior, ptr, off, lift, inExplicitConstructor()).peephole().keep(); - storeMem(st,alias,prior); - st.unkeep(); - prior.unkeep(); - } lift.unkill(); @@ -2109,35 +2100,12 @@ public class Parser { if( inExplicitConstructor() && var._uninit && missingInit(rvalue,new BitSet()) ) throw error("Field '"+id+"' might not be initialized",var._loc); - // Check for an instance field load - int kx = _scope.kindx(var); // Declaration scope - int fx = _scope.enclosingFunction(); // Enclosing function scope - Kind kk = _scope._kinds.at(kx); - Kind fk = _scope._kinds.at(fx); - // Access instance field from 'self' - if( kx+1 == fx && kk instanceof Kind.Func inst && FunNode.isInstance(inst._name) && fk instanceof Kind.Func method && !inExplicitConstructor() ) - return parsePostfixName(_scope.in(method._lexSize),id,pre); - - // Check for a function-escaping variable; these require true - // closures. Final constants are OK; final vars require a hidden var - // argument; not-final fields can just use an explicit struct arg. - if( kx < fx && !inExplicitConstructor() && // Out of scope - !(var._final && rvalue._type.isConstant()) ) { // Not a final constant - if( kx > 0 ) // Global scope is OK, only ever one of these (not one per function invoke) - throw error("Variable '"+var._name+"' is out of function scope and must be a final constant"); - - // var.idx==2 is self argument, 3 is args, 4 or more are now static globals - if( var._idx >= 4 ) { - // Read from global scope. - // Surely a nicer way to get the top-level scope compile name? - Var clzptr = _scope.var( 2 ); - // Get the most recent sharpen global - TypeStruct clz = (TypeStruct) TYPES.get( ((TypeMemPtr) clzptr.type())._obj._name ); - TypeMemPtr clztmp = TypeMemPtr.make( (byte) 2, clz, true ); - return parsePostfixName( con( clztmp ), id,pre ); - //return parsePostfixName(_scope.in(2),id); - } - } + Node self = fieldSelf(var); + if( self!=null ) return parsePostfixName(self,id,pre); + int kx = _scope.kindx(var), fx = _scope.enclosingFunction(); + if( kx>0 && kx<fx && !inExplicitConstructor() && + !(var._final && rvalue._type.isConstant()) ) + throw error("Variable '"+var._name+"' is out of function scope and must be a final constant"); // Check for assign-update, x += e0; char ch = pre==0 ? _lexer.matchOperAssign() : (char)pre; @@ -2382,6 +2350,31 @@ public class Parser { return parsePostfixMethod(value,defaultSelf()); } + // Find the receiver for a field lvalue. Initializers retain Scope values; + // class declarations retain their Scope values until initializer exit. + private Node fieldSelf(Var var) { + int kx = _scope.kindx(var); + ScopeNode.Kind kind = _scope._kinds.at(kx); + if( !(kind instanceof Kind.Func owner) || !FunNode.isInit(owner._name) || var._idx<owner._lexSize+2 ) return null; + // Instance constructors still accumulate their fields in Scope here. + if( FunNode.isInstance(owner._name) && (inExplicitConstructor() || _scope.enclosingFuncOrDecl()==kx) ) return null; + // Class declarations still accumulate their initial values in Scope. + // This also preserves declaration-time struct default expressions. + if( FunNode.isClz(owner._name) && _scope.enclosingFunction()==kx ) return null; + // Nested functions have their own receiver parameter. Resolve fields + // through it even across intervening function and block scopes. + Node self = defaultSelf(); + Var receiver = _scope.var(owner._lexSize); + if( self._type instanceof TypeMemPtr ptr && receiver.type() instanceof TypeMemPtr declared && + ptr._obj._name.equals(declared._obj._name) ) return self; + // An instance method can also name fields of its enclosing class. + // Use that declaration's receiver; normal folding handles its identity. + if( !FunNode.isClz(owner._name) ) return null; + // The enclosing declaration may have discovered more fields since + // creating its receiver. View that same receiver with its current type. + return peep(new ConvertNode(receiver.type().upgradeType(TYPES),_scope.in(receiver))); + } + private void checkSharedFunction(Var v) { if( _scope.canInit(v) && v._final && v.type() instanceof TypeFunPtr t && t.isConstant() ) throw error("Cannot reassign shared function '"+v._name+"'"); @@ -2573,7 +2566,7 @@ public class Parser { java.util.BitSet finals = new java.util.BitSet(); Type self = implicitSelfType(); ts.push(self); - ids.push(self == TypePtr.PTR ? "#self" : "self"); + ids.push("self"); // Parse other arguments _lexer.skipWhiteSpace(); @@ -2583,6 +2576,10 @@ public class Parser { if( t==null ) break; finals.set(ids.size(),bindingFinal(t)); String id = requireId(); + // Older free functions may explicitly name a source argument + // "self". It shadows the implicit class receiver, not its ABI slot. + if( id=="self" && ts.at(0)==TypePtr.PTR && ids.at(0)=="self" ) + ids.set(0,"#self"); ts .push(t ); // Push type/arg pairs ids.push(id); match(","); diff --git a/chapter28b/src/main/java/com/seaofnodes/simple/node/CallNode.java b/chapter28b/src/main/java/com/seaofnodes/simple/node/CallNode.java index 23188e84..a69708c0 100644 --- a/chapter28b/src/main/java/com/seaofnodes/simple/node/CallNode.java +++ b/chapter28b/src/main/java/com/seaofnodes/simple/node/CallNode.java @@ -6,6 +6,7 @@ import com.seaofnodes.simple.Parser; import com.seaofnodes.simple.codegen.CodeGen; import com.seaofnodes.simple.codegen.Iter; import com.seaofnodes.simple.type.Type; +import com.seaofnodes.simple.type.TypePtr; import com.seaofnodes.simple.type.TypeFunPtr; import com.seaofnodes.simple.type.TypeMem; import com.seaofnodes.simple.type.TypeRPC; @@ -90,13 +91,14 @@ public class CallNode extends CFGNode { // A broad scalar target can refine to a function pointer during Iter. // It cannot yet promise that the call exposes nothing. if( _type!=Type.CONTROL ) return TypeMem.BOT; - if( !(fptr()._type instanceof TypeFunPtr) ) + if( !(fptr()._type instanceof TypeFunPtr tfp) ) return fptr()._type.isHigh() ? TypeMem.START : TypeMem.BOT; if( !external() ) return TypeMem.START; Type input = dep.addDepForwards(mem())._type; TypeMem escaped = input instanceof TypeMem m ? m : input.isHigh() ? TypeMem.TOP : TypeMem.BOT; TypeMem outside = CodeGen.CODE._start.outside(dep); - for( int i = 2; i<nIns()-1; i++ ) + // A class receiver belongs to the callee; the caller does not expose its class. + for( int i = tfp.nargs()>0 && tfp.arg(0)==TypePtr.PTR ? 3 : 2; i<nIns()-1; i++ ) escaped = escaped.escapesFrom(dep.addDepForwards(arg(i))._type,outside); return TypeMem.make(1,Type.BOTTOM,false,false,false,escaped._escFs,escaped._escAs); } @@ -173,7 +175,10 @@ public class CallNode extends CFGNode { CodeGen.CODE.add(fun).addDef(this); for( Node use : fun._outputs ) if( use instanceof ParmNode parm ) { - Node def = parm._idx==0 ? ConstantNode.seed(cend()._rpc).peephole() : arg(parm._idx); + // Match the callee's declared receiver view, including forward fields. + Node def = parm._idx==0 ? ConstantNode.seed(cend()._rpc).peephole() + : parm._idx==2 && fun.sig().arg(0)==TypePtr.PTR + ? ConstantNode.seed(parm._declaredType).peephole() : arg(parm._idx); CodeGen.CODE.add(parm).addDef(def); // Linking can happen during post-SCCP inlining. Keep an RPC // Parm's cached finite set synchronized with its newly added diff --git a/chapter28b/src/main/java/com/seaofnodes/simple/node/PhiNode.java b/chapter28b/src/main/java/com/seaofnodes/simple/node/PhiNode.java index 3cf6f854..de255a97 100644 --- a/chapter28b/src/main/java/com/seaofnodes/simple/node/PhiNode.java +++ b/chapter28b/src/main/java/com/seaofnodes/simple/node/PhiNode.java @@ -114,7 +114,8 @@ public class PhiNode extends Node { // Generic "pull down op" Node progress; - if( same_op() && (progress = drop_same_op()) != null ) + Node op = factoringOp(); + if( same_op(op) && (progress = drop_same_op(op)) != null ) return progress; // If merging Phi(ZERO, guardNZ(N)) at the matching `if(N)` join, the @@ -150,10 +151,28 @@ public class PhiNode extends Node { return tested!=null && (early==null || early.dominates(r,this)) ? n : null; } + // View x<<1 as x+x only while matching mixed Phi arms. Do not + // expand the graph into Adds that would immediately strength-reduce again. + private Node factoringOp() { + Node op = in(1); + if( doubled(op) ) + for( int i=2; i<nIns(); i++ ) + if( in(i) instanceof AddNode add && add._mode==1 ) return in(i); + return op; + } + + private boolean doubled(Node n) { + return n instanceof ShlNode && + addDep(n.in(2))._type instanceof TypeInteger con && con.isConstant() && con.value()==1; + } + + private static Node factoringInput(Node op, Node n, int j) { + return op instanceof AddNode && !(n instanceof AddNode) ? n.in(1) : n.in(j); + } + // Same op on all Phi paths; all ops have only the Phi as a use. // None have a control input. - private boolean same_op() { - Node op = in(1); + private boolean same_op(Node op) { if( op instanceof EscapeNode || op instanceof CFGNode || op instanceof ConstantNode || op instanceof PhiNode || op instanceof ProjNode || op instanceof NewNode || op instanceof ScopeNode || op instanceof MemMergeNode ) return false; // A bulk Phi must split its aliases before factoring precise Stores. @@ -171,7 +190,8 @@ public class PhiNode extends Node { for( int i=1; i<nIns(); i++ ) { Node n = in(i); if( addDep(region().in(i))._type==Type.XCONTROL || - op.getClass()!=n.getClass() || n.nIns()!=op.nIns() || n.in(0)!=null || !op.eq(n) ) return false; + !((op.getClass()==n.getClass() && op.eq(n)) || (op instanceof AddNode add && add._mode==1 && doubled(n))) || + n.nIns()!=op.nIns() || n.in(0)!=null ) return false; if( n instanceof MemOpNode mem && !mem.canDrop((MemOpNode)op,this) ) return false; // Moving a Store must remove the old effect, not duplicate it. // Allow one shared arm: the other arms disappear into the single @@ -189,21 +209,21 @@ public class PhiNode extends Node { return true; } - private Node drop_same_op() { - Node op = in(1), cp = op.copyEmpty(); + private Node drop_same_op(Node op) { + Node cp = op.copyEmpty(); cp._type = null; cp.addDef(null); for( int j=1; j<op.nIns(); j++ ) { - Node x = op.in(j); + Node x = factoringInput(op,in(1),j); boolean different = false; for( int i=2; i<nIns(); i++ ) - if( in(i).in(j)!=x ) different=true; + if( factoringInput(op,in(i),j)!=x ) different=true; if( different ) { Node[] ins = new Node[nIns()]; ins[0] = region(); Type t = Type.TOP; for( int i=1; i<nIns(); i++ ) { - ins[i] = in(i).in(j); + ins[i] = factoringInput(op,in(i),j); t = t.meet(ins[i]._type); } // Do not introduce an operand Phi mixing incompatible type families. diff --git a/chapter28b/src/main/java/com/seaofnodes/simple/node/RegionNode.java b/chapter28b/src/main/java/com/seaofnodes/simple/node/RegionNode.java index 8883ba8e..55f635ae 100644 --- a/chapter28b/src/main/java/com/seaofnodes/simple/node/RegionNode.java +++ b/chapter28b/src/main/java/com/seaofnodes/simple/node/RegionNode.java @@ -68,7 +68,7 @@ public class RegionNode extends CFGNode { if( use instanceof PhiNode phi ) { PhiNode phi2 = phi.in(i) instanceof PhiNode phi2x && phi2x.region()==region ? phi2x : null; for( int j=1; j<region.nIns(); j++ ) - phi.addDef(phi2==null ? phi.in(i) : phi2.in(j)); + phi.addDef(CodeGen.CODE.add(phi2==null ? phi.in(i) : phi2.in(j))); CodeGen.CODE.add(phi); } } diff --git a/chapter28b/src/main/java/com/seaofnodes/simple/node/SummaryNode.java b/chapter28b/src/main/java/com/seaofnodes/simple/node/SummaryNode.java index 483aab89..d0da3250 100644 --- a/chapter28b/src/main/java/com/seaofnodes/simple/node/SummaryNode.java +++ b/chapter28b/src/main/java/com/seaofnodes/simple/node/SummaryNode.java @@ -27,7 +27,7 @@ public class SummaryNode extends CFGNode implements MultiNode { TypeMem mem = in(1)._type instanceof TypeMem m ? m : in(1)._type.isHigh() ? TypeMem.TOP : TypeMem.BOT; mem = (TypeMem)mem.meet(_state.mem()); TypeMem outside = CodeGen.CODE._start.outside(this); - for( int i = 2; i<nIns(); i++ ) mem = mem.escapesFrom(in(i)._type,outside); + for( int i = firstArgument(); i<nIns(); i++ ) mem = mem.escapesFrom(in(i)._type,outside); return TypeTuple.make(_state.ctl(),mem,_state.ret()); } @Override public Node idealize() { return null; } @@ -36,9 +36,16 @@ public class SummaryNode extends CFGNode implements MultiNode { if( dep.addDepForwards(in(0))._type.isHigh() ) return TypeMem.START; TypeMem mem = (TypeMem)_state.mem(); TypeMem outside = CodeGen.CODE._start.outside(dep); - for( int i = 2; i<nIns(); i++ ) mem = mem.escapesFrom(dep.addDepForwards(in(i))._type,outside); + for( int i = firstArgument(); i<nIns(); i++ ) mem = mem.escapesFrom(dep.addDepForwards(in(i))._type,outside); return TypeMem.make(1,Type.BOTTOM,false,false,false,mem._escFs,mem._escAs); } + // A class receiver is supplied by the callee, not exposed by its caller. + // Actual uses which publish self are already represented in _state. + private int firstArgument() { + if( !(in(0) instanceof FunNode fun) ) return 2; + TypeFunPtr sig = fun.sig(); + return sig.nargs()>0 && sig.arg(0)==TypePtr.PTR ? 3 : 2; + } @Override boolean _upgradeType(HashMap<String,Type> types) { TypeTuple state = (TypeTuple)_state.upgradeType(types); if( state==_state ) return false; diff --git a/chapter28b/src/test/java/com/seaofnodes/simple/Chapter05Test.java b/chapter28b/src/test/java/com/seaofnodes/simple/Chapter05Test.java index afdb1071..82a08dac 100644 --- a/chapter28b/src/test/java/com/seaofnodes/simple/Chapter05Test.java +++ b/chapter28b/src/test/java/com/seaofnodes/simple/Chapter05Test.java @@ -2,6 +2,7 @@ package com.seaofnodes.simple; import com.seaofnodes.simple.codegen.CodeGen; import com.seaofnodes.simple.node.*; +import com.seaofnodes.simple.type.TypeInteger; import org.junit.Test; import static org.junit.Assert.*; @@ -201,4 +202,27 @@ return a; catch( RuntimeException e ) { assertEquals("Undefined name 'ififif'",e.getMessage()); } } + private static <N extends Node> N init(N n) { n._type=n.compute(); return n; } + + @Test public void testDoublingBeforeAndAfterStrengthReduction() { + for( boolean reduced : new boolean[]{false,true} ) + for( boolean reverse : new boolean[]{false,true} ) { + CodeGen code = new CodeGen(""); + Node ctrl = init(new CProjNode(code._start,0,"Ctrl")); + RegionNode region = init(new RegionNode(null,null,ctrl,ctrl)); + Node p = code.con(TypeInteger.BOT); + Node i = init(new MinusNode(p)); + Node twice = reduced ? init(new ShlNode(null,p,code.con(1))) : init(new AddNode(p,p,(byte)1)); + Node sum = init(new AddNode(i,p,(byte)1)); + PhiNode phi = init(new PhiNode("sum",region,reverse ? sum : twice,reverse ? twice : sum)); + phi.keep(); + Node factored = phi.idealize(); + assertTrue(factored instanceof AddNode); + assertSame(p,factored.in(2)); + assertTrue(factored.in(1) instanceof PhiNode); + assertSame(reverse ? i : p,factored.in(1).in(1)); + assertSame(reverse ? p : i,factored.in(1).in(2)); + phi.unkeep(); + } + } } diff --git a/chapter28b/src/test/java/com/seaofnodes/simple/Chapter09Test.java b/chapter28b/src/test/java/com/seaofnodes/simple/Chapter09Test.java index 7025b98a..85d4987f 100644 --- a/chapter28b/src/test/java/com/seaofnodes/simple/Chapter09Test.java +++ b/chapter28b/src/test/java/com/seaofnodes/simple/Chapter09Test.java @@ -41,7 +41,7 @@ else { return x; """); code.driver(CodeGen.Phase.FinalizeIR); - assertEquals("return Phi(Region,(arg<<1),(Shl+1));", code.print()); + assertEquals("return (Phi(Region,arg,1)+Phi(Region,arg,(arg<<1)));", code.print()); Assert.assertEquals( "2", Eval2.eval(code, 1)); Assert.assertEquals("23", Eval2.eval(code, 11)); } diff --git a/chapter28b/src/test/java/com/seaofnodes/simple/Chapter20Test.java b/chapter28b/src/test/java/com/seaofnodes/simple/Chapter20Test.java index 7eb1f255..19408f3b 100644 --- a/chapter28b/src/test/java/com/seaofnodes/simple/Chapter20Test.java +++ b/chapter28b/src/test/java/com/seaofnodes/simple/Chapter20Test.java @@ -257,9 +257,9 @@ val hashCode = { !String self -> }; """; // Return the public hashCode wrapper; keep its helper private. - testCPU(src,"x86_64_v2", "SystemV",12,null); - testCPU(src,"riscv" , "SystemV",8,null); - testCPU(src,"arm" , "SystemV",6,null); + testCPU(src,"x86_64_v2", "SystemV",15,null); + testCPU(src,"riscv" , "SystemV",11,null); + testCPU(src,"arm" , "SystemV",11,null); } @Test diff --git a/chapter28b/src/test/java/com/seaofnodes/simple/Chapter21Test.java b/chapter28b/src/test/java/com/seaofnodes/simple/Chapter21Test.java index e15c2581..f3af31a2 100644 --- a/chapter28b/src/test/java/com/seaofnodes/simple/Chapter21Test.java +++ b/chapter28b/src/test/java/com/seaofnodes/simple/Chapter21Test.java @@ -384,9 +384,9 @@ val hashCode = { !String self -> }; """; // Return the public hashCode wrapper; keep its helper private. - testCPU(src,"x86_64_v2", "SystemV",12,null); - testCPU(src,"riscv" , "SystemV",8,null); - testCPU(src,"arm" , "SystemV",6,null); + testCPU(src,"x86_64_v2", "SystemV",15,null); + testCPU(src,"riscv" , "SystemV",11,null); + testCPU(src,"arm" , "SystemV",11,null); } @Test public void testStringExport() throws IOException { @@ -423,7 +423,7 @@ val hashCode = { !String self -> : (self._hashCode = _hashCodeString(self)); }; """; - TestC.runC(src, "stringHash", "",12); + TestC.runC(src, "stringHash", "",15); } @Test public void testLoop2() { diff --git a/chapter28b/src/test/java/com/seaofnodes/simple/Chapter22Test.java b/chapter28b/src/test/java/com/seaofnodes/simple/Chapter22Test.java index 00d77f65..115ee1ca 100644 --- a/chapter28b/src/test/java/com/seaofnodes/simple/Chapter22Test.java +++ b/chapter28b/src/test/java/com/seaofnodes/simple/Chapter22Test.java @@ -301,17 +301,17 @@ val p = { u8[~] str -> p("Hello, World!"); return 0; """; - TestC.runSF(src,"helloWorld", "Hello, World!",2); + TestC.runSF(src,"helloWorld", "Hello, World!",4); // Evaluate on RISC5 emulator - EvalRisc5 R5 = TestRisc5.build( src, "helloWorld", 0, 5, false); + EvalRisc5 R5 = TestRisc5.build( src, "helloWorld", 0, 8, false); int trap = R5.step(100); assertEquals(0,trap); assertEquals(0,R5.regs[riscv.A0]); assertEquals("Hello, World!",R5._stdout.toString()); // Evaluate on ARM emulator - EvalArm64 arm = TestArm64.build("helloWorld", src,0, 5, false); + EvalArm64 arm = TestArm64.build("helloWorld", src,0, 8, false); trap = arm.step(100); assertEquals(0,trap); assertEquals(0,arm.regs[0]); diff --git a/chapter28b/src/test/java/com/seaofnodes/simple/GlobalAssignmentTest.java b/chapter28b/src/test/java/com/seaofnodes/simple/GlobalAssignmentTest.java new file mode 100644 index 00000000..e24baee0 --- /dev/null +++ b/chapter28b/src/test/java/com/seaofnodes/simple/GlobalAssignmentTest.java @@ -0,0 +1,71 @@ +package com.seaofnodes.simple; + +import com.seaofnodes.simple.codegen.CodeGen; + +import org.junit.Test; +import static org.junit.Assert.*; + +public class GlobalAssignmentTest { + private static final String SOURCE = """ + int value=1; + int writes=0; + u8 small=0; + val set={int n -> value=n; return value;}; + val set_noInline={int n -> + if( n<0 ) value=3; + else value=n; + return value; + }; + val rhs_noInline={ -> writes=writes+1; return value+1;}; + val shadow={int value -> value=42; return value;}; + struct Writer { + int seen; + new Writer={int n -> value=n; seen=value;}; + }; + struct InitWriter { int seen=(value=17); }; + val main={ -> + if( set(5)!=5 || value!=5 ) return 1; + if( set_noInline(-1)!=3 || value!=3 ) return 2; + if( set_noInline(8)!=8 || value!=8 ) return 3; + int result=(value=rhs_noInline()); + if( result!=9 || value!=9 || writes!=1 ) return 4; + value=writes=11; + if( value!=11 || writes!=11 ) return 5; + if( shadow(0)!=42 || value!=11 ) return 6; + int wide=(small=257); + if( wide!=257 || small!=1 ) return 7; + val constructed=new Writer(13); + if( value!=13 || constructed.seen!=13 ) return 8; + val initialized=new InitWriter; + // Default expressions run at declaration time, not per instance. + if( value!=13 || initialized.seen!=17 ) return 9; + return 0; + }; + return main(); + """; + + @Test public void storesGlobalMemory() throws Exception { + assertEquals("0",Eval2.eval(new CodeGen(SOURCE).driver(CodeGen.Phase.TypeCheck),0)); + TestC.runSF(SOURCE,"global_assignment","",-1); + } + + @Test public void rejectsFinalGlobal() { + try { + new CodeGen("val value=1; val set={ -> value=2; }; return set();") + .driver(CodeGen.Phase.TypeCheck); + fail("Assigned a final global"); + } catch( Parser.ParseException e ) { + assertEquals("Cannot reassign final 'value'",e.getMessage()); + } + } + + @Test public void rejectsIncompatibleGlobalValue() { + try { + new CodeGen("struct S { int x; }; int value=1; val set={ -> value=new S; }; set(); return value;") + .driver(CodeGen.Phase.TypeCheck); + fail("Stored an object in an integer global"); + } catch( Parser.ParseException expected ) { + assertTrue(expected.getMessage(),expected.getMessage().contains("not of declared type")); + } + } +} diff --git a/chapter28b/src/test/java/com/seaofnodes/simple/ReceiverTest.java b/chapter28b/src/test/java/com/seaofnodes/simple/ReceiverTest.java new file mode 100644 index 00000000..0342d9a2 --- /dev/null +++ b/chapter28b/src/test/java/com/seaofnodes/simple/ReceiverTest.java @@ -0,0 +1,94 @@ +package com.seaofnodes.simple; + +import com.seaofnodes.simple.codegen.*; +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 ReceiverTest { + @Test public void classAndInstanceFields() throws Exception { + String source=""" + int total=1; + val forward={ -> late(); }; + val early={ -> total; }; + val late={ -> early(); }; + val add_noInline={int n -> self.total=self.total+n; return total;}; + val read_noInline={ -> self.total; }; + val nested={ -> + val inc={ -> self.total++; }; + inc(); + return total; + }; + struct Counter { + int total=100; + val read=read_noInline; + }; + struct Writer { + int count=2; + val step={ -> self.count++; total=count; return total; }; + }; + u16[] !table=new u16[2]; + val lookup={u8 c -> c<2 ? table[c] : 0;}; + val main={ -> + total=1; + table=new u16[2]; table[0]=7; table[1]=9; + if( forward()!=1 ) return 4; + if( lookup(1)!=9 || lookup(2)!=0 ) return 5; + if( add_noInline(5)!=6 || nested()!=7 ) return 1; + val counter=new Counter; + if( counter.read()!=7 || counter.total!=100 ) return 2; + val a=new Writer, b=new Writer; + if( a.step()!=3 || total!=3 || a.count!=3 || b.count!=2 ) return 3; + return 0; + }; + return main(); + """; + assertEquals("0",Eval2.eval(new CodeGen(source).driver(CodeGen.Phase.TypeCheck),0)); + TestC.runSF(source,"class_instance_receivers","",-1); + } + + @Test public void importedCallbackKeepsItsClass() throws Exception { + Path build=Path.of("build/objs/receivers"); + Files.createDirectories(build); + Path lib=Files.createTempDirectory(build,"classes-"); + new CodeGen(null,lib.toString(),null,"Owner", + "int value=7; val get_noInline={ -> self.value; };",123,true,TypeInteger.BOT) + .driver(TestC.CPU_PORT,TestC.CALL_CONVENTION,false,false); + new CodeGen(null,lib.toString(),null,"Forwarder", + "int value=99; val apply_noInline={ {int} action -> action()+self.value; };",123,true,TypeInteger.BOT) + .driver(TestC.CPU_PORT,TestC.CALL_CONVENTION,false,false); + var paths=new Ary<>(new String[]{lib.toString()}); + String source="return Forwarder.apply_noInline(Owner.get_noInline)==106 ? 0 : 1;"; + CodeGen code=new CodeGen(null,null,paths,"ReceiverClient",source,123,true,TypeInteger.BOT) + .driver(CodeGen.Phase.TypeCheck); + assertEquals("0",Eval2.eval(code,0)); + TestC.run(source,"imported_receivers",paths,TestC.CALL_CONVENTION,null,null,"",-1); + } + + @Test public void classReceiverHasNoNativeArgument() throws Exception { + String source=""" + int base=10; + val calc={i64 a,i64 b,i64 c,i64 d,i64 e,i64 f,i64 g -> + self.base+a+2*b+3*c+4*d+5*e+6*f+7*g; + }; + val callback_noInline={i64 n -> self.base+n;}; + { {i64 -> i64} i64 -> i64 } invoke="C"; + val viaC={i64 n -> invoke(callback_noInline,n);}; + """; + Path build=Path.of("build/objs/receivers"); + Files.createDirectories(build); + Path driver=build.resolve("native_receiver.c"); + Files.writeString(driver,""" + typedef long long (__attribute__((CALL_CONV)) *action_t)(long long); + __attribute__((CALL_CONV)) long long invoke(action_t action, long long n) { return action(n); } + __attribute__((CALL_CONV)) extern long long calc(long long,long long,long long,long long,long long,long long,long long); + __attribute__((CALL_CONV)) extern long long viaC(long long); + int main(void) { return calc(1,2,3,4,5,6,7)!=150 || viaC(5)!=15; } + """); + TestC.run(source,"native_receiver",null,TestC.CALL_CONVENTION, + TestC.CALL_CONVENTION.equals("win64") ? "ms_abi" : "sysv_abi",driver.toString(),"",-1); + } +} |
