feat(pbs): add array-backed Stack and circular Queue
This commit is contained in:
+1
-1
@@ -245,7 +245,7 @@ public final class PbsGenericInstantiation {
|
||||
return null;
|
||||
}
|
||||
if (PbsSdkCollections.isCollection(template) && PbsSdkCollections.directOptional(arguments.getFirst())) {
|
||||
error(PbsSdkCollections.isMap(template)?"MAP_OPTIONAL_KEY":PbsSdkCollections.isSet(template)?"SET_OPTIONAL_ELEMENT":PbsSdkCollections.isLinked(template) ? "LINKED_OPTIONAL_ELEMENT" : "LIST_OPTIONAL_ELEMENT",
|
||||
error(PbsSdkCollections.isMap(template)?"MAP_OPTIONAL_KEY":PbsSdkCollections.isSet(template)?"SET_OPTIONAL_ELEMENT":PbsSdkCollections.isStack(template)?"STACK_OPTIONAL_ELEMENT":PbsSdkCollections.isQueue(template)?"QUEUE_OPTIONAL_ELEMENT":PbsSdkCollections.isLinked(template) ? "LINKED_OPTIONAL_ELEMENT" : "LIST_OPTIONAL_ELEMENT",
|
||||
"SDK " + name(template) + " does not permit a directly optional " + (PbsSdkCollections.isMap(template)?"key":"element"), site);
|
||||
return null;
|
||||
}
|
||||
|
||||
+10
-1
@@ -15,6 +15,15 @@ public final class PbsSdkCollections {
|
||||
public static boolean isIndexedCollection(PbsAst.TopDecl declaration) {
|
||||
return isList(declaration) || isLinked(declaration);
|
||||
}
|
||||
public static boolean isStack(PbsAst.TopDecl declaration) {
|
||||
return declaration instanceof PbsAst.StructDecl s && attribute(s.attributes(), "SdkStack") != null;
|
||||
}
|
||||
public static boolean isQueue(PbsAst.TopDecl declaration) {
|
||||
return declaration instanceof PbsAst.StructDecl s && attribute(s.attributes(), "SdkQueue") != null;
|
||||
}
|
||||
public static boolean hasCapacityConstructor(PbsAst.TopDecl declaration) {
|
||||
return isIndexedCollection(declaration) || isStack(declaration) || isQueue(declaration);
|
||||
}
|
||||
public static boolean isSet(PbsAst.TopDecl declaration) {
|
||||
return declaration instanceof PbsAst.StructDecl s && attribute(s.attributes(), "SdkSet") != null;
|
||||
}
|
||||
@@ -25,7 +34,7 @@ public final class PbsSdkCollections {
|
||||
return isIndexedCollection(declaration) || isMap(declaration);
|
||||
}
|
||||
public static boolean isCollection(PbsAst.TopDecl declaration) {
|
||||
return hasIndexer(declaration)||isSet(declaration);
|
||||
return hasIndexer(declaration)||isSet(declaration)||isStack(declaration)||isQueue(declaration);
|
||||
}
|
||||
public static boolean hasDefaultIdentity(PbsAst.TypeRef type,PbsContractTypes types) {
|
||||
while(type!=null&&type.kind()==PbsAst.TypeRefKind.GROUP)type=type.inner();
|
||||
|
||||
+1
-1
@@ -1868,7 +1868,7 @@ 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.isIndexedCollection(declaration);
|
||||
boolean list=p.studio.compiler.pbs.PbsSdkCollections.hasCapacityConstructor(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().orElse(null);
|
||||
if (ctor == null) {
|
||||
|
||||
+1
-1
@@ -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", "SdkSet", "SdkMap").contains(attribute.name()) && "struct declarations".equals(targetSurface)) {
|
||||
java.util.Set.of("SdkList", "SdkLinked", "SdkSet", "SdkMap", "SdkStack", "SdkQueue").contains(attribute.name()) && "struct declarations".equals(targetSurface)) {
|
||||
continue;
|
||||
}
|
||||
p.studio.compiler.source.diagnostics.Diagnostics.error(context.diagnostics(),
|
||||
|
||||
+139
@@ -141,6 +141,145 @@ declare struct list<T>(storage: array<T>, length: long) {
|
||||
}
|
||||
}
|
||||
|
||||
[SdkStack]
|
||||
declare struct stack<T>(storage: array<T>, length: long) {
|
||||
ctor make() {
|
||||
this.storage = new array<T>(16);
|
||||
this.length = 0;
|
||||
}
|
||||
ctor make(capacity: long) {
|
||||
_checkLength(capacity);
|
||||
this.storage = new array<T>(capacity);
|
||||
this.length = 0;
|
||||
}
|
||||
fn size() -> long { return this.length; }
|
||||
fn capacity() -> long { return this.storage.length; }
|
||||
fn isEmpty() -> bool { return this.length == (0 as long); }
|
||||
fn peek() -> optional T {
|
||||
if this.length == (0 as long) { return none; }
|
||||
return this.storage[this.length - (1 as long)];
|
||||
}
|
||||
fn push(value: T) {
|
||||
let required: long = this.length + 1;
|
||||
_checkLength(required);
|
||||
if required > this.storage.length {
|
||||
let target: array<T> = new array<T>(_grownCapacity(this.storage.length, required));
|
||||
_copy<T>(this.storage, 0, target, 0, this.length);
|
||||
target[this.length] = value;
|
||||
this.storage = target;
|
||||
} else {
|
||||
this.storage[this.length] = value;
|
||||
}
|
||||
this.length = required;
|
||||
}
|
||||
fn pop() -> optional T {
|
||||
if this.length == (0 as long) { return none; }
|
||||
let length: long = this.length - 1;
|
||||
let previous: optional T = this.storage[length];
|
||||
this.storage.clear(length);
|
||||
this.length = length;
|
||||
return previous;
|
||||
}
|
||||
fn clear() {
|
||||
let index: long = 0;
|
||||
while index < this.length {
|
||||
this.storage.clear(index);
|
||||
index = index + 1;
|
||||
}
|
||||
this.length = 0;
|
||||
}
|
||||
fn cursor() -> Cursor<T> {
|
||||
let head: optional _SnapshotNode<T> = none;
|
||||
let index: long = 0;
|
||||
while index < this.length {
|
||||
if let value = this.storage[index] {
|
||||
head = some(new _SnapshotNode<T>(value, head));
|
||||
}
|
||||
index = index + 1;
|
||||
}
|
||||
return new _SnapshotCursor<T>(head) as Cursor<T>;
|
||||
}
|
||||
}
|
||||
|
||||
// Valid only for nonempty backing, start < capacity and offset <= capacity.
|
||||
// The checked u32 capacity bounds make start + offset fit long without narrowing.
|
||||
fn _ringIndex(start: long, offset: long, capacity: long) -> long {
|
||||
let index: long = start + offset;
|
||||
if index >= capacity { index = index - capacity; }
|
||||
return index;
|
||||
}
|
||||
|
||||
[SdkQueue]
|
||||
declare struct queue<T>(storage: array<T>, start: long, length: long) {
|
||||
ctor make() {
|
||||
this.storage = new array<T>(16);
|
||||
this.start = 0;
|
||||
this.length = 0;
|
||||
}
|
||||
ctor make(capacity: long) {
|
||||
_checkLength(capacity);
|
||||
this.storage = new array<T>(capacity);
|
||||
this.start = 0;
|
||||
this.length = 0;
|
||||
}
|
||||
fn size() -> long { return this.length; }
|
||||
fn capacity() -> long { return this.storage.length; }
|
||||
fn isEmpty() -> bool { return this.length == (0 as long); }
|
||||
fn peek() -> optional T {
|
||||
if this.length == (0 as long) { return none; }
|
||||
return this.storage[this.start];
|
||||
}
|
||||
fn enqueue(value: T) {
|
||||
let required: long = this.length + 1;
|
||||
_checkLength(required);
|
||||
if required > this.storage.length {
|
||||
let target: array<T> = new array<T>(_grownCapacity(this.storage.length, required));
|
||||
let first: long = this.storage.length - this.start;
|
||||
if first > this.length { first = this.length; }
|
||||
_copy<T>(this.storage, this.start, target, 0, first);
|
||||
_copy<T>(this.storage, 0, target, first, this.length - first);
|
||||
target[this.length] = value;
|
||||
this.storage = target;
|
||||
this.start = 0;
|
||||
} else {
|
||||
let index: long = _ringIndex(this.start, this.length, this.storage.length);
|
||||
this.storage[index] = value;
|
||||
}
|
||||
this.length = required;
|
||||
}
|
||||
fn dequeue() -> optional T {
|
||||
if this.length == (0 as long) { return none; }
|
||||
let length: long = this.length - 1;
|
||||
let start: long = 0;
|
||||
if length > (0 as long) { start = _ringIndex(this.start, 1, this.storage.length); }
|
||||
let previous: optional T = this.storage[this.start];
|
||||
this.storage.clear(this.start);
|
||||
this.start = start;
|
||||
this.length = length;
|
||||
return previous;
|
||||
}
|
||||
fn clear() {
|
||||
let offset: long = 0;
|
||||
while offset < this.length {
|
||||
this.storage.clear(_ringIndex(this.start, offset, this.storage.length));
|
||||
offset = offset + 1;
|
||||
}
|
||||
this.start = 0;
|
||||
this.length = 0;
|
||||
}
|
||||
fn cursor() -> Cursor<T> {
|
||||
let head: optional _SnapshotNode<T> = none;
|
||||
let offset: long = this.length;
|
||||
while offset > (0 as long) {
|
||||
offset = offset - 1;
|
||||
if let value = this.storage[_ringIndex(this.start, offset, this.storage.length)] {
|
||||
head = some(new _SnapshotNode<T>(value, head));
|
||||
}
|
||||
}
|
||||
return new _SnapshotCursor<T>(head) as Cursor<T>;
|
||||
}
|
||||
}
|
||||
|
||||
declare contract Cursor<T> {
|
||||
fn hasNext() -> bool;
|
||||
fn next();
|
||||
|
||||
+2
@@ -5,3 +5,5 @@ pub struct set<T>;
|
||||
pub contract Identity<T>;
|
||||
pub struct map<K, V>;
|
||||
pub struct keyval<K, V>;
|
||||
pub struct stack<T>;
|
||||
pub struct queue<T>;
|
||||
|
||||
+1
@@ -7,3 +7,4 @@ pub fn linkedExample() -> int;
|
||||
pub fn setExample() -> int;
|
||||
pub fn hashingExample() -> int;
|
||||
pub fn mapsExample() -> int;
|
||||
pub fn stackQueueExample() -> int;
|
||||
|
||||
+25
@@ -0,0 +1,25 @@
|
||||
import {stack, queue, Cursor} from @sdk:collections;
|
||||
|
||||
fn stackQueueExample() -> int {
|
||||
let history = new stack<int>(0);
|
||||
let pending = new queue<int>(2);
|
||||
history.push(20);
|
||||
history.push(22);
|
||||
pending.enqueue(20);
|
||||
pending.enqueue(22);
|
||||
let lastFirst: Cursor<int> = history.cursor();
|
||||
let firstFirst: Cursor<int> = pending.cursor();
|
||||
history.clear();
|
||||
pending.dequeue();
|
||||
pending.enqueue(0);
|
||||
pending.enqueue(1);
|
||||
pending.clear();
|
||||
if (lastFirst.current() else 0) != 22 { return 0; }
|
||||
if (firstFirst.current() else 0) != 20 { return 0; }
|
||||
lastFirst.next();
|
||||
firstFirst.next();
|
||||
if lastFirst.hasNext() or firstFirst.hasNext() { return 0; }
|
||||
if (lastFirst.current() else 0) != 20 { return 0; }
|
||||
if (firstFirst.current() else 0) != 22 { return 0; }
|
||||
return (lastFirst.current() else 0) + (firstFirst.current() else 0);
|
||||
}
|
||||
+21
@@ -124,6 +124,27 @@ class PbsGateUSdkInterfaceConformanceTest {
|
||||
assertTrue(copied.hasErrors());
|
||||
}
|
||||
|
||||
@Test
|
||||
void stackQueueExportsPreserveCapacityRulesAndRejectIndexing() throws IOException {
|
||||
var positive=compileWorkspaceModule(tempDir.resolve("stack-queue-positive"),"""
|
||||
import {stack as Lifo,queue as Fifo} from @sdk:collections;
|
||||
[Frame]fn frame()->void{let n:int=0;let s:Lifo<int>=new Lifo(n);let q:Fifo<int>=new Fifo<>();s.push(20);q.enqueue(22);}
|
||||
""","pub fn frame()->void;",1,null);
|
||||
assertFalse(positive.diagnostics().hasErrors(),positive.diagnostics().toString());
|
||||
for(String type:java.util.List.of("stack","queue")) {
|
||||
for(var entry:java.util.Map.of(
|
||||
"optional","let xs=new "+type+"<optional int>();",
|
||||
"index","let xs=new "+type+"<int>();let invalid=xs[0];",
|
||||
"private","let xs=new "+type+"<int>();let exposed=xs.storage;",
|
||||
"capacity","let xs=new "+type+"<int>(true);",
|
||||
"bounded","let xs=new "+type+"<int>();xs.reserve(4);").entrySet()) {
|
||||
var negative=compileWorkspaceModule(tempDir.resolve(type+"-negative-"+entry.getKey()),
|
||||
"import {"+type+"} from @sdk:collections;[Frame]fn frame()->void{"+entry.getValue()+"}","pub fn frame()->void;",1,null);
|
||||
assertTrue(negative.diagnostics().hasErrors(),type+"/"+entry.getKey());
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
@Test
|
||||
void mapExportsUseOriginCheckedKeyTypingAndPrivateAssociations() throws IOException {
|
||||
var positive=compileWorkspaceModule(tempDir.resolve("map-positive"),"""
|
||||
|
||||
+66
@@ -0,0 +1,66 @@
|
||||
package p.studio.compiler.pbs;
|
||||
|
||||
import org.junit.jupiter.api.Test;
|
||||
import p.studio.compiler.models.SourceKind;
|
||||
import p.studio.compiler.source.diagnostics.DiagnosticSink;
|
||||
import p.studio.compiler.source.identifiers.FileId;
|
||||
import java.nio.charset.StandardCharsets;
|
||||
import static org.junit.jupiter.api.Assertions.*;
|
||||
|
||||
class PbsStackQueueTest {
|
||||
private DiagnosticSink compile(String source) throws Exception {
|
||||
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 diagnostics=DiagnosticSink.empty();
|
||||
new PbsFrontendCompiler().compileFile(new FileId(0),sdk+"\n"+source,diagnostics,SourceKind.SDK_INTERFACE);
|
||||
return diagnostics;
|
||||
}
|
||||
@Test void capacitiesContextAndOptionalFieldsUseOrdinaryGenericRules() throws Exception {
|
||||
var diagnostics=compile("""
|
||||
declare struct Item(pub value:optional int);
|
||||
fn sample(){
|
||||
let n:int=0;let wide:long=4;
|
||||
let s:stack<int>=new stack(n);let q:queue<int>=new queue<>(wide);
|
||||
let defaultStack:stack<int>=new stack();let defaultQueue:queue<int>=new queue<>();
|
||||
let maybe:optional (stack<Item>)=some(new stack());
|
||||
let nested=new queue<array<int>>();nested.enqueue(new array<int>(0));
|
||||
let items=new stack<Item>();items.push(new Item(none));
|
||||
s.push(42);q.enqueue(42);s.pop();q.dequeue();s.peek();q.peek();s.clear();q.clear();
|
||||
}
|
||||
""");
|
||||
assertFalse(diagnostics.hasErrors(),()->diagnostics.stream().map(d->d.getCode()+":"+d.getMessage()).toList().toString());
|
||||
}
|
||||
@Test void optionalInvariancePrivacyAndUnsupportedSurfacesAreRejected() throws Exception {
|
||||
for (String type:java.util.List.of("stack","queue")) {
|
||||
for (String optional:java.util.List.of("optional int","(optional int)")) {
|
||||
var d=compile("fn f(){let x=new "+type+"<"+optional+">();}");
|
||||
assertTrue(d.stream().anyMatch(i->i.getCode().contains(type.toUpperCase()+"_OPTIONAL_ELEMENT")),d.toString());
|
||||
}
|
||||
for (String statement:java.util.List.of(
|
||||
"let x=new "+type+"();",
|
||||
"let x:"+type+"<long>=new "+type+"<int>();",
|
||||
"let x=new "+type+"<int>(true);",
|
||||
"let x=new "+type+"<int>();let y=x[0];",
|
||||
"let x=new "+type+"<int>();x.reserve(10);",
|
||||
"let x=new "+type+"<int>();x.trim();",
|
||||
"let x=new "+type+"<int>();let y=x.storage;")) {
|
||||
assertTrue(compile("fn f(){"+statement+"}").hasErrors(),statement);
|
||||
}
|
||||
String insert=type.equals("stack")?"push":"enqueue";
|
||||
assertTrue(compile("fn f(){let x=new "+type+"<long>();let n:int=1;x."+insert+"(n);}").hasErrors());
|
||||
}
|
||||
assertTrue(compile("fn f(){let q=new queue<int>();let hidden=q.start;}").hasErrors());
|
||||
}
|
||||
@Test void projectHomonymsDoNotAcquireTrustedSdkBehavior() {
|
||||
for (String type:java.util.List.of("stack","queue")) {
|
||||
var d=DiagnosticSink.empty();
|
||||
new PbsFrontendCompiler().compileFile(new FileId(0),"declare struct "+type+"<T>(pub value:T);fn f(){let x=new "+type+"<optional int>(none);}",d);
|
||||
assertFalse(d.hasErrors(),d.toString());
|
||||
var forged=DiagnosticSink.empty();
|
||||
new PbsFrontendCompiler().compileFile(new FileId(0),"[Sdk"+(type.equals("stack")?"Stack":"Queue")+"]declare struct "+type+"<T>(value:T);",forged);
|
||||
assertTrue(forged.hasErrors());
|
||||
}
|
||||
}
|
||||
}
|
||||
+45
@@ -0,0 +1,45 @@
|
||||
package p.studio.compiler.pbs.semantics;
|
||||
|
||||
import org.junit.jupiter.api.Test;
|
||||
import p.studio.compiler.pbs.ast.PbsAst;
|
||||
import p.studio.compiler.pbs.lexer.PbsLexer;
|
||||
import p.studio.compiler.pbs.parser.PbsParser;
|
||||
import p.studio.compiler.source.diagnostics.DiagnosticSink;
|
||||
import p.studio.compiler.source.identifiers.FileId;
|
||||
import p.studio.utilities.structures.ReadOnlyList;
|
||||
import java.nio.charset.StandardCharsets;
|
||||
import java.util.Set;
|
||||
import java.util.stream.Collectors;
|
||||
import static org.junit.jupiter.api.Assertions.*;
|
||||
|
||||
class PbsStackQueueEditorialTest {
|
||||
@Test void aliasesShowConcretePublicApiConstructorsAndOriginalSdkDefinitions() 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);
|
||||
for (String type:java.util.List.of("stack","queue")) {
|
||||
String insert=type.equals("stack")?"push":"enqueue",remove=type.equals("stack")?"pop":"dequeue";
|
||||
String source="import {"+type+" as Values} from @sdk:collections;fn f(values:Values<int>){let x:Values<int>=new Values();values."+insert+"(42);values.storage;}";
|
||||
var id=new FileId(2);var ast=PbsParser.parse(PbsLexer.lex(source,id,diagnostics),id,diagnostics);
|
||||
var declarations=new java.util.ArrayList<PbsAst.TopDecl>(library.topDecls().stream().toList());
|
||||
var origin=library.topDecls().stream().filter(d->d instanceof PbsAst.StructDecl s&&s.name().equals(type)).findFirst().orElseThrow();
|
||||
declarations.add(new PbsAst.TypeBindingDecl("Values",origin,ast.span()));
|
||||
var supplemental=ReadOnlyList.wrap(declarations);var service=new PbsEditorialSupportService();
|
||||
int offset=source.indexOf("values."+insert)+7;
|
||||
assertEquals(Set.of(insert,remove,"peek","size","capacity","isEmpty","clear","cursor"),
|
||||
service.completion(source,ast,supplemental,offset).stream().map(c->c.label()).collect(Collectors.toSet()));
|
||||
assertTrue(service.hover(source,ast,supplemental,offset).orElseThrow().signatures().getFirst().label().contains("int"));
|
||||
assertEquals(sdkId,service.definition(source,ast,supplemental,offset).getFirst().span().getFileId());
|
||||
var constructors=service.signatureHelp(source,ast,supplemental,source.indexOf("new Values(")+11).orElseThrow().signatures();
|
||||
assertEquals(2,constructors.size());
|
||||
assertTrue(constructors.stream().anyMatch(c->c.label().contains("capacity: long")),constructors.toString());
|
||||
assertTrue(constructors.stream().noneMatch(c->c.label().contains("storage")||c.label().contains("$generic$")));
|
||||
int hidden=source.indexOf("values.storage")+7;
|
||||
assertTrue(service.hover(source,ast,supplemental,hidden).isEmpty());
|
||||
assertTrue(service.definition(source,ast,supplemental,hidden).isEmpty());
|
||||
}
|
||||
assertFalse(diagnostics.hasErrors(),diagnostics.toString());
|
||||
}
|
||||
}
|
||||
Reference in New Issue
Block a user