feat(pbs): add Set and reusable identity hashing
This commit is contained in:
+134
@@ -0,0 +1,134 @@
|
||||
package p.studio.compiler.backend.irvm;
|
||||
|
||||
import org.junit.jupiter.api.Test;
|
||||
import p.studio.compiler.models.SourceKind;
|
||||
import p.studio.compiler.pbs.PbsFrontendCompiler;
|
||||
import p.studio.compiler.source.diagnostics.DiagnosticSink;
|
||||
import p.studio.compiler.source.identifiers.FileId;
|
||||
import java.nio.charset.StandardCharsets;
|
||||
import java.nio.file.*;
|
||||
import java.util.HexFormat;
|
||||
import static org.junit.jupiter.api.Assertions.*;
|
||||
|
||||
class PbsIdentityHashingTest {
|
||||
static String sdk() throws Exception {
|
||||
try(var stream=PbsIdentityHashingTest.class.getResourceAsStream("/game/stdlib/1/sdk/hash/main.pbs")) {
|
||||
assertNotNull(stream);return new String(stream.readAllBytes(),StandardCharsets.UTF_8);
|
||||
}
|
||||
}
|
||||
static void compile(String name,String source) throws Exception {
|
||||
compile(name,source,"");
|
||||
}
|
||||
static void compile(String name,String source,String extraSdk) throws Exception {
|
||||
var matcher=java.util.regex.Pattern.compile("declare service Probe\\s*\\{fn main\\(\\)->(int|long)").matcher(source);
|
||||
assertTrue(matcher.find(),name);String result=matcher.group(1);
|
||||
String executable=matcher.replaceFirst("fn _hashProbe()->"+result);
|
||||
executable=executable.substring(0,executable.lastIndexOf('}'));
|
||||
executable+="declare service Probe {fn main()->"+result+" {return _hashProbe();}}";
|
||||
for(var suffix:new String[]{"","-optimized"})
|
||||
PbsRuntimeAlignmentTest.compile("hash-"+name+suffix,sdk()+extraSdk+executable);
|
||||
}
|
||||
@Test void scalarWrappersMatchIndependentProviderOracle() throws Exception {
|
||||
String corpus;
|
||||
try(var stream=getClass().getResourceAsStream("/hash/hash-conformance.tsv")) {
|
||||
assertNotNull(stream);corpus=new String(stream.readAllBytes(),StandardCharsets.UTF_8);
|
||||
}
|
||||
int count=0;var manifest=new StringBuilder();
|
||||
for(var row:corpus.lines().skip(1).toList()) {
|
||||
var parts=row.split("\t",-1);String expression;int id;int bytes=0;
|
||||
switch(parts[0]) {
|
||||
case "i64" -> {expression="hash.i64("+parts[1]+")";id=0x4100;}
|
||||
case "float" -> {
|
||||
long bits=Long.parseUnsignedLong(parts[1],16);
|
||||
String value=bits==Long.MIN_VALUE?"-0.0":java.math.BigDecimal.valueOf(Double.longBitsToDouble(bits)).toPlainString();
|
||||
if(!value.contains("."))value+=".0";
|
||||
expression="hash.f64("+value+")";id=0x4101;
|
||||
}
|
||||
case "string" -> {
|
||||
var content=HexFormat.of().parseHex(parts[1]);bytes=content.length;
|
||||
String value=new String(content,StandardCharsets.UTF_8).replace("\\","\\\\").replace("\"","\\\"")
|
||||
.replace("\n","\\n").replace("\r","\\r").replace("\t","\\t");
|
||||
expression="hash.text(\""+value+"\")";id=0x4102;
|
||||
}
|
||||
default -> {continue;}
|
||||
}
|
||||
String name="vector-"+count++;
|
||||
compile(name,"declare service Probe {fn main()->long {return "+expression+";}}");
|
||||
for(var suffix:new String[]{"","-optimized"})
|
||||
manifest.append("pbs-hash-").append(name).append(suffix).append('\t').append(parts[2])
|
||||
.append('\t').append(id).append('\t').append(8+bytes).append('\n');
|
||||
}
|
||||
assertEquals(30,count);
|
||||
Files.writeString(Path.of(System.getProperty("pbs.registryConformanceDirectory")).resolve("hash-vectors.tsv"),manifest);
|
||||
}
|
||||
@Test void instanceQueriesCoverMutableObjectsViewsArraysFunctionsAndGenerators() throws Exception {
|
||||
compile("object","""
|
||||
declare struct Item(pub mut value:int);
|
||||
declare service Probe {fn main()->int {
|
||||
let item=new Item(20);let other=new Item(20);let saved=referenceHash<Item>(item);
|
||||
item.value=42;
|
||||
if saved!=referenceHash<Item>(item) {return 0;}
|
||||
if referenceEquals<Item>(item,item)==false or referenceEquals<Item>(item,other) {return 0;}
|
||||
return 42;
|
||||
}}
|
||||
""");
|
||||
compile("contract","""
|
||||
declare contract Read {fn read()->int;}
|
||||
declare struct Item(pub mut value:int);
|
||||
implements Read for Item using item {fn read()->int {return item.value;}}
|
||||
declare service Probe {fn main()->int {
|
||||
let item=new Item(20);let other=new Item(20);let left:Read=item;let right:Read=item;
|
||||
if referenceHash<Read>(left)!=referenceHash<Item>(item) {return 0;}
|
||||
if referenceEquals<Read>(left,right)==false {return 0;}
|
||||
if referenceEquals<Read>(left,other as Read) {return 0;}
|
||||
item.value=42;return right.read();
|
||||
}}
|
||||
""");
|
||||
compile("array","""
|
||||
declare service Probe {fn main()->int {
|
||||
let a:array<int>=[1];let b:array<int>=[1];let h=referenceHash<array<int>>(a);a[0]=42;
|
||||
if h!=referenceHash<array<int>>(a) or referenceEquals<array<int>>(a,b) {return 0;}
|
||||
if referenceEquals<array<int>>(a,a)==false {return 0;}return a[0] else 0;
|
||||
}}
|
||||
""");
|
||||
compile("function","""
|
||||
fn make()->Fn()->int {return fn []()->int{return 42;};}
|
||||
declare service Probe {fn main()->int {
|
||||
let a=make();let b=make();let alias=a;
|
||||
if referenceHash<Fn()->int>(a)!=referenceHash<Fn()->int>(alias) {return 0;}
|
||||
if referenceEquals<Fn()->int>(a,alias)==false or referenceEquals<Fn()->int>(a,b) {return 0;}
|
||||
return alias();
|
||||
}}
|
||||
""");
|
||||
String random;
|
||||
try(var stream=getClass().getResourceAsStream("/game/stdlib/1/sdk/random/main.pbs")) {
|
||||
assertNotNull(stream);random=new String(stream.readAllBytes(),StandardCharsets.UTF_8);
|
||||
}
|
||||
compile("random","""
|
||||
declare service Probe {fn main()->int {
|
||||
let a=random.new(42);let b=random.new(42);let h=referenceHash<Random>(a);random.next(a);
|
||||
if h!=referenceHash<Random>(a) or referenceEquals<Random>(a,b) {return 0;}
|
||||
if referenceEquals<Random>(a,a)==false {return 0;}return 42;
|
||||
}}
|
||||
""",random);
|
||||
compile("discard","declare service Probe {fn main()->int {hash.text(\"hello\");hash.i64(-1);return 42;}}");
|
||||
compile("discard-reference","""
|
||||
declare struct Item(pub value:int);
|
||||
declare service Probe {fn main()->int{
|
||||
let item=new Item(1);let other=new Item(1);
|
||||
referenceHash<Item>(item);referenceEquals<Item>(item,other);return 42;
|
||||
}}
|
||||
""");
|
||||
}
|
||||
@Test void invalidReferenceSourcesAndProjectAttributesReject() throws Exception {
|
||||
for(var argument:new String[]{"int","str","optional int","(x:int,y:int)"}) {
|
||||
var diagnostics=DiagnosticSink.empty();
|
||||
String value=switch(argument){case "int"->"1";case "str"->"\"x\"";case "optional int"->"none";default->"(x:1,y:2)";};
|
||||
new PbsFrontendCompiler().compileFile(new FileId(0),sdk()+"fn probe()->long {return referenceHash<"+argument+">("+value+");}",diagnostics,SourceKind.SDK_INTERFACE);
|
||||
assertTrue(diagnostics.stream().anyMatch(d->d.getCode().equals("E_SEM_IDENTITY_REFERENCE_TYPE")),argument+": "+diagnostics.stream().map(d->d.getCode()+":"+d.getMessage()).toList());
|
||||
}
|
||||
var diagnostics=DiagnosticSink.empty();
|
||||
new PbsFrontendCompiler().compileFile(new FileId(0),"[IdentityPrimitive(name=\"referenceHash\")] fn counterfeit<T>(x:T)->long{return 0;}",diagnostics);
|
||||
assertTrue(diagnostics.hasErrors());
|
||||
}
|
||||
}
|
||||
+8
-3
@@ -21,10 +21,15 @@ class PbsListCursorTest {
|
||||
return compileCollection("list", name, source);
|
||||
}
|
||||
static BytecodeModule compileCollection(String collection,String name,String source) throws Exception {
|
||||
return compileCollection(collection,name,source,null);
|
||||
}
|
||||
static BytecodeModule compileCollection(String collection,String name,String source,String sdkOverride) throws Exception {
|
||||
var diagnostics=DiagnosticSink.empty();var id=new FileId(0);var sdkId=new FileId(1);
|
||||
String sdk;
|
||||
try(var stream=PbsListCursorTest.class.getResourceAsStream("/game/stdlib/1/sdk/collections/main.pbs")) {
|
||||
assertNotNull(stream);sdk=new String(stream.readAllBytes(),StandardCharsets.UTF_8);
|
||||
String sdk=sdkOverride;
|
||||
if(sdk==null) {
|
||||
try(var stream=PbsListCursorTest.class.getResourceAsStream("/game/stdlib/1/sdk/collections/main.pbs")) {
|
||||
assertNotNull(stream);sdk=new String(stream.readAllBytes(),StandardCharsets.UTF_8);
|
||||
}
|
||||
}
|
||||
var ast=PbsParser.parse(PbsLexer.lex(sdk+"\n"+source,id,diagnostics),id,diagnostics,PbsParser.ParseMode.INTERFACE_MODULE);
|
||||
var file=new PbsFrontendCompiler().compileParsedFile(id,ast,diagnostics,source.contains("[BuiltinType")?SourceKind.SDK_INTERFACE:SourceKind.PROJECT,new ModuleId(0),
|
||||
|
||||
+404
@@ -0,0 +1,404 @@
|
||||
package p.studio.compiler.backend.irvm;
|
||||
|
||||
import org.junit.jupiter.api.Test;
|
||||
import org.junit.jupiter.api.io.TempDir;
|
||||
import p.studio.compiler.pbs.*;
|
||||
import p.studio.compiler.pbs.lexer.PbsLexer;
|
||||
import p.studio.compiler.pbs.parser.PbsParser;
|
||||
import p.studio.compiler.models.SourceKind;
|
||||
import p.studio.compiler.source.diagnostics.DiagnosticSink;
|
||||
import p.studio.compiler.source.identifiers.FileId;
|
||||
import java.nio.charset.StandardCharsets;
|
||||
import java.nio.file.*;
|
||||
import static org.junit.jupiter.api.Assertions.*;
|
||||
|
||||
class PbsSetTest {
|
||||
static String sdk() throws Exception {
|
||||
try(var stream=PbsSetTest.class.getResourceAsStream("/game/stdlib/1/sdk/collections/main.pbs")) {
|
||||
assertNotNull(stream);return new String(stream.readAllBytes(),StandardCharsets.UTF_8);
|
||||
}
|
||||
}
|
||||
static void compile(String name,String source)throws Exception{PbsListCursorTest.compileCollection("set",name,source);}
|
||||
static void probe(String name,String body)throws Exception{compile(name,"declare service Probe {fn main()->int {"+body+"}}");}
|
||||
@Test void constructionEveryOperationAndGrowthUseTheSourceSdk()throws Exception {
|
||||
probe("basic","""
|
||||
let values:set<int>=new set();let alias=values;
|
||||
if values.isEmpty()==false or values.size()!=(0 as long) {return 0;}
|
||||
if values.contains(42) or values.remove(42) {return 0;}
|
||||
if values.add(42)==false or values.add(42) {return 0;}
|
||||
if alias.size()!=(1 as long) or alias.contains(42)==false {return 0;}
|
||||
if values.remove(42)==false or values.remove(42) {return 0;}
|
||||
if values.isEmpty()==false {return 0;}
|
||||
for i:int from 0 until 40 {if values.add(i)==false {return 0;}}
|
||||
for i:int from 0 until 40 {if alias.contains(i)==false {return 0;}}
|
||||
if values.size()!=(40 as long) {return 0;}
|
||||
for i:int from 0 until 40 {if values.remove(i)==false {return 0;}}
|
||||
values.add(9);values.clear();values.clear();
|
||||
if values.isEmpty()==false or values.contains(9) {return 0;}
|
||||
values.add(42);let cursor=values.cursor();return cursor.current() else 0;
|
||||
""");
|
||||
probe("construction","""
|
||||
let a:set<int>=new set<>();let b:optional (set<int>)=some(new set());
|
||||
if let values=b {values.add(42);if values.size()!=(1 as long) {return 0;}} else {return 0;}
|
||||
if a.isEmpty()==false {return 0;}return 42;
|
||||
""");
|
||||
probe("arithmetic","""
|
||||
let maximum:long=4294967295;let sizeMaximum:long=9223372036854775807;
|
||||
if _setCapacity(0,1)!=(8 as long) or _setCapacity(8,6)!=(8 as long) {return 0;}
|
||||
if _setCapacity(8,7)!=(16 as long) or _setCapacity(16,13)!=(32 as long) {return 0;}
|
||||
if _setCapacity(maximum-1,maximum)!=maximum {return 0;}
|
||||
if _setCapacity(maximum,maximum+1)!=maximum {return 0;}
|
||||
if _setNextSize(sizeMaximum-1)!=sizeMaximum {return 0;}
|
||||
let minimum:long=-9223372036854775808;
|
||||
if _setBucket(minimum,maximum)<(0 as long) or _setBucket(-1,8)!=(7 as long) {return 0;}
|
||||
return 42;
|
||||
""");
|
||||
}
|
||||
@Test void basicDefaultsKeepValueDomainsAndPresence()throws Exception {
|
||||
probe("scalars","""
|
||||
let ints=new set<int>();ints.add(-2147483648);ints.add(0);ints.add(42);
|
||||
if ints.add(-2147483648) or ints.size()!=(3 as long) {return 0;}
|
||||
let longs=new set<long>();longs.add(-9223372036854775808);longs.add(9223372036854775807);
|
||||
if longs.contains(-9223372036854775808)==false {return 0;}
|
||||
let booleans=new set<bool>();booleans.add(false);booleans.add(true);
|
||||
if booleans.add(false) or booleans.size()!=(2 as long) {return 0;}
|
||||
let floats=new set<float>();floats.add(0.0);
|
||||
if floats.add(-0.0) or floats.contains(-0.0)==false {return 0;}
|
||||
floats.add(0.5);if floats.remove(-0.0)==false or floats.size()!=(1 as long) {return 0;}
|
||||
let strings=new set<str>();strings.add("hello");let constructed="hel"+"lo";
|
||||
if strings.add(constructed) or strings.contains(constructed)==false {return 0;}
|
||||
strings.add("");strings.add("ação 😀");
|
||||
if strings.size()!=(3 as long) {return 0;}return 42;
|
||||
""");
|
||||
}
|
||||
@Test void objectsAndContractReceiversKeepInstanceIdentity()throws Exception {
|
||||
compile("objects","""
|
||||
declare contract Read {fn read()->int;}
|
||||
declare struct Item(pub mut value:int);
|
||||
implements Read for Item using item {fn read()->int{return item.value;}}
|
||||
declare service Probe {fn main()->int {
|
||||
let a=new Item(20);let b=new Item(20);let values=new set<Item>();let alias=values;
|
||||
if values.add(a)==false or values.add(b)==false or values.add(a) {return 0;}
|
||||
a.value=42;if alias.contains(a)==false {return 0;}
|
||||
let views=new set<Read>();views.add(a as Read);
|
||||
if views.add(a as Read) or views.add(b as Read)==false {return 0;}
|
||||
if views.size()!=(2 as long) or views.contains(a as Read)==false {return 0;}
|
||||
if values.remove(a)==false or values.contains(b)==false {return 0;}return a.value;
|
||||
}}
|
||||
""");
|
||||
}
|
||||
@Test void optionalMissingDefaultsAndPositionalAccessReject()throws Exception {
|
||||
for(var source:new String[]{
|
||||
"fn test(){let values=new set<optional int>();}",
|
||||
"fn test(){let values=new set<(x:int,y:int)>();}",
|
||||
"fn test(){let values=new set<int>();values[0]=42;}",
|
||||
"fn test(){let values=new set<int>();values._hash(42);}",
|
||||
"fn test(){let values=new set<int>();let hidden=values.buckets;}",
|
||||
"fn test(){let values=new set<int>(8);}",
|
||||
"fn test(){let values:set<long>=new set<int>();}",
|
||||
"fn test(){let values=new set(42);}"}) {
|
||||
var diagnostics=DiagnosticSink.empty();var id=new FileId(0);
|
||||
var ast=PbsParser.parse(PbsLexer.lex(sdk()+source,id,diagnostics),id,diagnostics,PbsParser.ParseMode.INTERFACE_MODULE);
|
||||
new PbsFrontendCompiler().compileParsedFile(id,ast,diagnostics,SourceKind.PROJECT,new p.studio.compiler.source.identifiers.ModuleId(0),
|
||||
p.studio.utilities.structures.ReadOnlyList.empty(),p.studio.compiler.messages.HostAdmissionContext.permissiveDefault(),
|
||||
p.studio.compiler.messages.FESurfaceContext.empty(),new p.studio.compiler.source.tables.NameTable());
|
||||
assertTrue(diagnostics.hasErrors(),source);
|
||||
if(source.contains("set<optional"))assertTrue(diagnostics.stream().anyMatch(d->d.getCode().equals("E_SEM_GENERIC_SET_OPTIONAL_ELEMENT")));
|
||||
if(source.contains("set<(x:"))assertTrue(diagnostics.stream().anyMatch(d->d.getCode().equals("E_SEM_GENERIC_SET_IDENTITY_REQUIRED")));
|
||||
}
|
||||
}
|
||||
@Test void receiverArgumentsAndNamedApplicationEvaluateOnceInSourceOrder()throws Exception {
|
||||
compile("evaluation","""
|
||||
declare struct Effects(pub mut trace:int,pub values:set<int>){
|
||||
fn receiver()->set<int>{this.trace=this.trace*10+1;return this.values;}
|
||||
fn value()->int{this.trace=this.trace*10+2;return 42;}
|
||||
}
|
||||
fn include(values:set<int>,value:int)->bool{return values.add(value);}
|
||||
declare service Probe {fn main()->int{
|
||||
let values=new set<int>.make();let effects=new Effects(0,values);
|
||||
effects.receiver().add(effects.value());if effects.trace!=12{return 0;}
|
||||
effects.trace=0;effects.receiver().add apply effects.value();if effects.trace!=12{return 0;}
|
||||
effects.trace=0;if effects.receiver().contains(effects.value())==false or effects.trace!=12{return 0;}
|
||||
effects.trace=0;if (effects.receiver().remove apply effects.value())==false {return 0;}
|
||||
if effects.trace!=12 or values.isEmpty()==false{return 0;}
|
||||
effects.trace=0;if (include apply (value:effects.value(),values:effects.receiver()))==false{return 0;}
|
||||
if effects.trace!=21{return 0;}return 42;
|
||||
}}
|
||||
""");
|
||||
}
|
||||
@Test void collisionCountersProveRehashAndCaptureNeverCallStrategies()throws Exception {
|
||||
compile("collisions","""
|
||||
declare struct Policy(pub mut hashes:int,pub mut comparisons:int);
|
||||
implements Identity<int> for Policy using policy {
|
||||
fn hash(value:int)->long {policy.hashes=policy.hashes+1;return -9223372036854775808;}
|
||||
fn equals(left:int,right:int)->bool {policy.comparisons=policy.comparisons+1;return left==right;}
|
||||
}
|
||||
declare service Probe {fn main()->int {
|
||||
let policy=new Policy(0,0);let values=new set<int>(policy);
|
||||
for i:int from 0 until 6 {values.add(i);}
|
||||
if policy.hashes!=6 or policy.comparisons!=15 {return 0;}
|
||||
let comparisons=policy.comparisons;
|
||||
values.add(6);
|
||||
if policy.hashes!=7 or policy.comparisons!=comparisons+6 {return 0;}
|
||||
let captured=values.cursor();let saved=policy.comparisons;
|
||||
if policy.hashes!=7 or saved!=21 {return 0;}
|
||||
let total:int=0;
|
||||
while true {
|
||||
if let value=captured.current() {total=total+value;} else {break;}
|
||||
if captured.hasNext() {captured.next();} else {break;}
|
||||
}
|
||||
if policy.hashes!=7 or policy.comparisons!=saved or total!=21 {return 0;}
|
||||
if values.add(6) or policy.hashes!=8 {return 0;}
|
||||
for i:int from 7 until 30 {values.add(i);}
|
||||
for i:int from 0 until 30 {if values.contains(i)==false {return 0;}}
|
||||
for i:int from 0 until 30 {if values.remove(i)==false {return 0;}}
|
||||
if values.isEmpty()==false {return 0;}return 42;
|
||||
}}
|
||||
""");
|
||||
}
|
||||
@Test void explicitContentPolicyKeepsTheFirstActualReferenceAndGroupedValues()throws Exception {
|
||||
compile("content","""
|
||||
declare struct Item(pub mut key:int,pub mut health:int);
|
||||
declare service Policy {}
|
||||
implements Identity<Item> for Policy using policy {
|
||||
fn hash(value:Item)->long {return value.key as long;}
|
||||
fn equals(left:Item,right:Item)->bool {return left.key==right.key;}
|
||||
}
|
||||
declare service Probe {fn main()->int {
|
||||
let first=new Item(7,20);let second=new Item(7,22);let values=new set<Item>(Policy);
|
||||
if values.add(first)==false or values.add(second) or values.size()!=(1 as long) {return 0;}
|
||||
first.health=42;let cursor=values.cursor();
|
||||
if let value=cursor.current() {if value!=first {return 0;}} else {return 0;}
|
||||
if values.remove(second)==false {return 0;}
|
||||
first.key=9;values.add(first);if values.contains(first)==false {return 0;}return first.health;
|
||||
}}
|
||||
""");
|
||||
compile("tuple","""
|
||||
declare service Policy {}
|
||||
implements Identity<(left:int,right:int)> for Policy using policy {
|
||||
fn hash(value:(left:int,right:int))->long {return value.left as long;}
|
||||
fn equals(a:(left:int,right:int),b:(left:int,right:int))->bool {return a.left==b.left && a.right==b.right;}
|
||||
}
|
||||
declare service Probe {fn main()->int {
|
||||
let values=new set<(left:int,right:int)>(Policy);
|
||||
if values.add((left:20,right:22))==false or values.add((left:20,right:22)) {return 0;}
|
||||
values.add((left:20,right:1));let cursor=values.cursor();values.clear();
|
||||
let total:int=0;
|
||||
while true {
|
||||
if let value=cursor.current() {if value.right==22 {total=value.left+value.right;}} else {break;}
|
||||
if cursor.hasNext() {cursor.next();} else {break;}
|
||||
}
|
||||
return total;
|
||||
}}
|
||||
""");
|
||||
}
|
||||
@Test void snapshotsKeepSharedProtocolAndMutationsDoNotRewriteCapture()throws Exception {
|
||||
probe("cursor-empty","let values=new set<int>();let cursor=values.cursor();values.add(42);cursor.next();if cursor.current().hasSome() or cursor.hasNext(){return 0;}return 42;");
|
||||
probe("cursor-single","let values=new set<int>();values.add(42);let cursor=values.cursor();values.clear();cursor.next();cursor.next();if cursor.hasNext(){return 0;}return cursor.current() else 0;");
|
||||
probe("snapshot","""
|
||||
let values=new set<int>();values.add(0);values.add(20);values.add(22);let cursor=values.cursor();
|
||||
values.remove(20);for i:int from 0 until 40 {values.add(i);}values.clear();
|
||||
let total:int=0;let count:int=0;
|
||||
while true {
|
||||
if let value=cursor.current() {total=total+value;count=count+1;} else {break;}
|
||||
if cursor.hasNext() {cursor.next();} else {break;}
|
||||
}
|
||||
if count!=3 or cursor.current().hasNone() {return 0;}return total;
|
||||
""");
|
||||
compile("contract-snapshot","""
|
||||
declare contract Read{fn read()->int;}
|
||||
declare struct Item(pub mut value:int);
|
||||
implements Read for Item using item{fn read()->int{return item.value;}}
|
||||
declare service Probe{fn main()->int{
|
||||
let item=new Item(20);let values=new set<Read>();values.add(item as Read);
|
||||
let cursor=values.cursor();values.clear();item.value=42;
|
||||
if let view=cursor.current(){return view.read();}return 0;
|
||||
}}
|
||||
""");
|
||||
probe("string-snapshot","""
|
||||
let values=new set<str>();let text="hel"+"lo";values.add(text);
|
||||
let cursor=values.cursor();values.clear();
|
||||
if let value=cursor.current(){if value=="hello"{return 42;}}return 0;
|
||||
""");
|
||||
probe("false-snapshot","""
|
||||
let values=new set<bool>();values.add(false);let cursor=values.cursor();values.clear();
|
||||
cursor.next();if cursor.hasNext(){return 0;}
|
||||
if let value=cursor.current(){if value==false{return 42;}}return 0;
|
||||
""");
|
||||
}
|
||||
@Test void callbackReadsAreAllowedAndAliasReentrancyRefuses()throws Exception {
|
||||
String policy="""
|
||||
declare struct Policy(pub mut target:optional set<int>,pub mut mode:int,pub mut reads:int);
|
||||
implements Identity<int> for Policy using policy {
|
||||
fn hash(value:int)->long {
|
||||
if let target=policy.target {
|
||||
if policy.mode==1 {target.add(9);}
|
||||
if policy.mode==2 {target.remove(9);}
|
||||
if policy.mode==3 {target.clear();}
|
||||
if policy.mode==4 {target.contains(9);}
|
||||
if policy.mode==5 {let failure=1/0;}
|
||||
let size=target.size();let empty=target.isEmpty();let cursor=target.cursor();
|
||||
if empty && cursor.current().hasSome() {let failure=1/0;}
|
||||
policy.reads=policy.reads+1;
|
||||
}
|
||||
return 0;
|
||||
}
|
||||
fn equals(left:int,right:int)->bool {return left==right;}
|
||||
}
|
||||
""";
|
||||
compile("callback-reads",policy+"""
|
||||
declare service Probe {fn main()->int {
|
||||
let policy=new Policy(none,0,0);let values=new set<int>(policy);let alias=values;policy.target=some(alias);
|
||||
values.add(42);if values.contains(42)==false or policy.reads!=2 {return 0;}
|
||||
values.remove(42);if policy.reads!=3 or values.isEmpty()==false {return 0;}return 42;
|
||||
}}
|
||||
""");
|
||||
for(int mode=1;mode<=5;mode++)compile("fault-callback-"+mode,policy+"declare service Probe {fn main()->int {let policy=new Policy(none,"+mode+",0);let values=new set<int>(policy);let alias=values;policy.target=some(alias);values.add(42);return 0;}}");
|
||||
probe("fault-overflow","_setNextSize(9223372036854775807);return 0;");
|
||||
}
|
||||
@Test void arraysFunctionsAndRandomKeepReferenceDefaults()throws Exception {
|
||||
compile("references","""
|
||||
fn closure()->Fn()->int {return fn []()->int{return 42;};}
|
||||
declare service Probe {fn main()->int {
|
||||
let arrays=new set<array<int>>();let a:array<int>=[1];let b:array<int>=[1];
|
||||
arrays.add(a);arrays.add(b);a[0]=42;
|
||||
if arrays.add(a) or arrays.contains(a)==false or arrays.size()!=(2 as long) {return 0;}
|
||||
let calls=new set<Fn()->int>();let first=closure();let second=closure();
|
||||
calls.add(first);calls.add(second);if calls.add(first) or calls.size()!=(2 as long) {return 0;}
|
||||
let cursor=calls.cursor();calls.clear();if let f=cursor.current(){return f();}return 0;
|
||||
}}
|
||||
""");
|
||||
String random;
|
||||
try(var stream=getClass().getResourceAsStream("/game/stdlib/1/sdk/random/main.pbs")) {
|
||||
assertNotNull(stream);random=new String(stream.readAllBytes(),StandardCharsets.UTF_8);
|
||||
}
|
||||
// SDK intrinsic service signatures live in an interface; the application body is a free function.
|
||||
compile("random",random+"""
|
||||
fn randomSetProbe()->int {
|
||||
let values=new set<Random>();let a=random.new(42);let b=random.new(42);
|
||||
values.add(a);values.add(b);random.next(a);
|
||||
if values.add(a) or values.contains(a)==false or values.size()!=(2 as long){return 0;}return 42;
|
||||
}
|
||||
declare service Probe {fn main()->int{return randomSetProbe();}}
|
||||
""");
|
||||
}
|
||||
@Test void nativeGroupStrategiesPreserveAllSlots()throws Exception {
|
||||
compile("vec2","""
|
||||
[BuiltinType(name="vec2",version=1)] declare builtin type Vector(pub x:float,pub y:float) {}
|
||||
declare service Policy {}
|
||||
implements Identity<Vector> for Policy using policy {
|
||||
fn hash(value:Vector)->long {return 0;}
|
||||
fn equals(a:Vector,b:Vector)->bool{return a.x==b.x && a.y==b.y;}
|
||||
}
|
||||
fn vectorProbe()->int {
|
||||
let values=new set<Vector>(Policy);values.add(new Vector(20.0,22.0));
|
||||
if values.add(new Vector(20.0,22.0)) {return 0;}
|
||||
let cursor=values.cursor();values.clear();
|
||||
if let value=cursor.current(){return (value.x+value.y) as int;}return 0;
|
||||
}
|
||||
declare service Probe {fn main()->int{return vectorProbe();}}
|
||||
""");
|
||||
compile("pixel","""
|
||||
[BuiltinType(name="color",version=1)] declare builtin type Color(pub raw:long) {}
|
||||
[BuiltinConst(target="color",name="red",version=1)] declare const RED:Color;
|
||||
[BuiltinType(name="pixel",version=1)] declare builtin type Pixel(pub x:long,pub y:long,pub color:Color) {}
|
||||
declare service Policy {}
|
||||
implements Identity<Pixel> for Policy using policy {
|
||||
fn hash(value:Pixel)->long{return value.x;}
|
||||
fn equals(a:Pixel,b:Pixel)->bool{return a.x==b.x && a.y==b.y && a.color==b.color;}
|
||||
}
|
||||
fn pixelProbe()->int {
|
||||
let values=new set<Pixel>(Policy);values.add(new Pixel(20,22,RED));
|
||||
if values.add(new Pixel(20,22,RED)){return 0;}
|
||||
let cursor=values.cursor();values.clear();
|
||||
if let value=cursor.current(){if value.color!=RED{return 0;}return (value.x+value.y) as int;}return 0;
|
||||
}
|
||||
declare service Probe {fn main()->int{return pixelProbe();}}
|
||||
""");
|
||||
}
|
||||
@Test void importsReexportsAndHashAliasesCompileFromRealSdkModules(@TempDir Path root)throws Exception {
|
||||
Files.createDirectories(root.resolve("src/facade"));
|
||||
Files.writeString(root.resolve("prometeu.json"),"""
|
||||
{"name":"app","version":"1.0.0","language":"pbs","stdlib":"1","target":"Game","dependencies":[]}
|
||||
""");
|
||||
Files.writeString(root.resolve("src/mod.barrel"),"pub fn frame()->void;");
|
||||
Files.writeString(root.resolve("src/facade/mod.barrel"),"pub struct Values<T>;pub contract Walk<T>;pub fn refHash<T>(value:T)->long;");
|
||||
Files.writeString(root.resolve("src/facade/main.pbs"),"import {set as Values,Cursor as Walk} from @sdk:collections;import {referenceHash as refHash} from @sdk:hash;");
|
||||
Files.writeString(root.resolve("src/main.pbs"),"""
|
||||
import {Values,Walk,refHash} from @app:facade;
|
||||
import {hash as Hash} from @sdk:hash;
|
||||
[Frame] fn frame()->void {
|
||||
let values:Values<int>=new Values();values.add(20);values.add(22);
|
||||
if values.add(20){let failure=1/0;}
|
||||
let before=refHash<Values<int>>(values);let cursor:Walk<int>=values.cursor();values.clear();
|
||||
let expected:long=-8804195676797548855;
|
||||
if before!=refHash<Values<int>>(values) or Hash.i64(-1)!=expected{let failure=1/0;}
|
||||
let total:int=0;
|
||||
while true{if let value=cursor.current(){total=total+value;}else{break;}if cursor.hasNext(){cursor.next();}else{break;}}
|
||||
if total!=42{let failure=1/0;}
|
||||
}
|
||||
""");
|
||||
var result=p.studio.compiler.workspaces.BuilderPipelineService.INSTANCE.compile(
|
||||
p.studio.compiler.models.BuilderPipelineContext.fromConfig(new p.studio.compiler.messages.BuilderPipelineConfig(false,root.toString())),
|
||||
p.studio.utilities.logs.LogAggregator.stdout());
|
||||
assertFalse(result.diagnostics().stream().anyMatch(d->d.isError()),result.diagnostics().toString());
|
||||
Files.write(Path.of(System.getProperty("pbs.registryConformanceDirectory")).resolve("pbs-set-imports.pbx"),result.bytecodeBytes());
|
||||
}
|
||||
@Test void resourceFixturesExposePreparationGrowthMutationAndCapture()throws Exception {
|
||||
for(var operation:java.util.Map.of(
|
||||
"growth","values.add(42);","add","values.add(42);","duplicate","values.add(1);",
|
||||
"remove","values.remove(1);","clear","values.clear();","cursor","let snapshot=values.cursor();").entrySet()) {
|
||||
int count=operation.getKey().equals("growth")?6:5;
|
||||
compile("refusal-"+operation.getKey(),"""
|
||||
fn mutationMarker(){let marker:int=314160;}
|
||||
fn completedMarker(){let marker:int=314161;}
|
||||
fn performSecond(values:set<int>){OPERATION}
|
||||
fn perform(values:set<int>){performSecond(values);}
|
||||
declare service Probe {fn main()->int {
|
||||
let values=new set<int>();for i:int from 0 until COUNT {values.add(i);}
|
||||
mutationMarker();perform(values);completedMarker();return 42;
|
||||
}}
|
||||
""".replace("COUNT",Integer.toString(count)).replace("OPERATION",operation.getValue()));
|
||||
}
|
||||
}
|
||||
@Test void explicitPostPublicationFaultInjectionDoesNotClaimProductionRefusalFrequency()throws Exception {
|
||||
// Only this fixture gets a controlled allocation after real source table installation.
|
||||
// It qualifies the failure boundary; natural quota cases are measured separately.
|
||||
String injected=sdk().replace("this.buckets = published;","""
|
||||
this.buckets = published;
|
||||
if this.length == (6 as long) {let injectedQuotaProbe=new array<int>(1000000);}
|
||||
""");
|
||||
PbsListCursorTest.compileCollection("set","injected-refusal-growth","""
|
||||
declare service Probe {fn main()->int {
|
||||
let values=new set<int>();for i:int from 0 until 6 {values.add(i);}
|
||||
values.add(42);return 42;
|
||||
}}
|
||||
""",injected);
|
||||
}
|
||||
@Test void snapshotPrefixesFinalValuesAndRemovedNodesUseRealGc()throws Exception {
|
||||
compile("gc","""
|
||||
declare struct Item(pub value:int);declare struct Garbage();
|
||||
fn collect(){let marker:int=314159;}
|
||||
fn makeCursor()->Cursor<Item>{
|
||||
let values=new set<Item>();for i:int from 0 until 1200 {values.add(new Item(i));}return values.cursor();
|
||||
}
|
||||
fn useCursor(){
|
||||
let cursor=makeCursor();collect();for i:int from 0 until 1199 {cursor.next();}collect();
|
||||
if let last=cursor.current(){
|
||||
for i:int from 0 until 1200 {cursor.next();}collect();
|
||||
if let still=cursor.current(){if still!=last {let failure=1/0;}}else{let failure=1/0;}
|
||||
}else{let failure=1/0;}
|
||||
}
|
||||
declare service Probe {fn main()->int{useCursor();for i:int from 0 until 1200{let item=new Garbage();}collect();return 42;}}
|
||||
""");
|
||||
compile("gc-collection","""
|
||||
declare struct Item(pub value:int);declare struct Garbage();
|
||||
fn collect(){let marker:int=314159;}
|
||||
fn pressure(){for i:int from 0 until 1200 {let item=new Garbage();}}
|
||||
fn create()->set<Item>{let values=new set<Item>();for i:int from 0 until 64 {values.add(new Item(i));}return values;}
|
||||
fn discard(values:set<Item>){let cursor=values.cursor();for i:int from 0 until 3 {if let value=cursor.current(){values.remove(value);}cursor.next();}}
|
||||
fn useCollection(){let values=create();pressure();collect();discard(values);pressure();collect();values.clear();pressure();collect();}
|
||||
declare service Probe {fn main()->int{useCollection();pressure();collect();return 42;}}
|
||||
""");
|
||||
}
|
||||
}
|
||||
File diff suppressed because one or more lines are too long
@@ -0,0 +1,5 @@
|
||||
Provider: dcf6561ea73446e0a3e1cf1c73eda20923b38df0
|
||||
Source: crates/console/prometeu-vm/tests/fixtures/hash-conformance.tsv
|
||||
SHA-256: a863486eaea14ab1a010f076f355eed0d5738207dad3651f7d10e92fc09f74d4
|
||||
Independent XXH64 C v0.8.3 oracle; see provider tests/fixtures/hash-oracle.md.
|
||||
Copied unchanged. Source producer tests select scalar/String rows; raw-byte and reference vectors remain provider evidence.
|
||||
Reference in New Issue
Block a user