feat(pbs): add Set and reusable identity hashing
This commit is contained in:
+5
-1
@@ -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) {
|
||||
|
||||
+26
-4
@@ -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 "
|
||||
|
||||
+19
-2
@@ -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();
|
||||
|
||||
+20
@@ -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);
|
||||
}
|
||||
|
||||
+67
-2
@@ -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);
|
||||
|
||||
+8
@@ -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");
|
||||
|
||||
+2
-2
@@ -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()) {
|
||||
|
||||
+2
-2
@@ -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,
|
||||
|
||||
+6
@@ -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())) {
|
||||
|
||||
+10
@@ -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();
|
||||
|
||||
+193
@@ -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>;
|
||||
}
|
||||
}
|
||||
|
||||
+2
@@ -1,3 +1,5 @@
|
||||
pub struct list<T>;
|
||||
pub contract Cursor<T>;
|
||||
pub struct linked<T>;
|
||||
pub struct set<T>;
|
||||
pub contract Identity<T>;
|
||||
|
||||
+26
@@ -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; }
|
||||
+3
@@ -0,0 +1,3 @@
|
||||
pub service hash;
|
||||
pub fn referenceHash<T>(value: T) -> long;
|
||||
pub fn referenceEquals<T>(left: T, right: T) -> bool;
|
||||
+19
@@ -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;
|
||||
}
|
||||
+2
@@ -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;
|
||||
|
||||
+25
@@ -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);
|
||||
}
|
||||
+31
-1
@@ -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);
|
||||
|
||||
+3
-3
@@ -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;
|
||||
|
||||
Reference in New Issue
Block a user