feat(pbs): add linked collections and bidirectional snapshots

Implement SDK linked<T> with forward and reverse Cursor snapshots, trusted compiler integration, and neutral FIELDS_PUBLISH producer support. Pin the tested runtime revision and include specs, editor and installed knowledge coverage, conformance fixtures, and DSC-0091 lessons and evidence.
This commit is contained in:
2026-10-23 10:28:44 +01:00
parent c410e35001
commit 77aada6259
38 changed files with 3040 additions and 57 deletions
@@ -237,8 +237,9 @@ public final class PbsGenericInstantiation {
error("ARITY", name(template)+" requires "+parameters(template).size()+" explicit type argument(s)", site);
return null;
}
if (PbsSdkCollections.isList(template) && PbsSdkCollections.directOptional(arguments.getFirst())) {
error("LIST_OPTIONAL_ELEMENT", "SDK list<T> does not permit a directly optional element", site);
if (PbsSdkCollections.isIndexedCollection(template) && PbsSdkCollections.directOptional(arguments.getFirst())) {
error(PbsSdkCollections.isLinked(template) ? "LINKED_OPTIONAL_ELEMENT" : "LIST_OPTIONAL_ELEMENT",
"SDK " + name(template) + "<T> does not permit a directly optional element", site);
return null;
}
var application = PbsAst.TypeRef.applied(name(template), arguments, template.span());
@@ -631,7 +632,12 @@ public final class PbsGenericInstantiation {
}
var concreteType = type(applied);
if (symbolicProbe) requiredShapes.add(concreteType.name());
var constructor = PbsSdkCollections.isList(s) && n.ctorName() == null ? "make" : n.ctorName();
var constructor = PbsSdkCollections.isIndexedCollection(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 "
+ n.arguments().size() + " argument(s) for " + name(s), n.span());
}
var fields = constructorParameters(concreteType, constructor, n.arguments().size());
var arguments = new ArrayList<PbsAst.Expression>();
for (int i = 0; i < n.arguments().size(); i++) arguments.add(expression(n.arguments().get(i),
@@ -153,7 +153,7 @@ final class PbsGenericTemplateValidator {
context.error("CONTEXT", "Generic construction requires an expected application or explicit type arguments", n.span());
if (d instanceof PbsAst.StructDecl s) {
var env = bindings(s, result);
var constructor = PbsSdkCollections.isList(s) && n.ctorName()==null ? "make" : n.ctorName();
var constructor = PbsSdkCollections.isIndexedCollection(s) && n.ctorName()==null ? "make" : n.ctorName();
var expectedParameters = constructor == null ? map(s.fields(), f -> new PbsAst.Parameter(f.name(), PbsTypeSubstitution.substitute(f.typeRef(), env), f.span()))
: s.ctors().stream().filter(c -> c.name().equals(constructor) && c.parameters().size()==n.arguments().size()).findFirst().map(c ->
map(c.parameters(), p -> new PbsAst.Parameter(p.name(), PbsTypeSubstitution.substitute(p.typeRef(), env), p.span()))).orElse(ReadOnlyList.empty());
@@ -9,6 +9,12 @@ public final class PbsSdkCollections {
public static boolean isList(PbsAst.TopDecl declaration) {
return declaration instanceof PbsAst.StructDecl s && attribute(s.attributes(), "SdkList") != null;
}
public static boolean isLinked(PbsAst.TopDecl declaration) {
return declaration instanceof PbsAst.StructDecl s && attribute(s.attributes(), "SdkLinked") != null;
}
public static boolean isIndexedCollection(PbsAst.TopDecl declaration) {
return isList(declaration) || isLinked(declaration);
}
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);
}
@@ -1113,7 +1113,7 @@ final class PbsExecutableBodyLowerer {
var methods=declaration.methods().stream().filter(m->m.name().equals(member.memberName())&&m.parameters().size()==tuple.items().size()).toList();
if(methods.size()!=1)return false;
var method=methods.getFirst();
boolean listIndex=p.studio.compiler.pbs.PbsSdkCollections.isList(declaration)&&java.util.Set.of("insert","clearAt","removeAt","resize","reserve").contains(member.memberName());
boolean listIndex=p.studio.compiler.pbs.PbsSdkCollections.isIndexedCollection(declaration)&&java.util.Set.of("insert","clearAt","removeAt","resize","reserve").contains(member.memberName());
var receiverName=c.nextLabel("named_receiver");
lowerExpected(member.receiver(),owner,c);
int receiver=c.declareLocalSlots(receiverName,1);c.localTypes.put(receiverName,owner);
@@ -1166,7 +1166,7 @@ final class PbsExecutableBodyLowerer {
var array = PbsRuntimeTypes.unwrap(expressionType(index.receiver(), c));
if(array==null)return null;
var declaration=c.types().structs.get(array.name());
return p.studio.compiler.pbs.PbsSdkCollections.isList(declaration)
return p.studio.compiler.pbs.PbsSdkCollections.isIndexedCollection(declaration)
? declaration.methods().stream().filter(m->m.name().equals("_at")).findFirst().orElseThrow().returnType()
: PbsAst.TypeRef.optional(array.inner(),index.span());
}
@@ -1617,6 +1617,43 @@ final class PbsExecutableBodyLowerer {
var operation=p.studio.compiler.pbs.PbsSdkCollections.argument(binding,"name");
var span=function.span();
switch(operation) {
case "publishFields" -> {
var owners = new java.util.ArrayList<IRRegistry.TypeRef>();
int parameter = 0, offset = 0, pops = 0;
while (parameter < function.parameters().size()) {
var receiver = PbsRuntimeTypes.unwrap(function.parameters().get(parameter++).typeRef());
var owner = receiver.kind() == PbsAst.TypeRefKind.OPTIONAL
? PbsRuntimeTypes.unwrap(receiver.inner()) : receiver;
var declaration = c.types().structs.get(owner.name());
if (declaration == null) throw new IllegalArgumentException("Publication destination must be Struct");
owners.add(c.types().registryType(owner));
if (receiver.kind() == PbsAst.TypeRefKind.OPTIONAL) {
var absent = c.nextLabel("absent_publication_destination");
var ready = c.nextLabel("publication_destination_ready");
optionalPresence(offset, receiver, span, c);
emitJump(IRBackendExecutableFunction.InstructionKind.JMP_IF_FALSE, absent, span, c);
unwrapOptional(offset, receiver, span, c);
emitJump(IRBackendExecutableFunction.InstructionKind.JMP, ready, span, c);
emitLabel(absent, span, c);
emitDefault(c.types().registryType(owner), 1, span, c);
emitLabel(ready, span, c);
} else emitGetLocal(offset, span, c);
offset += c.types().slots(receiver);
pops++;
for (var field : declaration.fields()) {
if (parameter >= function.parameters().size()) throw new IllegalArgumentException("Missing publication field");
var value = function.parameters().get(parameter++).typeRef();
if (!c.types().key(value).equals(c.types().key(field.typeRef())))
throw new IllegalArgumentException("Publication field type mismatch");
int width = c.types().slots(value);
emitLoadLocalSlots(offset, width, span, c);
packStorage(value, span, c);
offset += width;
pops += storageWidth(value, c);
}
}
registry(FIELDS_PUBLISH, c.types().publicationSchema(owners), 0, pops, 0, span, c);
}
case "indexGuard" -> {
emitLoadLocalSlots(0,2,span,c);
registry(INDEX_GUARD,null,0,2,0,span,c);
@@ -1668,9 +1705,9 @@ final class PbsExecutableBodyLowerer {
c.instructions().add(new IRBackendExecutableFunction.Instruction(IRBackendExecutableFunction.InstructionKind.RET,"",null,null,span));
}
private boolean lowerListIndex(PbsAst.IndexExpr index, PbsAst.Expression value, PbsAst.TypeRef type, PbsExecutableLoweringContext c) {
private boolean lowerCollectionIndex(PbsAst.IndexExpr index, PbsAst.Expression value, PbsAst.TypeRef type, PbsExecutableLoweringContext c) {
var declaration=type==null?null:c.types().structs.get(type.name());
if(!p.studio.compiler.pbs.PbsSdkCollections.isList(declaration))return false;
if(!p.studio.compiler.pbs.PbsSdkCollections.isIndexedCollection(declaration))return false;
var name=value==null?"_at":"_put";
var method=declaration.methods().stream().filter(m->m.name().equals(name)).findFirst().orElseThrow();
lowerExpected(index.receiver(),type,c);
@@ -1723,7 +1760,7 @@ final class PbsExecutableBodyLowerer {
}
private void lowerArrayWrite(PbsAst.IndexExpr index,PbsAst.Expression value,PbsExecutableLoweringContext c) {
var type=PbsRuntimeTypes.unwrap(expressionType(index.receiver(),c));
if(lowerListIndex(index,value,type,c))return;
if(lowerCollectionIndex(index,value,type,c))return;
lowerExpected(index.receiver(),type,c);
lowerArrayIndex(index.index(),c);
lowerExpected(value,type.inner(),c);
@@ -1733,7 +1770,7 @@ final class PbsExecutableBodyLowerer {
}
private void lowerArrayRead(PbsAst.IndexExpr index,PbsExecutableLoweringContext c) {
var type=PbsRuntimeTypes.unwrap(expressionType(index.receiver(),c));
if(lowerListIndex(index,null,type,c))return;
if(lowerCollectionIndex(index,null,type,c))return;
var optional=PbsAst.TypeRef.optional(type.inner(),index.span());
lowerExpected(index.receiver(),type,c);
lowerArrayIndex(index.index(),c);
@@ -1839,9 +1876,14 @@ final class PbsExecutableBodyLowerer {
}
private void lowerStructNew(PbsAst.NewExpr expr,PbsExecutableLoweringContext c) {
var declaration=c.types().structs.get(expr.typeName());var ref=c.types().registryType(PbsRuntimeTypes.type(expr.typeName()));
boolean list=p.studio.compiler.pbs.PbsSdkCollections.isList(declaration);
boolean list=p.studio.compiler.pbs.PbsSdkCollections.isIndexedCollection(declaration);
if(expr.ctorName()!=null) {
var ctor=declaration.ctors().stream().filter(f->f.name().equals(expr.ctorName()) && parametersMatch(f.parameters(),expr.arguments(),c,list)).findFirst().orElseThrow();
var ctor=declaration.ctors().stream().filter(f->f.name().equals(expr.ctorName()) && parametersMatch(f.parameters(),expr.arguments(),c,list)).findFirst().orElse(null);
if (ctor == null) {
reportUnsupportedLowering("No matching constructor '" + expr.ctorName() + "' for "
+ expr.typeName() + " with " + expr.arguments().size() + " argument(s)", expr.span(), c);
return;
}
var arguments=new java.util.ArrayList<Integer>();
for(int i=0;i<expr.arguments().size();i++){var type=PbsTypeSubstitution.replaceSelf(ctor.parameters().get(i).typeRef(),expr.typeName());if(list)lowerArrayIndex(expr.arguments().get(i),c);else lowerExpected(expr.arguments().get(i),type,c);arguments.add(save(c.types().slots(type),expr.span(),c));}
registry(STRUCT_NEW,ref,0,0,1,expr.span(),c);int instance=save(1,expr.span(),c);emitGetLocal(instance,expr.span(),c);
@@ -1916,7 +1958,7 @@ final class PbsExecutableBodyLowerer {
emitStructuredFunction(owner.name()+"."+method.name(),method.parameters().stream().map(PbsAst.Parameter::typeRef).toList(),PbsTypeSubstitution.replaceSelf(method.returnType(),owner.name()),pops,c.types().slots(method.returnType()),call.span(),c);return true;
}
var struct=c.types().structs.get(owner.name());if(struct==null)return false;
boolean listIndex=p.studio.compiler.pbs.PbsSdkCollections.isList(struct) && java.util.Set.of("insert","clearAt","removeAt","resize","reserve").contains(member.memberName());
boolean listIndex=p.studio.compiler.pbs.PbsSdkCollections.isIndexedCollection(struct) && java.util.Set.of("insert","clearAt","removeAt","resize","reserve").contains(member.memberName());
var method=struct.methods().stream().filter(m->m.name().equals(member.memberName())&&parametersMatch(m.parameters(),call.arguments(),c,listIndex) && returnMatches(m.returnType(),owner.name(),c)).findFirst().orElse(null);
if(method==null)return false;
lowerExpected(member.receiver(),owner,c);int pops=1;
@@ -138,6 +138,15 @@ final class PbsRuntimeTypes {
used.putIfAbsent(ref.declarationKey(), new IRRegistry.TypeDeclaration(ref, null, new IRRegistry.Array(element)));
return ref;
}
IRRegistry.TypeRef publicationSchema(List<IRRegistry.TypeRef> owners) {
var ref = new IRRegistry.TypeRef("pbs:field-publication:" + owners.stream()
.map(IRRegistry.TypeRef::declarationKey).map(k -> k.length() + ":" + k)
.collect(java.util.stream.Collectors.joining()));
used.putIfAbsent(ref.declarationKey(), new IRRegistry.TypeDeclaration(ref, null,
new IRRegistry.Struct(ReadOnlyList.wrap(owners.stream()
.map(owner -> new IRRegistry.NamedType(owner, null)).toList()))));
return ref;
}
IRRegistry.TypeRef builtin(int id) {
var ref = IRRegistry.TypeRef.builtin(id);
used.putIfAbsent(ref.declarationKey(),new IRRegistry.TypeDeclaration(ref,null,new IRRegistry.Builtin(id)));
@@ -685,7 +685,7 @@ final class PbsDeclarationParser {
final String targetSurface) {
for (final var attribute : attributes) {
if ("Doc".equals(attribute.name()) || attribute.trustedSdkOrigin() &&
"SdkList".equals(attribute.name()) && "struct declarations".equals(targetSurface)) {
java.util.Set.of("SdkList", "SdkLinked").contains(attribute.name()) && "struct declarations".equals(targetSurface)) {
continue;
}
p.studio.compiler.source.diagnostics.Diagnostics.error(context.diagnostics(),
@@ -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.isList(symbolic)||field.isPublic()) completions.put(field.name(), new PbsEditorialCompletionCandidate(
for (var field : symbolic.fields()) if(!p.studio.compiler.pbs.PbsSdkCollections.isIndexedCollection(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.isSdkList(receiverType)&&!field.getValue().isPublic())continue;
if(model.isSdkIndexedCollection(receiverType)&&!field.getValue().isPublic())continue;
completions.put(field.getKey(), new PbsEditorialCompletionCandidate(
field.getKey(),
PbsEditorialSymbolKind.FIELD,
@@ -786,7 +786,7 @@ public final class PbsEditorialSupportService {
receiverType.name()));
}
for (final var method : structInfo.methods().entrySet()) {
if(model.isSdkList(receiverType)&&java.util.Set.of("_at","_put").contains(method.getKey()))continue;
if(model.isSdkPrivateMember(receiverType, method.getKey()))continue;
completions.put(method.getKey(), new PbsEditorialCompletionCandidate(
method.getKey(),
PbsEditorialSymbolKind.METHOD,
@@ -51,7 +51,7 @@ final class PbsFlowCallableResolutionAnalyzer {
}
final boolean listIndexArgument = callExpr.callee() instanceof PbsAst.MemberExpr member
&& java.util.Set.of("insert","clearAt","removeAt","resize","reserve").contains(member.memberName())
&& context.model().isSdkList(analyzeValueExpression(member.receiver(),context,null).type());
&& context.model().isSdkIndexedCollection(analyzeValueExpression(member.receiver(),context,null).type());
final var callee = analyzeTargetExpression(callExpr.callee(), context, ExprUse.CALL_TARGET);
final var expectedInputs = callee.callables().size() == 1 ? callee.callables().getFirst().inputTypes() : java.util.List.<TypeView>of();
@@ -88,7 +88,7 @@ final class PbsFlowCallableResolutionAnalyzer {
final var callee = analyzeTargetExpression(applyExpr.callee(), context, ExprUse.APPLY_TARGET);
boolean listIndex=applyExpr.callee() instanceof PbsAst.MemberExpr member
&& java.util.Set.of("insert","clearAt","removeAt","resize","reserve").contains(member.memberName())
&& context.model().isSdkList(analyzeValueExpression(member.receiver(),context,null).type());
&& context.model().isSdkIndexedCollection(analyzeValueExpression(member.receiver(),context,null).type());
TypeView argument;
if (applyExpr.argument() instanceof PbsAst.TupleExpr tuple && !tuple.items().isEmpty()
&& tuple.items().getFirst().label() != null && callee.callables().size() == 1) {
@@ -209,7 +209,8 @@ final class PbsFlowCallableResolutionAnalyzer {
}
return ExprResult.type(field.type());
}
if(model.isSdkList(receiver) && java.util.Set.of("_at","_put").contains(memberExpr.memberName())) {
if(model.isSdkPrivateMember(receiver, memberExpr.memberName())
&& (receiverType == null || !receiver.name().equals(receiverType.name()))) {
Diagnostics.error(diagnostics,"E_SEM_SDK_PRIVATE_MEMBER","SDK storage adapters are private",memberExpr.span());
return ExprResult.type(TypeView.unknown());
}
@@ -198,10 +198,17 @@ final class PbsFlowSemanticSupport {
static final class Model {
p.studio.compiler.pbs.PbsContractTypes contractTypes;
boolean isSdkList(TypeView type) {
return type != null && p.studio.compiler.pbs.PbsSdkCollections.isList(contractTypes.declaration(
boolean isSdkIndexedCollection(TypeView type) {
return type != null && p.studio.compiler.pbs.PbsSdkCollections.isIndexedCollection(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
? PbsAst.TypeRef.simple(type.name(), Span.none()) : type.sourceType());
return declaration instanceof PbsAst.StructDecl owner && owner.methods().stream()
.anyMatch(m -> m.name().equals(member) && p.studio.compiler.pbs.PbsSdkCollections.attribute(m.attributes(), "SdkPrivate") != null);
}
final Map<String, List<CallableSymbol>> topLevelCallables = new HashMap<>();
final Map<String, StructInfo> structs = new HashMap<>();
final Map<String, ServiceInfo> services = new HashMap<>();
@@ -53,7 +53,7 @@ final class PbsFlowStructuralExpressionAnalyzer {
if (expression instanceof PbsAst.IndexExpr index) {
final var receiver = analyzeValueExpression(index.receiver(), context, null).type();
checkArrayIndex(index.index(), context);
if (model.isSdkList(receiver)) {
if (model.isSdkIndexedCollection(receiver)) {
return ExprResult.type(model.structs.get(receiver.name()).methods().get("_at").getFirst().outputType());
}
if (receiver.kind() != Kind.ARRAY) {
@@ -154,3 +154,160 @@ implements<T> Cursor<T> for _SnapshotCursor<T> using snapshot {
fn next() { snapshot.next(); }
fn current() -> optional T { return snapshot.current(); }
}
// Complete-object publication is neutral; this source chooses the node topology.
[StoragePrimitive(name = "publishFields")]
fn _linkedPublish<T>(owner: linked<T>, head: optional _LinkedNode<T>, tail: optional _LinkedNode<T>, length: long,
previous: optional _LinkedNode<T>, previousValue: T, previousPrevious: optional _LinkedNode<T>, previousNext: optional _LinkedNode<T>,
next: optional _LinkedNode<T>, nextValue: T, nextPrevious: optional _LinkedNode<T>, nextNext: optional _LinkedNode<T>) {}
[StoragePrimitive(name = "publishFields")]
fn _linkedEmpty<T>(owner: linked<T>, head: optional _LinkedNode<T>, tail: optional _LinkedNode<T>, length: long) {}
[StoragePrimitive(name = "publishFields")]
fn _linkedReplace<T>(owner: _LinkedNode<T>, value: T, previous: optional _LinkedNode<T>, next: optional _LinkedNode<T>) {}
fn _linkedNextSize(length: long) -> long {
// Check before adding; Linked does not inherit Array's u32 structural bound.
let maximum: long = 9223372036854775807;
_bounds(length, maximum);
return length + 1;
}
declare struct _LinkedNode<T>(pub mut value: T, pub mut previous: optional _LinkedNode<T>, pub mut next: optional _LinkedNode<T>) {
ctor make(value: T, previous: optional _LinkedNode<T>, next: optional _LinkedNode<T>) {
this.value = value;
this.previous = previous;
this.next = next;
}
}
[SdkLinked]
declare struct linked<T>(head: optional _LinkedNode<T>, tail: optional _LinkedNode<T>, length: long) {
ctor make() {
this.head = none;
this.tail = none;
this.length = 0;
}
fn size() -> long { return this.length; }
fn first() -> optional T {
if let node = this.head { return some(node.value); }
return none;
}
fn last() -> optional T {
if let node = this.tail { return some(node.value); }
return none;
}
[SdkPrivate]
fn _node(index: long) -> optional _LinkedNode<T> {
_bounds(index, this.length);
let node: optional _LinkedNode<T> = none;
let remaining: long = 0;
if index < this.length / (2 as long) {
node = this.head;
remaining = index;
while remaining > (0 as long) {
if let current = node { node = current.next; }
remaining = remaining - 1;
}
} else {
node = this.tail;
remaining = this.length - index - 1;
while remaining > (0 as long) {
if let current = node { node = current.previous; }
remaining = remaining - 1;
}
}
return node;
}
[SdkPrivate]
fn _at(index: long) -> optional T {
if let node = this._node(index) { return some(node.value); }
return none;
}
[SdkPrivate]
fn _put(index: long, value: T) {
if let node = this._node(index) {
_linkedReplace<T>(node, value, node.previous, node.next);
}
}
fn add(value: T) { this.insert(this.length, value); }
fn addFirst(value: T) { this.insert(0, value); }
fn insert(index: long, value: T) {
if index != this.length { _bounds(index, this.length); }
let required: long = _linkedNextSize(this.length);
let next: optional _LinkedNode<T> = none;
let previous: optional _LinkedNode<T> = this.tail;
if index < this.length {
next = this._node(index);
if let node = next { previous = node.previous; }
}
let inserted: optional _LinkedNode<T> = some(new _LinkedNode<T>(value, previous, next));
let head: optional _LinkedNode<T> = this.head;
let tail: optional _LinkedNode<T> = this.tail;
if index == (0 as long) { head = inserted; }
if index == this.length { tail = inserted; }
let previousValue: T = value;
let previousPrevious: optional _LinkedNode<T> = none;
let nextValue: T = value;
let nextNext: optional _LinkedNode<T> = none;
if let node = previous { previousValue = node.value; previousPrevious = node.previous; }
if let node = next { nextValue = node.value; nextNext = node.next; }
_linkedPublish<T>(this, head, tail, required,
previous, previousValue, previousPrevious, inserted,
next, nextValue, inserted, nextNext);
}
fn removeAt(index: long) -> optional T {
if let removed = this._node(index) {
let removedValue: optional T = some(removed.value);
let previous: optional _LinkedNode<T> = removed.previous;
let next: optional _LinkedNode<T> = removed.next;
let head: optional _LinkedNode<T> = this.head;
let tail: optional _LinkedNode<T> = this.tail;
if previous.hasNone() { head = next; }
if next.hasNone() { tail = previous; }
let previousValue: T = removed.value;
let previousPrevious: optional _LinkedNode<T> = none;
let nextValue: T = removed.value;
let nextNext: optional _LinkedNode<T> = none;
if let node = previous { previousValue = node.value; previousPrevious = node.previous; }
if let node = next { nextValue = node.value; nextNext = node.next; }
_linkedPublish<T>(this, head, tail, this.length - 1,
previous, previousValue, previousPrevious, next,
next, nextValue, previous, nextNext);
return removedValue;
}
return none;
}
fn removeFirst() -> optional T {
if this.length == (0 as long) { return none; }
return this.removeAt(0);
}
fn removeLast() -> optional T {
if this.length == (0 as long) { return none; }
return this.removeAt(this.length - 1);
}
fn clear() { _linkedEmpty<T>(this, none, none, 0); }
fn cursor() -> Cursor<T> {
let captured: optional _SnapshotNode<T> = none;
let source: optional _LinkedNode<T> = this.tail;
while source.hasSome() {
if let node = source {
captured = some(new _SnapshotNode<T>(node.value, captured));
source = node.previous;
}
}
return new _SnapshotCursor<T>(captured) as Cursor<T>;
}
fn reverseCursor() -> Cursor<T> {
let captured: optional _SnapshotNode<T> = none;
let source: optional _LinkedNode<T> = this.head;
while source.hasSome() {
if let node = source {
captured = some(new _SnapshotNode<T>(node.value, captured));
source = node.next;
}
}
return new _SnapshotCursor<T>(captured) as Cursor<T>;
}
}
@@ -1,2 +1,3 @@
pub struct list<T>;
pub contract Cursor<T>;
pub struct linked<T>;
@@ -0,0 +1,27 @@
import { linked, Cursor } from @sdk:collections;
fn sumLinkedSnapshot(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 linkedExample() -> int {
let values: linked<int> = new linked();
values.add(20);
values.add(22);
let forward: Cursor<int> = values.cursor();
let reverse: Cursor<int> = values.reverseCursor();
values[0] = 99;
values.clear(); // Completed snapshots still visit 20/22 and 22/20.
let forwardTotal: int = sumLinkedSnapshot(forward);
let reverseTotal: int = sumLinkedSnapshot(reverse);
if forwardTotal != 42 or reverseTotal != 42 { return 0; }
// next() retains 22 in forward.current(), and 20 in reverse.current().
return reverseTotal;
}
@@ -3,3 +3,4 @@ pub fn frame() -> void;
pub fn contractExample() -> int;
pub fn genericsExample() -> int;
pub fn collectionsExample() -> int;
pub fn linkedExample() -> int;
@@ -89,6 +89,41 @@ class PbsGateUSdkInterfaceConformanceTest {
assertTrue(copied.hasErrors(),"Project attributes cannot acquire SDK bindings");
}
@Test
void linkedRejectsOptionalElementsCapacityAndPrivateProjectAccess() throws IOException {
var cases=java.util.Map.ofEntries(
java.util.Map.entry("optional","let xs:linked<optional int>=new linked<optional int>();"),
java.util.Map.entry("grouped","let xs:linked<(optional int)>=new linked<(optional int)>();"),
java.util.Map.entry("capacity","let xs=new linked<int>(4);"),
java.util.Map.entry("context","let xs=new linked();"),
java.util.Map.entry("invariance","let xs:linked<long>=new linked<int>();"),
java.util.Map.entry("index","let xs=new linked<int>();let invalid=xs[1.5];"),
java.util.Map.entry("head","let xs=new linked<int>();let exposed=xs.head;"),
java.util.Map.entry("node","let xs=new linked<int>();let exposed=xs._node(0);"),
java.util.Map.entry("adapter","let xs=new linked<int>();let exposed=xs._at(0);"),
java.util.Map.entry("payload","let xs=new linked<long>();let value:int=1;xs.add(value);"),
java.util.Map.entry("holes","let xs=new linked<int>();xs.clearAt(0);"),
java.util.Map.entry("value-remove","let xs=new linked<int>();xs.remove(42);"));
for(var entry:cases.entrySet()) {
var result=compileWorkspaceModule(tempDir.resolve("linked-negative-"+entry.getKey()),
"import {linked} from @sdk:collections;[Frame] fn frame()->void {"+entry.getValue()+"}",
"pub fn frame()->void;",1,null);
assertTrue(result.diagnostics().hasErrors(),entry.getKey());
}
var diagnostics=DiagnosticSink.empty();
new PbsFrontendCompiler().compileFile(new FileId(202),"""
declare struct linked<T>(value:T) {}
fn main() {let xs=new linked<int>(1);let invalid=xs[0];}
""",diagnostics,SourceKind.PROJECT);
assertTrue(diagnostics.stream().anyMatch(d->d.getCode().equals("E_SEM_ARRAY_RECEIVER")));
var copied=DiagnosticSink.empty();
new PbsFrontendCompiler().compileFile(new FileId(203),"""
[SdkLinked] declare struct linked<T>(value:T) {}
[StoragePrimitive(name="publishFields")] fn fake() {}
""",copied,SourceKind.PROJECT);
assertTrue(copied.hasErrors());
}
@Test
void removedInputObjectsExplainTheirMigration() throws IOException {
final var result = compileWorkspaceModule(tempDir.resolve("removed-input"), """
@@ -11,14 +11,16 @@ import java.nio.charset.StandardCharsets;
import static org.junit.jupiter.api.Assertions.*;
class PbsListCursorEditorialTest {
@Test void concreteApiHidesStorageAndKeepsSdkDefinitionOrigins() throws Exception {
@org.junit.jupiter.params.ParameterizedTest
@org.junit.jupiter.params.provider.ValueSource(strings={"list","linked"})
void concreteApiHidesStorageAndKeepsSdkDefinitionOrigins(String collection) throws Exception {
var diagnostics=DiagnosticSink.empty();var sdkId=new FileId(1);
String sdk;
try(var stream=getClass().getResourceAsStream("/game/stdlib/1/sdk/collections/main.pbs")) {
assertNotNull(stream);sdk=new String(stream.readAllBytes(),StandardCharsets.UTF_8);
}
var library=PbsParser.parse(PbsLexer.lex(sdk,sdkId,diagnostics),sdkId,diagnostics,PbsParser.ParseMode.INTERFACE_MODULE);
var list=library.topDecls().stream().filter(d->d instanceof PbsAst.StructDecl s&&s.name().equals("list")).findFirst().orElseThrow();
var list=library.topDecls().stream().filter(d->d instanceof PbsAst.StructDecl s&&s.name().equals(collection)).findFirst().orElseThrow();
var cursor=library.topDecls().stream().filter(d->d instanceof PbsAst.ContractDecl c&&c.name().equals("Cursor")).findFirst().orElseThrow();
var source="""
import {list as Values,Cursor} from @sdk:collections;
@@ -26,19 +28,19 @@ class PbsListCursorEditorialTest {
let created:Values<int>=new Values(0);
values.add(42); cursor.hasNext(); return cursor.current();
}
""";
""".replace("{list as", "{"+collection+" as").replace("new Values(0)", collection.equals("list")?"new Values(0)":"new Values()");
var id=new FileId(2);var ast=PbsParser.parse(PbsLexer.lex(source,id,diagnostics),id,diagnostics);
assertFalse(diagnostics.hasErrors());
var supplemental=ReadOnlyList.<PbsAst.TopDecl>from(new PbsAst.TypeBindingDecl("Values",list,ast.span()),cursor);
var service=new PbsEditorialSupportService();int member=source.indexOf("values.add")+7;
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(0")+11).orElseThrow().signatures();
assertEquals(2,constructors.size());
var constructors=service.signatureHelp(source,ast,supplemental,source.indexOf("new Values(")+11).orElseThrow().signatures();
assertEquals(collection.equals("list")?2:1,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","_at","_put").contains(c.label())));
assertFalse(completions.stream().anyMatch(c->java.util.Set.of("storage","length","head","tail","_at","_put","_node").contains(c.label())));
var definition=service.definition(source,ast,supplemental,member);
assertEquals(sdkId,definition.getFirst().span().getFileId());
int current=source.indexOf("cursor.current")+7;