feat(pbs): implement typed arrays, optional binding and contract execution
This commit is contained in:
+70
@@ -0,0 +1,70 @@
|
||||
---
|
||||
id: LSN-0083
|
||||
ticket: pbs-typed-collections-and-dynamic
|
||||
title: PBS Arrays Optional and Contract Execution
|
||||
created: 2026-10-16
|
||||
tags: [compiler/pbs, runtime-integration]
|
||||
---
|
||||
|
||||
# PBS arrays, optional values and contract execution
|
||||
|
||||
Owner: compiler/pbs. This lesson consolidates accepted DEC-0067 and completed PLN-0146 (DSC-0079). The [typed arrays specification](../../../docs/compiler/pbs/specs/typed-arrays-and-optional-execution.md) is the normative reference; the [implementation evidence](../../evidence/DSC-0079-implementation/README.md) records the tested tree and commands.
|
||||
|
||||
## The original problem
|
||||
|
||||
Games need to reserve enemy positions before constructing enemies. Filling storage with fabricated objects or treating numeric zero as absence gives the wrong semantics. The runtime already offered Array, Dynamic, Struct and Trait, but their existence did not make PBS source executable: optional lowering, struct construction/fields and contract dispatch were incomplete.
|
||||
|
||||
The solution separates static source types, optional presence and physical storage. It also completes the existing struct/contract execution path instead of deferring it to closure work.
|
||||
|
||||
## The resulting source contract
|
||||
|
||||
```pbs
|
||||
let enemies: array Enemy = new array(10);
|
||||
let groups: array[2] Enemy = new array(3);
|
||||
let scores: array int = [10, 20, 30];
|
||||
|
||||
if let enemy = enemies[1] {
|
||||
enemy.takeDamage(10);
|
||||
}
|
||||
enemies.clear(1);
|
||||
```
|
||||
|
||||
Arrays have fixed length, shared reference identity and invariant element/depth types. Allocation initializes only outer positions to empty; it does not create enemies or nested arrays. Both constructors and every array literal require an expected array type. Depth is a positive literal; compiler structural limits prevent unbounded expansion. Length and indices accept int/long without loss, with the promotion confined to these operations.
|
||||
|
||||
Reads return optional T. A vacant position is none, zero is present, and an invalid index faults. `if let` evaluates once and binds only in the success block. Optional fallback is lazy. Optional values, tuples, fields, parameters and results preserve complete groups. Optional array elements are rejected; an optional array itself is valid. PBS gains neither public Dynamic nor public null.
|
||||
|
||||
## How the implementation works
|
||||
|
||||
Array positions use internal Array<Dynamic>. Single-slot values are packed directly, while native multi-slot values use the runtime's immutable Dynamic boxing. A null Dynamic tag marks vacancy. Checking DYN_CAN_UNPACK alone is incorrect because a null carrier can be compatible with nullable types such as strings or references.
|
||||
|
||||
Private nullable Struct carriers represent optional values. None is null; some owns a carrier holding the complete payload. Named tuples are flattened across callable boundaries and privately boxed for storage. Tuple labels remain editorial metadata rather than changing compatible storage identity. Nominal struct and contract identities include declaration provenance, preventing unrelated modules from sharing a type merely because their names match.
|
||||
|
||||
The compiler emits actual struct allocations, field loads/stores, constructors, typed receivers, contract adapters and CALL_TRAIT. It selects overloads using parameter and result shapes and substitutes Self consistently in semantics and executable metadata. Imported calls retain their module identity. Services have a private singleton accessor so imports share the provider's instance.
|
||||
|
||||
Global initializers run through the file-init path in dependency order. This matters for reserved arrays: a source declaration must create storage before subsequent code uses it. Grouped global values use private carriers rather than losing slots.
|
||||
|
||||
## Lessons from failures found during implementation
|
||||
|
||||
- **VM availability is not frontend support.** A parser accepting an expression, or an assembly probe passing, says nothing about complete source lowering.
|
||||
- **Presence and compatibility are different questions.** Test the Dynamic tag before unpacking; do not turn type or bounds faults into absence.
|
||||
- **Global defaults are not nullable defaults.** VM global slots initially contain Int32 zero. The service singleton guard must recognize that initial state before publishing a reference.
|
||||
- **A tuple is not just its first slot.** Optional extraction, field storage and callable transport must agree on full layouts. Tuples stored in private carriers must be flattened again when read.
|
||||
- **Arity is insufficient for overloads.** Preserve input/output shape, Self substitution and module identity. Choosing a method by name and arity silently changes program meaning.
|
||||
- **Lexical scope also exists during lowering.** Restore slot/type/owner/projection bindings after blocks and if-let branches; semantic scope checks alone do not preserve shadowed runtime locals.
|
||||
- **Generated tests must be mandatory.** A runtime harness that scans only available files can pass while a producer stopped generating required fixtures. The structured corpus names every required case.
|
||||
|
||||
## Verified result and boundaries
|
||||
|
||||
The final gates executed 500 tests without failures; 13 pre-existing disabled tests are listed in the evidence. All 27 new PBS-to-production-PBX cases and 18 resource-refusal runs passed the real loader/VM, alongside 114 existing PBS fixtures and the common backend/catalog corpus. The integer-array case succeeds with one handle total. The GC case reclaims at least 1,100 discarded objects while preserving referenced objects, tuples and strings.
|
||||
|
||||
The GC safepoint is provided by an explicit test-only driver hook; it does not claim PBS sync/closure delivery. Default runtime quotas and GC thresholds were not relaxed. Two pre-existing upstream JSON-schema enum gaps remain explicitly reported by the existing harness. No installed-game qualification or performance claim is inferred from these results.
|
||||
|
||||
The installed knowledge package includes the specification and an executable [array example](../../../prometeu-compiler/frontends/prometeu-frontend-pbs/src/main/resources/pbs-knowledge/examples/game/1/src/arrays.pbs). SDK collections continue in AGD89, closures in AGD82, and installed reference-game qualification in AGD88.
|
||||
|
||||
## Implementation references
|
||||
|
||||
- [Source conformance tests](../../../prometeu-architecture-tests/src/test/java/p/studio/compiler/backend/irvm/PbsStructuredValuesTest.java)
|
||||
- [Runtime harness and reproduction instructions](../../../tools/pbx-conformance/README.md)
|
||||
- [Static semantics](../../../docs/specs/compiler-languages/pbs/4.%20Static%20Semantics%20Specification.md)
|
||||
- [Dynamic semantics](../../../docs/specs/compiler-languages/pbs/9.%20Dynamic%20Semantics%20Specification.md)
|
||||
- [Earlier typed common IR/PBX lesson](../DSC-0074-compiler-pbx-registry-conformance/LSN-0079-typed-common-ir-to-production-pbx.md)
|
||||
@@ -0,0 +1,76 @@
|
||||
# Typed arrays and optional execution
|
||||
|
||||
Owner: `compiler/pbs`. This specification defines the source contract for typed arrays and their integration with existing optional, struct and contract semantics. Runtime Registry, PBX, ownership, limits and faults remain governed by the runtime specifications. The completed implementation and conformance gates are recorded in [LSN-0083](../../../../discussion/lessons/DSC-0079-pbs-typed-collections-and-dynamic/LSN-0083-pbs-arrays-optional-and-contract-execution.md) and its evidence.
|
||||
|
||||
## Types and construction
|
||||
|
||||
`array T` denotes a fixed-length reference to positions holding values of T or no value. `array[N] T` denotes N nested array levels, where N is a positive integer literal. `array[1] T` and `array T` are equivalent. Depth belongs to the type; allocation length belongs to the constructor. The compiler bounds expanded type nesting to 256 nodes and diagnoses excessive depth without expanding an unbounded AST.
|
||||
|
||||
```pbs
|
||||
let enemies: array Enemy = new array(10);
|
||||
let groups: array[2] Enemy = new array(3);
|
||||
let scores: array int = [10, 20, 30];
|
||||
let empty: array Enemy = [];
|
||||
```
|
||||
|
||||
`new array(length)` requires an expected array type. It allocates only the outer array: each position is empty, with no implicit subarray, element construction or callback. Every array literal, including a nonempty literal, requires an expected array type. The compiler must not infer an array type from its elements. Expected types propagate through annotated bindings, assignments, parameters, returns and nested value expressions. Incompatible elements are errors; they do not produce a public Dynamic type.
|
||||
|
||||
Arrays are invariant in element type and depth. Assignment and argument passing share the array reference. The runtime's shared storage carrier must not make different PBS array types interchangeable. `array (optional T)` is invalid, including through grouped types. `optional (array T)` remains valid and distinguishes an absent array from a present array whose positions are empty.
|
||||
|
||||
`T[]`, `[]T`, `array !! T`, `new T[n]` and `new array[n]` are not alternative spellings. PBS exposes neither a null value nor a Dynamic type.
|
||||
|
||||
## Operations and ordering
|
||||
|
||||
- `values.length` returns long and includes empty positions. Length is fixed; zero is valid.
|
||||
- `values[index]` returns `optional T`. Empty positions return none; populated positions return some(value). Numeric zero is present.
|
||||
- `values[index] = value` stores T and replaces the previous position.
|
||||
- `values.clear(index)` empties a position without changing length and returns unit.
|
||||
|
||||
Allocation lengths, indices and clear indices accept int and long literals, variables and expressions. The compiler promotes int to long without loss in these operations only. This does not introduce general implicit numeric conversions. Lengths must satisfy the runtime's u32 and resource bounds; long values must not be truncated.
|
||||
|
||||
Receiver, index and value expressions are evaluated once, left to right. Array literals evaluate elements in source order. Invalid indices fault, including accesses to a zero-length array; they must never be reported as none. Runtime type and resource failures retain their original meanings.
|
||||
|
||||
## Optional control flow
|
||||
|
||||
```pbs
|
||||
if let enemy = enemies[1] {
|
||||
enemy.takeDamage(10);
|
||||
} else {
|
||||
// Runs only when the position is empty.
|
||||
}
|
||||
```
|
||||
|
||||
`if let name = expression` requires optional T and evaluates its expression once. For some, the success block receives name of type T. For none, the success block is skipped and the optional else branch runs. The binding exists only inside the success block and must not leak into else or following statements. Outer bindings retain their identities after the conditional.
|
||||
|
||||
`value else fallback` evaluates fallback only for none. `some(value)`, contextual `none`, optional parameters/results, tuple payloads and nested optional values preserve their complete source types and groups. The existing `hasSome()` and `hasNone()` methods take no arguments and return bool. Optional function fallthrough yields none, following existing PBS rules; a trailing expression in a function body is not an implicit return.
|
||||
|
||||
## Runtime representation
|
||||
|
||||
Array positions use runtime `Array<Dynamic>` internally. An empty position is the untyped-null group `[Null, Null]`. A present position carries the exact runtime TypeId and payload for its statically checked PBS value. Runtime-supported single-slot payloads, including numeric values, are stored directly. Runtime multi-slot values use its immutable Dynamic boxing contract; the compiler must not introduce a heap box per single-slot integer.
|
||||
|
||||
Presence must be checked using the Dynamic tag before extraction. `DYN_CAN_UNPACK` alone is insufficient because untyped null can be compatible with nullable types. Type incompatibility must fault rather than becoming absence. Clearing restores the complete empty Dynamic group.
|
||||
|
||||
PBS optional values use private nullable Struct carriers: null denotes none and a private instance contains the full payload for some. Named tuples remain flattened at callable boundaries and use private storage carriers where a single Registry type is required. These private carriers are inaccessible to source programs. They preserve nested optional distinctions, tuple value behavior and reference aliases within payloads.
|
||||
|
||||
Lowering must keep complete receiver/index/value groups rooted across allocations, calls and collection operations. GC, native ownership, quota accounting, costs and atomic refusals remain runtime contracts. No failure may publish partially initialized handles or be suppressed as none; no quota may be relaxed to satisfy conformance.
|
||||
|
||||
## Struct and contract integration
|
||||
|
||||
Existing PBS struct and contract rules apply unchanged: structs have reference identity; field visibility and `pub mut` control access; positional and named constructors obey overload selection and definite assignment; receiver `this`, fields and grouped values must execute faithfully. Runtime default initialization does not authorize exposure of a partially constructed source value.
|
||||
|
||||
`contract` and `implements` lower to typed Registry Trait descriptors and implementation tables. Adaptations preserve receiver and ImplementationId, including valid ID zero. `CALL_TRAIT` must use the selected method signature and complete argument/result groups. Struct and service owners are supported; service adaptations preserve singleton identity. This execution base is independent of future closure support.
|
||||
|
||||
## Diagnostics, tooling and conformance
|
||||
|
||||
Diagnostics must reject missing expected array types, invalid depth, optional elements, incompatible invariant arrays, non-integral sizes/indices and non-optional if-let operands. Editor types and hints use PBS array notation. Hover, completion, definitions, references and rename must respect success-only binding scope and source element identity.
|
||||
|
||||
Conformance must compile real PBS through typed IR and production PBX into the production loader/VM. Required cases include vacancy versus zero, alias mutation, contextual literals, nested arrays, int/long bounds, lazy and single evaluation, multi-slot groups, constructors and contract dispatch, service identity, resource refusal and GC/ownership. Assembly-only probes are insufficient. Installed knowledge must package this specification and executable examples.
|
||||
|
||||
## Related specifications
|
||||
|
||||
- [Core syntax](../../../specs/compiler-languages/pbs/3.%20Core%20Syntax%20Specification.md)
|
||||
- [Static semantics](../../../specs/compiler-languages/pbs/4.%20Static%20Semantics%20Specification.md)
|
||||
- [Dynamic semantics](../../../specs/compiler-languages/pbs/9.%20Dynamic%20Semantics%20Specification.md)
|
||||
- [Existing type runtime alignment](input-and-existing-type-runtime-alignment.md)
|
||||
|
||||
List/Set/Map, growth, iteration, equality and hashing policies belong to the separate SDK collections discussion. A future list capacity does not create logical elements; fixed array length does.
|
||||
@@ -335,3 +335,7 @@ This document is ready to move beyond temporary draft status only when:
|
||||
3. the VM heap versus host-memory boundary is normatively described,
|
||||
4. memory-related cost facts are specified well enough for diagnostics/tooling hooks,
|
||||
5. the remaining TODO items are reduced to editorial integration or future optional work rather than semantic uncertainty.
|
||||
|
||||
## Typed arrays and optional execution extension
|
||||
|
||||
The [typed arrays and optional execution specification](../../../compiler/pbs/specs/typed-arrays-and-optional-execution.md) defines array types/construction/indexing, contextual literals, optional bindings and runtime storage. Its rules extend this specification, including source typing, complete groups, Struct/contract execution and diagnostics.
|
||||
|
||||
@@ -176,3 +176,7 @@ This document is healthy when:
|
||||
2. recovery/rejection invariants are explicit and test-backed,
|
||||
3. attribution invariants are explicit and test-backed,
|
||||
4. lowering preconditions consumed by `13` are unambiguous.
|
||||
|
||||
## Typed arrays and optional execution extension
|
||||
|
||||
The [typed arrays and optional execution specification](../../../compiler/pbs/specs/typed-arrays-and-optional-execution.md) defines array types/construction/indexing, contextual literals, optional bindings and runtime storage. Its rules extend this specification, including source typing, complete groups, Struct/contract execution and diagnostics.
|
||||
|
||||
@@ -300,3 +300,7 @@ This document is ready to move beyond temporary status only when:
|
||||
## Existing values and input runtime alignment
|
||||
|
||||
The [PBS input and value alignment contract](../../../compiler/pbs/specs/input-and-existing-type-runtime-alignment.md) governs int/Int32, long/Int64, exact builtin carriers, the Pad/Button/LowPad and Touch API, named-argument evaluation order, migration diagnostics and executable conformance. It supersedes older input-object and untyped executable-lowering descriptions.
|
||||
|
||||
## Typed arrays and optional execution extension
|
||||
|
||||
The [typed arrays and optional execution specification](../../../compiler/pbs/specs/typed-arrays-and-optional-execution.md) defines array types/construction/indexing, contextual literals, optional bindings and runtime storage. Its rules extend this specification, including source typing, complete groups, Struct/contract execution and diagnostics.
|
||||
|
||||
@@ -242,3 +242,7 @@ At frontend `IRBackend` emission time:
|
||||
## Existing values and input runtime alignment
|
||||
|
||||
The [PBS input and value alignment contract](../../../compiler/pbs/specs/input-and-existing-type-runtime-alignment.md) governs int/Int32, long/Int64, exact builtin carriers, the Pad/Button/LowPad and Touch API, named-argument evaluation order, migration diagnostics and executable conformance. It supersedes older input-object and untyped executable-lowering descriptions.
|
||||
|
||||
## Typed arrays and optional execution extension
|
||||
|
||||
The [typed arrays and optional execution specification](../../../compiler/pbs/specs/typed-arrays-and-optional-execution.md) defines array types/construction/indexing, contextual literals, optional bindings and runtime storage. Its rules extend this specification, including source typing, complete groups, Struct/contract execution and diagnostics.
|
||||
|
||||
@@ -1236,3 +1236,7 @@ fn test(e: Enum) -> str {
|
||||
return label;
|
||||
}
|
||||
```
|
||||
|
||||
## Typed arrays and optional execution extension
|
||||
|
||||
The [typed arrays and optional execution specification](../../../compiler/pbs/specs/typed-arrays-and-optional-execution.md) defines array types/construction/indexing, contextual literals, optional bindings and runtime storage. Its rules extend this specification, including source typing, complete groups, Struct/contract execution and diagnostics.
|
||||
|
||||
@@ -878,3 +878,7 @@ At minimum, deterministic static diagnostics are required for:
|
||||
## Existing values and input runtime alignment
|
||||
|
||||
The [PBS input and value alignment contract](../../../compiler/pbs/specs/input-and-existing-type-runtime-alignment.md) governs int/Int32, long/Int64, exact builtin carriers, the Pad/Button/LowPad and Touch API, named-argument evaluation order, migration diagnostics and executable conformance. It supersedes older input-object and untyped executable-lowering descriptions.
|
||||
|
||||
## Typed arrays and optional execution extension
|
||||
|
||||
The [typed arrays and optional execution specification](../../../compiler/pbs/specs/typed-arrays-and-optional-execution.md) defines array types/construction/indexing, contextual literals, optional bindings and runtime storage. Its rules extend this specification, including source typing, complete groups, Struct/contract execution and diagnostics.
|
||||
|
||||
@@ -391,3 +391,7 @@ This document is ready to move beyond temporary draft status only when:
|
||||
## Existing values and input runtime alignment
|
||||
|
||||
The [PBS input and value alignment contract](../../../compiler/pbs/specs/input-and-existing-type-runtime-alignment.md) governs int/Int32, long/Int64, exact builtin carriers, the Pad/Button/LowPad and Touch API, named-argument evaluation order, migration diagnostics and executable conformance. It supersedes older input-object and untyped executable-lowering descriptions.
|
||||
|
||||
## Typed arrays and optional execution extension
|
||||
|
||||
The [typed arrays and optional execution specification](../../../compiler/pbs/specs/typed-arrays-and-optional-execution.md) defines array types/construction/indexing, contextual literals, optional bindings and runtime storage. Its rules extend this specification, including source typing, complete groups, Struct/contract execution and diagnostics.
|
||||
|
||||
+471
@@ -0,0 +1,471 @@
|
||||
package p.studio.compiler.backend.irvm;
|
||||
|
||||
import org.junit.jupiter.api.Test;
|
||||
import p.studio.compiler.pbs.PbsFrontendCompiler;
|
||||
import p.studio.compiler.models.IRBackend;
|
||||
import p.studio.compiler.models.IRBackendExecutableFunction;
|
||||
import p.studio.compiler.backend.bytecode.*;
|
||||
import p.studio.compiler.source.diagnostics.DiagnosticSink;
|
||||
import p.studio.compiler.source.identifiers.FileId;
|
||||
import p.studio.compiler.models.SourceKind;
|
||||
import java.nio.file.*;
|
||||
import p.studio.compiler.pbs.ast.PbsAst;
|
||||
import p.studio.utilities.structures.ReadOnlyList;
|
||||
import p.studio.compiler.source.identifiers.ModuleId;
|
||||
import static org.junit.jupiter.api.Assertions.*;
|
||||
|
||||
class PbsStructuredValuesTest {
|
||||
private static BytecodeModule compile(String name,String source) throws Exception {
|
||||
var diagnostics=DiagnosticSink.empty();
|
||||
var fileId = new FileId(0);
|
||||
var ast = p.studio.compiler.pbs.parser.PbsParser.parse(p.studio.compiler.pbs.lexer.PbsLexer.lex(source,fileId,diagnostics),fileId,diagnostics,p.studio.compiler.pbs.parser.PbsParser.ParseMode.INTERFACE_MODULE);
|
||||
var file=new PbsFrontendCompiler().compileParsedFile(fileId,ast,diagnostics,source.contains("[BuiltinType") ? SourceKind.SDK_INTERFACE : SourceKind.PROJECT,
|
||||
new p.studio.compiler.source.identifiers.ModuleId(0),p.studio.utilities.structures.ReadOnlyList.empty(),
|
||||
p.studio.compiler.messages.HostAdmissionContext.permissiveDefault(),p.studio.compiler.messages.FESurfaceContext.empty(),new p.studio.compiler.source.tables.NameTable());
|
||||
assertFalse(diagnostics.hasErrors(), ()->diagnostics.stream().map(d->d.getCode()+":"+d.getMessage()).toList().toString());
|
||||
var functions = new java.util.ArrayList<>(file.executableFunctions().asList());
|
||||
var signatures = new java.util.ArrayList<>(file.callableSignatures().asList());
|
||||
String entry = "Probe.main";
|
||||
var initializer = functions.stream().filter(f -> f.callableName().startsWith("__pbs.file_init$")).findFirst();
|
||||
if (initializer.isPresent()) {
|
||||
// The fixture driver performs the same ordered file-init call as the production lifecycle wrapper.
|
||||
var main = functions.stream().filter(f -> f.callableName().equals("Probe.main")).findFirst().orElseThrow();
|
||||
var init = initializer.get();
|
||||
var id = new p.studio.compiler.source.identifiers.CallableId(signatures.size());
|
||||
entry = "$test.entry";
|
||||
signatures.add(new p.studio.compiler.source.tables.CallableSignatureRef(new ModuleId(0),entry,0,"()->simple:int"));
|
||||
var kind = IRBackendExecutableFunction.InstructionKind.RET;
|
||||
var instructions = ReadOnlyList.from(
|
||||
new IRBackendExecutableFunction.Instruction(IRBackendExecutableFunction.InstructionKind.CALL_FUNC,
|
||||
new ModuleId(0),init.callableName(),init.callableId(),null,null,0,0,init.span()),
|
||||
new IRBackendExecutableFunction.Instruction(IRBackendExecutableFunction.InstructionKind.CALL_FUNC,
|
||||
new ModuleId(0),main.callableName(),main.callableId(),null,null,0,1,main.span()),
|
||||
new IRBackendExecutableFunction.Instruction(kind,"",null,null,main.span()));
|
||||
functions.add(new IRBackendExecutableFunction(fileId,new ModuleId(0),entry,id,0,0,0,0,1,1,instructions,main.span(),main.metadata()));
|
||||
}
|
||||
var backend=IRBackend.builder().entryPointCallableName(entry).entryPointModuleId(new ModuleId(0)).executableFunctions(ReadOnlyList.wrap(functions))
|
||||
.globals(file.globals()).registry(file.registry()).intrinsicPool(file.intrinsicPool()).callableSignatures(ReadOnlyList.wrap(signatures)).build();
|
||||
var program=new LowerToIRVMService().lower(backend);
|
||||
var module=new BytecodeEmitter().emit(program.coherentEmissionPlan());
|
||||
if (name.equals("gc-roots")) module = withTestSafepoint(module);
|
||||
new BytecodePreloadVerifierService().verify(module);
|
||||
var directory=Path.of(System.getProperty("pbs.registryConformanceDirectory"));Files.createDirectories(directory);
|
||||
Files.write(directory.resolve("pbs-structured-"+name+".pbx"),module.serialize());
|
||||
return module;
|
||||
}
|
||||
// PBS sync/closure syntax belongs to AGD82. This test-only driver hook replaces
|
||||
// an isolated marker assignment with FRAME_SYNC + NOPs, preserving every offset.
|
||||
// All allocations, roots, field/array access and post-GC assertions are compiled PBS.
|
||||
private static BytecodeModule withTestSafepoint(BytecodeModule module) {
|
||||
byte[] code = module.code().clone();
|
||||
var marker = java.nio.ByteBuffer.allocate(6).order(java.nio.ByteOrder.LITTLE_ENDIAN)
|
||||
.putShort((short) 0x17).putInt(314159).array();
|
||||
int found = 0;
|
||||
for (int offset = 0; offset + 12 <= code.length; offset++) {
|
||||
if (!java.util.Arrays.equals(marker, java.util.Arrays.copyOfRange(code, offset, offset + 6))) continue;
|
||||
assertEquals(0x43, code[offset + 6]);
|
||||
assertEquals(0, code[offset + 7]);
|
||||
java.util.Arrays.fill(code, offset, offset + 12, (byte) 0);
|
||||
code[offset] = (byte) 0x80;
|
||||
found++;
|
||||
}
|
||||
assertEquals(1, found, "exactly one test safepoint marker");
|
||||
return new BytecodeModule(module.version(), module.constPool(), module.functions(), code,
|
||||
module.debugInfo(), module.exports(), module.syscalls(), module.registry(), module.intrinsicSignatures());
|
||||
}
|
||||
|
||||
@Test void arraysAndOptionalReachProductionPbx() throws Exception {
|
||||
compile("array-cycle", """
|
||||
declare service Probe {
|
||||
fn main() -> int {
|
||||
let count: int = 3;
|
||||
let values: array int = new array(count);
|
||||
let index: int = 1;
|
||||
values[index] = 42;
|
||||
let answer = values[index] else 0;
|
||||
values.clear(index);
|
||||
if let absent = values[index] { return 999; }
|
||||
return answer;
|
||||
}
|
||||
}
|
||||
""");
|
||||
}
|
||||
@Test void literalsAndNestingReachProductionPbx() throws Exception {
|
||||
compile("array-nested", """
|
||||
declare service Probe {
|
||||
fn main() -> int {
|
||||
let groups: array[2] int = new array(3);
|
||||
groups[0] = [10, 42];
|
||||
if let group = groups[0] {
|
||||
if let value = group[1] { return value; }
|
||||
}
|
||||
return 0;
|
||||
}
|
||||
}
|
||||
""");
|
||||
}
|
||||
@Test void optionalFunctionAndLazyFallbackReachProductionPbx() throws Exception {
|
||||
compile("optional-flow", """
|
||||
declare service Probe {
|
||||
fn present() -> optional int { return some(42); }
|
||||
fn absent() -> optional int { return none; }
|
||||
fn main() -> int {
|
||||
let value: optional int = Probe.present();
|
||||
if let answer = value { return answer; }
|
||||
return Probe.absent() else 0;
|
||||
}
|
||||
}
|
||||
""");
|
||||
}
|
||||
@Test void structsConstructorsAndContractsReachProductionPbx() throws Exception {
|
||||
compile("struct-contract", """
|
||||
declare contract Target { fn health() -> int; }
|
||||
declare struct Enemy(pub mut hp: int) {
|
||||
ctor create(hp: int) { this.hp = hp; }
|
||||
fn damage(amount: int) { this.hp -= amount; }
|
||||
fn health() -> int { return this.hp; }
|
||||
}
|
||||
implements Target for Enemy using enemy { fn health() -> int { return enemy.health(); } }
|
||||
declare service Probe {
|
||||
fn main() -> int {
|
||||
let enemies: array Enemy = new array(2);
|
||||
let enemy = new Enemy.create(50);
|
||||
enemies[0] = enemy;
|
||||
if let selected = enemies[0] { selected.damage(8); }
|
||||
let target: Target = enemy;
|
||||
return target.health();
|
||||
}
|
||||
}
|
||||
""");
|
||||
}
|
||||
@Test void serviceContractAndOptionalGroupsReachProductionPbx() throws Exception {
|
||||
compile("service-contract", """
|
||||
declare contract Answer { fn value() -> int; }
|
||||
declare service Source { fn value() -> int { return 42; } }
|
||||
implements Answer for Source using source { fn value() -> int { return source.value(); } }
|
||||
declare service Probe {
|
||||
fn main() -> int {
|
||||
let first: Answer = Source;
|
||||
let second: Answer = Source;
|
||||
return first.value();
|
||||
}
|
||||
}
|
||||
""");
|
||||
compile("optional-tuple", """
|
||||
declare service Probe {
|
||||
fn pair() -> optional (left: int, right: int) { return some((left: 20, right: 22)); }
|
||||
fn main() -> int {
|
||||
if let pair = Probe.pair() { return pair.left + pair.right; }
|
||||
return 0;
|
||||
}
|
||||
}
|
||||
""");
|
||||
}
|
||||
@Test void tupleStorageAndOptionalIntrinsicsReachProductionPbx() throws Exception {
|
||||
compile("tuple-storage", """
|
||||
declare struct Pair(pub mut value: (left: int, right: int)) {}
|
||||
declare service Probe {
|
||||
fn main() -> int {
|
||||
let values: array (left: int, right: int) = [(left: 20, right: 22)];
|
||||
if let pair = values[0] {
|
||||
let holder = new Pair(pair);
|
||||
holder.value = (left: 21, right: 21);
|
||||
return holder.value.left + holder.value.right;
|
||||
}
|
||||
return 0;
|
||||
}
|
||||
}
|
||||
""");
|
||||
compile("optional-intrinsics", """
|
||||
declare service Probe {
|
||||
fn absent() -> optional int {}
|
||||
fn main() -> int {
|
||||
let values: array int = [0];
|
||||
if values[0].hasSome() {
|
||||
if Probe.absent().hasNone() { return 42; }
|
||||
}
|
||||
return 0;
|
||||
}
|
||||
}
|
||||
""");
|
||||
compile("optional-lazy", """
|
||||
declare service Probe {
|
||||
fn forbidden() -> int {
|
||||
let empty: array int = [];
|
||||
return empty[0] else 999;
|
||||
}
|
||||
fn main() -> int {
|
||||
let value: optional int = some(42);
|
||||
return value else Probe.forbidden();
|
||||
}
|
||||
}
|
||||
""");
|
||||
}
|
||||
@Test void contextualArraysAndAliasReachProductionPbx() throws Exception {
|
||||
compile("array-context", """
|
||||
declare service Probe {
|
||||
fn make() -> array int { return [20, 22]; }
|
||||
fn sum(values: array int) -> int { return (values[0] else 0) + (values[1] else 0); }
|
||||
fn main() -> int {
|
||||
let values: array int = { [1, 2] };
|
||||
let alias = values;
|
||||
alias[0] = 20;
|
||||
alias[1] = 22;
|
||||
let answer = Probe.sum(values);
|
||||
if answer != Probe.sum([20, 22]) { return 999; }
|
||||
if answer != Probe.sum(Probe.make()) { return 998; }
|
||||
return answer;
|
||||
}
|
||||
}
|
||||
""");
|
||||
compile("binding-scope", """
|
||||
declare service Probe {
|
||||
fn main() -> int {
|
||||
let answer = 42;
|
||||
let value: optional int = some(8);
|
||||
if let answer = value { let ignored = answer; }
|
||||
return answer;
|
||||
}
|
||||
}
|
||||
""");
|
||||
}
|
||||
@Test void overloadsAndEvaluationOrderReachProductionPbx() throws Exception {
|
||||
compile("overloads", """
|
||||
declare struct Enemy(pub hp: int) {
|
||||
ctor create(value: int) { this.hp = value; }
|
||||
ctor create(value: bool) { this.hp = 999; }
|
||||
fn add(value: int) -> int { return this.hp + value; }
|
||||
fn add(value: bool) -> int { return 999; }
|
||||
}
|
||||
declare service Probe {
|
||||
fn main() -> int { return new Enemy.create(40).add(2); }
|
||||
}
|
||||
""");
|
||||
compile("single-evaluation", """
|
||||
declare struct Counter(pub mut count: int) {
|
||||
fn next() -> int { this.count += 1; return this.count - 1; }
|
||||
fn present() -> optional int { this.count += 1; return some(42); }
|
||||
}
|
||||
declare service Probe {
|
||||
fn main() -> int {
|
||||
let counter = new Counter(0);
|
||||
let values: array int = new array(2);
|
||||
values[counter.next()] = counter.next();
|
||||
if counter.count != 2 { return 999; }
|
||||
if (values[0] else 99) != 1 { return 998; }
|
||||
if let value = counter.present() {
|
||||
if counter.count == 3 { return value; }
|
||||
}
|
||||
return 997;
|
||||
}
|
||||
}
|
||||
""");
|
||||
}
|
||||
@Test void boundsFixturesReachProductionPbx() throws Exception {
|
||||
for (var entry : java.util.Map.of(
|
||||
"negative-index", "let a: array int = new array(1); return a[-1] else 42;",
|
||||
"past-end", "let a: array int = new array(1); return a[1] else 42;",
|
||||
"negative-length", "let size: int = -1; let a: array int = new array(size); return 42;",
|
||||
"large-length", "let size: long = 4294967296; let a: array int = new array(size); return 42;"
|
||||
).entrySet()) compile(entry.getKey(), "declare service Probe { fn main() -> int { " + entry.getValue() + " } }");
|
||||
compile("long-boundaries", """
|
||||
declare service Probe {
|
||||
fn main() -> int {
|
||||
let size: long = 2;
|
||||
let a: array int = new array(size);
|
||||
let first: long = 0;
|
||||
let last: int = 1;
|
||||
a[first] = 20;
|
||||
a[last] = 22;
|
||||
if a.length != size { return 999; }
|
||||
return (a[first] else 0) + (a[last] else 0);
|
||||
}
|
||||
}
|
||||
""");
|
||||
}
|
||||
@Test void sourceOwnedGroupsSurviveRuntimeSafepoint() throws Exception {
|
||||
compile("gc-roots", """
|
||||
declare struct Enemy(pub hp: int) {}
|
||||
declare service Probe {
|
||||
fn garbage() { let discarded: array int = new array(1); }
|
||||
fn gcCollect() { let marker = 314159; }
|
||||
fn main() -> int {
|
||||
let keep: array Enemy = [new Enemy(42)];
|
||||
let tuples: array (left: int, right: int) = [(left: 20, right: 22)];
|
||||
let names: array str = new array(2);
|
||||
names[0] = "enemy";
|
||||
for i: int from 0 until 1100 { Probe.garbage(); }
|
||||
Probe.gcCollect();
|
||||
if let unexpected = names[1] { return 997; }
|
||||
if (names[0] else "missing") != "enemy" { return 996; }
|
||||
if let enemy = keep[0] {
|
||||
if let pair = tuples[0] {
|
||||
if pair.left + pair.right == enemy.hp { return enemy.hp; }
|
||||
}
|
||||
}
|
||||
return 999;
|
||||
}
|
||||
}
|
||||
""");
|
||||
}
|
||||
@Test void nativeGroupsAndContractElementsReachProductionPbx() throws Exception {
|
||||
compile("native-groups", """
|
||||
[BuiltinType(name = "vec2", version = 1)]
|
||||
declare builtin type Vector(pub x: float, pub y: float) {}
|
||||
declare service Probe {
|
||||
fn main() -> int {
|
||||
let vectors: array Vector = [new Vector(20.0, 22.0)];
|
||||
let vector = vectors[0] else new Vector(0.0, 0.0);
|
||||
return (vector.x + vector.y) as int;
|
||||
}
|
||||
}
|
||||
""");
|
||||
compile("contract-elements", """
|
||||
declare contract Target { fn health() -> int; }
|
||||
declare struct Enemy(pub hp: int) { fn same() -> Self { return this; } }
|
||||
implements Target for Enemy using enemy { fn health() -> int { return enemy.hp; } }
|
||||
declare service Probe {
|
||||
fn main() -> int {
|
||||
let enemy = new Enemy(42);
|
||||
let targets: array Target = [enemy as Target];
|
||||
if let target = targets[0] { return target.health(); }
|
||||
return 999;
|
||||
}
|
||||
}
|
||||
""");
|
||||
}
|
||||
@Test void importedStructAndServiceUseProviderIdentity() throws Exception {
|
||||
var diagnostics = DiagnosticSink.empty();
|
||||
String providerSource = """
|
||||
declare contract Answer { fn answer() -> int; }
|
||||
declare struct Enemy(pub hp: int) {
|
||||
ctor create(hp: int) { this.hp = hp; }
|
||||
fn health() -> int { return this.hp; }
|
||||
}
|
||||
implements Answer for Enemy using enemy { fn answer() -> int { return enemy.hp; } }
|
||||
declare service Source { fn value() -> int { return 42; } }
|
||||
""";
|
||||
String clientSource = """
|
||||
declare service Probe {
|
||||
fn main() -> int {
|
||||
let values: array Enemy = [new Enemy.create(42)];
|
||||
let first = Source;
|
||||
let second = Source;
|
||||
if first != second { return 999; }
|
||||
if let enemy = values[0] {
|
||||
let target: Answer = enemy as Answer;
|
||||
if enemy.health() == first.value() { return target.answer(); }
|
||||
}
|
||||
return 998;
|
||||
}
|
||||
}
|
||||
""";
|
||||
var compiler = new PbsFrontendCompiler();
|
||||
var host = p.studio.compiler.messages.HostAdmissionContext.permissiveDefault();
|
||||
var surface = p.studio.compiler.messages.FESurfaceContext.empty();
|
||||
var names = new p.studio.compiler.source.tables.NameTable();
|
||||
var providerId = new FileId(10);
|
||||
var providerAst = p.studio.compiler.pbs.parser.PbsParser.parse(
|
||||
p.studio.compiler.pbs.lexer.PbsLexer.lex(providerSource, providerId, diagnostics), providerId, diagnostics,
|
||||
p.studio.compiler.pbs.parser.PbsParser.ParseMode.INTERFACE_MODULE);
|
||||
var modules = ReadOnlyList.from(new p.studio.compiler.source.tables.ModuleReference("test",ReadOnlyList.from("provider")),
|
||||
new p.studio.compiler.source.tables.ModuleReference("test",ReadOnlyList.from("client")));
|
||||
var provider = compiler.compileParsedFile(providerId, providerAst, diagnostics, SourceKind.PROJECT,
|
||||
new ModuleId(0), modules, host, surface, names);
|
||||
var imported = new java.util.ArrayList<PbsFrontendCompiler.ImportedCallableSurface>();
|
||||
for (var signature : provider.callableSignatures()) {
|
||||
var executable = provider.executableFunctions().stream().filter(f -> f.callableName().equals(signature.callableName())).findFirst().orElseThrow();
|
||||
var type = signature.callableName().endsWith("$instance") ? PbsAst.TypeRef.simple("Source",providerAst.span())
|
||||
: executable.returnSlots() == 0 ? PbsAst.TypeRef.unit(providerAst.span()) : PbsAst.TypeRef.simple("int",providerAst.span());
|
||||
imported.add(new PbsFrontendCompiler.ImportedCallableSurface(new ModuleId(0),signature.callableName(), signature.arity(),
|
||||
executable.returnSlots(), executable.returnSlots()==0?PbsAst.ReturnKind.EXPLICIT_UNIT:PbsAst.ReturnKind.PLAIN, type, signature.typeShape()));
|
||||
}
|
||||
var clientId = new FileId(11);
|
||||
var clientAst = p.studio.compiler.pbs.parser.PbsParser.parse(
|
||||
p.studio.compiler.pbs.lexer.PbsLexer.lex(clientSource, clientId, diagnostics), clientId, diagnostics,
|
||||
p.studio.compiler.pbs.parser.PbsParser.ParseMode.INTERFACE_MODULE);
|
||||
var client = compiler.compileParsedFile(clientId, clientAst, diagnostics, SourceKind.PROJECT, new ModuleId(1),modules,
|
||||
host,surface,names,providerAst.topDecls(),ReadOnlyList.wrap(imported),ReadOnlyList.empty(),
|
||||
p.studio.compiler.models.IRReservedMetadata.empty(),java.util.Map.of());
|
||||
assertFalse(diagnostics.hasErrors(), () -> diagnostics.stream().map(d -> d.getCode()+":"+d.getMessage()).toList().toString());
|
||||
var aggregator = IRBackend.aggregator();
|
||||
aggregator.merge(provider); aggregator.merge(client);
|
||||
var backend = aggregator.entryPointCallableName("Probe.main").entryPointModuleId(new ModuleId(1)).emit();
|
||||
var program = new LowerToIRVMService().lower(backend);
|
||||
var module = new BytecodeEmitter().emit(program.coherentEmissionPlan());
|
||||
new BytecodePreloadVerifierService().verify(module);
|
||||
Files.write(Path.of(System.getProperty("pbs.registryConformanceDirectory"),"pbs-structured-imports.pbx"),module.serialize());
|
||||
}
|
||||
@Test void globalArraysAreInitializedBeforeUse() throws Exception {
|
||||
compile("global-array", """
|
||||
declare global values: array int = [20, 22];
|
||||
declare global empty: array int = new array(3);
|
||||
declare service Probe {
|
||||
fn main() -> int {
|
||||
if empty.length != 3 as long { return 999; }
|
||||
if let unexpected = empty[0] { return 998; }
|
||||
return (values[0] else 0) + (values[1] else 0);
|
||||
}
|
||||
}
|
||||
""");
|
||||
}
|
||||
@Test void installedArrayExampleExecutes() throws Exception {
|
||||
try (var stream = PbsFrontendCompiler.class.getResourceAsStream("/pbs-knowledge/examples/game/1/src/arrays.pbs")) {
|
||||
assertNotNull(stream);
|
||||
var source = new String(stream.readAllBytes(),java.nio.charset.StandardCharsets.UTF_8);
|
||||
compile("installed-example",source+"\ndeclare service Probe { fn main() -> int { return arrayExample(); } }");
|
||||
}
|
||||
}
|
||||
@Test void returnOverloadsAndInferredOptionalGroupsExecute() throws Exception {
|
||||
compile("return-overloads", """
|
||||
declare struct Box(pub n: int) {
|
||||
fn get() -> int { return this.n; }
|
||||
fn get() -> long { return 999; }
|
||||
fn same() -> Self { return this; }
|
||||
}
|
||||
declare service Probe {
|
||||
fn main() -> int {
|
||||
let box = new Box(42);
|
||||
let answer: int = box.same().get();
|
||||
return answer;
|
||||
}
|
||||
}
|
||||
""");
|
||||
compile("inferred-optional-tuple", """
|
||||
declare service Probe {
|
||||
fn main() -> int {
|
||||
let value = some((left: 20, right: 22));
|
||||
if let pair = value { return pair.left + pair.right; }
|
||||
return 999;
|
||||
}
|
||||
}
|
||||
""");
|
||||
}
|
||||
@Test void integerStorageNeedsOnlyTheArrayHandle() throws Exception {
|
||||
compile("inline-integers", """
|
||||
declare service Probe {
|
||||
fn main() -> int {
|
||||
let values: array int = [10, 20, 30];
|
||||
return (values.length as int) + 39;
|
||||
}
|
||||
}
|
||||
""");
|
||||
}
|
||||
@Test void invalidArraySurfacesAreRejected() {
|
||||
for(var body : new String[] {
|
||||
"let values = [1, 2];", "let values = [];", "let values = new array(3);",
|
||||
"let values: array (optional int) = new array(3);",
|
||||
"let values: array[2147483647] int = new array(3);", "let values: array[0] int = new array(3);", "let values: array[-1] int = new array(3);",
|
||||
"let values: array int = new array(3); let x = values[true];",
|
||||
"let values: array int = new array(3); values[0] = true;",
|
||||
"if let value = 42 { let x = value; }",
|
||||
"let value: optional int = some(1); if let found = value {} let bad = found;",
|
||||
"let value: optional int = some(1); if let found = value {} else { let bad = found; }",
|
||||
"let values: array int = new array(3); let wrong: array bool = values;"
|
||||
}) {
|
||||
var diagnostics=DiagnosticSink.empty();
|
||||
new PbsFrontendCompiler().compileFile(new FileId(0),"fn main() { "+body+" }",diagnostics);
|
||||
assertTrue(diagnostics.hasErrors(), body);
|
||||
}
|
||||
}
|
||||
}
|
||||
+10
-1
@@ -244,7 +244,10 @@ public final class PbsCallHierarchy {
|
||||
}
|
||||
case PbsAst.LetStatement letStatement -> collectCalls(letStatement.initializer(), calls);
|
||||
case PbsAst.ReturnStatement returnStatement -> collectCalls(returnStatement.value(), calls);
|
||||
case PbsAst.AssignStatement assignStatement -> collectCalls(assignStatement.value(), calls);
|
||||
case PbsAst.AssignStatement assignStatement -> {
|
||||
collectCalls(assignStatement.target().expression(), calls);
|
||||
collectCalls(assignStatement.value(), calls);
|
||||
}
|
||||
case PbsAst.ExpressionStatement expressionStatement -> collectCalls(expressionStatement.expression(), calls);
|
||||
case PbsAst.IfStatement ifStatement -> {
|
||||
collectCalls(ifStatement.condition(), calls);
|
||||
@@ -280,6 +283,12 @@ public final class PbsCallHierarchy {
|
||||
}
|
||||
}
|
||||
}
|
||||
case PbsAst.ArrayLiteralExpr literal -> literal.elements().forEach(value -> collectCalls(value, calls));
|
||||
case PbsAst.IndexExpr index -> { collectCalls(index.receiver(), calls); collectCalls(index.index(), calls); }
|
||||
case PbsAst.NewExpr value -> value.arguments().forEach(argument -> collectCalls(argument, calls));
|
||||
case PbsAst.SomeExpr value -> collectCalls(value.value(), calls);
|
||||
case PbsAst.ElseExpr value -> { collectCalls(value.optionalExpression(), calls); collectCalls(value.fallbackExpression(), calls); }
|
||||
case PbsAst.TupleExpr tuple -> tuple.items().forEach(item -> collectCalls(item.expression(), calls));
|
||||
case PbsAst.MemberExpr memberExpr -> collectCalls(memberExpr.receiver(), calls);
|
||||
case PbsAst.BinaryExpr binaryExpr -> {
|
||||
collectCalls(binaryExpr.left(), calls);
|
||||
|
||||
+15
-4
@@ -189,9 +189,8 @@ public final class PbsFrontendCompiler {
|
||||
final ReadOnlyList<IRSyntheticFunction> syntheticFunctions = sourceKind == SourceKind.SDK_INTERFACE
|
||||
? ReadOnlyList.empty()
|
||||
: lowerSyntheticFunctions(fileId, effectiveModuleId, ast);
|
||||
final ReadOnlyList<IRGlobal> globals = sourceKind == SourceKind.SDK_INTERFACE
|
||||
? ReadOnlyList.empty()
|
||||
: lowerGlobals(fileId, effectiveModuleId, ast, effectiveDeclaredGlobalVisibilityByName);
|
||||
final ReadOnlyList<IRGlobal> globals = lowerGlobals(fileId, effectiveModuleId, ast, effectiveDeclaredGlobalVisibilityByName,
|
||||
sourceKind != SourceKind.SDK_INTERFACE);
|
||||
final var loweringErrorBaseline = diagnostics.errorCount();
|
||||
final var executableLowering = executableLoweringService.lower(
|
||||
fileId,
|
||||
@@ -279,13 +278,15 @@ public final class PbsFrontendCompiler {
|
||||
final FileId fileId,
|
||||
final ModuleId moduleId,
|
||||
final PbsAst.File ast,
|
||||
final Map<String, IRGlobalVisibility> declaredGlobalVisibilityByName) {
|
||||
final Map<String, IRGlobalVisibility> declaredGlobalVisibilityByName,
|
||||
final boolean includeUserGlobals) {
|
||||
final var globals = new ArrayList<IRGlobal>();
|
||||
var nextSlot = 0;
|
||||
for (final var topDecl : ast.topDecls()) {
|
||||
if (!(topDecl instanceof PbsAst.GlobalDecl globalDecl)) {
|
||||
continue;
|
||||
}
|
||||
if (!includeUserGlobals) { nextSlot++; continue; }
|
||||
globals.add(new IRGlobal(
|
||||
fileId,
|
||||
moduleId,
|
||||
@@ -303,6 +304,12 @@ public final class PbsFrontendCompiler {
|
||||
globalDecl.name()),
|
||||
globalDecl.span()));
|
||||
}
|
||||
for (var decl : ast.topDecls()) if (decl instanceof PbsAst.ServiceDecl service) {
|
||||
var name = "$service."+service.name();
|
||||
globals.add(new IRGlobal(fileId,moduleId,name,service.name(),nextSlot++,IRGlobalVisibility.MODULE,
|
||||
false,p.studio.compiler.models.IRHiddenGlobalKind.NONE,
|
||||
new IRGlobalOrigin(fileId,moduleId,name,service.span(),name),service.span()));
|
||||
}
|
||||
return ReadOnlyList.wrap(globals);
|
||||
}
|
||||
|
||||
@@ -350,6 +357,10 @@ public final class PbsFrontendCompiler {
|
||||
callableSignatures.add(new CallableSignatureRef(moduleId, syntheticCallableName, 0, "() -> unit"));
|
||||
|
||||
final var instructions = new ArrayList<IRBackendExecutableFunction.Instruction>();
|
||||
var globalInit = resolveLifecycleExecutable(executableFunctions,moduleId,"$globals."+fileId.getId());
|
||||
if (globalInit != null) instructions.add(new IRBackendExecutableFunction.Instruction(
|
||||
IRBackendExecutableFunction.InstructionKind.CALL_FUNC,moduleId,globalInit.callableName(),globalInit.callableId(),
|
||||
null,null,0,0,globalInit.span()));
|
||||
final var moduleInitSource = ordinaryFileInit;
|
||||
if (moduleInitSource != null) {
|
||||
final var initExecutable = resolveLifecycleExecutable(executableFunctions, moduleId, moduleInitSource.name());
|
||||
|
||||
+1
@@ -238,6 +238,7 @@ public final class PbsReservedMetadataExtractor {
|
||||
return switch (typeRef.kind()) {
|
||||
case SIMPLE -> "simple:" + typeRef.name();
|
||||
case SELF -> "self";
|
||||
case ARRAY -> "array(" + typeSurfaceKey(typeRef.inner()) + ")";
|
||||
case OPTIONAL -> "optional(" + typeSurfaceKey(typeRef.inner()) + ")";
|
||||
case UNIT -> "unit";
|
||||
case GROUP -> "group(" + typeSurfaceKey(typeRef.inner()) + ")";
|
||||
|
||||
+29
@@ -0,0 +1,29 @@
|
||||
package p.studio.compiler.pbs;
|
||||
|
||||
import p.studio.compiler.pbs.ast.PbsAst;
|
||||
import p.studio.utilities.structures.ReadOnlyList;
|
||||
|
||||
/** Resolves Self consistently in source signatures and executable metadata. */
|
||||
public final class PbsTypeSubstitution {
|
||||
private PbsTypeSubstitution() {}
|
||||
|
||||
public static PbsAst.TypeRef replaceSelf(PbsAst.TypeRef type, String owner) {
|
||||
if (type == null) return null;
|
||||
if (type.kind() == PbsAst.TypeRefKind.SELF) return PbsAst.TypeRef.simple(owner, type.span());
|
||||
if (type.kind() == PbsAst.TypeRefKind.NAMED_TUPLE) {
|
||||
return PbsAst.TypeRef.namedTuple(ReadOnlyList.wrap(type.fields().stream().map(field ->
|
||||
new PbsAst.NamedTypeField(field.label(), replaceSelf(field.typeRef(), owner), field.span())).toList()), type.span());
|
||||
}
|
||||
if (type.inner() != null) {
|
||||
return new PbsAst.TypeRef(type.kind(), type.name(), type.fields(), replaceSelf(type.inner(), owner), type.span());
|
||||
}
|
||||
return type;
|
||||
}
|
||||
|
||||
public static PbsAst.FunctionDecl forOwner(PbsAst.FunctionDecl function, String owner) {
|
||||
var parameters = ReadOnlyList.wrap(function.parameters().stream().map(parameter ->
|
||||
new PbsAst.Parameter(parameter.name(), replaceSelf(parameter.typeRef(), owner), parameter.span())).toList());
|
||||
return new PbsAst.FunctionDecl(function.name(), parameters, function.returnKind(), replaceSelf(function.returnType(), owner),
|
||||
replaceSelf(function.resultErrorType(), owner), function.attributes(), function.lifecycleMarker(), function.body(), function.span());
|
||||
}
|
||||
}
|
||||
+22
-2
@@ -20,6 +20,7 @@ public final class PbsAst {
|
||||
SIMPLE,
|
||||
SELF,
|
||||
OPTIONAL,
|
||||
ARRAY,
|
||||
UNIT,
|
||||
GROUP,
|
||||
NAMED_TUPLE,
|
||||
@@ -262,6 +263,10 @@ public final class PbsAst {
|
||||
return new TypeRef(TypeRefKind.SELF, "Self", ReadOnlyList.empty(), null, span);
|
||||
}
|
||||
|
||||
public static TypeRef array(final TypeRef inner, final Span span) {
|
||||
return new TypeRef(TypeRefKind.ARRAY, "array", ReadOnlyList.empty(), inner, span);
|
||||
}
|
||||
|
||||
public static TypeRef optional(final TypeRef inner, final Span span) {
|
||||
return new TypeRef(TypeRefKind.OPTIONAL, "optional", ReadOnlyList.empty(), inner, span);
|
||||
}
|
||||
@@ -351,7 +356,11 @@ public final class PbsAst {
|
||||
public record LValue(
|
||||
String rootName,
|
||||
ReadOnlyList<String> pathSegments,
|
||||
Span span) {
|
||||
Span span,
|
||||
Expression expression) {
|
||||
public LValue(String rootName, ReadOnlyList<String> pathSegments, Span span) {
|
||||
this(rootName, pathSegments, span, null);
|
||||
}
|
||||
}
|
||||
|
||||
public record LetStatement(
|
||||
@@ -380,7 +389,12 @@ public final class PbsAst {
|
||||
Block thenBlock,
|
||||
IfStatement elseIf,
|
||||
Block elseBlock,
|
||||
Span span) implements Statement {
|
||||
Span span,
|
||||
String bindingName,
|
||||
Span bindingSpan) implements Statement {
|
||||
public IfStatement(Expression condition, Block thenBlock, IfStatement elseIf, Block elseBlock, Span span) {
|
||||
this(condition, thenBlock, elseIf, elseBlock, span, null, null);
|
||||
}
|
||||
}
|
||||
|
||||
public record ForStatement(
|
||||
@@ -428,6 +442,8 @@ public final class PbsAst {
|
||||
AsExpr,
|
||||
CallExpr,
|
||||
MemberExpr,
|
||||
IndexExpr,
|
||||
ArrayLiteralExpr,
|
||||
PropagateExpr,
|
||||
GroupExpr,
|
||||
ThisExpr,
|
||||
@@ -582,6 +598,10 @@ public final class PbsAst {
|
||||
Span span) implements Expression {
|
||||
}
|
||||
|
||||
public record IndexExpr(Expression receiver, Expression index, Span span) implements Expression {}
|
||||
|
||||
public record ArrayLiteralExpr(ReadOnlyList<Expression> elements, Span span) implements Expression {}
|
||||
|
||||
public record MemberExpr(
|
||||
Expression receiver,
|
||||
String memberName,
|
||||
|
||||
+2
-1
@@ -62,7 +62,7 @@ final class PbsCallableShapeSurfaceService {
|
||||
};
|
||||
}
|
||||
|
||||
private String typeSurfaceKey(final PbsAst.TypeRef typeRef) {
|
||||
String typeSurfaceKey(final PbsAst.TypeRef typeRef) {
|
||||
final var unwrapped = unwrapGroup(typeRef);
|
||||
if (unwrapped == null) {
|
||||
return "unit";
|
||||
@@ -70,6 +70,7 @@ final class PbsCallableShapeSurfaceService {
|
||||
return switch (unwrapped.kind()) {
|
||||
case SIMPLE -> "simple:" + unwrapped.name();
|
||||
case SELF -> "self";
|
||||
case ARRAY -> "array(" + typeSurfaceKey(unwrapped.inner()) + ")";
|
||||
case OPTIONAL -> "optional(" + typeSurfaceKey(unwrapped.inner()) + ")";
|
||||
case UNIT -> "unit";
|
||||
case GROUP -> typeSurfaceKey(unwrapped.inner());
|
||||
|
||||
+465
-16
@@ -1,8 +1,13 @@
|
||||
package p.studio.compiler.pbs.lowering;
|
||||
|
||||
import p.studio.compiler.models.IRBackendExecutableFunction;
|
||||
import p.studio.compiler.models.registry.IRRegistry;
|
||||
import p.studio.compiler.models.registry.IRRegistryInstruction;
|
||||
import p.studio.compiler.source.Span;
|
||||
import static p.studio.compiler.models.registry.IRRegistryInstruction.Kind.*;
|
||||
import p.studio.compiler.pbs.PbsCallableSlotCounter;
|
||||
import p.studio.compiler.pbs.ast.PbsAst;
|
||||
import p.studio.compiler.pbs.PbsTypeSubstitution;
|
||||
import p.studio.compiler.pbs.semantics.PbsSemanticsErrors;
|
||||
import p.studio.compiler.source.diagnostics.DiagnosticPhase;
|
||||
import p.studio.compiler.source.diagnostics.DiagnosticSink;
|
||||
@@ -23,6 +28,7 @@ final class PbsExecutableBodyLowerer {
|
||||
|
||||
PbsLoweredExecutableBody lower(
|
||||
final PbsAst.FunctionDecl functionDecl,
|
||||
final String callableName,
|
||||
final DiagnosticSink diagnostics,
|
||||
final NameTable nameTable,
|
||||
final PbsExecutableMetadataIndex metadataIndex,
|
||||
@@ -40,6 +46,8 @@ final class PbsExecutableBodyLowerer {
|
||||
localOwnerByNameId,
|
||||
functionDecl.parameters().stream().mapToInt(p -> metadataIndex.types().slots(p.typeRef())).sum());
|
||||
for (var parameter : functionDecl.parameters()) context.localTypes.put(parameter.name(), parameter.typeRef());
|
||||
var separator=callableName.indexOf('.');
|
||||
if(separator>0 && metadataIndex.types().services.containsKey(callableName.substring(0,separator))) context.serviceOwner=callableName.substring(0,separator);
|
||||
context.returnType = functionDecl.returnType();
|
||||
final var terminated = lowerBlock(functionDecl.body(), context);
|
||||
finalizeFunctionInstructions(functionDecl, context, terminated);
|
||||
@@ -102,6 +110,10 @@ final class PbsExecutableBodyLowerer {
|
||||
if (terminated) {
|
||||
return;
|
||||
}
|
||||
var returnType = PbsRuntimeTypes.unwrap(context.returnType);
|
||||
if (returnType != null && returnType.kind() == PbsAst.TypeRefKind.OPTIONAL) {
|
||||
emitDefault(context.types().registryType(returnType), 1, functionDecl.span(), context);
|
||||
}
|
||||
context.instructions().add(new IRBackendExecutableFunction.Instruction(
|
||||
IRBackendExecutableFunction.InstructionKind.RET,
|
||||
"",
|
||||
@@ -117,6 +129,7 @@ final class PbsExecutableBodyLowerer {
|
||||
if (block == null) {
|
||||
return false;
|
||||
}
|
||||
final var scope = context.snapshotScope();
|
||||
var terminated = false;
|
||||
for (final var statement : block.statements()) {
|
||||
if (terminated) {
|
||||
@@ -127,6 +140,7 @@ final class PbsExecutableBodyLowerer {
|
||||
if (!terminated && block.tailExpression() != null) {
|
||||
lowerExpression(block.tailExpression(), context);
|
||||
}
|
||||
context.restoreScope(scope);
|
||||
return terminated;
|
||||
}
|
||||
|
||||
@@ -158,10 +172,11 @@ final class PbsExecutableBodyLowerer {
|
||||
final PbsExecutableLoweringContext context) {
|
||||
final var localOwner = callsiteEmitter.resolveExpressionOwnerForLowering(letStatement.initializer(), context);
|
||||
final var tupleProjection = tupleProjectionOf(letStatement.initializer(), context);
|
||||
final var valueSlots = Math.max(1, materializedValueSlots(letStatement.initializer(), context));
|
||||
final var localType = letStatement.explicitType() != null ? letStatement.explicitType() : expressionType(letStatement.initializer(), context);
|
||||
final var valueSlots = localType != null ? context.types().slots(localType) : Math.max(1, materializedValueSlots(letStatement.initializer(), context));
|
||||
lowerExpected(letStatement.initializer(), localType, context);
|
||||
context.localTypes.put(letStatement.name(), localType);
|
||||
context.localSlotByNameId().remove(context.nameTable().register(letStatement.name()));
|
||||
final var localSlot = context.declareLocalSlots(letStatement.name(), valueSlots);
|
||||
context.bindLocalOwner(letStatement.name(), localOwner);
|
||||
context.bindLocalTupleProjection(letStatement.name(), tupleProjection);
|
||||
@@ -173,12 +188,16 @@ final class PbsExecutableBodyLowerer {
|
||||
final PbsAst.AssignStatement assignStatement,
|
||||
final PbsExecutableLoweringContext context) {
|
||||
final var target = assignStatement.target();
|
||||
if (target.expression() instanceof PbsAst.IndexExpr index) {
|
||||
lowerArrayWrite(index, assignStatement.value(), context);
|
||||
return false;
|
||||
}
|
||||
if (target == null || target.rootName() == null || target.rootName().isBlank()) {
|
||||
reportUnsupportedLowering("assignment target requires a local root name", assignStatement.span(), context);
|
||||
return false;
|
||||
}
|
||||
if (target.pathSegments() != null && !target.pathSegments().isEmpty()) {
|
||||
reportUnsupportedLowering("path assignment lowering is not supported in executable lowering v1", assignStatement.span(), context);
|
||||
lowerFieldAssignment(assignStatement, context);
|
||||
return false;
|
||||
}
|
||||
final var targetLocalSlot = context.resolveLocalSlot(target.rootName());
|
||||
@@ -197,6 +216,8 @@ final class PbsExecutableBodyLowerer {
|
||||
context.bindLocalTupleProjection(target.rootName(), tupleProjection);
|
||||
emitStoreLocalSlots(targetLocalSlot, valueSlots, assignStatement.span(), context);
|
||||
} else {
|
||||
var type = context.types().values.get(target.rootName());
|
||||
if (context.types().slots(type) > 1) wrapOptional(type,assignStatement.span(),context);
|
||||
emitSetGlobal(targetGlobalSlot, assignStatement.span(), context);
|
||||
}
|
||||
return false;
|
||||
@@ -256,6 +277,7 @@ final class PbsExecutableBodyLowerer {
|
||||
private boolean lowerIfStatement(
|
||||
final PbsAst.IfStatement ifStatement,
|
||||
final PbsExecutableLoweringContext context) {
|
||||
if (ifStatement.bindingName() != null) return lowerIfLet(ifStatement, context);
|
||||
lowerExpression(ifStatement.condition(), context);
|
||||
final var elseLabel = context.nextLabel("if_else");
|
||||
final var endLabel = context.nextLabel("if_end");
|
||||
@@ -368,6 +390,8 @@ final class PbsExecutableBodyLowerer {
|
||||
return;
|
||||
}
|
||||
switch (expression) {
|
||||
case PbsAst.ArrayLiteralExpr literal -> lowerArrayLiteral(literal, context);
|
||||
case PbsAst.IndexExpr index -> lowerArrayRead(index, context);
|
||||
case PbsAst.CallExpr callExpr -> lowerCallExpression(callExpr, context);
|
||||
case PbsAst.ApplyExpr applyExpr -> lowerApply(applyExpr, context);
|
||||
case PbsAst.BinaryExpr binaryExpr -> {
|
||||
@@ -379,10 +403,7 @@ final class PbsExecutableBodyLowerer {
|
||||
lowerExpression(unaryExpr.expression(), context);
|
||||
emitUnaryOperatorInstruction(unaryExpr.operator(), unaryExpr.span(), context);
|
||||
}
|
||||
case PbsAst.ElseExpr elseExpr -> {
|
||||
lowerExpression(elseExpr.optionalExpression(), context);
|
||||
lowerExpression(elseExpr.fallbackExpression(), context);
|
||||
}
|
||||
case PbsAst.ElseExpr elseExpr -> lowerOptionalFallback(elseExpr, context);
|
||||
case PbsAst.IfExpr ifExpr -> lowerIfExpression(ifExpr, context);
|
||||
case PbsAst.SwitchExpr switchExpr -> lowerSwitch(switchExpr, context);
|
||||
case PbsAst.HandleExpr handleExpr -> lowerUnsupportedExpression(
|
||||
@@ -395,11 +416,25 @@ final class PbsExecutableBodyLowerer {
|
||||
case PbsAst.PropagateExpr propagateExpr -> lowerExpression(propagateExpr.expression(), context);
|
||||
case PbsAst.GroupExpr groupExpr -> lowerExpression(groupExpr.expression(), context);
|
||||
case PbsAst.NewExpr newExpr -> {
|
||||
if (newExpr.typeName().equals("array")) {
|
||||
lowerArrayIndex(newExpr.arguments().getFirst(), context);
|
||||
registry(ARRAY_NEW, context.types().arrayStorage(), 0, 1, 1, newExpr.span(), context);
|
||||
break;
|
||||
}
|
||||
if (context.types().structs.containsKey(newExpr.typeName())) {
|
||||
lowerStructNew(newExpr, context);
|
||||
break;
|
||||
}
|
||||
var fields = context.types().fields.get(newExpr.typeName());
|
||||
for(int i=0; i<newExpr.arguments().size(); i++) lowerExpected(newExpr.arguments().get(i), fields != null && i < fields.size() ? fields.get(i).typeRef() : null, context);
|
||||
}
|
||||
case PbsAst.BindExpr bindExpr -> lowerExpression(bindExpr.contextExpression(), context);
|
||||
case PbsAst.SomeExpr someExpr -> lowerExpression(someExpr.value(), context);
|
||||
case PbsAst.SomeExpr someExpr -> {
|
||||
var optional = PbsRuntimeTypes.unwrap(context.expectedType);
|
||||
var payload = optional != null && optional.kind() == PbsAst.TypeRefKind.OPTIONAL ? optional.inner() : expressionType(someExpr.value(), context);
|
||||
lowerExpected(someExpr.value(), payload, context);
|
||||
wrapOptional(payload, someExpr.span(), context);
|
||||
}
|
||||
case PbsAst.OkExpr okExpr -> lowerExpression(okExpr.value(), context);
|
||||
case PbsAst.TupleExpr tupleExpr -> {
|
||||
var expected = context.expectedType;
|
||||
@@ -416,10 +451,11 @@ final class PbsExecutableBodyLowerer {
|
||||
case PbsAst.BoundedLiteralExpr literal -> emitPushI32(literal.value(), literal.span(), context);
|
||||
case PbsAst.StringLiteralExpr stringLiteralExpr -> emitPushConst(stringLiteralExpr.value(), stringLiteralExpr.span(), context);
|
||||
case PbsAst.BoolLiteralExpr boolLiteralExpr -> emitPushBool(boolLiteralExpr.value(), boolLiteralExpr.span(), context);
|
||||
case PbsAst.ThisExpr ignored -> {
|
||||
}
|
||||
case PbsAst.NoneExpr ignored -> {
|
||||
case PbsAst.ThisExpr value -> {
|
||||
if (context.resolveLocalSlot("this") != null) emitGetLocal(context.resolveLocalSlot("this"),value.span(),context);
|
||||
else lowerServiceValue(context.serviceOwner,value.span(),context);
|
||||
}
|
||||
case PbsAst.NoneExpr value -> emitDefault(context.types().registryType(context.expectedType), 1, value.span(), context);
|
||||
case PbsAst.ErrExpr ignored -> {
|
||||
}
|
||||
case PbsAst.UnitExpr ignored -> {
|
||||
@@ -430,6 +466,28 @@ final class PbsExecutableBodyLowerer {
|
||||
private void lowerCallExpression(
|
||||
final PbsAst.CallExpr callExpr,
|
||||
final PbsExecutableLoweringContext context) {
|
||||
if (lowerStructuredCall(callExpr, context)) return;
|
||||
if (callExpr.callee() instanceof PbsAst.MemberExpr member) {
|
||||
var receiverType = PbsRuntimeTypes.unwrap(expressionType(member.receiver(), context));
|
||||
if (receiverType != null && receiverType.kind() == PbsAst.TypeRefKind.OPTIONAL
|
||||
&& (member.memberName().equals("hasSome") || member.memberName().equals("hasNone"))) {
|
||||
lowerExpression(member.receiver(), context);
|
||||
int slot = save(1, callExpr.span(), context);
|
||||
optionalPresence(slot, receiverType, callExpr.span(), context);
|
||||
if (member.memberName().equals("hasNone")) {
|
||||
emitPushBool(false, callExpr.span(), context);
|
||||
emitBinaryOperatorInstruction("==", callExpr.span(), context);
|
||||
}
|
||||
return;
|
||||
}
|
||||
if (receiverType != null && receiverType.kind() == PbsAst.TypeRefKind.ARRAY && member.memberName().equals("clear")) {
|
||||
lowerExpression(member.receiver(), context);
|
||||
lowerArrayIndex(callExpr.arguments().getFirst(), context);
|
||||
emitDefault(context.types().dynamic(), 2, callExpr.span(), context);
|
||||
registry(ARRAY_SET, context.types().arrayStorage(), 0, 4, 0, callExpr.span(), context);
|
||||
return;
|
||||
}
|
||||
}
|
||||
lowerCallsiteReceiver(callExpr.callee(), context);
|
||||
lowerCallArguments(callExpr, context);
|
||||
callsiteEmitter.emitCallsite(callExpr, context);
|
||||
@@ -482,6 +540,32 @@ final class PbsExecutableBodyLowerer {
|
||||
private void lowerMemberExpression(
|
||||
final PbsAst.MemberExpr memberExpr,
|
||||
final PbsExecutableLoweringContext context) {
|
||||
var receiverType = PbsRuntimeTypes.unwrap(expressionType(memberExpr.receiver(), context));
|
||||
if (receiverType != null && receiverType.kind() == PbsAst.TypeRefKind.ARRAY && memberExpr.memberName().equals("length")) {
|
||||
lowerExpected(memberExpr.receiver(), receiverType, context);
|
||||
registry(ARRAY_LEN, context.types().arrayStorage(), 0, 1, 1, memberExpr.span(), context);
|
||||
return;
|
||||
}
|
||||
if (receiverType != null && receiverType.kind() == PbsAst.TypeRefKind.NAMED_TUPLE) {
|
||||
lowerExpression(memberExpr.receiver(),context);
|
||||
int slot=save(context.types().slots(receiverType),memberExpr.span(),context);
|
||||
int offset=0;
|
||||
for(var field:receiverType.fields()) {
|
||||
int width=context.types().slots(field.typeRef());
|
||||
if(field.label().equals(memberExpr.memberName())) {emitLoadLocalSlots(slot+offset,width,memberExpr.span(),context);return;}
|
||||
offset+=width;
|
||||
}
|
||||
}
|
||||
var struct = receiverType == null ? null : context.types().structs.get(receiverType.name());
|
||||
if (struct != null) {
|
||||
for (int i=0;i<struct.fields().size();i++) if (struct.fields().get(i).name().equals(memberExpr.memberName())) {
|
||||
lowerExpected(memberExpr.receiver(), receiverType, context);
|
||||
registry(STRUCT_GET, context.types().registryType(receiverType), i, 1, storageWidth(struct.fields().get(i).typeRef(),context), memberExpr.span(), context);
|
||||
unpackStorage(struct.fields().get(i).typeRef(),memberExpr.span(),context);
|
||||
return;
|
||||
}
|
||||
}
|
||||
|
||||
if (memberExpr.receiver() instanceof PbsAst.IdentifierExpr owner) {
|
||||
final var enumValue = context.types().enumValue(owner.name(), memberExpr.memberName());
|
||||
if (enumValue != null) { emitPushI32(enumValue, memberExpr.span(), context); return; }
|
||||
@@ -519,7 +603,7 @@ final class PbsExecutableBodyLowerer {
|
||||
}
|
||||
}
|
||||
}
|
||||
lowerExpression(memberExpr.receiver(), context);
|
||||
lowerExpected(memberExpr.receiver(), receiverType, context);
|
||||
}
|
||||
|
||||
private void lowerAssetFacingArgument(
|
||||
@@ -572,6 +656,10 @@ final class PbsExecutableBodyLowerer {
|
||||
private void lowerIdentifierExpression(
|
||||
final PbsAst.IdentifierExpr identifierExpr,
|
||||
final PbsExecutableLoweringContext context) {
|
||||
if (context.types().services.containsKey(identifierExpr.name())) {
|
||||
lowerServiceValue(identifierExpr.name(), identifierExpr.span(), context);
|
||||
return;
|
||||
}
|
||||
if ("assets".equals(identifierExpr.name())) {
|
||||
return;
|
||||
}
|
||||
@@ -588,6 +676,11 @@ final class PbsExecutableBodyLowerer {
|
||||
final var globalSlot = context.resolveGlobalSlot(identifierExpr.name());
|
||||
if (globalSlot != null) {
|
||||
emitGetGlobal(globalSlot, identifierExpr.span(), context);
|
||||
var type = context.types().values.get(identifierExpr.name());
|
||||
if (context.types().slots(type) > 1) {
|
||||
int value = save(1,identifierExpr.span(),context);
|
||||
unwrapOptional(value,PbsAst.TypeRef.optional(type,identifierExpr.span()),identifierExpr.span(),context);
|
||||
}
|
||||
return;
|
||||
}
|
||||
final var constDecl = context.resolveConstDecl(identifierExpr.name());
|
||||
@@ -631,7 +724,11 @@ final class PbsExecutableBodyLowerer {
|
||||
if (expression == null) {
|
||||
return 0;
|
||||
}
|
||||
var resolvedType = expressionType(expression, context);
|
||||
if (resolvedType != null) return context.types().slots(resolvedType);
|
||||
return switch (expression) {
|
||||
case PbsAst.ArrayLiteralExpr ignored -> 1;
|
||||
case PbsAst.IndexExpr ignored -> 1;
|
||||
case PbsAst.CallExpr callExpr -> callsiteEmitter.returnSlotsOf(callExpr, context);
|
||||
case PbsAst.ApplyExpr apply -> callsiteEmitter.returnSlotsOf(applyCall(apply), context);
|
||||
case PbsAst.BinaryExpr ignored -> 1;
|
||||
@@ -716,6 +813,9 @@ final class PbsExecutableBodyLowerer {
|
||||
private boolean producesIdentifierValue(
|
||||
final PbsAst.IdentifierExpr identifierExpr,
|
||||
final PbsExecutableLoweringContext context) {
|
||||
if (context.types().services.containsKey(identifierExpr.name())) {
|
||||
return true;
|
||||
}
|
||||
if ("assets".equals(identifierExpr.name())) {
|
||||
return false;
|
||||
}
|
||||
@@ -842,11 +942,37 @@ final class PbsExecutableBodyLowerer {
|
||||
private void lowerExpected(PbsAst.Expression expression, PbsAst.TypeRef expected, PbsExecutableLoweringContext context) {
|
||||
var previous = context.expectedType;
|
||||
context.expectedType = expected;
|
||||
try { lowerExpression(expression, context); } finally { context.expectedType = previous; }
|
||||
try {
|
||||
var target=PbsRuntimeTypes.unwrap(expected);
|
||||
var actual=PbsRuntimeTypes.unwrap(expressionType(expression,context));
|
||||
if(target!=null && actual!=null && context.types().contracts.containsKey(target.name()) && !target.name().equals(actual.name()))
|
||||
lowerConversion(new PbsAst.AsExpr(expression,target.name(),expression.span()),context);
|
||||
else lowerExpression(expression, context);
|
||||
} finally { context.expectedType = previous; }
|
||||
}
|
||||
|
||||
private PbsAst.TypeRef expressionType(PbsAst.Expression e, PbsExecutableLoweringContext c) {
|
||||
if (e instanceof PbsAst.IdentifierExpr i) return c.localTypes.getOrDefault(i.name(), c.types().values.get(i.name()));
|
||||
if (e == null) return null;
|
||||
if (e instanceof PbsAst.ArrayLiteralExpr || e instanceof PbsAst.NoneExpr) return c.expectedType;
|
||||
if (e instanceof PbsAst.TupleExpr tuple) return PbsAst.TypeRef.namedTuple(ReadOnlyList.wrap(tuple.items().stream()
|
||||
.map(item -> new PbsAst.NamedTypeField(item.label(),expressionType(item.expression(),c),item.span())).toList()),tuple.span());
|
||||
if (e instanceof PbsAst.BlockExpr block) return expressionType(block.block().tailExpression(),c);
|
||||
if (e instanceof PbsAst.ThisExpr) return c.localTypes.getOrDefault("this", c.serviceOwner == null ? null : PbsRuntimeTypes.type(c.serviceOwner));
|
||||
if (e instanceof PbsAst.SomeExpr some) return PbsAst.TypeRef.optional(expressionType(some.value(), c), some.span());
|
||||
if (e instanceof PbsAst.ElseExpr fallback) {var opt = PbsRuntimeTypes.unwrap(expressionType(fallback.optionalExpression(), c)); return opt == null ? null : opt.inner();}
|
||||
if (e instanceof PbsAst.IndexExpr index) {var array = PbsRuntimeTypes.unwrap(expressionType(index.receiver(), c)); return array == null ? null : PbsAst.TypeRef.optional(array.inner(), index.span());}
|
||||
if (e instanceof PbsAst.MemberExpr member) {
|
||||
var receiver = PbsRuntimeTypes.unwrap(expressionType(member.receiver(), c));
|
||||
if (receiver != null && receiver.kind() == PbsAst.TypeRefKind.ARRAY && member.memberName().equals("length")) return PbsRuntimeTypes.type("long");
|
||||
if (receiver != null && receiver.kind() == PbsAst.TypeRefKind.NAMED_TUPLE)
|
||||
for (var field : receiver.fields()) if (field.label().equals(member.memberName())) return field.typeRef();
|
||||
var struct = receiver == null ? null : c.types().structs.get(receiver.name());
|
||||
if (struct != null) for (var field : struct.fields()) if (field.name().equals(member.memberName())) return field.typeRef();
|
||||
}
|
||||
if (e instanceof PbsAst.IdentifierExpr i) {
|
||||
if(c.types().services.containsKey(i.name()))return PbsRuntimeTypes.type(i.name());
|
||||
return c.localTypes.getOrDefault(i.name(), c.types().values.get(i.name()));
|
||||
}
|
||||
if (e instanceof PbsAst.GroupExpr g) return expressionType(g.expression(), c);
|
||||
if (e instanceof PbsAst.AsExpr a) return PbsRuntimeTypes.type(a.contractName());
|
||||
if (e instanceof PbsAst.UnaryExpr u) return java.util.Set.of("!", "not").contains(u.operator()) ? PbsRuntimeTypes.type("bool") : expressionType(u.expression(), c);
|
||||
@@ -854,8 +980,31 @@ final class PbsExecutableBodyLowerer {
|
||||
if (e instanceof PbsAst.IfExpr branch) return expressionType(branch.thenBlock().tailExpression(), c);
|
||||
if (e instanceof PbsAst.SwitchExpr branch && !branch.arms().isEmpty()) return expressionType(branch.arms().getFirst().block().tailExpression(), c);
|
||||
if (e instanceof PbsAst.ApplyExpr apply) return expressionType(applyCall(apply), c);
|
||||
if (e instanceof PbsAst.NewExpr value) return PbsRuntimeTypes.type(value.typeName());
|
||||
if (e instanceof PbsAst.NewExpr value) return value.typeName().equals("array") ? c.expectedType : PbsRuntimeTypes.type(value.typeName());
|
||||
if (e instanceof PbsAst.CallExpr call) {
|
||||
var sourceFunction = sourceFunction(call,c);
|
||||
if (sourceFunction != null) return sourceFunction.returnType();
|
||||
if (call.callee() instanceof PbsAst.MemberExpr member && member.memberName().equals("clear")) {
|
||||
var receiver = PbsRuntimeTypes.unwrap(expressionType(member.receiver(), c));
|
||||
if (receiver != null && receiver.kind() == PbsAst.TypeRefKind.ARRAY) return PbsAst.TypeRef.unit(call.span());
|
||||
}
|
||||
if(call.callee() instanceof PbsAst.MemberExpr member) {
|
||||
var owner=PbsRuntimeTypes.unwrap(expressionType(member.receiver(),c));
|
||||
if(owner!=null) {
|
||||
if (owner.kind() == PbsAst.TypeRefKind.OPTIONAL
|
||||
&& (member.memberName().equals("hasSome") || member.memberName().equals("hasNone"))) return PbsRuntimeTypes.type("bool");
|
||||
var contract=c.types().contracts.get(owner.name());
|
||||
if(contract!=null) for(var method:contract.signatures()) if(method.name().equals(member.memberName()) && parametersMatch(method.parameters(),call.arguments(),c)
|
||||
&& returnMatches(method.returnType(),owner.name(),c)) return method.returnType();
|
||||
var struct = c.types().structs.get(owner.name());
|
||||
var service = c.types().services.get(owner.name());
|
||||
var methods = struct != null ? struct.methods() : service != null ? service.methods() : ReadOnlyList.<PbsAst.FunctionDecl>empty();
|
||||
for (var candidate : methods) if (candidate.name().equals(member.memberName()) && parametersMatch(candidate.parameters(),call.arguments(),c)
|
||||
&& returnMatches(candidate.returnType(),owner.name(),c)) return PbsTypeSubstitution.replaceSelf(candidate.returnType(),owner.name());
|
||||
var method=c.types().signatures.get(owner.name()+"."+member.memberName()+"#"+call.arguments().size());
|
||||
if(method!=null)return PbsTypeSubstitution.replaceSelf(method.returnType(),owner.name());
|
||||
}
|
||||
}
|
||||
var sig = c.types().signatures.get(PbsRuntimeTypes.path(call.callee())+"#"+call.arguments().size());
|
||||
return sig == null ? null : sig.returnType();
|
||||
}
|
||||
@@ -875,8 +1024,16 @@ final class PbsExecutableBodyLowerer {
|
||||
}
|
||||
|
||||
private void lowerConversion(PbsAst.AsExpr expr, PbsExecutableLoweringContext c) {
|
||||
var source = c.types().canonical(expressionType(expr.expression(), c));
|
||||
var sourceType = expressionType(expr.expression(),c);
|
||||
var source = c.types().canonical(sourceType);
|
||||
var target = expr.contractName();
|
||||
if(c.types().contracts.containsKey(target)) {
|
||||
lowerExpected(expr.expression(),null,c);
|
||||
c.instructions().add(new IRBackendExecutableFunction.Instruction(IRBackendExecutableFunction.InstructionKind.REGISTRY,
|
||||
null,"",null,null,null,"","",c.types().slots(sourceType),2,expr.span(),
|
||||
new IRRegistryInstruction(REF_TO_TRAIT,c.types().registryType(sourceType),c.types().registryType(PbsRuntimeTypes.type(target)),null,0)));
|
||||
return;
|
||||
}
|
||||
lowerExpected(expr.expression(), null, c);
|
||||
if (source.equals(target)) return;
|
||||
String name = switch(source + "->" + target) {
|
||||
@@ -936,7 +1093,7 @@ final class PbsExecutableBodyLowerer {
|
||||
return;
|
||||
}
|
||||
switch (callee) {
|
||||
case PbsAst.MemberExpr memberExpr -> lowerExpression(memberExpr.receiver(), context);
|
||||
case PbsAst.MemberExpr memberExpr -> lowerExpected(memberExpr.receiver(), expressionType(memberExpr.receiver(),context), context);
|
||||
case PbsAst.GroupExpr groupExpr -> lowerCallsiteReceiver(groupExpr.expression(), context);
|
||||
default -> {
|
||||
}
|
||||
@@ -1216,4 +1373,296 @@ final class PbsExecutableBodyLowerer {
|
||||
message,
|
||||
span);
|
||||
}
|
||||
|
||||
private void registry(IRRegistryInstruction.Kind kind, IRRegistry.TypeRef type, int field, int pops, int pushes, Span span, PbsExecutableLoweringContext c) {
|
||||
c.instructions().add(new IRBackendExecutableFunction.Instruction(IRBackendExecutableFunction.InstructionKind.REGISTRY,
|
||||
null, "", null, null, null, "", "", pops, pushes, span,
|
||||
new IRRegistryInstruction(kind,type,null,null,field)));
|
||||
}
|
||||
private void emitDefault(IRRegistry.TypeRef type, int width, Span span, PbsExecutableLoweringContext c) {
|
||||
var holder = c.types().holder(type);
|
||||
registry(STRUCT_NEW,holder,0,0,1,span,c);
|
||||
registry(STRUCT_GET,holder,0,1,width,span,c);
|
||||
}
|
||||
private int save(int width, Span span, PbsExecutableLoweringContext c) {
|
||||
int slot=c.declareLocalSlots(c.nextLabel("temporary"),width);
|
||||
emitStoreLocalSlots(slot,width,span,c); return slot;
|
||||
}
|
||||
private void lowerArrayIndex(PbsAst.Expression index, PbsExecutableLoweringContext c) {
|
||||
var type=expressionType(index,c);
|
||||
if (index instanceof PbsAst.IntLiteralExpr) lowerExpected(index,PbsRuntimeTypes.type("long"),c);
|
||||
else if ("int".equals(c.types().canonical(type))) lowerConversion(new PbsAst.AsExpr(index,"long",index.span()),c);
|
||||
else lowerExpected(index,type,c);
|
||||
}
|
||||
private void lowerArrayLiteral(PbsAst.ArrayLiteralExpr literal, PbsExecutableLoweringContext c) {
|
||||
var type=PbsRuntimeTypes.unwrap(c.expectedType);
|
||||
if(type==null || type.kind()!=PbsAst.TypeRefKind.ARRAY) {reportUnsupportedLowering("Array literal requires expected type",literal.span(),c);return;}
|
||||
emitLiteral(IRBackendExecutableFunction.InstructionKind.PUSH_I64,Integer.toString(literal.elements().size()),literal.span(),c);
|
||||
registry(ARRAY_NEW,c.types().arrayStorage(),0,1,1,literal.span(),c);
|
||||
int array=save(1,literal.span(),c);
|
||||
for(int i=0;i<literal.elements().size();i++) {
|
||||
emitGetLocal(array,literal.span(),c);
|
||||
emitLiteral(IRBackendExecutableFunction.InstructionKind.PUSH_I64,Integer.toString(i),literal.span(),c);
|
||||
lowerExpected(literal.elements().get(i),type.inner(),c);
|
||||
packStorage(type.inner(), literal.span(), c);
|
||||
registry(DYN_PACK,c.types().registryType(type.inner()),0,storageWidth(type.inner(),c),2,literal.span(),c);
|
||||
registry(ARRAY_SET,c.types().arrayStorage(),0,4,0,literal.span(),c);
|
||||
}
|
||||
emitGetLocal(array,literal.span(),c);
|
||||
}
|
||||
private void lowerArrayWrite(PbsAst.IndexExpr index,PbsAst.Expression value,PbsExecutableLoweringContext c) {
|
||||
var type=PbsRuntimeTypes.unwrap(expressionType(index.receiver(),c));
|
||||
lowerExpected(index.receiver(),type,c);
|
||||
lowerArrayIndex(index.index(),c);
|
||||
lowerExpected(value,type.inner(),c);
|
||||
packStorage(type.inner(), index.span(), c);
|
||||
registry(DYN_PACK,c.types().registryType(type.inner()),0,storageWidth(type.inner(),c),2,index.span(),c);
|
||||
registry(ARRAY_SET,c.types().arrayStorage(),0,4,0,index.span(),c);
|
||||
}
|
||||
private void lowerArrayRead(PbsAst.IndexExpr index,PbsExecutableLoweringContext c) {
|
||||
var type=PbsRuntimeTypes.unwrap(expressionType(index.receiver(),c));
|
||||
var optional=PbsAst.TypeRef.optional(type.inner(),index.span());
|
||||
lowerExpected(index.receiver(),type,c);
|
||||
lowerArrayIndex(index.index(),c);
|
||||
registry(ARRAY_GET,c.types().arrayStorage(),0,2,2,index.span(),c);
|
||||
int group=save(2,index.span(),c);
|
||||
emitGetLocal(group,index.span(),c);
|
||||
emitDefault(c.types().dynamic(),2,index.span(),c);
|
||||
c.instructions().add(new IRBackendExecutableFunction.Instruction(IRBackendExecutableFunction.InstructionKind.POP,"",null,null,index.span()));
|
||||
emitBinaryOperatorInstruction("==",index.span(),c);
|
||||
var empty=c.nextLabel("empty"); var end=c.nextLabel("array_read_end");
|
||||
emitJump(IRBackendExecutableFunction.InstructionKind.JMP_IF_TRUE,empty,index.span(),c);
|
||||
emitLoadLocalSlots(group,2,index.span(),c);
|
||||
registry(DYN_UNPACK,c.types().registryType(type.inner()),0,2,storageWidth(type.inner(),c),index.span(),c);
|
||||
unpackStorage(type.inner(), index.span(), c);
|
||||
wrapOptional(type.inner(),index.span(),c);
|
||||
emitJump(IRBackendExecutableFunction.InstructionKind.JMP,end,index.span(),c);
|
||||
emitLabel(empty,index.span(),c);
|
||||
emitDefault(c.types().registryType(optional),1,index.span(),c);
|
||||
emitLabel(end,index.span(),c);
|
||||
}
|
||||
// Named tuples are flattened at callable boundaries and boxed only for storage.
|
||||
private int storageWidth(PbsAst.TypeRef type, PbsExecutableLoweringContext c) {
|
||||
return registryWidth(c.types().registryType(type), c);
|
||||
}
|
||||
private void packStorage(PbsAst.TypeRef type, Span span, PbsExecutableLoweringContext c) {
|
||||
type = PbsRuntimeTypes.unwrap(type);
|
||||
if (type.kind() != PbsAst.TypeRefKind.NAMED_TUPLE) return;
|
||||
int value = save(c.types().slots(type), span, c);
|
||||
var ref = c.types().registryType(type);
|
||||
registry(STRUCT_NEW, ref, 0, 0, 1, span, c);
|
||||
int box = save(1, span, c);
|
||||
int offset = 0, field = 0;
|
||||
for (var part : c.types().results(type)) {
|
||||
int width = registryWidth(part, c);
|
||||
emitGetLocal(box, span, c);
|
||||
emitLoadLocalSlots(value + offset, width, span, c);
|
||||
registry(STRUCT_SET, ref, field++, 1 + width, 0, span, c);
|
||||
offset += width;
|
||||
}
|
||||
emitGetLocal(box, span, c);
|
||||
}
|
||||
private void unpackStorage(PbsAst.TypeRef type, Span span, PbsExecutableLoweringContext c) {
|
||||
type = PbsRuntimeTypes.unwrap(type);
|
||||
if (type.kind() != PbsAst.TypeRefKind.NAMED_TUPLE) return;
|
||||
int box = save(1, span, c), field = 0;
|
||||
var ref = c.types().registryType(type);
|
||||
for (var part : c.types().results(type)) {
|
||||
emitGetLocal(box, span, c);
|
||||
registry(STRUCT_GET, ref, field++, 1, registryWidth(part, c), span, c);
|
||||
}
|
||||
}
|
||||
private void wrapOptional(PbsAst.TypeRef payload,Span span,PbsExecutableLoweringContext c) {
|
||||
var optional=c.types().registryType(PbsAst.TypeRef.optional(payload,span));
|
||||
int value=save(c.types().slots(payload),span,c);
|
||||
registry(STRUCT_NEW,optional,0,0,1,span,c); int box=save(1,span,c);
|
||||
int offset=0,field=0;
|
||||
for(var part:c.types().results(payload)) {
|
||||
int width=registryWidth(part,c);
|
||||
emitGetLocal(box,span,c);emitLoadLocalSlots(value+offset,width,span,c);
|
||||
registry(STRUCT_SET,optional,field++,1+width,0,span,c);offset+=width;
|
||||
}
|
||||
emitGetLocal(box,span,c);
|
||||
}
|
||||
private int registryWidth(IRRegistry.TypeRef ref,PbsExecutableLoweringContext c) {
|
||||
var body=c.types().registry().types().stream().filter(t->t.identity().equals(ref)).findFirst().orElseThrow().body();
|
||||
if(body instanceof IRRegistry.Trait)return 2;
|
||||
if(body instanceof IRRegistry.Builtin builtin) return switch(builtin.id()) {case 2,0x15->2;case 3->3;default->1;};
|
||||
return 1;
|
||||
}
|
||||
private void unwrapOptional(int slot,PbsAst.TypeRef optional,Span span,PbsExecutableLoweringContext c) {
|
||||
var ref=c.types().registryType(optional);int field=0;
|
||||
for(var part:c.types().results(optional.inner())) {emitGetLocal(slot,span,c);registry(STRUCT_GET,ref,field++,1,registryWidth(part,c),span,c);}
|
||||
}
|
||||
private void optionalPresence(int slot,PbsAst.TypeRef optional,Span span,PbsExecutableLoweringContext c) {
|
||||
emitGetLocal(slot,span,c);emitDefault(c.types().registryType(optional),1,span,c);emitBinaryOperatorInstruction("!=",span,c);
|
||||
}
|
||||
private void lowerOptionalFallback(PbsAst.ElseExpr expr,PbsExecutableLoweringContext c) {
|
||||
var type=PbsRuntimeTypes.unwrap(expressionType(expr.optionalExpression(),c));
|
||||
lowerExpected(expr.optionalExpression(),type,c);int slot=save(1,expr.span(),c);
|
||||
optionalPresence(slot,type,expr.span(),c);
|
||||
var absent=c.nextLabel("optional_absent");var end=c.nextLabel("optional_end");
|
||||
emitJump(IRBackendExecutableFunction.InstructionKind.JMP_IF_FALSE,absent,expr.span(),c);
|
||||
unwrapOptional(slot,type,expr.span(),c);emitJump(IRBackendExecutableFunction.InstructionKind.JMP,end,expr.span(),c);
|
||||
emitLabel(absent,expr.span(),c);lowerExpected(expr.fallbackExpression(),type.inner(),c);emitLabel(end,expr.span(),c);
|
||||
}
|
||||
private boolean lowerIfLet(PbsAst.IfStatement stmt,PbsExecutableLoweringContext c) {
|
||||
var type=PbsRuntimeTypes.unwrap(expressionType(stmt.condition(),c));
|
||||
lowerExpected(stmt.condition(),type,c);int slot=save(1,stmt.span(),c);optionalPresence(slot,type,stmt.span(),c);
|
||||
var absent=c.nextLabel("iflet_absent");var end=c.nextLabel("iflet_end");
|
||||
emitJump(IRBackendExecutableFunction.InstructionKind.JMP_IF_FALSE,absent,stmt.span(),c);
|
||||
var scope=c.snapshotScope();
|
||||
c.localSlotByNameId().remove(c.nameTable().register(stmt.bindingName()));
|
||||
c.localTypes.put(stmt.bindingName(),type.inner());
|
||||
unwrapOptional(slot,type,stmt.span(),c);
|
||||
int binding=c.declareLocalSlots(stmt.bindingName(),c.types().slots(type.inner()));
|
||||
emitStoreLocalSlots(binding,c.types().slots(type.inner()),stmt.span(),c);
|
||||
boolean yes=lowerBlock(stmt.thenBlock(),c);
|
||||
c.restoreScope(scope);
|
||||
if(!yes)emitJump(IRBackendExecutableFunction.InstructionKind.JMP,end,stmt.span(),c);
|
||||
emitLabel(absent,stmt.span(),c);boolean no=lowerElseBranch(stmt,c);
|
||||
if(!yes||!no)emitLabel(end,stmt.span(),c);
|
||||
return hasElseBranch(stmt)&&yes&&no;
|
||||
}
|
||||
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()));
|
||||
if(expr.ctorName()!=null) {
|
||||
var ctor=declaration.ctors().stream().filter(f->f.name().equals(expr.ctorName()) && parametersMatch(f.parameters(),expr.arguments(),c)).findFirst().orElseThrow();
|
||||
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());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);
|
||||
for(int i=0;i<arguments.size();i++)emitLoadLocalSlots(arguments.get(i),c.types().slots(ctor.parameters().get(i).typeRef()),expr.span(),c);
|
||||
emitStructuredFunction(expr.typeName()+".$ctor."+expr.ctorName(),receiverParameters(expr.typeName(),ctor.parameters()),PbsAst.TypeRef.unit(expr.span()),1+ctor.parameters().stream().mapToInt(p->c.types().slots(p.typeRef())).sum(),0,expr.span(),c);
|
||||
emitGetLocal(instance,expr.span(),c);return;
|
||||
}
|
||||
var args=new java.util.ArrayList<Integer>();
|
||||
for(int i=0;i<expr.arguments().size();i++){var type=declaration.fields().get(i).typeRef();lowerExpected(expr.arguments().get(i),type,c);args.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);
|
||||
for(int i=0;i<args.size();i++){int width=c.types().slots(declaration.fields().get(i).typeRef());emitGetLocal(instance,expr.span(),c);emitLoadLocalSlots(args.get(i),width,expr.span(),c);packStorage(declaration.fields().get(i).typeRef(),expr.span(),c);registry(STRUCT_SET,ref,i,1+storageWidth(declaration.fields().get(i).typeRef(),c),0,expr.span(),c);}
|
||||
emitGetLocal(instance,expr.span(),c);
|
||||
}
|
||||
|
||||
private void lowerFieldAssignment(PbsAst.AssignStatement statement,PbsExecutableLoweringContext c) {
|
||||
var target=statement.target();
|
||||
PbsAst.Expression receiver=target.rootName().equals("this")?new PbsAst.ThisExpr(target.span()):new PbsAst.IdentifierExpr(target.rootName(),target.span());
|
||||
for(int i=0;i<target.pathSegments().size()-1;i++)receiver=new PbsAst.MemberExpr(receiver,target.pathSegments().get(i),target.span());
|
||||
var type=expressionType(receiver,c);var struct=c.types().structs.get(type.name());
|
||||
var name=target.pathSegments().getLast();int field=0;
|
||||
while(!struct.fields().get(field).name().equals(name))field++;
|
||||
var fieldType=struct.fields().get(field).typeRef();int width=c.types().slots(fieldType);
|
||||
lowerExpression(receiver,c);int slot=save(1,target.span(),c);emitGetLocal(slot,target.span(),c);
|
||||
if(statement.operator()!=PbsAst.AssignOperator.ASSIGN){emitGetLocal(slot,target.span(),c);registry(STRUCT_GET,c.types().registryType(type),field,1,storageWidth(fieldType,c),target.span(),c);unpackStorage(fieldType,target.span(),c);}
|
||||
lowerExpected(statement.value(),fieldType,c);
|
||||
if(statement.operator()!=PbsAst.AssignOperator.ASSIGN)emitBinaryOperatorInstruction(compoundAssignBinaryOperator(statement.operator()),statement.span(),c);
|
||||
packStorage(fieldType,statement.span(),c);
|
||||
registry(STRUCT_SET,c.types().registryType(type),field,1+storageWidth(fieldType,c),0,statement.span(),c);
|
||||
}
|
||||
private boolean lowerStructuredCall(PbsAst.CallExpr call,PbsExecutableLoweringContext c) {
|
||||
if (call.callee() instanceof PbsAst.IdentifierExpr name && c.types().functions.containsKey(name.name())) {
|
||||
var method = sourceFunction(call,c);
|
||||
if (method == null) return false;
|
||||
int pops = 0;
|
||||
for (int i = 0; i < call.arguments().size(); i++) {
|
||||
var type = method.parameters().get(i).typeRef();
|
||||
lowerExpected(call.arguments().get(i),type,c);
|
||||
pops += c.types().slots(type);
|
||||
}
|
||||
emitStructuredFunction(name.name(),method.parameters().stream().map(PbsAst.Parameter::typeRef).toList(),
|
||||
method.returnType(),pops,c.types().slots(method.returnType()),call.span(),c);
|
||||
return true;
|
||||
}
|
||||
if(!(call.callee() instanceof PbsAst.MemberExpr member))return false;
|
||||
var owner=PbsRuntimeTypes.unwrap(expressionType(member.receiver(),c));if(owner==null)return false;
|
||||
var contract=c.types().contracts.get(owner.name());
|
||||
if(contract!=null) {
|
||||
int ordinal=-1;
|
||||
for(int i=0;i<contract.signatures().size();i++) {
|
||||
var signature=contract.signatures().get(i);
|
||||
if(signature.name().equals(member.memberName()) && parametersMatch(signature.parameters(),call.arguments(),c) && returnMatches(signature.returnType(),owner.name(),c)){ordinal=i;break;}
|
||||
}
|
||||
if(ordinal<0)return false;
|
||||
var method=contract.signatures().get(ordinal);lowerExpected(member.receiver(),owner,c);
|
||||
int pops=2;
|
||||
for(int i=0;i<call.arguments().size();i++){var type=PbsTypeSubstitution.replaceSelf(method.parameters().get(i).typeRef(),owner.name());lowerExpected(call.arguments().get(i),type,c);pops+=c.types().slots(type);}
|
||||
registry(CALL_TRAIT,c.types().registryType(owner),ordinal,pops,c.types().slots(method.returnType()),call.span(),c);return true;
|
||||
}
|
||||
var service=c.types().services.get(owner.name());
|
||||
if(service!=null) {
|
||||
var method=service.methods().stream().filter(m->m.name().equals(member.memberName())&¶metersMatch(m.parameters(),call.arguments(),c) && returnMatches(m.returnType(),owner.name(),c)).findFirst().orElse(null);
|
||||
if(method==null)return false;
|
||||
if(!(member.receiver() instanceof PbsAst.IdentifierExpr id && id.name().equals(owner.name()))) {
|
||||
lowerExpected(member.receiver(),owner,c);
|
||||
c.instructions().add(new IRBackendExecutableFunction.Instruction(IRBackendExecutableFunction.InstructionKind.POP,"",null,null,call.span()));
|
||||
}
|
||||
int pops=0;
|
||||
for(int i=0;i<call.arguments().size();i++){var type=PbsTypeSubstitution.replaceSelf(method.parameters().get(i).typeRef(),owner.name());lowerExpected(call.arguments().get(i),type,c);pops+=c.types().slots(type);}
|
||||
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;
|
||||
var method=struct.methods().stream().filter(m->m.name().equals(member.memberName())&¶metersMatch(m.parameters(),call.arguments(),c) && returnMatches(m.returnType(),owner.name(),c)).findFirst().orElse(null);
|
||||
if(method==null)return false;
|
||||
lowerExpected(member.receiver(),owner,c);int pops=1;
|
||||
for(int i=0;i<call.arguments().size();i++){var type=PbsTypeSubstitution.replaceSelf(method.parameters().get(i).typeRef(),owner.name());lowerExpected(call.arguments().get(i),type,c);pops+=c.types().slots(type);}
|
||||
emitStructuredFunction(owner.name()+"."+method.name(),receiverParameters(owner.name(),method.parameters()),PbsTypeSubstitution.replaceSelf(method.returnType(),owner.name()),pops,c.types().slots(method.returnType()),call.span(),c);return true;
|
||||
}
|
||||
private java.util.List<PbsAst.TypeRef> receiverParameters(String owner, ReadOnlyList<PbsAst.Parameter> parameters) {
|
||||
var types = new java.util.ArrayList<PbsAst.TypeRef>();
|
||||
types.add(PbsRuntimeTypes.type(owner));
|
||||
for (var parameter : parameters) types.add(PbsTypeSubstitution.replaceSelf(parameter.typeRef(), owner));
|
||||
return types;
|
||||
}
|
||||
|
||||
private PbsAst.FunctionDecl sourceFunction(PbsAst.CallExpr call, PbsExecutableLoweringContext c) {
|
||||
if (!(call.callee() instanceof PbsAst.IdentifierExpr name)) return null;
|
||||
var candidates = c.types().functions.getOrDefault(name.name(),java.util.List.of()).stream()
|
||||
.filter(method -> parametersMatch(method.parameters(),call.arguments(),c)).toList();
|
||||
if (candidates.size() == 1) return candidates.getFirst();
|
||||
return candidates.stream().filter(method -> returnMatches(method.returnType(),"",c)).findFirst().orElse(null);
|
||||
}
|
||||
|
||||
private boolean returnMatches(PbsAst.TypeRef type, String owner, PbsExecutableLoweringContext c) {
|
||||
return c.expectedType == null || c.types().shapeKey(PbsTypeSubstitution.replaceSelf(type,owner))
|
||||
.equals(c.types().shapeKey(c.expectedType));
|
||||
}
|
||||
|
||||
private boolean parametersMatch(ReadOnlyList<PbsAst.Parameter> parameters,
|
||||
ReadOnlyList<PbsAst.Expression> arguments, PbsExecutableLoweringContext c) {
|
||||
if (parameters.size() != arguments.size()) return false;
|
||||
for (int i = 0; i < parameters.size(); i++) {
|
||||
var actual = PbsRuntimeTypes.unwrap(expressionType(arguments.get(i), c));
|
||||
var expected = PbsRuntimeTypes.unwrap(parameters.get(i).typeRef());
|
||||
if (expected.kind() == PbsAst.TypeRefKind.SELF) continue;
|
||||
// Contextual expressions have already been disambiguated by static semantics.
|
||||
if (actual == null || arguments.get(i) instanceof PbsAst.ArrayLiteralExpr
|
||||
|| arguments.get(i) instanceof PbsAst.NoneExpr) 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 (c.types().contracts.containsKey(expected.name()) && c.types().implementations.stream().anyMatch(
|
||||
impl -> impl.ownerName().equals(actual.name()) && impl.contractName().equals(expected.name()))) continue;
|
||||
return false;
|
||||
}
|
||||
return true;
|
||||
}
|
||||
|
||||
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);
|
||||
if (callableId == null) {
|
||||
reportUnsupportedLowering("Structured call requires exact overload: " + name, span, c);
|
||||
return;
|
||||
}
|
||||
c.instructions().add(new IRBackendExecutableFunction.Instruction(IRBackendExecutableFunction.InstructionKind.CALL_FUNC,
|
||||
c.callableSignatureByCallableId().get(callableId).moduleId(),
|
||||
name, callableId, null, null, pops, pushes, span));
|
||||
}
|
||||
|
||||
private void lowerServiceValue(String name,Span span,PbsExecutableLoweringContext c) {
|
||||
var slot=c.resolveGlobalSlot("$service."+name);
|
||||
if(slot==null){emitStructuredFunction(name+".$instance",java.util.List.of(),PbsRuntimeTypes.type(name),0,1,span,c);return;}
|
||||
var type=c.types().registryType(PbsRuntimeTypes.type(name));
|
||||
// VM global slots start as Int32(0); a published singleton is always a heap reference.
|
||||
emitGetGlobal(slot,span,c);emitPushI32(0,span,c);emitBinaryOperatorInstruction("!=",span,c);
|
||||
var ready=c.nextLabel("service_ready");emitJump(IRBackendExecutableFunction.InstructionKind.JMP_IF_TRUE,ready,span,c);
|
||||
registry(STRUCT_NEW,type,0,0,1,span,c);emitSetGlobal(slot,span,c);emitLabel(ready,span,c);emitGetGlobal(slot,span,c);
|
||||
}
|
||||
}
|
||||
|
||||
+54
-2
@@ -3,6 +3,7 @@ package p.studio.compiler.pbs.lowering;
|
||||
import p.studio.compiler.pbs.PbsCallableSlotCounter;
|
||||
import p.studio.compiler.pbs.PbsFrontendCompiler;
|
||||
import p.studio.compiler.pbs.ast.PbsAst;
|
||||
import p.studio.compiler.pbs.PbsTypeSubstitution;
|
||||
import p.studio.compiler.source.identifiers.CallableId;
|
||||
import p.studio.compiler.source.identifiers.ModuleId;
|
||||
import p.studio.compiler.source.tables.*;
|
||||
@@ -15,7 +16,7 @@ import java.util.Map;
|
||||
|
||||
import static p.studio.compiler.pbs.lowering.PbsExecutableLoweringModels.*;
|
||||
|
||||
final class PbsExecutableCallableRegistryFactory {
|
||||
public final class PbsExecutableCallableRegistryFactory {
|
||||
private final PbsCallableShapeSurfaceService callableShapeSurfaceService = new PbsCallableShapeSurfaceService();
|
||||
|
||||
PbsExecutableCallableRegistry create(
|
||||
@@ -77,20 +78,71 @@ final class PbsExecutableCallableRegistryFactory {
|
||||
|
||||
private ReadOnlyList<PbsLowerableCallable> collectLocalLowerableCallables(final PbsAst.File ast) {
|
||||
final var callables = new ArrayList<PbsLowerableCallable>();
|
||||
var globals = new java.util.LinkedHashMap<String, PbsAst.GlobalDecl>();
|
||||
for (var declaration : ast.topDecls()) if (declaration instanceof PbsAst.GlobalDecl global) globals.put(global.name(),global);
|
||||
if (!globals.isEmpty()) {
|
||||
var statements = new ArrayList<PbsAst.Statement>();
|
||||
var visited = new java.util.HashSet<String>();
|
||||
for (var name : globals.keySet()) appendGlobalInitialization(name,globals,visited,statements);
|
||||
var name = "$globals."+ast.span().getFileId().getId();
|
||||
var function = new PbsAst.FunctionDecl(name,ReadOnlyList.empty(),PbsAst.ReturnKind.EXPLICIT_UNIT,
|
||||
PbsAst.TypeRef.unit(ast.span()),null,ReadOnlyList.empty(),PbsAst.LifecycleMarker.NONE,
|
||||
new PbsAst.Block(ReadOnlyList.wrap(statements),null,ast.span()),ast.span());
|
||||
callables.add(new PbsLowerableCallable(name,function));
|
||||
}
|
||||
for (final var functionDecl : ast.functions()) {
|
||||
callables.add(new PbsLowerableCallable(functionDecl.name(), functionDecl));
|
||||
}
|
||||
for (final var topDecl : ast.topDecls()) {
|
||||
if (topDecl instanceof PbsAst.StructDecl struct) {
|
||||
for (var method : struct.methods()) callables.add(new PbsLowerableCallable(struct.name()+"."+method.name(), withReceiver(method,struct.name(),"this")));
|
||||
for (var ctor : struct.ctors()) {
|
||||
var function = new PbsAst.FunctionDecl(ctor.name(),ctor.parameters(),PbsAst.ReturnKind.EXPLICIT_UNIT,
|
||||
PbsAst.TypeRef.unit(ctor.span()),null,ReadOnlyList.empty(),PbsAst.LifecycleMarker.NONE,ctor.body(),ctor.span());
|
||||
callables.add(new PbsLowerableCallable(struct.name()+".$ctor."+ctor.name(),withReceiver(function,struct.name(),"this")));
|
||||
}
|
||||
}
|
||||
if (topDecl instanceof PbsAst.ImplementsDecl implementation) {
|
||||
for (var method : implementation.methods()) callables.add(new PbsLowerableCallable(
|
||||
implementation.ownerName()+".$impl."+implementation.contractName()+"."+method.name(),
|
||||
withReceiver(method,implementation.ownerName(),implementation.binderName())));
|
||||
}
|
||||
if (!(topDecl instanceof PbsAst.ServiceDecl serviceDecl)) {
|
||||
continue;
|
||||
}
|
||||
callables.add(new PbsLowerableCallable(serviceDecl.name()+".$instance", singletonAccessor(serviceDecl)));
|
||||
for (final var method : serviceDecl.methods()) {
|
||||
callables.add(new PbsLowerableCallable(serviceDecl.name() + "." + method.name(), method));
|
||||
callables.add(new PbsLowerableCallable(serviceDecl.name() + "." + method.name(), PbsTypeSubstitution.forOwner(method,serviceDecl.name())));
|
||||
}
|
||||
}
|
||||
return ReadOnlyList.wrap(callables);
|
||||
}
|
||||
|
||||
private void appendGlobalInitialization(String name, Map<String,PbsAst.GlobalDecl> globals,
|
||||
java.util.Set<String> visited, ArrayList<PbsAst.Statement> statements) {
|
||||
if (!visited.add(name)) return;
|
||||
var global = globals.get(name);
|
||||
for (var dependency : p.studio.compiler.pbs.semantics.PbsGlobalDependencySupport.collectDependencies(
|
||||
global.initializer(),ModuleId.none(),globals.keySet(),Map.of()))
|
||||
if (globals.containsKey(dependency.globalName())) appendGlobalInitialization(dependency.globalName(),globals,visited,statements);
|
||||
statements.add(new PbsAst.AssignStatement(new PbsAst.LValue(name,ReadOnlyList.empty(),global.span()),
|
||||
PbsAst.AssignOperator.ASSIGN,global.initializer(),global.span()));
|
||||
}
|
||||
|
||||
public static PbsAst.FunctionDecl singletonAccessor(PbsAst.ServiceDecl service) {
|
||||
var span = service.span();
|
||||
return new PbsAst.FunctionDecl("$instance", ReadOnlyList.empty(), PbsAst.ReturnKind.PLAIN,
|
||||
PbsRuntimeTypes.type(service.name()), null, ReadOnlyList.empty(), PbsAst.LifecycleMarker.NONE,
|
||||
new PbsAst.Block(ReadOnlyList.from(new PbsAst.ReturnStatement(new PbsAst.ThisExpr(span), span)), null, span), span);
|
||||
}
|
||||
|
||||
public static PbsAst.FunctionDecl withReceiver(PbsAst.FunctionDecl function,String owner,String receiver) {
|
||||
var params=new ArrayList<PbsAst.Parameter>();
|
||||
params.add(new PbsAst.Parameter(receiver,PbsRuntimeTypes.type(owner),function.span()));
|
||||
for(var p:function.parameters()) params.add(new PbsAst.Parameter(p.name(),PbsTypeSubstitution.replaceSelf(p.typeRef(),owner),p.span()));
|
||||
return new PbsAst.FunctionDecl(function.name(),ReadOnlyList.wrap(params),function.returnKind(),
|
||||
PbsTypeSubstitution.replaceSelf(function.returnType(),owner),function.resultErrorType(),function.attributes(),function.lifecycleMarker(),function.body(),function.span());
|
||||
}
|
||||
private void registerLocalCallables(
|
||||
final ModuleId moduleId,
|
||||
final NameTable nameTable,
|
||||
|
||||
+49
@@ -26,6 +26,7 @@ final class PbsExecutableLoweringContext {
|
||||
p.studio.compiler.pbs.ast.PbsAst.TypeRef expectedType;
|
||||
p.studio.compiler.pbs.ast.PbsAst.TypeRef returnType;
|
||||
PbsRuntimeTypes types() { return metadataIndex.types(); }
|
||||
String serviceOwner;
|
||||
private int nextLabelId = 0;
|
||||
private int nextLocalSlot;
|
||||
|
||||
@@ -92,6 +93,38 @@ final class PbsExecutableLoweringContext {
|
||||
return metadataIndex.intrinsicReturnOwnerByCanonical();
|
||||
}
|
||||
|
||||
p.studio.compiler.source.identifiers.CallableId exactLocalCallable(String name,
|
||||
java.util.List<p.studio.compiler.pbs.ast.PbsAst.TypeRef> parameterTypes,
|
||||
p.studio.compiler.pbs.ast.PbsAst.TypeRef returnType) {
|
||||
for (var callable : callableRegistry.localCallables()) {
|
||||
var parameters = callable.functionDecl().parameters();
|
||||
if (!callable.callableName().equals(name) || parameters.size() != parameterTypes.size()) continue;
|
||||
boolean matches = true;
|
||||
for (int i = 0; i < parameters.size(); i++)
|
||||
matches &= types().key(parameters.get(i).typeRef()).equals(types().key(parameterTypes.get(i)));
|
||||
matches &= types().shapeKey(callable.functionDecl().returnType()).equals(types().shapeKey(returnType));
|
||||
if (matches) return callableRegistry.callableIdByDeclaration().get(callable);
|
||||
}
|
||||
var formatter = new PbsCallableShapeSurfaceService();
|
||||
var inputs = "(" + parameterTypes.stream().map(formatter::typeSurfaceKey)
|
||||
.collect(java.util.stream.Collectors.joining(",")) + ")->";
|
||||
var output = returnType == null || returnType.kind() == p.studio.compiler.pbs.ast.PbsAst.TypeRefKind.UNIT
|
||||
? "unit" : formatter.typeSurfaceKey(returnType);
|
||||
var candidates = callableSignatureByCallableId().entrySet().stream().filter(entry ->
|
||||
entry.getValue().callableName().equals(name) && entry.getValue().arity() == parameterTypes.size()
|
||||
&& normalizeShape(entry.getValue().typeShape()).equals(normalizeShape(inputs + output))).toList();
|
||||
if (candidates.size() == 1) return candidates.getFirst().getKey();
|
||||
return null;
|
||||
}
|
||||
|
||||
private String normalizeShape(String shape) {
|
||||
var normalized = shape.replace(" ", "");
|
||||
for (var alias : types().aliases.entrySet()) normalized = normalized.replaceAll(
|
||||
"simple:" + java.util.regex.Pattern.quote(alias.getKey()) + "(?=[,()])",
|
||||
java.util.regex.Matcher.quoteReplacement("simple:" + alias.getValue()));
|
||||
return normalized;
|
||||
}
|
||||
|
||||
Map<PbsCallableResolutionKey, List<p.studio.compiler.source.identifiers.CallableId>> callableIdsByNameAndArity() {
|
||||
return callableRegistry.callableIdsByNameAndArity();
|
||||
}
|
||||
@@ -209,6 +242,22 @@ final class PbsExecutableLoweringContext {
|
||||
localTupleProjectionByNameId.put(nameId, tupleProjection);
|
||||
}
|
||||
|
||||
record ScopeSnapshot(Map<NameId, Integer> slots, Map<NameId, String> owners,
|
||||
Map<NameId, PbsTupleProjection> projections,
|
||||
Map<String, p.studio.compiler.pbs.ast.PbsAst.TypeRef> types) {}
|
||||
|
||||
ScopeSnapshot snapshotScope() {
|
||||
return new ScopeSnapshot(new HashMap<>(localSlotByNameId), new HashMap<>(localOwnerByNameId),
|
||||
new HashMap<>(localTupleProjectionByNameId), new HashMap<>(localTypes));
|
||||
}
|
||||
|
||||
void restoreScope(ScopeSnapshot scope) {
|
||||
localSlotByNameId.clear(); localSlotByNameId.putAll(scope.slots());
|
||||
localOwnerByNameId.clear(); localOwnerByNameId.putAll(scope.owners());
|
||||
localTupleProjectionByNameId.clear(); localTupleProjectionByNameId.putAll(scope.projections());
|
||||
localTypes.clear(); localTypes.putAll(scope.types());
|
||||
}
|
||||
|
||||
int nextLocalSlot() {
|
||||
return nextLocalSlot;
|
||||
}
|
||||
|
||||
+27
-1
@@ -51,6 +51,32 @@ public final class PbsExecutableLoweringService {
|
||||
var signature = metadataIndex.types().signatures.get(entry.getValue().callableName()+"#"+entry.getValue().arity());
|
||||
if (signature != null) callableRegistry.returnSlotsByCallableId().put(entry.getKey(), signature.returnKind() == PbsAst.ReturnKind.PLAIN ? metadataIndex.types().slots(signature.returnType()) : 0);
|
||||
}
|
||||
for (var callable : callableRegistry.localCallables()) {
|
||||
var f=callable.functionDecl();
|
||||
callableRegistry.returnSlotsByCallableId().put(callableRegistry.callableIdByDeclaration().get(callable),
|
||||
f.returnKind() == PbsAst.ReturnKind.PLAIN ? metadataIndex.types().slots(f.returnType()) : 0);
|
||||
metadataIndex.types().signatures.put(callable.callableName()+"#"+f.parameters().size(),
|
||||
new PbsAst.FunctionSignature(f.name(),f.parameters(),f.returnKind(),f.returnType(),f.resultErrorType(),f.attributes(),f.span()));
|
||||
}
|
||||
for (var implementation : metadataIndex.types().implementations) {
|
||||
var methods = new ArrayList<p.studio.compiler.source.identifiers.CallableId>();
|
||||
var contract = metadataIndex.types().contracts.get(implementation.contractName());
|
||||
for (var signature : contract.signatures()) {
|
||||
var candidates = callableRegistry.localCallables().stream().filter(callable ->
|
||||
callable.callableName().equals(implementation.ownerName()+".$impl."+implementation.contractName()+"."+signature.name())
|
||||
&& callable.functionDecl().parameters().size()==signature.parameters().size()+1
|
||||
&& metadataIndex.types().shapeKey(callable.functionDecl().returnType()).equals(metadataIndex.types().shapeKey(signature.returnType()))
|
||||
&& java.util.stream.IntStream.range(0, signature.parameters().size()).allMatch(i ->
|
||||
metadataIndex.types().key(callable.functionDecl().parameters().get(i+1).typeRef()).equals(
|
||||
metadataIndex.types().key(signature.parameters().get(i).typeRef())))).toList();
|
||||
if (candidates.size()!=1) throw new IllegalStateException("Implementation method requires exact callable resolution");
|
||||
methods.add(callableRegistry.callableIdByDeclaration().get(candidates.getFirst()));
|
||||
}
|
||||
metadataIndex.types().runtimeImplementations.add(new p.studio.compiler.models.registry.IRRegistry.Implementation(
|
||||
"pbs:impl:"+metadataIndex.types().key(PbsRuntimeTypes.type(implementation.ownerName()))+":"+metadataIndex.types().key(PbsRuntimeTypes.type(implementation.contractName())),
|
||||
metadataIndex.types().registryType(PbsRuntimeTypes.type(implementation.ownerName())),
|
||||
metadataIndex.types().registryType(PbsRuntimeTypes.type(implementation.contractName())),ReadOnlyList.wrap(methods)));
|
||||
}
|
||||
final var intrinsicIdTable = new IntrinsicTable();
|
||||
final var executableFunctions = new ArrayList<IRBackendExecutableFunction>(callableRegistry.localCallables().size());
|
||||
|
||||
@@ -98,7 +124,7 @@ public final class PbsExecutableLoweringService {
|
||||
return null;
|
||||
}
|
||||
final var loweredBody = bodyLowerer.lower(
|
||||
functionDecl,
|
||||
functionDecl, callable.callableName(),
|
||||
diagnostics,
|
||||
nameTable,
|
||||
metadataIndex,
|
||||
|
||||
+2
@@ -117,6 +117,8 @@ final class PbsExecutableMetadataIndexFactory {
|
||||
}
|
||||
globalSlotByNameId.putIfAbsent(nameTable.register(globalDecl.name()), nextSlot++);
|
||||
}
|
||||
for (var decl : ast.topDecls()) if (decl instanceof PbsAst.ServiceDecl service)
|
||||
globalSlotByNameId.put(nameTable.register("$service."+service.name()),nextSlot++);
|
||||
return globalSlotByNameId;
|
||||
}
|
||||
|
||||
|
||||
+1
-1
@@ -60,7 +60,7 @@ final class PbsExecutableStackAnalyzer {
|
||||
"stack underflow at " + instruction.kind().name().toLowerCase() + ": need=1 have=" + outHeight);
|
||||
}
|
||||
}
|
||||
case CALL_FUNC -> {
|
||||
case REGISTRY, CALL_FUNC -> {
|
||||
final var argSlots = instruction.expectedArgSlots() == null ? 0 : instruction.expectedArgSlots();
|
||||
final var retSlots = instruction.expectedRetSlots() == null ? 0 : instruction.expectedRetSlots();
|
||||
if (outHeight < argSlots) {
|
||||
|
||||
+114
-8
@@ -9,21 +9,39 @@ import java.util.*;
|
||||
/** PBS-owned source identities and layouts; never inferred from slot widths. */
|
||||
final class PbsRuntimeTypes {
|
||||
final Map<String, String> builtinNames;
|
||||
final Map<String, String> aliases = new HashMap<>();
|
||||
final Map<String, ReadOnlyList<PbsAst.BuiltinFieldDecl>> fields = new HashMap<>();
|
||||
final Map<String, PbsAst.EnumDecl> enums = new HashMap<>();
|
||||
final Map<String, PbsAst.FunctionSignature> signatures = new HashMap<>();
|
||||
final Map<String, List<PbsAst.FunctionDecl>> functions = new HashMap<>();
|
||||
final Map<String, PbsAst.TypeRef> values = new HashMap<>();
|
||||
private final Map<Integer, IRRegistry.TypeDeclaration> used = new TreeMap<>();
|
||||
private final Map<String, IRRegistry.TypeDeclaration> used = new TreeMap<>();
|
||||
final Map<String, PbsAst.StructDecl> structs = new LinkedHashMap<>();
|
||||
final Map<String, PbsAst.ContractDecl> contracts = new LinkedHashMap<>();
|
||||
final Map<String, PbsAst.ServiceDecl> services = new LinkedHashMap<>();
|
||||
final List<PbsAst.ImplementsDecl> implementations = new ArrayList<>();
|
||||
final List<IRRegistry.Implementation> runtimeImplementations = new ArrayList<>();
|
||||
|
||||
PbsRuntimeTypes(PbsAst.File ast, ReadOnlyList<PbsAst.TopDecl> supplemental, Map<String,String> builtins) {
|
||||
builtinNames = builtins;
|
||||
for (var declaration : ast.topDecls()) if (declaration instanceof PbsAst.ImplementsDecl implementation)
|
||||
implementations.add(implementation);
|
||||
var declarations = new ArrayList<>(ast.topDecls().asList());
|
||||
declarations.addAll(supplemental.asList());
|
||||
for (var decl : declarations) {
|
||||
if (decl instanceof PbsAst.StructDecl s) {
|
||||
structs.put(s.name(), s);
|
||||
for (var f : s.methods()) addSignature(s.name()+"."+f.name(), f);
|
||||
}
|
||||
if (decl instanceof PbsAst.ContractDecl c) contracts.put(c.name(), c);
|
||||
if (decl instanceof PbsAst.ServiceDecl s) services.put(s.name(), s);
|
||||
if (decl instanceof PbsAst.EnumDecl e) enums.put(e.name(), e);
|
||||
if (decl instanceof PbsAst.ConstDecl c) values.put(c.name(), c.explicitType());
|
||||
if (decl instanceof PbsAst.GlobalDecl g) values.put(g.name(), g.explicitType());
|
||||
if (decl instanceof PbsAst.FunctionDecl f) addSignature(f.name(), f);
|
||||
if (decl instanceof PbsAst.FunctionDecl f) {
|
||||
addSignature(f.name(), f);
|
||||
functions.computeIfAbsent(f.name(), ignored -> new ArrayList<>()).add(f);
|
||||
}
|
||||
if (decl instanceof PbsAst.ServiceDecl s) for (var f : s.methods()) addSignature(s.name()+"."+f.name(), f);
|
||||
if (decl instanceof PbsAst.BuiltinTypeDecl b) {
|
||||
fields.put(b.name(), b.fields());
|
||||
@@ -31,6 +49,14 @@ final class PbsRuntimeTypes {
|
||||
}
|
||||
if (decl instanceof PbsAst.HostDecl h) for(var f:h.signatures()) signatures.put(h.name()+"."+f.name()+"#"+f.parameters().size(), f);
|
||||
}
|
||||
for (var imported : ast.imports()) for (var item : imported.items()) {
|
||||
if (item.alias() == null || item.alias().isBlank()) continue;
|
||||
aliases.put(item.alias(), item.name());
|
||||
if (functions.containsKey(item.name())) functions.put(item.alias(),functions.get(item.name()));
|
||||
if (structs.containsKey(item.name())) structs.put(item.alias(), structs.get(item.name()));
|
||||
if (services.containsKey(item.name())) services.put(item.alias(), services.get(item.name()));
|
||||
if (contracts.containsKey(item.name())) contracts.put(item.alias(), contracts.get(item.name()));
|
||||
}
|
||||
}
|
||||
private void addSignature(String name, PbsAst.FunctionDecl f) {
|
||||
signatures.put(name+"#"+f.parameters().size(), new PbsAst.FunctionSignature(f.name(), f.parameters(), f.returnKind(), f.returnType(), f.resultErrorType(), f.attributes(), f.span()));
|
||||
@@ -39,15 +65,97 @@ final class PbsRuntimeTypes {
|
||||
String canonical(PbsAst.TypeRef t) {
|
||||
if(t==null) return "void";
|
||||
if(t.kind()==PbsAst.TypeRefKind.GROUP) return canonical(t.inner());
|
||||
return builtinNames.getOrDefault(t.name(), t.name());
|
||||
var name = aliases.getOrDefault(t.name(), t.name());
|
||||
return builtinNames.getOrDefault(name, name);
|
||||
}
|
||||
int slots(PbsAst.TypeRef t) {
|
||||
if(t==null || t.kind()==PbsAst.TypeRefKind.UNIT) return 0;
|
||||
if(t.kind()==PbsAst.TypeRefKind.GROUP) return slots(t.inner());
|
||||
if(t.kind()==PbsAst.TypeRefKind.NAMED_TUPLE) return t.fields().stream().mapToInt(f->slots(f.typeRef())).sum();
|
||||
if (contracts.containsKey(canonical(t))) return 2;
|
||||
return switch(canonical(t)) { case "vec2" -> 2; case "pixel" -> 3; default -> 1; };
|
||||
}
|
||||
IRRegistry.TypeRef registryType(PbsAst.TypeRef t) {
|
||||
static PbsAst.TypeRef unwrap(PbsAst.TypeRef t) {
|
||||
while (t != null && t.kind() == PbsAst.TypeRefKind.GROUP) t = t.inner();
|
||||
return t;
|
||||
}
|
||||
String key(PbsAst.TypeRef t) {
|
||||
t = unwrap(t);
|
||||
if (t == null) return "void";
|
||||
if (t.kind() == PbsAst.TypeRefKind.ARRAY) return "array("+key(t.inner())+")";
|
||||
if (t.kind() == PbsAst.TypeRefKind.OPTIONAL) return "optional("+key(t.inner())+")";
|
||||
if (t.kind() == PbsAst.TypeRefKind.NAMED_TUPLE) return "tuple("+t.fields().stream().map(f->key(f.typeRef())).reduce((a,b)->a+","+b).orElse("")+")";
|
||||
if (structs.containsKey(t.name())) return nominalKey("struct", structs.get(t.name()).span());
|
||||
if (services.containsKey(t.name())) return nominalKey("struct", services.get(t.name()).span());
|
||||
if (contracts.containsKey(t.name())) return nominalKey("contract", contracts.get(t.name()).span());
|
||||
return canonical(t);
|
||||
}
|
||||
String shapeKey(PbsAst.TypeRef type) {
|
||||
var t = unwrap(type);
|
||||
if (t == null || t.kind() == PbsAst.TypeRefKind.UNIT) return "";
|
||||
if (t.kind() == PbsAst.TypeRefKind.NAMED_TUPLE) return t.fields().stream()
|
||||
.map(field -> shapeKey(field.typeRef())).collect(java.util.stream.Collectors.joining(","));
|
||||
return key(t);
|
||||
}
|
||||
private String nominalKey(String category, Span span) {
|
||||
return "pbs:" + category + ":file" + span.getFileId().getId() + ":" + span.getStart();
|
||||
}
|
||||
IRRegistry.TypeRef dynamic() { return builtin(0x15); }
|
||||
IRRegistry.TypeRef arrayStorage() {
|
||||
var element = dynamic();
|
||||
var ref = new IRRegistry.TypeRef("pbs:array-storage");
|
||||
used.putIfAbsent(ref.declarationKey(), new IRRegistry.TypeDeclaration(ref, null, new IRRegistry.Array(element)));
|
||||
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)));
|
||||
return ref;
|
||||
}
|
||||
IRRegistry.TypeRef holder(IRRegistry.TypeRef value) {
|
||||
var ref = new IRRegistry.TypeRef("pbs:default:"+value.declarationKey());
|
||||
used.putIfAbsent(ref.declarationKey(),new IRRegistry.TypeDeclaration(ref,null,new IRRegistry.Struct(ReadOnlyList.from(new IRRegistry.NamedType(value,"value")))));
|
||||
return ref;
|
||||
}
|
||||
IRRegistry.TypeRef registryType(PbsAst.TypeRef type) {
|
||||
var t = unwrap(type);
|
||||
if (t.kind() == PbsAst.TypeRefKind.ARRAY) return arrayStorage();
|
||||
if (t.kind() == PbsAst.TypeRefKind.OPTIONAL || t.kind() == PbsAst.TypeRefKind.NAMED_TUPLE) {
|
||||
var ref = new IRRegistry.TypeRef("pbs:value:"+key(t));
|
||||
if (!used.containsKey(ref.declarationKey())) {
|
||||
used.put(ref.declarationKey(),new IRRegistry.TypeDeclaration(ref,null,new IRRegistry.Struct(null)));
|
||||
var fields = new ArrayList<IRRegistry.NamedType>();
|
||||
for (var field : t.kind() == PbsAst.TypeRefKind.OPTIONAL ? results(t.inner()) : results(t))
|
||||
fields.add(new IRRegistry.NamedType(field,null));
|
||||
used.put(ref.declarationKey(),new IRRegistry.TypeDeclaration(ref,null,new IRRegistry.Struct(ReadOnlyList.wrap(fields))));
|
||||
}
|
||||
return ref;
|
||||
}
|
||||
if (structs.containsKey(t.name()) || services.containsKey(t.name())) {
|
||||
var ref = new IRRegistry.TypeRef(key(t));
|
||||
if (!used.containsKey(ref.declarationKey())) {
|
||||
used.put(ref.declarationKey(),new IRRegistry.TypeDeclaration(ref,canonical(t),new IRRegistry.Struct(null)));
|
||||
var fields = new ArrayList<IRRegistry.NamedType>();
|
||||
if (structs.containsKey(t.name())) for(var field : structs.get(t.name()).fields())
|
||||
fields.add(new IRRegistry.NamedType(registryType(field.typeRef()),field.name()));
|
||||
used.put(ref.declarationKey(),new IRRegistry.TypeDeclaration(ref,canonical(t),new IRRegistry.Struct(ReadOnlyList.wrap(fields))));
|
||||
}
|
||||
return ref;
|
||||
}
|
||||
if (contracts.containsKey(t.name())) {
|
||||
var ref = new IRRegistry.TypeRef(key(t));
|
||||
if (!used.containsKey(ref.declarationKey())) {
|
||||
used.put(ref.declarationKey(),new IRRegistry.TypeDeclaration(ref,canonical(t),new IRRegistry.Trait(null)));
|
||||
var methods = new ArrayList<IRRegistry.Method>();
|
||||
for (var method : contracts.get(t.name()).signatures()) {
|
||||
var args = new ArrayList<IRRegistry.NamedType>();
|
||||
for(var arg : method.parameters()) for(var part : results(arg.typeRef())) args.add(new IRRegistry.NamedType(part,arg.name()));
|
||||
methods.add(new IRRegistry.Method(method.name(),new IRRegistry.Signature(ReadOnlyList.wrap(args),ReadOnlyList.wrap(results(method.returnType())))));
|
||||
}
|
||||
used.put(ref.declarationKey(),new IRRegistry.TypeDeclaration(ref,canonical(t),new IRRegistry.Trait(ReadOnlyList.wrap(methods))));
|
||||
}
|
||||
return ref;
|
||||
}
|
||||
int id = switch(canonical(t)) {
|
||||
case "int" -> 0x10; case "long" -> 0x11; case "float" -> 0x12;
|
||||
case "bool" -> 0x13; case "str" -> 0x14;
|
||||
@@ -55,9 +163,7 @@ final class PbsRuntimeTypes {
|
||||
default -> { if(enums.containsKey(t.name())) yield 0x10;
|
||||
throw new UnsupportedOperationException("Unsupported PBS runtime type: "+t.name()); }
|
||||
};
|
||||
var ref=IRRegistry.TypeRef.builtin(id);
|
||||
used.putIfAbsent(id,new IRRegistry.TypeDeclaration(ref,null,new IRRegistry.Builtin(id)));
|
||||
return ref;
|
||||
return builtin(id);
|
||||
}
|
||||
List<IRRegistry.TypeRef> results(PbsAst.TypeRef t) {
|
||||
if(t==null || t.kind()==PbsAst.TypeRefKind.UNIT) return List.of();
|
||||
@@ -76,7 +182,7 @@ final class PbsRuntimeTypes {
|
||||
var returns=f.returnKind()==PbsAst.ReturnKind.PLAIN ? results(f.returnType()) : List.<IRRegistry.TypeRef>of();
|
||||
return IRRegistry.FunctionMetadata.ordinary(new IRRegistry.Signature(ReadOnlyList.wrap(params),ReadOnlyList.wrap(returns)));
|
||||
}
|
||||
IRRegistry registry() { return new IRRegistry(ReadOnlyList.wrap(new ArrayList<>(used.values())),ReadOnlyList.empty()); }
|
||||
IRRegistry registry() { return new IRRegistry(ReadOnlyList.wrap(new ArrayList<>(used.values())),ReadOnlyList.wrap(runtimeImplementations)); }
|
||||
Integer enumValue(String owner,String label) {
|
||||
var e=enums.get(owner); if(e==null) return null;
|
||||
int index=0;
|
||||
|
||||
+20
-1
@@ -40,6 +40,18 @@ final class PbsBlockParser {
|
||||
}
|
||||
|
||||
final var expression = exprParser.parseExpression();
|
||||
if (cursor.check(PbsTokenKind.EQUAL)) {
|
||||
cursor.advance();
|
||||
final var value = exprParser.parseExpression();
|
||||
final var end = consume(PbsTokenKind.SEMICOLON, "Expected ';' after assignment");
|
||||
if (!(expression instanceof PbsAst.IndexExpr)) {
|
||||
context.report(cursor.previous(), ParseErrors.E_PARSE_INVALID_ASSIGN_TARGET, "Expected array index assignment target");
|
||||
}
|
||||
statements.add(new PbsAst.AssignStatement(
|
||||
new PbsAst.LValue("", ReadOnlyList.empty(), expression.span(), expression),
|
||||
PbsAst.AssignOperator.ASSIGN, value, context.span(expression.span().getStart(), end.end())));
|
||||
continue;
|
||||
}
|
||||
if (cursor.match(PbsTokenKind.SEMICOLON)) {
|
||||
statements.add(new PbsAst.ExpressionStatement(
|
||||
expression,
|
||||
@@ -184,6 +196,11 @@ final class PbsBlockParser {
|
||||
}
|
||||
|
||||
private PbsAst.IfStatement parseIfStatement(final PbsToken ifToken) {
|
||||
PbsToken binding = null;
|
||||
if (cursor.match(PbsTokenKind.LET)) {
|
||||
binding = consume(PbsTokenKind.IDENTIFIER, "Expected binding name after 'if let'");
|
||||
consume(PbsTokenKind.EQUAL, "Expected '=' after optional binding name");
|
||||
}
|
||||
final var condition = exprParser.parseExpression();
|
||||
final var thenBlock = parseBlock();
|
||||
|
||||
@@ -206,7 +223,9 @@ final class PbsBlockParser {
|
||||
thenBlock,
|
||||
elseIf,
|
||||
elseBlock,
|
||||
context.span(ifToken.start(), end));
|
||||
context.span(ifToken.start(), end),
|
||||
binding == null ? null : binding.lexeme(),
|
||||
binding == null ? null : context.span(binding.start(), binding.end()));
|
||||
}
|
||||
|
||||
private PbsAst.Statement parseForStatement(final PbsToken forToken) {
|
||||
|
||||
+16
@@ -54,6 +54,12 @@ final class PbsExprPrimaryParser {
|
||||
continue;
|
||||
}
|
||||
|
||||
if (cursor.match(PbsTokenKind.LEFT_BRACKET)) {
|
||||
final var index = expressionParserDelegate.parse();
|
||||
final var close = context.consume(PbsTokenKind.RIGHT_BRACKET, "Expected ']' after array index");
|
||||
expression = new PbsAst.IndexExpr(expression, index, context.span(expression.span().getStart(), close.end()));
|
||||
continue;
|
||||
}
|
||||
if (cursor.match(PbsTokenKind.DOT)) {
|
||||
final var member = context.consumeMemberName("Expected member name after '.'");
|
||||
expression = new PbsAst.MemberExpr(
|
||||
@@ -81,6 +87,16 @@ final class PbsExprPrimaryParser {
|
||||
}
|
||||
|
||||
PbsAst.Expression parsePrimary() {
|
||||
if (cursor.match(PbsTokenKind.LEFT_BRACKET)) {
|
||||
final var open = cursor.previous();
|
||||
final var elements = new ArrayList<PbsAst.Expression>();
|
||||
if (!cursor.check(PbsTokenKind.RIGHT_BRACKET)) {
|
||||
do { elements.add(expressionParserDelegate.parse()); }
|
||||
while (cursor.match(PbsTokenKind.COMMA));
|
||||
}
|
||||
final var close = context.consume(PbsTokenKind.RIGHT_BRACKET, "Expected ']' after array literal");
|
||||
return new PbsAst.ArrayLiteralExpr(ReadOnlyList.wrap(elements), context.span(open.start(), close.end()));
|
||||
}
|
||||
final var literal = literalSupport.parseLiteralExpression();
|
||||
if (literal != null) {
|
||||
return literal;
|
||||
|
||||
+40
@@ -8,6 +8,8 @@ import java.util.ArrayList;
|
||||
|
||||
final class PbsTypeParser {
|
||||
private static final int MAX_NAMED_TUPLE_ARITY = 6;
|
||||
private static final int MAX_TYPE_DEPTH = 256;
|
||||
private int typeDepth;
|
||||
|
||||
private final PbsParserContext context;
|
||||
private final PbsTokenCursor cursor;
|
||||
@@ -56,6 +58,44 @@ final class PbsTypeParser {
|
||||
}
|
||||
|
||||
PbsAst.TypeRef parseTypeRef() {
|
||||
if (typeDepth >= MAX_TYPE_DEPTH) {
|
||||
var token = cursor.peek();
|
||||
context.report(token, ParseErrors.E_PARSE_INVALID_TYPE_SURFACE, "Type nesting exceeds compiler limit of " + MAX_TYPE_DEPTH);
|
||||
if (!cursor.isAtEnd()) cursor.advance();
|
||||
return PbsAst.TypeRef.error(context.span(token.start(), token.end()));
|
||||
}
|
||||
typeDepth++;
|
||||
try { return parseTypeRefBody(); }
|
||||
finally { typeDepth--; }
|
||||
}
|
||||
|
||||
private PbsAst.TypeRef parseTypeRefBody() {
|
||||
if (cursor.check(PbsTokenKind.IDENTIFIER) && cursor.peek().lexeme().equals("array")) {
|
||||
final var start = cursor.advance();
|
||||
int depth = 1;
|
||||
if (cursor.match(PbsTokenKind.LEFT_BRACKET)) {
|
||||
final var number = consume(PbsTokenKind.INT_LITERAL, "Array depth must be a positive integer literal");
|
||||
try { depth = Integer.parseInt(number.lexeme()); }
|
||||
catch (NumberFormatException invalid) { depth = 0; }
|
||||
if (depth < 1) {
|
||||
context.report(number, ParseErrors.E_PARSE_INVALID_TYPE_SURFACE, "Array depth must be a positive integer literal");
|
||||
depth = 1;
|
||||
}
|
||||
consume(PbsTokenKind.RIGHT_BRACKET, "Expected ']' after array depth");
|
||||
}
|
||||
if (depth > MAX_TYPE_DEPTH - typeDepth) {
|
||||
context.report(start, ParseErrors.E_PARSE_INVALID_TYPE_SURFACE, "Array depth exceeds compiler type nesting limit of " + MAX_TYPE_DEPTH);
|
||||
depth = 1;
|
||||
}
|
||||
typeDepth += depth - 1;
|
||||
PbsAst.TypeRef inner;
|
||||
try { inner = parseTypeRef(); }
|
||||
finally { typeDepth -= depth - 1; }
|
||||
for (int level = 0; level < depth; level++) {
|
||||
inner = PbsAst.TypeRef.array(inner, context.span(start.start(), inner.span().getEnd()));
|
||||
}
|
||||
return inner;
|
||||
}
|
||||
if (cursor.match(PbsTokenKind.OPTIONAL)) {
|
||||
final var optionalToken = cursor.previous();
|
||||
final var inner = parseTypeRef();
|
||||
|
||||
+1
@@ -306,6 +306,7 @@ final class PbsAstDocumentSymbols {
|
||||
case UNIT -> typeRef.name() == null || typeRef.name().isBlank() ? "void" : typeRef.name();
|
||||
case SELF -> "Self";
|
||||
case SIMPLE -> typeRef.name() == null ? "void" : typeRef.name();
|
||||
case ARRAY -> "array " + formatTypeRef(typeRef.inner());
|
||||
case OPTIONAL -> "optional " + formatTypeRef(typeRef.inner());
|
||||
case GROUP -> "(" + formatTypeRef(typeRef.inner()) + ")";
|
||||
case NAMED_TUPLE -> {
|
||||
|
||||
+1
@@ -217,6 +217,7 @@ public final class PbsBuiltinLayoutResolver {
|
||||
return switch (typeRef.kind()) {
|
||||
case SIMPLE -> typeRef.name();
|
||||
case SELF -> "Self";
|
||||
case ARRAY -> "array %s".formatted(renderTypeSurface(typeRef.inner()));
|
||||
case OPTIONAL -> "optional %s".formatted(renderTypeSurface(typeRef.inner()));
|
||||
case UNIT -> "void";
|
||||
case GROUP -> "(%s)".formatted(renderTypeSurface(typeRef.inner()));
|
||||
|
||||
+1
@@ -78,6 +78,7 @@ final class PbsCallableShape {
|
||||
return switch (unwrapped.kind()) {
|
||||
case SIMPLE -> "simple:" + unwrapped.name();
|
||||
case SELF -> "self";
|
||||
case ARRAY -> "array(" + typeKey(unwrapped.inner()) + ")";
|
||||
case OPTIONAL -> "optional(" + typeKey(unwrapped.inner()) + ")";
|
||||
case UNIT -> "unit";
|
||||
case GROUP -> typeKey(unwrapped.inner());
|
||||
|
||||
+7
@@ -221,6 +221,13 @@ final class PbsDeclarationRuleValidator {
|
||||
if (expression instanceof PbsAst.MemberExpr memberExpr) {
|
||||
return firstUnsupportedGlobalInitializerSpan(memberExpr.receiver());
|
||||
}
|
||||
if (expression instanceof PbsAst.ArrayLiteralExpr literal) {
|
||||
for (var value : literal.elements()) {
|
||||
var invalid = firstUnsupportedGlobalInitializerSpan(value);
|
||||
if (invalid != null) return invalid;
|
||||
}
|
||||
return null;
|
||||
}
|
||||
if (expression instanceof PbsAst.NewExpr newExpr) {
|
||||
for (final var argument : newExpr.arguments()) {
|
||||
final var invalid = firstUnsupportedGlobalInitializerSpan(argument);
|
||||
|
||||
+11
@@ -373,6 +373,17 @@ public final class PbsDeclarationSemanticsValidator {
|
||||
validateSdkExecutableExpression(memberExpr.receiver(), diagnostics);
|
||||
case PbsAst.GroupExpr groupExpr ->
|
||||
validateSdkExecutableExpression(groupExpr.expression(), diagnostics);
|
||||
case PbsAst.ElseExpr value -> {
|
||||
validateSdkExecutableExpression(value.optionalExpression(), diagnostics);
|
||||
validateSdkExecutableExpression(value.fallbackExpression(), diagnostics);
|
||||
}
|
||||
case PbsAst.ArrayLiteralExpr literal -> {
|
||||
for (var value : literal.elements()) validateSdkExecutableExpression(value, diagnostics);
|
||||
}
|
||||
case PbsAst.IndexExpr index -> {
|
||||
validateSdkExecutableExpression(index.receiver(), diagnostics);
|
||||
validateSdkExecutableExpression(index.index(), diagnostics);
|
||||
}
|
||||
case PbsAst.NewExpr newExpr -> {
|
||||
for (final var argument : newExpr.arguments()) {
|
||||
validateSdkExecutableExpression(argument, diagnostics);
|
||||
|
||||
+31
-5
@@ -493,8 +493,15 @@ public final class PbsEditorialSupportService {
|
||||
}
|
||||
if (statement.span().contains(offset)) {
|
||||
if (statement instanceof PbsAst.IfStatement ifStatement) {
|
||||
if (ifStatement.thenBlock().span().contains(offset)) {
|
||||
return populateScopeUntilOffset(ifStatement.thenBlock(), scope, frame, offset);
|
||||
if (ifStatement.thenBlock().span().contains(offset)
|
||||
|| (ifStatement.bindingSpan() != null && ifStatement.bindingSpan().contains(offset))) {
|
||||
var successScope = scope.copy();
|
||||
if (ifStatement.bindingName() != null) {
|
||||
var optional = analyzeExpressionType(ifStatement.condition(),scope,null,frame.returnType(),frame.resultErrorName(),frame.receiverType());
|
||||
if (optional.kind() == Kind.OPTIONAL) successScope.bind(ifStatement.bindingName(),optional.inner());
|
||||
}
|
||||
if (ifStatement.bindingSpan() != null && ifStatement.bindingSpan().contains(offset)) return successScope;
|
||||
return populateScopeUntilOffset(ifStatement.thenBlock(), successScope, frame, offset);
|
||||
}
|
||||
if (ifStatement.elseBlock() != null && ifStatement.elseBlock().span().contains(offset)) {
|
||||
return populateScopeUntilOffset(ifStatement.elseBlock(), scope, frame, offset);
|
||||
@@ -569,7 +576,7 @@ public final class PbsEditorialSupportService {
|
||||
final TypeView receiverType,
|
||||
final Model ignoredModel,
|
||||
final DiagnosticSink diagnostics,
|
||||
final boolean valueContext) {
|
||||
final boolean valueContext, final TypeView blockExpectedType) {
|
||||
final Scope scoped = outerScope.copy();
|
||||
for (final var statement : block.statements()) {
|
||||
if (statement instanceof PbsAst.LetStatement letStatement) {
|
||||
@@ -598,7 +605,7 @@ public final class PbsEditorialSupportService {
|
||||
return expressionAnalyzer.analyzeExpression(
|
||||
block.tailExpression(),
|
||||
scoped,
|
||||
null,
|
||||
blockExpectedType,
|
||||
returnType,
|
||||
resultErrorName,
|
||||
receiverType,
|
||||
@@ -711,6 +718,14 @@ public final class PbsEditorialSupportService {
|
||||
return List.of();
|
||||
}
|
||||
final Map<String, PbsEditorialCompletionCandidate> completions = new LinkedHashMap<>();
|
||||
if (receiverType.kind() == Kind.ARRAY) {
|
||||
return List.of(new PbsEditorialCompletionCandidate("length", PbsEditorialSymbolKind.FIELD, "long", "array"),
|
||||
new PbsEditorialCompletionCandidate("clear", PbsEditorialSymbolKind.METHOD, "clear(index: int | long) -> unit", "array"));
|
||||
}
|
||||
if (receiverType.kind() == Kind.OPTIONAL) {
|
||||
return List.of(new PbsEditorialCompletionCandidate("hasSome", PbsEditorialSymbolKind.METHOD, "hasSome() -> bool", "optional"),
|
||||
new PbsEditorialCompletionCandidate("hasNone", PbsEditorialSymbolKind.METHOD, "hasNone() -> bool", "optional"));
|
||||
}
|
||||
if (receiverType.kind() == Kind.STRUCT) {
|
||||
final StructInfo structInfo = model.structs.get(receiverType.name());
|
||||
if (structInfo != null) {
|
||||
@@ -807,6 +822,10 @@ public final class PbsEditorialSupportService {
|
||||
if (receiverType == null) {
|
||||
return Optional.empty();
|
||||
}
|
||||
if (receiverType.kind() == Kind.ARRAY || receiverType.kind() == Kind.OPTIONAL) {
|
||||
return memberCompletions(receiverType).stream().filter(item -> item.label().equals(memberName))
|
||||
.findFirst().map(item -> new PbsEditorialResolvedSymbol(item.label(), item.kind(), item.detail(), item.origin(), List.of(), ""));
|
||||
}
|
||||
if (receiverType.kind() == Kind.STRUCT) {
|
||||
final StructInfo structInfo = model.structs.get(receiverType.name());
|
||||
if (structInfo == null) {
|
||||
@@ -999,8 +1018,11 @@ public final class PbsEditorialSupportService {
|
||||
}
|
||||
if (statement.span().contains(offset)) {
|
||||
if (statement instanceof PbsAst.IfStatement ifStatement) {
|
||||
if (symbolName.equals(ifStatement.bindingName()) && ifStatement.bindingSpan() != null
|
||||
&& ifStatement.bindingSpan().contains(offset)) return ifStatement.bindingSpan();
|
||||
if (ifStatement.thenBlock().span().contains(offset)) {
|
||||
return bindingSpan(ifStatement.thenBlock(), symbolName, offset, found);
|
||||
return bindingSpan(ifStatement.thenBlock(), symbolName, offset,
|
||||
symbolName.equals(ifStatement.bindingName()) ? ifStatement.bindingSpan() : found);
|
||||
}
|
||||
if (ifStatement.elseBlock() != null && ifStatement.elseBlock().span().contains(offset)) {
|
||||
return bindingSpan(ifStatement.elseBlock(), symbolName, offset, found);
|
||||
@@ -1370,6 +1392,7 @@ public final class PbsEditorialSupportService {
|
||||
case UNIT -> "unit";
|
||||
case SELF -> "Self";
|
||||
case SIMPLE -> typeRef.name();
|
||||
case ARRAY -> "array " + formatTypeRef(typeRef.inner());
|
||||
case OPTIONAL -> formatTypeRef(typeRef.inner()) + "?";
|
||||
case GROUP -> formatTypeRef(typeRef.inner());
|
||||
case NAMED_TUPLE -> {
|
||||
@@ -1836,6 +1859,7 @@ public final class PbsEditorialSupportService {
|
||||
return true;
|
||||
}
|
||||
if (statement instanceof PbsAst.IfStatement ifStatement) {
|
||||
if (ifStatement.bindingSpan() != null && keys.contains(locationKey(ifStatement.bindingSpan()))) return true;
|
||||
if (containsLetNameSpan(ifStatement.thenBlock(), keys)
|
||||
|| containsLetNameSpan(ifStatement.elseBlock(), keys)) {
|
||||
return true;
|
||||
@@ -1873,6 +1897,7 @@ public final class PbsEditorialSupportService {
|
||||
if (statement instanceof PbsAst.LetStatement letStatement) {
|
||||
names.add(letStatement.name());
|
||||
} else if (statement instanceof PbsAst.IfStatement ifStatement) {
|
||||
if (ifStatement.bindingName() != null) names.add(ifStatement.bindingName());
|
||||
collectLetNames(ifStatement.thenBlock(), names);
|
||||
collectLetNames(ifStatement.elseBlock(), names);
|
||||
} else if (statement instanceof PbsAst.ForStatement forStatement) {
|
||||
@@ -1996,6 +2021,7 @@ public final class PbsEditorialSupportService {
|
||||
}
|
||||
return switch (typeRef.kind()) {
|
||||
case SIMPLE -> aliasedTypeRefs.getOrDefault(typeRef.name(), typeRef);
|
||||
case ARRAY -> PbsAst.TypeRef.array(aliasExpandedTypeRef(typeRef.inner()), typeRef.span());
|
||||
case OPTIONAL -> PbsAst.TypeRef.optional(aliasExpandedTypeRef(typeRef.inner()), typeRef.span());
|
||||
case GROUP -> PbsAst.TypeRef.group(aliasExpandedTypeRef(typeRef.inner()), typeRef.span());
|
||||
case NAMED_TUPLE -> {
|
||||
|
||||
+7
-1
@@ -15,7 +15,7 @@ final class PbsFlowAssignmentAnalyzer {
|
||||
TypeView receiverType,
|
||||
Model model,
|
||||
p.studio.compiler.source.diagnostics.DiagnosticSink diagnostics,
|
||||
boolean valueContext);
|
||||
boolean valueContext, TypeView expectedType);
|
||||
}
|
||||
|
||||
private record AssignmentTargetResolution(
|
||||
@@ -75,6 +75,12 @@ final class PbsFlowAssignmentAnalyzer {
|
||||
private AssignmentTargetResolution resolveAssignmentTarget(
|
||||
final PbsAst.LValue lValue,
|
||||
final PbsFlowBodyContext context) {
|
||||
if (lValue.expression() instanceof PbsAst.IndexExpr index) {
|
||||
var readType = expressionAnalyzer.analyzeExpression(index, context.scope(), null, context.returnType(),
|
||||
context.resultErrorName(), context.receiverType(), context.model(), context.diagnostics(),
|
||||
ExprUse.VALUE, true, blockAnalysisDelegate::analyze).type();
|
||||
return new AssignmentTargetResolution(readType.kind() == Kind.OPTIONAL ? readType.inner() : TypeView.unknown(), true);
|
||||
}
|
||||
final var scope = context.scope();
|
||||
final var receiverType = context.receiverType();
|
||||
final var model = context.model();
|
||||
|
||||
+12
-3
@@ -95,6 +95,15 @@ final class PbsFlowBodyAnalyzer {
|
||||
final PbsAst.TopDecl topDecl,
|
||||
final Model model,
|
||||
final DiagnosticSink diagnostics) {
|
||||
if (topDecl instanceof PbsAst.GlobalDecl global && global.initializer() != null) {
|
||||
var expected = typeOps.typeFromTypeRef(global.explicitType(), model, null);
|
||||
var actual = expressionAnalyzer.analyzeExpression(global.initializer(), new Scope(), expected,
|
||||
TypeView.unit(), null, null, model, diagnostics, PbsFlowSemanticSupport.ExprUse.VALUE, true,
|
||||
this::analyzeBlock).type();
|
||||
if (!typeOps.compatible(actual, expected)) p.studio.compiler.source.diagnostics.Diagnostics.error(
|
||||
diagnostics,"E_SEM_GLOBAL_TYPE_MISMATCH","Global initializer does not match its declared type",global.span());
|
||||
return;
|
||||
}
|
||||
if (topDecl instanceof PbsAst.FunctionDecl functionDecl) {
|
||||
validateFunction(functionDecl, model, diagnostics);
|
||||
return;
|
||||
@@ -231,8 +240,8 @@ final class PbsFlowBodyAnalyzer {
|
||||
final TypeView receiverType,
|
||||
final Model model,
|
||||
final DiagnosticSink diagnostics,
|
||||
final boolean valueContext) {
|
||||
return analyzeBlock(
|
||||
final boolean valueContext, final TypeView expectedType) {
|
||||
return statementAnalyzer().analyzeBlock(
|
||||
block,
|
||||
new PbsFlowBodyContext(
|
||||
outerScope,
|
||||
@@ -241,7 +250,7 @@ final class PbsFlowBodyAnalyzer {
|
||||
receiverType,
|
||||
model,
|
||||
diagnostics),
|
||||
valueContext);
|
||||
valueContext, expectedType);
|
||||
}
|
||||
|
||||
private TypeView analyzeBlock(
|
||||
|
||||
+25
@@ -27,6 +27,28 @@ final class PbsFlowCallableResolutionAnalyzer {
|
||||
ExprResult analyzeCallExpression(
|
||||
final PbsAst.CallExpr callExpr,
|
||||
final PbsFlowExpressionContext context) {
|
||||
if (callExpr.callee() instanceof PbsAst.MemberExpr member
|
||||
&& (member.memberName().equals("hasSome") || member.memberName().equals("hasNone"))) {
|
||||
var receiver = analyzeValueExpression(member.receiver(), context, null).type();
|
||||
if (receiver.kind() == Kind.OPTIONAL) {
|
||||
if (!callExpr.arguments().isEmpty()) Diagnostics.error(context.diagnostics(),
|
||||
"E_SEM_OPTIONAL_PRESENCE_ARITY", "Optional presence methods take no arguments", callExpr.span());
|
||||
for (var argument : callExpr.arguments()) analyzeValueExpression(argument, context, null);
|
||||
return ExprResult.type(TypeView.bool());
|
||||
}
|
||||
}
|
||||
if (callExpr.callee() instanceof PbsAst.MemberExpr member && member.memberName().equals("clear")) {
|
||||
var receiver = analyzeValueExpression(member.receiver(), context, null).type();
|
||||
if (receiver.kind() == Kind.ARRAY) {
|
||||
if (callExpr.arguments().size() != 1) Diagnostics.error(context.diagnostics(), "E_SEM_ARRAY_CLEAR_ARITY", "clear requires one index", callExpr.span());
|
||||
for (var arg : callExpr.arguments()) {
|
||||
var index = analyzeValueExpression(arg, context, arg instanceof PbsAst.IntLiteralExpr ? TypeView.longType() : null).type();
|
||||
if (index.kind() != Kind.INT && index.kind() != Kind.LONG && index.kind() != Kind.UNKNOWN)
|
||||
Diagnostics.error(context.diagnostics(), "E_SEM_ARRAY_INDEX_TYPE", "Array index requires int or long", arg.span());
|
||||
}
|
||||
return ExprResult.type(TypeView.unit());
|
||||
}
|
||||
}
|
||||
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();
|
||||
@@ -105,6 +127,9 @@ final class PbsFlowCallableResolutionAnalyzer {
|
||||
final var receiverType = context.receiverType();
|
||||
final var use = context.use();
|
||||
|
||||
if (receiver.kind() == Kind.ARRAY && memberExpr.memberName().equals("length")) {
|
||||
return ExprResult.type(TypeView.longType());
|
||||
}
|
||||
if (receiver.kind() == Kind.TYPE_REF) {
|
||||
final var enumCases = model.enums.get(receiver.name());
|
||||
if (enumCases != null && enumCases.contains(memberExpr.memberName())) {
|
||||
|
||||
+2
-2
@@ -15,7 +15,7 @@ final class PbsFlowExpressionAnalyzer {
|
||||
TypeView receiverType,
|
||||
Model model,
|
||||
DiagnosticSink diagnostics,
|
||||
boolean valueContext);
|
||||
boolean valueContext, TypeView expectedType);
|
||||
}
|
||||
|
||||
private final PbsFlowTypeOps typeOps;
|
||||
@@ -120,7 +120,7 @@ final class PbsFlowExpressionAnalyzer {
|
||||
context.receiverType(),
|
||||
context.model(),
|
||||
context.diagnostics(),
|
||||
valueContext);
|
||||
valueContext, context.expectedType());
|
||||
}
|
||||
|
||||
}
|
||||
|
||||
+10
-2
@@ -46,6 +46,7 @@ final class PbsFlowSemanticSupport {
|
||||
ENUM,
|
||||
ERROR,
|
||||
OPTIONAL,
|
||||
ARRAY,
|
||||
RESULT,
|
||||
TUPLE,
|
||||
TYPE_REF,
|
||||
@@ -121,6 +122,10 @@ final class PbsFlowSemanticSupport {
|
||||
return new TypeView(Kind.ERROR, name, List.of(), null, null, List.of(), null);
|
||||
}
|
||||
|
||||
static TypeView array(final TypeView inner) {
|
||||
return new TypeView(Kind.ARRAY, "array", List.of(), inner, null, List.of(), null);
|
||||
}
|
||||
|
||||
static TypeView optional(final TypeView inner) {
|
||||
return new TypeView(Kind.OPTIONAL, "optional", List.of(), inner, null, List.of(), null);
|
||||
}
|
||||
@@ -280,7 +285,8 @@ final class PbsFlowSemanticSupport {
|
||||
field.isMutable()));
|
||||
}
|
||||
final var methods = new HashMap<String, List<CallableSymbol>>();
|
||||
for (final var method : structDecl.methods()) {
|
||||
for (final var declaredMethod : structDecl.methods()) {
|
||||
var method = p.studio.compiler.pbs.PbsTypeSubstitution.forOwner(declaredMethod,structDecl.name());
|
||||
methods.computeIfAbsent(method.name(), ignored -> new ArrayList<>())
|
||||
.add(callableFrom(
|
||||
method.name(),
|
||||
@@ -321,7 +327,8 @@ final class PbsFlowSemanticSupport {
|
||||
}
|
||||
if (topDecl instanceof PbsAst.ServiceDecl serviceDecl) {
|
||||
final var methods = new HashMap<String, List<CallableSymbol>>();
|
||||
for (final var method : serviceDecl.methods()) {
|
||||
for (final var declaredMethod : serviceDecl.methods()) {
|
||||
var method = p.studio.compiler.pbs.PbsTypeSubstitution.forOwner(declaredMethod,serviceDecl.name());
|
||||
methods.computeIfAbsent(method.name(), ignored -> new ArrayList<>())
|
||||
.add(callableFrom(
|
||||
method.name(),
|
||||
@@ -590,6 +597,7 @@ final class PbsFlowSemanticSupport {
|
||||
}
|
||||
yield TypeView.unknown();
|
||||
}
|
||||
case ARRAY -> TypeView.array(typeFrom(typeRef.inner()));
|
||||
case OPTIONAL -> TypeView.optional(typeFrom(typeRef.inner()));
|
||||
case GROUP -> typeFrom(typeRef.inner());
|
||||
case NAMED_TUPLE -> {
|
||||
|
||||
+25
-6
@@ -41,6 +41,10 @@ final class PbsFlowStatementAnalyzer {
|
||||
final PbsAst.Block block,
|
||||
final PbsFlowBodyContext context,
|
||||
final boolean valueContext) {
|
||||
return analyzeBlock(block, context, valueContext, null);
|
||||
}
|
||||
|
||||
TypeView analyzeBlock(PbsAst.Block block, PbsFlowBodyContext context, boolean valueContext, TypeView expectedType) {
|
||||
final var scope = context.scope().copy();
|
||||
final var scopedContext = context.withScope(scope);
|
||||
for (final var statement : block.statements()) {
|
||||
@@ -52,7 +56,7 @@ final class PbsFlowStatementAnalyzer {
|
||||
return expressionAnalyzer.analyzeExpression(
|
||||
block.tailExpression(),
|
||||
scope,
|
||||
null,
|
||||
expectedType,
|
||||
context.returnType(),
|
||||
context.resultErrorName(),
|
||||
context.receiverType(),
|
||||
@@ -71,7 +75,7 @@ final class PbsFlowStatementAnalyzer {
|
||||
final TypeView receiverType,
|
||||
final Model model,
|
||||
final p.studio.compiler.source.diagnostics.DiagnosticSink diagnostics,
|
||||
final boolean valueContext) {
|
||||
final boolean valueContext, final TypeView expectedType) {
|
||||
return analyzeBlock(
|
||||
block,
|
||||
new PbsFlowBodyContext(
|
||||
@@ -81,7 +85,7 @@ final class PbsFlowStatementAnalyzer {
|
||||
receiverType,
|
||||
model,
|
||||
diagnostics),
|
||||
valueContext);
|
||||
valueContext, expectedType);
|
||||
}
|
||||
|
||||
private void analyzeStatement(
|
||||
@@ -94,6 +98,8 @@ final class PbsFlowStatementAnalyzer {
|
||||
final var model = context.model();
|
||||
final var diagnostics = context.diagnostics();
|
||||
if (statement instanceof PbsAst.LetStatement letStatement) {
|
||||
if (letStatement.explicitType() != null) PbsTypeSurfaceSemanticsValidator.validateTypeSurfaceRecursive(
|
||||
java.util.List.of(letStatement.explicitType()), "local " + letStatement.name(), receiverType != null, diagnostics);
|
||||
final var expected = letStatement.explicitType() == null
|
||||
? null
|
||||
: typeOps.typeFromTypeRef(letStatement.explicitType(), model, receiverType);
|
||||
@@ -109,6 +115,10 @@ final class PbsFlowStatementAnalyzer {
|
||||
ExprUse.VALUE,
|
||||
true,
|
||||
this::analyzeNestedBlock);
|
||||
if (expected != null && (expected.kind() == Kind.ARRAY || initializer.type().kind() == Kind.ARRAY)
|
||||
&& !typeOps.compatible(initializer.type(),expected)) {
|
||||
Diagnostics.error(diagnostics,"E_SEM_ARRAY_TYPE_MISMATCH","Array assignment requires the exact element type",letStatement.span());
|
||||
}
|
||||
final var resolvedType = expected == null ? initializer.type() : expected;
|
||||
scope.bind(letStatement.name(), resolvedType, !letStatement.isConst());
|
||||
if (letStatement.explicitType() == null) {
|
||||
@@ -126,7 +136,7 @@ final class PbsFlowStatementAnalyzer {
|
||||
final var condition = expressionAnalyzer.analyzeExpression(
|
||||
ifStatement.condition(),
|
||||
scope,
|
||||
TypeView.bool(),
|
||||
ifStatement.bindingName() == null ? TypeView.bool() : null,
|
||||
returnType,
|
||||
resultErrorName,
|
||||
receiverType,
|
||||
@@ -135,13 +145,22 @@ final class PbsFlowStatementAnalyzer {
|
||||
ExprUse.VALUE,
|
||||
true,
|
||||
this::analyzeNestedBlock).type();
|
||||
if (!typeOps.isBool(condition)) {
|
||||
if (ifStatement.bindingName() == null && !typeOps.isBool(condition)) {
|
||||
Diagnostics.error(diagnostics,
|
||||
PbsSemanticsErrors.E_SEM_IF_NON_BOOL_CONDITION.name(),
|
||||
"If statement condition must have bool type",
|
||||
ifStatement.condition().span());
|
||||
}
|
||||
analyzeBlock(ifStatement.thenBlock(), context, false);
|
||||
var successContext = context;
|
||||
if (ifStatement.bindingName() != null) {
|
||||
var successScope = scope.copy();
|
||||
if (condition.kind() != Kind.OPTIONAL) {
|
||||
Diagnostics.error(diagnostics, "E_SEM_IF_LET_OPTIONAL", "if let requires optional T", ifStatement.condition().span());
|
||||
}
|
||||
successScope.bind(ifStatement.bindingName(), condition.kind() == Kind.OPTIONAL ? condition.inner() : TypeView.unknown(), true);
|
||||
successContext = context.withScope(successScope);
|
||||
}
|
||||
analyzeBlock(ifStatement.thenBlock(), successContext, false);
|
||||
if (ifStatement.elseBlock() != null) {
|
||||
analyzeBlock(ifStatement.elseBlock(), context, false);
|
||||
}
|
||||
|
||||
+40
@@ -41,6 +41,32 @@ final class PbsFlowStructuralExpressionAnalyzer {
|
||||
final var model = context.model();
|
||||
final var diagnostics = context.diagnostics();
|
||||
|
||||
if (expression instanceof PbsAst.ArrayLiteralExpr literal) {
|
||||
final var array = requireArrayContext(expectedType, expression, context);
|
||||
for (var element : literal.elements()) {
|
||||
var actual = analyzeValueExpression(element, context, array.inner()).type();
|
||||
if (!typeOps.compatible(actual, array.inner())) Diagnostics.error(diagnostics,
|
||||
"E_SEM_ARRAY_ELEMENT_TYPE", "Array literal element does not match its contextual type", element.span());
|
||||
}
|
||||
return ExprResult.type(array);
|
||||
}
|
||||
if (expression instanceof PbsAst.IndexExpr index) {
|
||||
final var receiver = analyzeValueExpression(index.receiver(), context, null).type();
|
||||
checkArrayIndex(index.index(), context);
|
||||
if (receiver.kind() != Kind.ARRAY) {
|
||||
Diagnostics.error(diagnostics, "E_SEM_ARRAY_RECEIVER", "Indexing requires an array", index.receiver().span());
|
||||
return ExprResult.type(TypeView.unknown());
|
||||
}
|
||||
return ExprResult.type(TypeView.optional(receiver.inner()));
|
||||
}
|
||||
if (expression instanceof PbsAst.NewExpr allocation && allocation.typeName().equals("array")) {
|
||||
final var array = requireArrayContext(expectedType, expression, context);
|
||||
if (allocation.ctorName() != null || allocation.arguments().size() != 1) {
|
||||
Diagnostics.error(diagnostics, "E_SEM_ARRAY_CONSTRUCTION", "Use new array(length)", allocation.span());
|
||||
}
|
||||
for (var length : allocation.arguments()) checkArrayIndex(length, context);
|
||||
return ExprResult.type(array);
|
||||
}
|
||||
if (expression instanceof PbsAst.IntLiteralExpr literal) {
|
||||
if (expectedType != null && expectedType.kind() == Kind.LONG) return ExprResult.type(TypeView.longType());
|
||||
if (literal.value() < Integer.MIN_VALUE || literal.value() > Integer.MAX_VALUE) {
|
||||
@@ -209,6 +235,20 @@ final class PbsFlowStructuralExpressionAnalyzer {
|
||||
return null;
|
||||
}
|
||||
|
||||
private TypeView requireArrayContext(TypeView expected, PbsAst.Expression expression, PbsFlowExpressionContext context) {
|
||||
if (expected != null && expected.kind() == Kind.ARRAY) return expected;
|
||||
Diagnostics.error(context.diagnostics(), "E_SEM_ARRAY_CONTEXT_REQUIRED",
|
||||
"Array construction and literals require an expected array type", expression.span());
|
||||
return TypeView.array(TypeView.unknown());
|
||||
}
|
||||
|
||||
private void checkArrayIndex(PbsAst.Expression expression, PbsFlowExpressionContext context) {
|
||||
final var type = analyzeValueExpression(expression, context,
|
||||
expression instanceof PbsAst.IntLiteralExpr ? TypeView.longType() : null).type();
|
||||
if (type.kind() != Kind.INT && type.kind() != Kind.LONG && type.kind() != Kind.UNKNOWN)
|
||||
Diagnostics.error(context.diagnostics(), "E_SEM_ARRAY_INDEX_TYPE", "Array index and length require int or long", expression.span());
|
||||
}
|
||||
|
||||
private ExprResult analyzeValueExpression(
|
||||
final PbsAst.Expression expression,
|
||||
final PbsFlowExpressionContext context,
|
||||
|
||||
+2
@@ -52,6 +52,7 @@ final class PbsFlowTypeOps {
|
||||
case UNIT, INT, LONG, FLOAT, BOOL, STR -> true;
|
||||
case STRUCT, SERVICE, CONTRACT, CALLBACK, ENUM, ERROR, TYPE_REF, ASSET_NAMESPACE -> actual.name().equals(expected.name());
|
||||
case ADDRESSABLE -> true;
|
||||
case ARRAY -> compatible(actual.inner(), expected.inner());
|
||||
case OPTIONAL -> compatible(actual.inner(), expected.inner());
|
||||
case RESULT -> compatible(actual.errorType(), expected.errorType()) && compatible(actual.inner(), expected.inner());
|
||||
case TUPLE -> tupleCompatible(actual, expected);
|
||||
@@ -105,6 +106,7 @@ final class PbsFlowTypeOps {
|
||||
case UNIT -> TypeView.unit();
|
||||
case SELF -> receiverType == null ? TypeView.unknown() : receiverType;
|
||||
case SIMPLE -> simpleType(typeRef.name(), model);
|
||||
case ARRAY -> TypeView.array(typeFromTypeRef(typeRef.inner(), model, receiverType));
|
||||
case OPTIONAL -> TypeView.optional(typeFromTypeRef(typeRef.inner(), model, receiverType));
|
||||
case GROUP -> typeFromTypeRef(typeRef.inner(), model, receiverType);
|
||||
case NAMED_TUPLE -> {
|
||||
|
||||
+9
@@ -66,6 +66,15 @@ public final class PbsGlobalDependencySupport {
|
||||
collectRecursive(memberExpr.receiver(), currentModuleId, localGlobals, importedGlobalsByLocalName, dependencies);
|
||||
return;
|
||||
}
|
||||
if (expression instanceof PbsAst.ArrayLiteralExpr literal) {
|
||||
for (var value : literal.elements()) collectRecursive(value, currentModuleId, localGlobals, importedGlobalsByLocalName, dependencies);
|
||||
return;
|
||||
}
|
||||
if (expression instanceof PbsAst.IndexExpr index) {
|
||||
collectRecursive(index.receiver(), currentModuleId, localGlobals, importedGlobalsByLocalName, dependencies);
|
||||
collectRecursive(index.index(), currentModuleId, localGlobals, importedGlobalsByLocalName, dependencies);
|
||||
return;
|
||||
}
|
||||
if (expression instanceof PbsAst.NewExpr newExpr) {
|
||||
for (final var argument : newExpr.arguments()) {
|
||||
collectRecursive(argument, currentModuleId, localGlobals, importedGlobalsByLocalName, dependencies);
|
||||
|
||||
+4
@@ -20,6 +20,10 @@ final class PbsInlineHintSurfaceFormatter {
|
||||
ERROR,
|
||||
TYPE_REF,
|
||||
ADDRESSABLE -> type.name();
|
||||
case ARRAY -> {
|
||||
final var inner = format(type.inner());
|
||||
yield inner == null ? null : "array (" + inner + ")";
|
||||
}
|
||||
case OPTIONAL -> {
|
||||
final var inner = format(type.inner());
|
||||
yield inner == null ? null : "optional " + inner;
|
||||
|
||||
+10
@@ -119,6 +119,7 @@ public final class PbsLifecycleSemanticsValidator {
|
||||
return;
|
||||
}
|
||||
if (statement instanceof PbsAst.AssignStatement assignStatement) {
|
||||
validateExpression(assignStatement.target().expression(), hostPolicy, diagnostics);
|
||||
validateExpression(assignStatement.value(), hostPolicy, diagnostics);
|
||||
return;
|
||||
}
|
||||
@@ -187,6 +188,15 @@ public final class PbsLifecycleSemanticsValidator {
|
||||
validateExpression(groupExpr.expression(), hostPolicy, diagnostics);
|
||||
return;
|
||||
}
|
||||
if (expression instanceof PbsAst.ArrayLiteralExpr literal) {
|
||||
for (var value : literal.elements()) validateExpression(value, hostPolicy, diagnostics);
|
||||
return;
|
||||
}
|
||||
if (expression instanceof PbsAst.IndexExpr index) {
|
||||
validateExpression(index.receiver(), hostPolicy, diagnostics);
|
||||
validateExpression(index.index(), hostPolicy, diagnostics);
|
||||
return;
|
||||
}
|
||||
if (expression instanceof PbsAst.NewExpr newExpr) {
|
||||
for (final var argument : newExpr.arguments()) {
|
||||
validateExpression(argument, hostPolicy, diagnostics);
|
||||
|
||||
+9
@@ -23,6 +23,15 @@ final class PbsTypeSurfaceSemanticsValidator {
|
||||
}
|
||||
|
||||
switch (typeRef.kind()) {
|
||||
case ARRAY -> {
|
||||
var element = typeRef.inner();
|
||||
while (element != null && element.kind() == PbsAst.TypeRefKind.GROUP) element = element.inner();
|
||||
if (element == null || element.kind() == PbsAst.TypeRefKind.OPTIONAL || element.kind() == PbsAst.TypeRefKind.UNIT) {
|
||||
p.studio.compiler.source.diagnostics.Diagnostics.error(diagnostics,
|
||||
"E_SEM_ARRAY_ELEMENT_TYPE", "Array elements must be non-optional values", typeRef.span());
|
||||
}
|
||||
if (typeRef.inner() != null) pending.add(typeRef.inner());
|
||||
}
|
||||
case OPTIONAL -> {
|
||||
if (typeRef.inner() == null || typeRef.inner().kind() == PbsAst.TypeRefKind.UNIT) {
|
||||
p.studio.compiler.source.diagnostics.Diagnostics.error(diagnostics,
|
||||
|
||||
+19
-1
@@ -85,6 +85,10 @@ final class PbsImportedSemanticContextService {
|
||||
appendSupplementalTopDecl(topDecl, supplementalTopDecls, supplementalKeys);
|
||||
appendTypeDependencyDecls(topDecl, importedTopDeclsByName, supplementalTopDecls, supplementalKeys);
|
||||
if (topDecl instanceof PbsAst.ServiceDecl serviceDecl) {
|
||||
var accessor = p.studio.compiler.pbs.lowering.PbsExecutableCallableRegistryFactory.singletonAccessor(serviceDecl);
|
||||
appendImportedCallable(importedCallables, importedCallableKeys,
|
||||
new PbsFrontendCompiler.ImportedCallableSurface(importedModuleId, localName+".$instance", 0, 1,
|
||||
accessor.returnKind(), accessor.returnType(), frontendCompiler.callableShapeSurfaceOf(accessor)));
|
||||
for (final var method : serviceDecl.methods()) {
|
||||
appendImportedCallable(
|
||||
importedCallables,
|
||||
@@ -100,6 +104,20 @@ final class PbsImportedSemanticContextService {
|
||||
}
|
||||
continue;
|
||||
}
|
||||
if (topDecl instanceof PbsAst.StructDecl structDecl) {
|
||||
var methods = new ArrayList<PbsAst.FunctionDecl>(structDecl.methods().asList());
|
||||
for (var ctor : structDecl.ctors()) methods.add(new PbsAst.FunctionDecl("$ctor."+ctor.name(),ctor.parameters(),
|
||||
PbsAst.ReturnKind.EXPLICIT_UNIT,PbsAst.TypeRef.unit(ctor.span()),null,ReadOnlyList.empty(),
|
||||
PbsAst.LifecycleMarker.NONE,ctor.body(),ctor.span()));
|
||||
for (var method : methods) {
|
||||
var executable = p.studio.compiler.pbs.lowering.PbsExecutableCallableRegistryFactory.withReceiver(method,structDecl.name(),"this");
|
||||
appendImportedCallable(importedCallables, importedCallableKeys,
|
||||
new PbsFrontendCompiler.ImportedCallableSurface(importedModuleId,localName+"."+method.name(),
|
||||
executable.parameters().size(),returnSlotsFor(executable),executable.returnKind(),executable.returnType(),
|
||||
frontendCompiler.callableShapeSurfaceOf(executable)));
|
||||
}
|
||||
continue;
|
||||
}
|
||||
if (topDecl instanceof PbsAst.FunctionDecl functionDecl) {
|
||||
appendImportedCallable(
|
||||
importedCallables,
|
||||
@@ -303,7 +321,7 @@ final class PbsImportedSemanticContextService {
|
||||
sink.addLast(simpleName);
|
||||
}
|
||||
}
|
||||
case OPTIONAL, GROUP -> collectReferencedTypeNames(typeRef.inner(), sink);
|
||||
case ARRAY, OPTIONAL, GROUP -> collectReferencedTypeNames(typeRef.inner(), sink);
|
||||
case NAMED_TUPLE -> {
|
||||
for (final var field : typeRef.fields()) {
|
||||
collectReferencedTypeNames(field.typeRef(), sink);
|
||||
|
||||
+25
@@ -0,0 +1,25 @@
|
||||
// Arrays reserve positions without creating enemies. Reads are always optional.
|
||||
declare struct ArrayExampleEnemy(pub mut hp: int) {
|
||||
fn takeDamage(amount: int) { this.hp -= amount; }
|
||||
}
|
||||
|
||||
fn arrayExample() -> int {
|
||||
let capacity: int = 3;
|
||||
let enemies: array ArrayExampleEnemy = new array(capacity);
|
||||
let enemy = new ArrayExampleEnemy(50);
|
||||
enemies[1] = enemy;
|
||||
|
||||
if let selected = enemies[1] {
|
||||
selected.takeDamage(8);
|
||||
}
|
||||
enemies.clear(1);
|
||||
|
||||
// Nested array allocation creates only the outer level.
|
||||
let groups: array[2] int = new array(2);
|
||||
groups[0] = [20, 22];
|
||||
if let group = groups[0] {
|
||||
let total = (group[0] else 0) + (group[1] else 0);
|
||||
if total == enemy.hp { return total; }
|
||||
}
|
||||
return 0;
|
||||
}
|
||||
+9
-8
@@ -312,7 +312,7 @@ class PbsFrontendCompilerTest {
|
||||
}
|
||||
|
||||
@Test
|
||||
void shouldRejectAmbiguousCallableIdentityInsteadOfGuessingByText() {
|
||||
void shouldResolveOverloadedCallableUsingItsTypedArgument() {
|
||||
final var source = """
|
||||
fn draw_pixel(x: int) -> int {
|
||||
return x;
|
||||
@@ -331,13 +331,14 @@ class PbsFrontendCompilerTest {
|
||||
final var compiler = new PbsFrontendCompiler();
|
||||
final var fileBackend = compiler.compileFile(new FileId(45), source, diagnostics);
|
||||
|
||||
final var loweringDiagnostic = diagnostics.stream()
|
||||
.filter(d -> d.getCode().equals(PbsSemanticsErrors.E_SEM_EXEC_LOWERING_UNRESOLVED_CALLEE.name()))
|
||||
.findFirst()
|
||||
.orElseThrow();
|
||||
assertEquals(DiagnosticPhase.STATIC_SEMANTICS, loweringDiagnostic.getPhase());
|
||||
assertTrue(loweringDiagnostic.getMessage().contains("ambiguous callable identity"));
|
||||
assertEquals(0, fileBackend.executableFunctions().size());
|
||||
assertFalse(diagnostics.hasErrors(), diagnostics.toString());
|
||||
var integerOverload = fileBackend.executableFunctions().stream()
|
||||
.filter(function -> function.callableName().equals("draw_pixel")).findFirst().orElseThrow();
|
||||
var main = fileBackend.executableFunctions().stream().filter(function -> function.callableName().equals("main")).findFirst().orElseThrow();
|
||||
var call = main.instructions().stream().filter(instruction -> instruction.kind() == IRBackendExecutableFunction.InstructionKind.CALL_FUNC)
|
||||
.findFirst().orElseThrow();
|
||||
assertEquals(integerOverload.callableId(), call.calleeCallableId());
|
||||
|
||||
}
|
||||
|
||||
@Test
|
||||
|
||||
+28
@@ -16,6 +16,34 @@ import static org.junit.jupiter.api.Assertions.*;
|
||||
final class PbsEditorialSupportServiceTest {
|
||||
private final PbsEditorialSupportService service = new PbsEditorialSupportService();
|
||||
|
||||
@Test
|
||||
void arrayAndOptionalBindingShareEditorialScope() {
|
||||
String source = """
|
||||
declare struct Enemy(pub hp: int) { fn health() -> int { return this.hp; } }
|
||||
fn main() {
|
||||
let enemies: array Enemy = new array(2);
|
||||
if let enemy = enemies[0] { let hp = enemy.health(); }
|
||||
enemies.clear(0);
|
||||
}
|
||||
""";
|
||||
var ast = parseOrdinary(source);
|
||||
int use = source.indexOf("enemy.health");
|
||||
assertFalse(service.definition(source, ast, ReadOnlyList.empty(), use).isEmpty());
|
||||
assertTrue(service.hover(source, ast, ReadOnlyList.empty(), use).isPresent());
|
||||
assertTrue(service.completion(source, ast, ReadOnlyList.empty(), use + "enemy.".length()).stream()
|
||||
.anyMatch(item -> item.label().equals("health")));
|
||||
var rename = service.rename(source, ast, ReadOnlyList.empty(), use, "selected");
|
||||
assertTrue(rename.allowed(), rename.refusal());
|
||||
assertEquals(2, rename.sites().size(), rename.sites().toString());
|
||||
var declarationRename = service.rename(source, ast, ReadOnlyList.empty(), source.indexOf("enemy ="), "selected");
|
||||
assertTrue(declarationRename.allowed(), declarationRename.refusal());
|
||||
assertEquals(2, declarationRename.sites().size());
|
||||
int clear = source.indexOf("enemies.clear") + "enemies.".length();
|
||||
assertTrue(service.completion(source, ast, ReadOnlyList.empty(), clear).stream()
|
||||
.anyMatch(item -> item.label().equals("length")));
|
||||
assertTrue(service.hover(source, ast, ReadOnlyList.empty(), clear).isPresent());
|
||||
}
|
||||
|
||||
@Test
|
||||
void receiverMatrixHandlesNestedCallsVariablesParenthesesAndRecovery() {
|
||||
final String declarations = """
|
||||
|
||||
@@ -7,7 +7,7 @@ From the Studio root:
|
||||
|
||||
```sh
|
||||
./gradlew :prometeu-compiler:prometeu-build-pipeline:test --tests '*LinkedRegistryTest' --tests '*PbxRegistryConformanceTest' --tests '*TypedCommonPipelineTest' --tests '*RuntimeCatalogPipelineTest'
|
||||
./gradlew :prometeu-architecture-tests:test --tests '*PbsRuntimeAlignmentTest'
|
||||
./gradlew :prometeu-architecture-tests:test --tests '*PbsRuntimeAlignmentTest' --tests '*PbsStructuredValuesTest'
|
||||
python3 tools/pbx-conformance/run.py --runtime ../runtime
|
||||
```
|
||||
|
||||
@@ -87,3 +87,28 @@ missing PBS fixtures. Integer arithmetic wrapping is distinct from checked
|
||||
Int64-to-Int32 narrowing and Float numeric-range faults. The full installed
|
||||
knowledge gate remains separate and mandatory for SDK resource/producer
|
||||
integration.
|
||||
|
||||
## PBS typed arrays, optional and Struct/contract execution
|
||||
|
||||
`PbsStructuredValuesTest` generates 27 mandatory `pbs-structured-*` fixtures.
|
||||
They cover contextual arrays, nested levels, vacancy/zero, clear/length, aliasing,
|
||||
int/long bounds, single evaluation, lazy optional fallback, inferred/explicit
|
||||
optional tuples, native vec2 groups, fields and constructors, overloads and Self,
|
||||
contract elements/dispatch, imported services/structs/contracts, global file-init,
|
||||
and the installed example. The runtime harness names every required fixture;
|
||||
a missing file is an error.
|
||||
|
||||
Eighteen additional runs lower GuestBytes or HandleSlots to 0, 1 or 2. They assert
|
||||
resource faults, bounded accounting, no object publication at zero quota, and
|
||||
release of session ownership. The integer-storage fixture succeeds with one
|
||||
handle total, proving that its three integers do not allocate individual boxes.
|
||||
String session accounting is checked after each structured execution.
|
||||
|
||||
The GC fixture compiles all allocations, roots and post-collection reads from PBS.
|
||||
A test-only driver hook replaces one isolated marker assignment with FRAME_SYNC
|
||||
and NOPs without changing code offsets; it does not add PBS sync syntax. At the
|
||||
real runtime safepoint, at least 1,100 discarded objects are reclaimed while
|
||||
nested references, tuples and strings remain readable. `resource-diagnostics`
|
||||
is enabled solely for observation. Default production ceilings and GC threshold
|
||||
are unchanged outside the explicitly lowered quota runs. This is semantic and
|
||||
resource conformance, not a performance benchmark or installed game qualification.
|
||||
|
||||
@@ -38,6 +38,8 @@ fn main() {
|
||||
let root = std::path::PathBuf::from(std::env::args().nth(1).expect("fixture directory"));
|
||||
verify_catalog_fixtures(&root);
|
||||
verify_pbs_fixtures(&root);
|
||||
verify_pbs_structured_fixtures(&root);
|
||||
verify_pbs_resource_refusals(&root);
|
||||
for name in [
|
||||
"minimal",
|
||||
"jump-end",
|
||||
@@ -472,7 +474,7 @@ fn verify_pbs_fixtures(root: &std::path::Path) {
|
||||
for entry in std::fs::read_dir(root).unwrap() {
|
||||
let path = entry.unwrap().path();
|
||||
let name = path.file_stem().unwrap().to_str().unwrap();
|
||||
if !name.starts_with("pbs-") || path.extension().and_then(|v| v.to_str()) != Some("pbx") { continue; }
|
||||
if name.starts_with("pbs-structured-") || !name.starts_with("pbs-") || path.extension().and_then(|v| v.to_str()) != Some("pbx") { continue; }
|
||||
count += 1;
|
||||
let bytes = std::fs::read(&path).unwrap();
|
||||
let image = ValidatedProgramImage::load(&bytes, &mut LoadBudget::new(LoadLimits::default()), caps::NONE)
|
||||
@@ -537,3 +539,74 @@ fn verify_pbs_fixtures(root: &std::path::Path) {
|
||||
println!("PBS Registry defaults PASS: all eight existing value types");
|
||||
assert_eq!(count, 114, "The complete PBS qualification corpus must be present");
|
||||
}
|
||||
|
||||
fn verify_pbs_structured_fixtures(root: &std::path::Path) {
|
||||
use prometeu_vm::LogicalFrameEndingReason as End;
|
||||
let success = ["array-cycle", "array-nested", "optional-flow", "struct-contract", "service-contract",
|
||||
"optional-tuple", "tuple-storage", "optional-intrinsics", "optional-lazy", "array-context",
|
||||
"binding-scope", "overloads", "single-evaluation", "long-boundaries", "gc-roots", "native-groups", "contract-elements", "imports", "global-array", "installed-example", "return-overloads", "inferred-optional-tuple", "inline-integers"];
|
||||
for name in success.into_iter().chain(["negative-index", "past-end", "negative-length", "large-length"]) {
|
||||
let bytes = std::fs::read(root.join(format!("pbs-structured-{name}.pbx")))
|
||||
.unwrap_or_else(|e| panic!("missing mandatory PBS structured fixture {name}: {e}"));
|
||||
let image = ValidatedProgramImage::load(&bytes, &mut LoadBudget::new(LoadLimits::default()), caps::NONE)
|
||||
.unwrap_or_else(|e| panic!("{name}: {e:?}"));
|
||||
let limits = if name == "inline-integers" {
|
||||
prometeu_vm::resource_budget::RuntimeLimits::default()
|
||||
.lowered(prometeu_vm::resource_budget::RuntimeResource::HandleSlots, 1).unwrap()
|
||||
} else { Default::default() };
|
||||
let mut vm = VirtualMachine::from_image(image, limits);
|
||||
vm.prepare_boot_call().unwrap();
|
||||
let mut report = vm.run_budget(100_000, &mut NoNative, &mut HostContext::new(None)).unwrap();
|
||||
if name == "gc-roots" {
|
||||
assert!(matches!(report.reason, End::FrameSync), "{report:?}");
|
||||
let snapshot = vm.resource_snapshot();
|
||||
assert_eq!(snapshot.gc.collections, 1);
|
||||
assert!(snapshot.gc.reclaimed >= 1100, "{:?}", snapshot.gc);
|
||||
report = vm.run_budget(100_000, &mut NoNative, &mut HostContext::new(None)).unwrap();
|
||||
}
|
||||
match name {
|
||||
"negative-index" | "past-end" | "negative-length" => assert!(matches!(report.reason,
|
||||
End::Trap(ref fault) if fault.code == prometeu_bytecode::TRAP_OOB), "{name}: {report:?}"),
|
||||
"large-length" => assert!(matches!(report.reason,
|
||||
End::Trap(ref fault) if fault.code == prometeu_bytecode::TRAP_RESOURCE_LIMIT), "{name}: {report:?}"),
|
||||
_ => {
|
||||
assert!(matches!(report.reason, End::Halted | End::EndOfRom), "{name}: {report:?}");
|
||||
assert_eq!(vm.operand_stack_top(1), vec![Value::Int32(42)], "{name}");
|
||||
}
|
||||
}
|
||||
if name == "inline-integers" { assert_eq!(vm.heap().len(), 1, "single-slot integers must not allocate boxes"); }
|
||||
let ownership = vm.resource_observer();
|
||||
drop(vm);
|
||||
for resource in [prometeu_vm::resource_budget::RuntimeResource::StringBytes,
|
||||
prometeu_vm::resource_budget::RuntimeResource::StringAllocations] {
|
||||
assert_eq!(ownership.used(resource), 0, "{name}: string ownership released");
|
||||
}
|
||||
println!("PBS STRUCTURED SOURCE/LOAD/EXEC PASS {name}");
|
||||
}
|
||||
}
|
||||
|
||||
fn verify_pbs_resource_refusals(root: &std::path::Path) {
|
||||
use prometeu_vm::{LogicalFrameEndingReason as End, resource_budget::{RuntimeLimits, RuntimeResource}};
|
||||
for name in ["array-cycle", "tuple-storage", "struct-contract"] {
|
||||
for resource in [RuntimeResource::GuestBytes, RuntimeResource::HandleSlots] {
|
||||
for limit in [0, 1, 2] {
|
||||
let bytes = std::fs::read(root.join(format!("pbs-structured-{name}.pbx"))).unwrap();
|
||||
let image = ValidatedProgramImage::load(&bytes, &mut LoadBudget::new(LoadLimits::default()), caps::NONE).unwrap();
|
||||
let limits = RuntimeLimits::default().lowered(resource, limit).unwrap();
|
||||
let mut vm = VirtualMachine::from_image(image, limits);
|
||||
let observer = vm.resource_observer();
|
||||
vm.prepare_boot_call().unwrap();
|
||||
let report = vm.run_budget(100_000, &mut NoNative, &mut HostContext::new(None)).unwrap();
|
||||
assert!(matches!(report.reason, End::Trap(ref fault) if fault.code == prometeu_bytecode::TRAP_RESOURCE_LIMIT), "{name}/{resource:?}/{limit}: {report:?}");
|
||||
assert!(observer.used(resource) <= limit);
|
||||
if limit == 0 { assert_eq!(vm.heap().len(), 0, "no partially published object"); }
|
||||
drop(vm);
|
||||
for domain in [RuntimeResource::GuestBytes, RuntimeResource::HandleSlots,
|
||||
RuntimeResource::AuxiliaryBytes, RuntimeResource::TemporaryBytes] {
|
||||
assert_eq!(observer.used(domain), 0, "{name}: session ownership released after refusal: {domain:?}");
|
||||
}
|
||||
println!("PBS QUOTA/OWNERSHIP PASS {name}/{resource:?}/{limit}");
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
@@ -18,7 +18,8 @@ with tempfile.TemporaryDirectory(prefix="pbx-conformance-") as directory:
|
||||
root = pathlib.Path(directory)
|
||||
manifest = '[package]\nname="studio-pbx-conformance"\nversion="0.1.0"\nedition="2024"\n[dependencies]\n'
|
||||
for crate in ["prometeu-bytecode", "prometeu-hal", "prometeu-vm", "prometeu-system"]:
|
||||
manifest += f'{crate}={{path={json.dumps(str(runtime / "crates/console" / crate))}}}\n'
|
||||
features = ',features=["resource-diagnostics"]' if crate == "prometeu-vm" else ''
|
||||
manifest += f'{crate}={{path={json.dumps(str(runtime / "crates/console" / crate))}{features}}}\n'
|
||||
manifest += 'serde_json="1.0.149"\njsonschema={version="0.33",default-features=false}\n'
|
||||
(root / "Cargo.toml").write_text(manifest)
|
||||
(root / "Cargo.lock").write_text((runtime / "Cargo.lock").read_text())
|
||||
|
||||
Reference in New Issue
Block a user