feat(pbs): add Set and reusable identity hashing

This commit is contained in:
2026-10-25 12:15:13 +00:00
parent 632ba6d0d6
commit 8105604f92
59 changed files with 4190 additions and 34 deletions
@@ -73,7 +73,11 @@ public final class PbsContractTypes {
declarations.put(name, declaration);
scopes.computeIfAbsent(declaration.span().getFileId(), ignored -> new HashMap<>()).put(name, declaration);
}
if (declaration instanceof PbsAst.ImplementsDecl implementation && implementations.stream().noneMatch(i -> i.span().equals(implementation.span()))) implementations.add(implementation);
// A generic owner family produces several concrete implementations at the
// same source span. Deduplicating by span alone loses all but its first T.
if (declaration instanceof PbsAst.ImplementsDecl implementation && implementations.stream().noneMatch(i ->
i.span().equals(implementation.span())&&key(i.ownerType()).equals(key(implementation.ownerType()))
&&key(i.contractType()).equals(key(implementation.contractType())))) implementations.add(implementation);
}
public PbsAst.TopDecl declaration(PbsAst.TypeRef type) {
@@ -221,7 +221,14 @@ public final class PbsGenericInstantiation {
if (t == null) return null;
var rewritten = super.type(t);
var d = types.declaration(t);
if (t.kind() != PbsAst.TypeRefKind.SIMPLE || d == null || PbsContractTypes.applicationOrigin(d) != null) return rewritten;
if (t.kind() != PbsAst.TypeRefKind.SIMPLE || d == null) return rewritten;
var origin=PbsContractTypes.applicationOrigin(d);
if(origin!=null) {
// A concrete argument still belongs to its defining module.
// The generic function's module must import that application.
dependency(definition,origin.declaration());
return rewritten;
}
var alias = nominalBinding(d);
types.index(new PbsAst.TypeBindingDecl(alias, d, definition));
var file = concrete.containsKey(definition.getFileId()) ? definition.getFileId() : sources.getFirst().ast().span().getFileId();
@@ -237,8 +244,8 @@ public final class PbsGenericInstantiation {
error("ARITY", name(template)+" requires "+parameters(template).size()+" explicit type argument(s)", site);
return null;
}
if (PbsSdkCollections.isIndexedCollection(template) && PbsSdkCollections.directOptional(arguments.getFirst())) {
error(PbsSdkCollections.isLinked(template) ? "LINKED_OPTIONAL_ELEMENT" : "LIST_OPTIONAL_ELEMENT",
if (PbsSdkCollections.isCollection(template) && PbsSdkCollections.directOptional(arguments.getFirst())) {
error(PbsSdkCollections.isSet(template)?"SET_OPTIONAL_ELEMENT":PbsSdkCollections.isLinked(template) ? "LINKED_OPTIONAL_ELEMENT" : "LIST_OPTIONAL_ELEMENT",
"SDK " + name(template) + "<T> does not permit a directly optional element", site);
return null;
}
@@ -535,6 +542,11 @@ public final class PbsGenericInstantiation {
if (s instanceof PbsAst.ReturnStatement r) return new PbsAst.ReturnStatement(expression(r.value(), result), r.span());
if (s instanceof PbsAst.AssignStatement a) {
var target = a.target().expression();
if(target==null&&!a.target().pathSegments().isEmpty()) {
target=a.target().rootName().equals("this")?new PbsAst.ThisExpr(a.target().span())
:new PbsAst.IdentifierExpr(a.target().rootName(),a.target().span());
for(var member:a.target().pathSegments())target=new PbsAst.MemberExpr(target,member,a.target().span());
}
var expected = target == null ? locals.get(a.target().rootName()) : infer(target);
return new PbsAst.AssignStatement(a.target(), a.operator(), expression(a.value(), expected), a.span());
}
@@ -543,6 +555,10 @@ public final class PbsGenericInstantiation {
@Override public PbsAst.Expression expression(PbsAst.Expression e, PbsAst.TypeRef expected) {
if (e != null) { budget.visit(e.span(), chain.size()); budget.store(e.span(), 64); }
if(symbolicProbe&&e instanceof PbsAst.MemberExpr member) {
var receiver=infer(member.receiver());
if(receiver!=null)requiredShapes.add(receiver.name());
}
if (e instanceof PbsAst.CallExpr c) {
var callee = expression(c.callee());
var signatures = callableSignatures(callee);
@@ -631,8 +647,14 @@ public final class PbsGenericInstantiation {
else { error("CONTEXT", "Construction of "+n.typeName()+" requires explicit arguments or an expected application", n.span()); return n; }
}
var concreteType = type(applied);
if(PbsSdkCollections.isSet(s)&&n.arguments().isEmpty()&&!symbolicProbe) {
var owner=types.declaration(concreteType);
var origin=PbsContractTypes.applicationOrigin(owner);
if(origin!=null&&!PbsSdkCollections.hasDefaultIdentity(origin.arguments().getFirst(),types))
error("SET_IDENTITY_REQUIRED","This Set element type requires an explicit Identity<T> strategy",n.span());
}
if (symbolicProbe) requiredShapes.add(concreteType.name());
var constructor = PbsSdkCollections.isIndexedCollection(s) && n.ctorName() == null ? "make" : n.ctorName();
var constructor = PbsSdkCollections.isCollection(s) && n.ctorName() == null ? "make" : n.ctorName();
if (constructor != null && s.ctors().stream().noneMatch(c -> c.name().equals(constructor)
&& c.parameters().size() == n.arguments().size())) {
error("CONSTRUCTOR_ARITY", "No constructor '" + constructor + "' with "
@@ -86,13 +86,30 @@ final class PbsGenericTemplateValidator {
}
@Override public PbsAst.Statement statement(PbsAst.Statement s) {
if (s instanceof PbsAst.LetStatement l) {
if(s instanceof PbsAst.IfStatement branch&&branch.bindingName()!=null) {
var optional=infer(branch.condition(),null);
while(optional!=null&&optional.kind()==PbsAst.TypeRefKind.GROUP)optional=optional.inner();
var previous=locals;locals=new HashMap<>(locals);
try {
if(optional!=null&&optional.kind()==PbsAst.TypeRefKind.OPTIONAL)locals.put(branch.bindingName(),optional.inner());
block(branch.thenBlock());
} finally {locals=previous;}
if(branch.elseIf()!=null)statement(branch.elseIf());
if(branch.elseBlock()!=null)block(branch.elseBlock());
return s;
} else if (s instanceof PbsAst.LetStatement l) {
var actual = infer(l.initializer(), l.explicitType());
checkCompatible(actual, l.explicitType(), l.span());
locals.put(l.name(), l.explicitType() == null ? actual : l.explicitType());
} else if (s instanceof PbsAst.ReturnStatement r) checkCompatible(infer(r.value(), result), result, r.span());
else if (s instanceof PbsAst.AssignStatement a) {
var target = a.target().expression() == null ? locals.get(a.target().rootName()) : infer(a.target().expression(), null);
var expression=a.target().expression();
if(expression==null&&!a.target().pathSegments().isEmpty()) {
expression=a.target().rootName().equals("this")?new PbsAst.ThisExpr(a.target().span())
:new PbsAst.IdentifierExpr(a.target().rootName(),a.target().span());
for(var member:a.target().pathSegments())expression=new PbsAst.MemberExpr(expression,member,a.target().span());
}
var target = expression == null ? locals.get(a.target().rootName()) : infer(expression, null);
// Indexed writes accept the element, while indexed reads are optional.
if(a.target().expression() instanceof PbsAst.IndexExpr && target!=null && target.kind()==PbsAst.TypeRefKind.OPTIONAL)
target=target.inner();
@@ -15,6 +15,26 @@ public final class PbsSdkCollections {
public static boolean isIndexedCollection(PbsAst.TopDecl declaration) {
return isList(declaration) || isLinked(declaration);
}
public static boolean isSet(PbsAst.TopDecl declaration) {
return declaration instanceof PbsAst.StructDecl s && attribute(s.attributes(), "SdkSet") != null;
}
public static boolean isCollection(PbsAst.TopDecl declaration) {
return isIndexedCollection(declaration)||isSet(declaration);
}
public static boolean hasDefaultIdentity(PbsAst.TypeRef type,PbsContractTypes types) {
while(type!=null&&type.kind()==PbsAst.TypeRefKind.GROUP)type=type.inner();
if(type==null)return false;
if(type.kind()==PbsAst.TypeRefKind.ARRAY||type.kind()==PbsAst.TypeRefKind.FN)return true;
if(type.kind()!=PbsAst.TypeRefKind.SIMPLE)return false;
if(java.util.Set.of("int","long","bool","float","str").contains(type.name()))return true;
var declaration=types.declaration(type);
if(declaration instanceof PbsAst.StructDecl||declaration instanceof PbsAst.ServiceDecl||declaration instanceof PbsAst.ContractDecl)return true;
if(declaration instanceof PbsAst.BuiltinTypeDecl builtin) {
var binding=builtin.attributes().stream().filter(a->a.name().equals("BuiltinType")).findFirst().orElse(null);
return binding!=null&&argument(binding,"name").equals("Random");
}
return false;
}
public static PbsAst.Attribute attribute(ReadOnlyList<PbsAst.Attribute> attributes, String name) {
return attributes.stream().filter(a -> a.trustedSdkOrigin() && a.name().equals(name)).findFirst().orElse(null);
}
@@ -61,7 +61,11 @@ final class PbsExecutableBodyLowerer {
var binding = functionDecl.attributes().stream().filter(a -> "IntrinsicCall".equals(a.name())).findFirst();
final boolean terminated;
var storageBinding = p.studio.compiler.pbs.PbsSdkCollections.attribute(functionDecl.attributes(), "StoragePrimitive");
if (storageBinding != null) {
var identityBinding = p.studio.compiler.pbs.PbsSdkCollections.attribute(functionDecl.attributes(), "IdentityPrimitive");
if (identityBinding != null) {
lowerIdentityPrimitive(functionDecl,identityBinding,context);
terminated = true;
} else if (storageBinding != null) {
lowerStoragePrimitive(functionDecl,storageBinding,context);
terminated = true;
} else if (binding.isPresent()) {
@@ -1613,6 +1617,61 @@ final class PbsExecutableBodyLowerer {
span);
}
private void lowerIdentityPrimitive(PbsAst.FunctionDecl function, PbsAst.Attribute binding, PbsExecutableLoweringContext c) {
var operation=p.studio.compiler.pbs.PbsSdkCollections.argument(binding,"name");
boolean equality=operation.equals("referenceEquals")||operation.equals("defaultEquals");
boolean fallback=operation.equals("defaultHash")||operation.equals("defaultEquals");
if(!fallback&&!operation.equals("referenceHash")&&!operation.equals("referenceEquals"))
throw new IllegalArgumentException("Unknown identity binding: "+operation);
var type=PbsRuntimeTypes.unwrap(function.parameters().getFirst().typeRef());
var span=function.span();int width=c.types().slots(type);
boolean reference=c.types().identitySource(type);
var scalar=c.types().canonical(type);
if(!reference&&(!fallback||!java.util.Set.of("int","long","bool","float","str").contains(scalar))) {
// Explicit strategy Sets instantiate this unreachable default branch too.
// Public reference queries always reject ineligible source applications.
if(!fallback) p.studio.compiler.source.diagnostics.Diagnostics.error(c.diagnostics(),
"E_SEM_IDENTITY_REFERENCE_TYPE","Reference identity requires Struct, Array, Fn, contract or Random",
function.applicationOrigin()==null?span:function.applicationOrigin().requestedAt());
c.instructions().add(new IRBackendExecutableFunction.Instruction(IRBackendExecutableFunction.InstructionKind.TRAP,"",null,null,span));
return;
}
emitLoadLocalSlots(0,width*(equality?2:1),span,c);
if(reference) {
var source=c.types().registryType(type);
c.instructions().add(new IRBackendExecutableFunction.Instruction(IRBackendExecutableFunction.InstructionKind.REGISTRY,
null,"",null,null,null,"","",width*(equality?2:1),1,span,
new IRRegistryInstruction(equality?REF_IDENTITY_EQ:REF_IDENTITY_HASH,source,equality?source:null,null,0)));
} else if(equality) {
emitBinaryOperatorInstruction("==",span,c);
} else {
String intrinsic;
switch(scalar) {
case "int" -> {identityIntrinsic("math.i32.to_i64",span,c);intrinsic="hash.i64";}
case "long" -> intrinsic="hash.i64";
case "float" -> intrinsic="hash.float";
case "str" -> intrinsic="hash.string";
case "bool" -> {
var zero=c.nextLabel("bool_hash_zero");var done=c.nextLabel("bool_hash_done");
emitJump(IRBackendExecutableFunction.InstructionKind.JMP_IF_FALSE,zero,span,c);
emitIdentityLong(1,span,c);emitJump(IRBackendExecutableFunction.InstructionKind.JMP,done,span,c);
emitLabel(zero,span,c);emitIdentityLong(0,span,c);emitLabel(done,span,c);intrinsic="hash.i64";
}
default -> throw new AssertionError(scalar);
}
identityIntrinsic(intrinsic,span,c);
}
c.instructions().add(new IRBackendExecutableFunction.Instruction(IRBackendExecutableFunction.InstructionKind.RET,"",null,null,span));
}
private void identityIntrinsic(String name,Span span,PbsExecutableLoweringContext c) {
c.instructions().add(new IRBackendExecutableFunction.Instruction(IRBackendExecutableFunction.InstructionKind.CALL_INTRINSIC,
"",null,new IRBackendExecutableFunction.IntrinsicCallMetadata(name,1,c.intrinsicIdTable().register(name,1)),1,1,span));
}
private void emitIdentityLong(long value,Span span,PbsExecutableLoweringContext c) {
c.instructions().add(new IRBackendExecutableFunction.Instruction(IRBackendExecutableFunction.InstructionKind.PUSH_I64,
null,"",null,null,null,Long.toString(value),"",null,null,span));
}
private void lowerStoragePrimitive(PbsAst.FunctionDecl function, PbsAst.Attribute binding, PbsExecutableLoweringContext c) {
var operation=p.studio.compiler.pbs.PbsSdkCollections.argument(binding,"name");
var span=function.span();
@@ -1929,13 +1988,19 @@ final class PbsExecutableBodyLowerer {
&& allocation.typeName().equals("array") && allocation.explicitType() == null) continue;
if (listIndex && i==0 && "int".equals(c.types().canonical(actual)) && "long".equals(c.types().canonical(expected))) continue;
if (c.types().shapeKey(actual).equals(c.types().shapeKey(expected))) continue;
if (arguments.get(i) instanceof PbsAst.IntLiteralExpr && "long".equals(c.types().canonical(expected))) continue;
if (integerLiteral(arguments.get(i)) && "long".equals(c.types().canonical(expected))) continue;
if (c.types().isContract(expected) && c.types().contractTypes.implementers(expected).contains(actual.name())) continue;
return false;
}
return true;
}
private static boolean integerLiteral(PbsAst.Expression expression) {
if(expression instanceof PbsAst.GroupExpr group)return integerLiteral(group.expression());
if(expression instanceof PbsAst.UnaryExpr unary&&"-".equals(unary.operator()))return integerLiteral(unary.expression());
return expression instanceof PbsAst.IntLiteralExpr;
}
private void emitStructuredFunction(String name, java.util.List<PbsAst.TypeRef> parameters, PbsAst.TypeRef returnType,
int pops, int pushes, Span span, PbsExecutableLoweringContext c) {
var callableId = c.exactLocalCallable(name, parameters, returnType);
@@ -132,6 +132,14 @@ final class PbsRuntimeTypes {
return "pbs:" + category + ":file" + span.getFileId().getId() + ":" + span.getStart();
}
IRRegistry.TypeRef dynamic() { return builtin(0x15); }
boolean identitySource(PbsAst.TypeRef type) {
var t=unwrap(type);
if(t==null)return false;
return t.kind()==PbsAst.TypeRefKind.ARRAY||t.kind()==PbsAst.TypeRefKind.FN
||contractTypes.declaration(t) instanceof PbsAst.StructDecl
||contractTypes.declaration(t) instanceof PbsAst.ServiceDecl
||isContract(t)||canonical(t).equals("Random");
}
IRRegistry.TypeRef arrayStorage() {
var element = dynamic();
var ref = new IRRegistry.TypeRef("pbs:array-storage");
@@ -685,7 +685,7 @@ final class PbsDeclarationParser {
final String targetSurface) {
for (final var attribute : attributes) {
if ("Doc".equals(attribute.name()) || attribute.trustedSdkOrigin() &&
java.util.Set.of("SdkList", "SdkLinked").contains(attribute.name()) && "struct declarations".equals(targetSurface)) {
java.util.Set.of("SdkList", "SdkLinked", "SdkSet").contains(attribute.name()) && "struct declarations".equals(targetSurface)) {
continue;
}
p.studio.compiler.source.diagnostics.Diagnostics.error(context.diagnostics(),
@@ -724,7 +724,7 @@ final class PbsDeclarationParser {
for (final var attribute : attributes) {
final PbsAst.LifecycleMarker nextMarker;
if ("Doc".equals(attribute.name()) || attribute.trustedSdkOrigin() &&
java.util.Set.of("StoragePrimitive","SdkPrivate").contains(attribute.name())) {
java.util.Set.of("StoragePrimitive","IdentityPrimitive","SdkPrivate").contains(attribute.name())) {
continue;
}
if (!isOrdinaryMode()) {
@@ -759,7 +759,7 @@ public final class PbsEditorialSupportService {
final Map<String, PbsEditorialCompletionCandidate> completions = new LinkedHashMap<>();
var symbolic = symbolicStruct(receiverType);
if (symbolic != null) {
for (var field : symbolic.fields()) if(!p.studio.compiler.pbs.PbsSdkCollections.isIndexedCollection(symbolic)||field.isPublic()) completions.put(field.name(), new PbsEditorialCompletionCandidate(
for (var field : symbolic.fields()) if(!p.studio.compiler.pbs.PbsSdkCollections.isCollection(symbolic)||field.isPublic()) completions.put(field.name(), new PbsEditorialCompletionCandidate(
field.name(), PbsEditorialSymbolKind.FIELD, field.typeRef().surface(), symbolic.name()));
for (var method : symbolic.methods()) if(p.studio.compiler.pbs.PbsSdkCollections.attribute(method.attributes(),"SdkPrivate")==null) completions.put(method.name(), new PbsEditorialCompletionCandidate(
method.name(), PbsEditorialSymbolKind.METHOD, signatureFromFunction(method.name(), method.parameters(),
@@ -778,7 +778,7 @@ public final class PbsEditorialSupportService {
final StructInfo structInfo = model.structs.get(receiverType.name());
if (structInfo != null) {
for (final var field : structInfo.fields().entrySet()) {
if(model.isSdkIndexedCollection(receiverType)&&!field.getValue().isPublic())continue;
if(model.isSdkCollection(receiverType)&&!field.getValue().isPublic())continue;
completions.put(field.getKey(), new PbsEditorialCompletionCandidate(
field.getKey(),
PbsEditorialSymbolKind.FIELD,
@@ -74,6 +74,12 @@ final class PbsFlowExpressionAnalyzer {
final PbsAst.Expression expression,
final PbsFlowExpressionContext context) {
var result = analyzeExpressionUnchecked(expression, context);
if (context.use() == ExprUse.VALUE && context.expectedType() != null
&& (context.model().isGenericStruct(result.type()) || context.model().isGenericStruct(context.expectedType()))
&& !typeOps.compatible(result.type(), context.expectedType())) {
p.studio.compiler.source.diagnostics.Diagnostics.error(context.diagnostics(), "E_SEM_GENERIC_TYPE_MISMATCH",
"Generic struct applications require the exact declared type arguments", expression.span());
}
if (context.use() == ExprUse.VALUE && context.expectedType() != null
&& (context.model().isOpaqueBuiltin(result.type()) || context.model().isOpaqueBuiltin(context.expectedType()))
&& !typeOps.compatible(result.type(), context.expectedType())) {
@@ -202,6 +202,10 @@ final class PbsFlowSemanticSupport {
return type != null && p.studio.compiler.pbs.PbsSdkCollections.isIndexedCollection(contractTypes.declaration(
type.sourceType() == null ? PbsAst.TypeRef.simple(type.name(), Span.none()) : type.sourceType()));
}
boolean isSdkCollection(TypeView type) {
return type != null && p.studio.compiler.pbs.PbsSdkCollections.isCollection(contractTypes.declaration(
type.sourceType() == null ? PbsAst.TypeRef.simple(type.name(), Span.none()) : type.sourceType()));
}
boolean isSdkPrivateMember(TypeView type, String member) {
if (type == null) return false;
var declaration = contractTypes.declaration(type.sourceType() == null
@@ -271,6 +275,12 @@ final class PbsFlowSemanticSupport {
type.functionInputs(), type.functionOutput(), contractTypes.key(reference), reference, type.implementers());
}
boolean isGenericStruct(TypeView type) {
return type.kind() == Kind.STRUCT && type.sourceType() != null
&& p.studio.compiler.pbs.PbsContractTypes.applicationOrigin(
contractTypes.declaration(type.sourceType())) != null;
}
TypeView contractView(PbsAst.TypeRef reference) {
var instance = contractTypes.resolve(reference);
if (instance == null) return TypeView.unknown();
@@ -307,3 +307,196 @@ declare struct linked<T>(head: optional _LinkedNode<T>, tail: optional _LinkedNo
return new _SnapshotCursor<T>(captured) as Cursor<T>;
}
}
// Equality policy is independent of private Set storage and reusable by Map.
declare contract Identity<T> {
fn hash(value: T) -> long;
fn equals(left: T, right: T) -> bool;
}
[IdentityPrimitive(name = "defaultHash")]
fn _collectionHash<T>(value: T) -> long { return 0; }
[IdentityPrimitive(name = "defaultEquals")]
fn _collectionEquals<T>(left: T, right: T) -> bool { return false; }
fn _setBucket(hash: long, capacity: long) -> long {
let bucket: long = hash % capacity;
if bucket < (0 as long) { bucket = bucket + capacity; }
return bucket;
}
fn _setNextSize(length: long) -> long {
let maximum: long = 9223372036854775807;
_bounds(length, maximum);
return length + 1;
}
fn _setCapacity(capacity: long, required: long) -> long {
let maximum: long = 4294967295;
if capacity == (0 as long) { return 8; }
if capacity < maximum && required > capacity * (3 as long) / (4 as long) {
let candidate: long = capacity * (2 as long);
if candidate > maximum { return maximum; }
return candidate;
}
return capacity;
}
declare struct _SetNode<T>(pub hash: long, pub value: T, pub mut next: optional _SetNode<T>) {
ctor make(hash: long, value: T, next: optional _SetNode<T>) {
this.hash = hash;
this.value = value;
this.next = next;
}
}
[SdkSet]
declare struct set<T>(buckets: optional array<_SetNode<T>>, length: long, strategy: optional Identity<T>, busy: bool) {
ctor make() {
this.buckets = none;
this.length = 0;
this.strategy = none;
this.busy = false;
}
ctor make(identity: Identity<T>) {
this.buckets = none;
this.length = 0;
this.strategy = some(identity);
this.busy = false;
}
fn size() -> long { return this.length; }
fn isEmpty() -> bool { return this.length == (0 as long); }
[SdkPrivate]
fn _check() { if this.busy { _fail(); } }
[SdkPrivate]
fn _begin() { this._check(); this.busy = true; }
[SdkPrivate]
fn _hash(value: T) -> long {
if let identity = this.strategy { return identity.hash(value); }
return _collectionHash<T>(value);
}
[SdkPrivate]
fn _equals(left: T, right: T) -> bool {
if let identity = this.strategy { return identity.equals(left, right); }
return _collectionEquals<T>(left, right);
}
[SdkPrivate]
fn _find(hash: long, value: T) -> bool {
if let buckets = this.buckets {
let current: optional _SetNode<T> = buckets[_setBucket(hash, buckets.length)];
while current.hasSome() {
if let node = current {
if node.hash == hash && this._equals(node.value, value) { return true; }
current = node.next;
}
}
}
return false;
}
[SdkPrivate]
fn _rehash(capacity: long) -> array<_SetNode<T>> {
let target: array<_SetNode<T>> = new array<>(capacity);
if let buckets = this.buckets {
let index: long = 0;
while index < buckets.length {
let current: optional _SetNode<T> = buckets[index];
while current.hasSome() {
if let node = current {
let bucket: long = _setBucket(node.hash, capacity);
let copied = new _SetNode<T>(node.hash, node.value, target[bucket]);
target[bucket] = copied;
current = node.next;
}
}
index = index + 1;
}
}
return target;
}
fn contains(value: T) -> bool {
this._begin();
let hash: long = this._hash(value);
let found: bool = this._find(hash, value);
this.busy = false;
return found;
}
fn add(value: T) -> bool {
this._begin();
let hash: long = this._hash(value);
if this._find(hash, value) { this.busy = false; return false; }
let required: long = _setNextSize(this.length);
let capacity: long = 0;
if let buckets = this.buckets { capacity = buckets.length; }
let nextCapacity: long = _setCapacity(capacity, required);
if nextCapacity != capacity {
let target = this._rehash(nextCapacity);
let bucket: long = _setBucket(hash, nextCapacity);
let inserted = new _SetNode<T>(hash, value, target[bucket]);
target[bucket] = inserted;
let published: optional array<_SetNode<T>> = some(target);
this.buckets = published;
} else {
if let buckets = this.buckets {
let bucket: long = _setBucket(hash, capacity);
let inserted = new _SetNode<T>(hash, value, buckets[bucket]);
buckets[bucket] = inserted;
}
}
this.length = required;
this.busy = false;
return true;
}
fn remove(value: T) -> bool {
this._begin();
let hash: long = this._hash(value);
if let buckets = this.buckets {
let bucket: long = _setBucket(hash, buckets.length);
let previous: optional _SetNode<T> = none;
let current: optional _SetNode<T> = buckets[bucket];
while current.hasSome() {
if let node = current {
if node.hash == hash && this._equals(node.value, value) {
let next: optional _SetNode<T> = node.next;
let length: long = this.length - 1;
if let predecessor = previous { predecessor.next = next; }
else {
if let successor = next { buckets[bucket] = successor; }
else { buckets.clear(bucket); }
}
this.length = length;
this.busy = false;
return true;
}
previous = current;
current = node.next;
}
}
}
this.busy = false;
return false;
}
fn clear() {
this._check();
this.buckets = none;
this.length = 0;
}
fn cursor() -> Cursor<T> {
let head: optional _SnapshotNode<T> = none;
if let buckets = this.buckets {
let index: long = 0;
while index < buckets.length {
let current: optional _SetNode<T> = buckets[index];
while current.hasSome() {
if let node = current {
head = some(new _SnapshotNode<T>(node.value, head));
current = node.next;
}
}
index = index + 1;
}
}
return new _SnapshotCursor<T>(head) as Cursor<T>;
}
}
@@ -1,3 +1,5 @@
pub struct list<T>;
pub contract Cursor<T>;
pub struct linked<T>;
pub struct set<T>;
pub contract Identity<T>;
@@ -0,0 +1,26 @@
[Doc(markdown = """
Runtime Hash-v1 operations. Results preserve all signed long digest bits.
Reference queries validate complete values and observe instance identity.
""")]
declare service hash {
[IntrinsicCall(name = "hash.i64", version = 1)]
fn i64(value: long) -> long;
[IntrinsicCall(name = "hash.float", version = 1)]
fn f64(value: float) -> long;
[IntrinsicCall(name = "hash.string", version = 1)]
fn text(value: str) -> long;
}
[Doc(markdown = """
Hashes a Struct, Array, Fn, contract receiver or Random by instance.
The hash stays stable while the object lives and does not retain that object.
""")]
[IdentityPrimitive(name = "referenceHash")]
fn referenceHash<T>(value: T) -> long { return 0; }
[Doc(markdown = """
Compares fully validated references of the same logical type by instance.
Contract views compare receivers, after validating the complete view groups.
""")]
[IdentityPrimitive(name = "referenceEquals")]
fn referenceEquals<T>(left: T, right: T) -> bool { return false; }
@@ -0,0 +1,3 @@
pub service hash;
pub fn referenceHash<T>(value: T) -> long;
pub fn referenceEquals<T>(left: T, right: T) -> bool;
@@ -0,0 +1,19 @@
import {hash, referenceHash, referenceEquals} from @sdk:hash;
declare struct HashExampleObject(pub mut value: int);
fn hashingExample() -> int {
// Hash-v1 preserves signed digest bits; negative hashes are ordinary results.
let expected: long = -8804195676797548855;
if hash.i64(-1) != expected { return 0; }
if hash.f64(0.0) != hash.f64(-0.0) { return 0; }
if hash.text("hel" + "lo") != hash.text("hello") { return 0; }
let first = new HashExampleObject(20);
let other = new HashExampleObject(20);
let saved: long = referenceHash<HashExampleObject>(first);
first.value = 42;
if saved != referenceHash<HashExampleObject>(first) { return 0; }
if referenceEquals<HashExampleObject>(first, first) == false { return 0; }
if referenceEquals<HashExampleObject>(first, other) { return 0; }
return first.value;
}
@@ -4,3 +4,5 @@ pub fn contractExample() -> int;
pub fn genericsExample() -> int;
pub fn collectionsExample() -> int;
pub fn linkedExample() -> int;
pub fn setExample() -> int;
pub fn hashingExample() -> int;
@@ -0,0 +1,25 @@
import {set, Cursor} from @sdk:collections;
fn sumSetSnapshot(snapshot: Cursor<int>) -> int {
let total: int = 0;
while true {
if let value = snapshot.current() { total = total + value; }
else { break; }
if snapshot.hasNext() { snapshot.next(); }
else { break; }
}
return total;
}
fn setExample() -> int {
let values: set<int> = new set();
values.add(20);
values.add(22);
if values.add(20) { return 0; } // Duplicate inclusion preserves the first value.
let captured: Cursor<int> = values.cursor();
values.remove(20);
values.clear();
if values.isEmpty() == false { return 0; }
// The capture owns both values; their traversal order is unspecified.
return sumSetSnapshot(captured);
}
@@ -6,6 +6,36 @@ import p.studio.compiler.source.identifiers.FileId;
import static org.junit.jupiter.api.Assertions.*;
class PbsGenericStructsTest {
@Test void nominalApplicationsStayInvariantInExpectedValueContexts() {
rejects(BOX+"fn main(){let value:Box<long>=new Box<int>(42);}", "E_SEM_GENERIC_TYPE_MISMATCH");
rejects(BOX+"fn main(){let value:Box<long>=new Box(42);value=new Box<int>(42);}", "E_SEM_GENERIC_TYPE_MISMATCH");
rejects(BOX+"fn main()->Box<long>{return new Box<int>(42);}", "E_SEM_GENERIC_TYPE_MISMATCH");
accepts(BOX+"fn main(){let value:Box<long>=new Box<long>(42);value=new Box(43);}");
}
@Test void optionalGenericStrategiesAndEveryConcreteOwnerFamilyKeepLogicalScope() {
accepts("""
declare contract Policy<T>{fn same(a:T,b:T)->bool;}
declare struct Compared<T>(policy:optional Policy<T>){
fn same(a:T,b:T)->bool{if let policy=this.policy{return policy.same(a,b);}return false;}
}
declare contract Read<T>{fn read()->T;}
declare struct Cell<T>(pub mut value:T){fn replace(value:T){this.value=value;}}
implements<T> Read<T> for Cell<T> using cell {fn read()->T{return cell.value;}}
fn main()->int{
let a=new Cell<int>(20);let b=new Cell<long>(22);let viewA:Read<int>=a;let viewB:Read<long>=b;
a.replace(20);b.replace(22);return viewA.read()+(viewB.read() as int);
}
""");
rejects("""
declare struct Broken<T>(value:optional T){
fn invalid()->optional T{if let value=this.value{return some(value+value);}return none;}
}
""","E_SEM_GENERIC_CAPABILITY");
accepts("""
declare struct set<T>(value:T){fn get()->T{return this.value;}}
fn main()->int{let userSet=new set<optional int>(some(42));return userSet.get() else 0;}
""");
}
@Test void recursiveOptionalBindingsAndContractViewsKeepTheirDefinitionShapes() {
accepts("""
declare contract Reader<T> {fn read()->optional T;}
@@ -41,7 +71,7 @@ class PbsGenericStructsTest {
}
private void accepts(String source) {
var diagnostics = compile(source);
assertFalse(diagnostics.hasErrors(), () -> diagnostics.stream().map(d -> d.getCode()+": "+d.getMessage()).toList().toString());
assertFalse(diagnostics.hasErrors(), () -> diagnostics.stream().map(d -> d.getCode()+": "+d.getMessage()+" at "+d.getSpan().getStart()+":"+d.getSpan().getEnd()).toList().toString());
}
private void rejects(String source, String code) {
var diagnostics = compile(source);
@@ -12,7 +12,7 @@ import static org.junit.jupiter.api.Assertions.*;
class PbsListCursorEditorialTest {
@org.junit.jupiter.params.ParameterizedTest
@org.junit.jupiter.params.provider.ValueSource(strings={"list","linked"})
@org.junit.jupiter.params.provider.ValueSource(strings={"list","linked","set"})
void concreteApiHidesStorageAndKeepsSdkDefinitionOrigins(String collection) throws Exception {
var diagnostics=DiagnosticSink.empty();var sdkId=new FileId(1);
String sdk;
@@ -36,11 +36,11 @@ class PbsListCursorEditorialTest {
var typeHover=service.hover(source,ast,supplemental,source.indexOf("Values<int>")).orElseThrow();
assertFalse(typeHover.signatures().stream().anyMatch(s->s.label().startsWith("_")));
var constructors=service.signatureHelp(source,ast,supplemental,source.indexOf("new Values(")+11).orElseThrow().signatures();
assertEquals(collection.equals("list")?2:1,constructors.size());
assertEquals(collection.equals("linked")?1:2,constructors.size());
assertTrue(constructors.stream().allMatch(s->!s.label().contains("storage")&&!s.label().contains("$generic$")));
var completions=service.completion(source,ast,supplemental,member);
assertTrue(completions.stream().anyMatch(c->c.label().equals("add")&&c.detail().contains("int")));
assertFalse(completions.stream().anyMatch(c->java.util.Set.of("storage","length","head","tail","_at","_put","_node").contains(c.label())));
assertFalse(completions.stream().anyMatch(c->java.util.Set.of("storage","length","head","tail","buckets","strategy","busy","_at","_put","_node","_hash","_find","_begin","_rehash").contains(c.label())));
var definition=service.definition(source,ast,supplemental,member);
assertEquals(sdkId,definition.getFirst().span().getFileId());
int current=source.indexOf("cursor.current")+7;
@@ -8,8 +8,8 @@ final class BytecodeOpcodeLayout {
0x30,0x31,0x32,0x33,0x34,0x35,0x36,0x37,0x38,0x39,0x3a,0x3b,0x3c,0x3d,0x3e,0x51,0x80 -> 2;
case 0x16 -> 3;
case 0x02,0x03,0x04,0x10,0x17,0x18,0x40,0x41,0x42,0x43,0x50,0x53,0x57,0x70,0x71,0x72,
0x90,0x91,0x92,0xa0,0xa3,0xa4,0xa5,0xa6,0xa9 -> 6;
case 0x14,0x15,0x52,0x58,0x93,0x94,0x95,0x96,0xa1,0xa2 -> 10;
0x90,0x91,0x92,0x97,0xa0,0xa3,0xa4,0xa5,0xa6,0xa9 -> 6;
case 0x14,0x15,0x52,0x58,0x93,0x94,0x95,0x96,0x98,0xa1,0xa2 -> 10;
default -> throw new BytecodeMarshalingException(BytecodeMarshalingErrorCode.MARSHAL_VERIFY_PRECHECK_UNKNOWN_OPCODE,
"unknown or retired opcode 0x%04X".formatted(opcode));
};
@@ -56,6 +56,7 @@ public class BytecodePreloadVerifierService {
case 0x58 -> method(r,a,b);
case 0x90,0x91,0x92 -> type(r,a);
case 0x93,0x94,0x95,0x96 -> {var src=type(r,a).body();var dst=type(r,b).body();check(src instanceof Struct||src instanceof Array||src instanceof Trait,"reference source category");check(op==0x94||op==0x95?dst instanceof Trait:dst instanceof Struct||dst instanceof Array,"reference target category");}
case 0x97,0x98 -> {identitySource(r,a);if(op==0x98)identitySource(r,b);}
case 0xa0 -> check(type(r,a).body() instanceof Struct,"Struct category");
case 0xa1,0xa2 -> field(r,a,b);
case 0xa3,0xa4,0xa5,0xa6,0xa9 -> array(r,a);
@@ -159,6 +160,8 @@ public class BytecodePreloadVerifierService {
case 0x91 -> {dynamic(pop(s,2),typed);produce(s,facts(r,type(r,a).identity()),i.pc());}
case 0x92 -> {dynamic(pop(s,2),typed);s.stack.add(carrier("bool"));}
case 0x93,0x94,0x95,0x96 -> {consume(s,facts(r,type(r,a).identity()),typed);if(op==0x93||op==0x94)s.stack.add(carrier("bool"));else produce(s,facts(r,type(r,b).identity()),i.pc());}
case 0x97 -> {consume(s,facts(r,type(r,a).identity()),typed);s.stack.add(carrier("i64"));}
case 0x98 -> {var expected=new ArrayList<>(facts(r,type(r,a).identity()));expected.addAll(facts(r,type(r,b).identity()));consume(s,expected,typed);s.stack.add(carrier("bool"));}
case 0xa0 -> produce(s,facts(r,type(r,a).identity()),i.pc());
case 0xa1 -> {consume(s,facts(r,type(r,a).identity()),typed);produce(s,facts(r,field(r,a,b).type()),i.pc());}
case 0xa2 -> {consume(s,facts(r,field(r,a,b).type()),typed);consume(s,facts(r,type(r,a).identity()),typed);}
@@ -266,6 +269,7 @@ public class BytecodePreloadVerifierService {
check((mask(actual.get(i+1).carrier())&64)!=0,"invalid null group pair");
}
}
private static void identitySource(LinkedRegistry r,int id){var body=type(r,id).body();check(body instanceof Struct||body instanceof Array||body instanceof Fn||body instanceof Trait||body instanceof Builtin builtin&&builtin.id()==0x16,"identity source category");}
private static TypeDeclaration type(LinkedRegistry r,int id){check(id>=0&&id<r.types().size(),"TypeId");return r.types().get(id);}
private static Fn fn(LinkedRegistry r,int id){check(type(r,id).body() instanceof Fn,"Fn category");return (Fn)type(r,id).body();}
private static Method method(LinkedRegistry r,int id,int member){check(type(r,id).body() instanceof Trait,"Trait category");var t=(Trait)type(r,id).body();check(member>=0&&member<t.methods().size(),"method index");return t.methods().get(member);}
@@ -42,6 +42,15 @@ public final class RegistryInstructionLowerer {
if(trait?!(target instanceof Trait):!(target instanceof Struct||target instanceof Array))throw new IllegalArgumentException("reference target category");
second=registry.id(instruction.targetType()).index();pops=registry.width(instruction.type());pushes=instruction.kind()==IRRegistryInstruction.Kind.REF_TO_TRAIT?2:1;
}
case REF_IDENTITY_HASH,REF_IDENTITY_EQ -> {
if(!identitySource(body))throw new IllegalArgumentException("identity source category");
pops=registry.width(instruction.type());pushes=1;
if(instruction.kind()==IRRegistryInstruction.Kind.REF_IDENTITY_EQ) {
if(!identitySource(registry.type(instruction.targetType()).body()))throw new IllegalArgumentException("identity right category");
pops=Math.addExact(pops,registry.width(instruction.targetType()));
second=registry.id(instruction.targetType()).index();
}
}
case STRUCT_NEW,STRUCT_GET,STRUCT_SET -> {
if(!(body instanceof Struct struct))throw new IllegalArgumentException("Struct category required");
if(instruction.kind()==IRRegistryInstruction.Kind.STRUCT_NEW)pushes=1;
@@ -64,4 +73,8 @@ public final class RegistryInstructionLowerer {
int bytes=second==null?4:8;
return new IRVMInstruction(new IRVMOp("REGISTRY_"+instruction.kind(),instruction.kind().opcode(),bytes,pops,pushes,false,false,false),first,second);
}
private static boolean identitySource(TypeBody body) {
return body instanceof Struct||body instanceof Array||body instanceof Fn||body instanceof Trait
||body instanceof Builtin builtin&&builtin.id()==0x16;
}
}
@@ -0,0 +1,108 @@
package p.studio.compiler.backend.registry;
import org.junit.jupiter.api.Test;
import p.studio.compiler.backend.bytecode.*;
import p.studio.compiler.backend.irvm.*;
import p.studio.compiler.models.*;
import p.studio.compiler.models.registry.*;
import p.studio.compiler.models.registry.IRRegistry.*;
import p.studio.compiler.source.identifiers.*;
import p.studio.utilities.structures.ReadOnlyList;
import java.nio.file.*;
import java.util.*;
import static p.studio.compiler.models.IRBackendExecutableFunction.InstructionKind.*;
import static p.studio.compiler.models.registry.IRRegistryInstruction.Kind.*;
import static org.junit.jupiter.api.Assertions.*;
/** Neutral producer: no PBS type, spelling or collection binding reaches the backend. */
class IdentityHashingPipelineTest {
private static final TypeRef LONG=TypeRef.builtin(0x11),BOOL=TypeRef.builtin(0x13),
OWNER=new TypeRef("neutral:object"),VIEW=new TypeRef("neutral:view");
private final List<IRBackendExecutableFunction.Instruction> code=new ArrayList<>();
private void emit(IRBackendExecutableFunction.InstructionKind op,String label,Integer index) {
code.add(new IRBackendExecutableFunction.Instruction(op,null,null,null,null,null,label,null,index,null,null));
}
private void typed(IRRegistryInstruction.Kind op,TypeRef left,TypeRef right,int field) {
code.add(new IRBackendExecutableFunction.Instruction(REGISTRY,null,null,null,null,null,null,null,null,null,null,
new IRRegistryInstruction(op,left,right,null,field)));
}
@Test void completeTraitViewsAndConcreteAliasesUseBothTypedQueries() throws Exception {
var registry=new IRRegistry(ReadOnlyList.from(
new TypeDeclaration(LONG,null,new Builtin(0x11)),new TypeDeclaration(BOOL,null,new Builtin(0x13)),
new TypeDeclaration(OWNER,"Object",new Struct(ReadOnlyList.from(new NamedType(LONG,"value")))),
new TypeDeclaration(VIEW,"View",new Trait(null))),
ReadOnlyList.from(new Implementation("neutral:implementation",OWNER,VIEW,null)));
typed(STRUCT_NEW,OWNER,null,0);emit(SET_LOCAL,null,0);
emit(GET_LOCAL,null,0);typed(REF_IDENTITY_HASH,OWNER,null,0);emit(SET_LOCAL,null,1);
emit(GET_LOCAL,null,0);emit(PUSH_I64,"42",null);typed(STRUCT_SET,OWNER,null,0);
emit(GET_LOCAL,null,0);typed(REF_TO_TRAIT,OWNER,VIEW,0);typed(REF_IDENTITY_HASH,VIEW,null,0);
emit(GET_LOCAL,null,1);emit(EQ,null,null);
emit(GET_LOCAL,null,0);emit(GET_LOCAL,null,0);typed(REF_TO_TRAIT,OWNER,VIEW,0);
typed(REF_IDENTITY_EQ,OWNER,VIEW,0);emit(AND,null,null);
emit(GET_LOCAL,null,0);typed(STRUCT_NEW,OWNER,null,0);typed(REF_IDENTITY_EQ,OWNER,OWNER,0);
emit(NOT,null,null);emit(AND,null,null);emit(RET,null,null);
var f=new IRBackendExecutableFunction(new FileId(0),new ModuleId(0),"main",new CallableId(0),0,0,0,2,1,5,
ReadOnlyList.wrap(code),null,FunctionMetadata.ordinary(new Signature(null,ReadOnlyList.from(BOOL))));
var backend=IRBackend.builder().entryPointModuleId(new ModuleId(0)).entryPointCallableName("main")
.registry(registry).executableFunctions(ReadOnlyList.from(f)).build();
for(boolean optimized:new boolean[]{false,true}) {
var program=new LowerToIRVMService().lower(backend);
if(optimized)program=new OptimizeIRVMService().optimize(program);
var queries=program.module().functions().getFirst().instructions().stream()
.filter(i->i.op().opcode()==0x97||i.op().opcode()==0x98).toList();
assertEquals(4,queries.size());
assertEquals(List.of(6,6,10,10),queries.stream().map(IRVMInstruction::encodedSize).toList());
assertEquals(List.of(1,2,3,2),queries.stream().map(i->i.op().pops()).toList());
var module=new BytecodeEmitter().emit(program.coherentEmissionPlan());new BytecodePreloadVerifierService().verify(module);
var directory=Path.of("build/registry-conformance");Files.createDirectories(directory);
Files.write(directory.resolve("common-identity"+(optimized?"-optimized":"")+".pbx"),module.serialize());
int pc=0,hashPc=-1,eqPc=-1;
for(var instruction:program.module().functions().getFirst().instructions()) {
if(hashPc<0&&instruction.op().opcode()==0x97)hashPc=pc;
if(eqPc<0&&instruction.op().opcode()==0x98)eqPc=pc;
pc+=instruction.encodedSize();
}
int boolId=LinkedRegistry.link(registry).id(BOOL).index();
for(var negative:new String[]{"bad-category","bad-right","dead-bad-category","bad-typeid"}) {
byte[] bad=module.code().clone();var buffer=java.nio.ByteBuffer.wrap(bad).order(java.nio.ByteOrder.LITTLE_ENDIAN);
if(negative.equals("bad-right"))buffer.putInt(eqPc+6,boolId);
else buffer.putInt(hashPc+2,negative.equals("bad-typeid")?-1:boolId);
if(negative.startsWith("dead"))for(int offset=0;offset<6;offset+=2)buffer.putShort(offset,(short)1);
var malformed=new BytecodeModule(module.version(),module.constPool(),module.functions(),bad,module.debugInfo(),module.exports(),module.syscalls(),module.registry(),module.intrinsicSignatures());
assertThrows(BytecodeMarshalingException.class,()->new BytecodePreloadVerifierService().verify(malformed),negative);
Files.write(directory.resolve("common-identity-"+negative+(optimized?"-optimized":"")+".pbx"),malformed.serialize());
}
}
}
@Test void neutralUnknownInputsKeepRuntimeValidationOfTheCompleteRightView()throws Exception {
var registry=new IRRegistry(ReadOnlyList.from(
new TypeDeclaration(LONG,null,new Builtin(0x11)),new TypeDeclaration(BOOL,null,new Builtin(0x13)),
new TypeDeclaration(OWNER,"Object",new Struct(null)),new TypeDeclaration(VIEW,"View",new Trait(null))),null);
var linked=LinkedRegistry.link(registry);int owner=linked.id(OWNER).index(),view=linked.id(VIEW).index();
for(var name:new String[]{"null-views","right-after-null","right-after-distinct","partial","truncated"}) {
var bytes=new java.io.ByteArrayOutputStream();
if(name.equals("truncated")){word(bytes,0x97);}
else {
if(name.equals("right-after-distinct"))instruction(bytes,0xa0,owner);else instruction(bytes,0x10,0);
if(name.startsWith("right")) {instruction(bytes,0x40,0);instruction(bytes,0x40,1);}
else {instruction(bytes,0x10,0);if(!name.equals("partial"))instruction(bytes,0x10,0);}
instruction(bytes,0x98,owner);integer(bytes,view);word(bytes,0x51);
}
byte[] raw=bytes.toByteArray();
var module=new BytecodeModule(0,ReadOnlyList.from(new BytecodeModule.NullConstant()),
ReadOnlyList.from(new BytecodeModule.FunctionMeta(0,raw.length,0,0,1,3,
FunctionMetadata.ordinary(new Signature(null,ReadOnlyList.from(BOOL))))),raw,null,ReadOnlyList.empty(),ReadOnlyList.empty(),registry);
if(name.equals("partial")||name.equals("truncated"))assertThrows(BytecodeMarshalingException.class,()->new BytecodePreloadVerifierService().verify(module));
else new BytecodePreloadVerifierService().verify(module);
var directory=Path.of("build/registry-conformance");Files.createDirectories(directory);
Files.write(directory.resolve("common-identity-"+name+".pbx"),module.serialize());
}
}
private static void word(java.io.ByteArrayOutputStream out,int n){out.write(n);out.write(n>>>8);}
private static void integer(java.io.ByteArrayOutputStream out,int n){for(int i=0;i<4;i++)out.write(n>>>(8*i));}
private static void instruction(java.io.ByteArrayOutputStream out,int op,int n){word(out,op);integer(out,n);}
@Test void identityEqualityRequiresTwoTypeOperands() {
assertThrows(NullPointerException.class,()->new IRRegistryInstruction(REF_IDENTITY_EQ,OWNER,null,null,0));
assertThrows(IllegalArgumentException.class,()->new IRRegistryInstruction(REF_IDENTITY_HASH,OWNER,VIEW,null,0));
}
}
@@ -10,6 +10,7 @@ public record IRRegistryInstruction(Kind kind, IRRegistry.TypeRef type, IRRegist
MAKE_CLOSURE(0x52), CALL_CLOSURE(0x53), GET_CAPTURE(0x57), CALL_TRAIT(0x58),
DYN_PACK(0x90), DYN_UNPACK(0x91), DYN_CAN_UNPACK(0x92),
REF_IS_EXACT(0x93), REF_IMPLEMENTS(0x94), REF_TO_TRAIT(0x95), REF_CAST(0x96),
REF_IDENTITY_HASH(0x97), REF_IDENTITY_EQ(0x98),
STRUCT_NEW(0xa0), STRUCT_GET(0xa1), STRUCT_SET(0xa2),
ARRAY_NEW(0xa3), ARRAY_LEN(0xa4), ARRAY_GET(0xa5), ARRAY_SET(0xa6),
ARRAY_COPY(0xa9);
@@ -23,7 +24,7 @@ public record IRRegistryInstruction(Kind kind, IRRegistry.TypeRef type, IRRegist
if(kind!=Kind.GET_CAPTURE)Objects.requireNonNull(type,"type");
if(kind==Kind.MAKE_CLOSURE) {Objects.requireNonNull(function,"function");function.getIndex();}
else if(function!=null)throw new IllegalArgumentException("unexpected function operand");
boolean pair=(kind.opcode()>=0x93&&kind.opcode()<=0x96);
boolean pair=(kind.opcode()>=0x93&&kind.opcode()<=0x96)||kind==Kind.REF_IDENTITY_EQ;
if(pair)Objects.requireNonNull(targetType,"targetType");
else if(targetType!=null)throw new IllegalArgumentException("unexpected target type");
if(kind==Kind.GET_CAPTURE&&type!=null)throw new IllegalArgumentException("capture index is not a TypeId");