feat(pbs): support quoted project imports and installed authoring contracts

This commit is contained in:
2026-11-10 15:19:53 +00:00
parent ea1cc26fe3
commit b351f2e582
159 changed files with 11368 additions and 50 deletions
@@ -0,0 +1,42 @@
package p.studio.compiler.pbs;
import p.studio.compiler.pbs.lexer.PbsLexer;
import p.studio.compiler.pbs.lexer.PbsTokenKind;
import p.studio.compiler.source.diagnostics.DiagnosticSink;
import p.studio.compiler.source.identifiers.FileId;
/** PBS source spelling only; decoded project identity belongs to the common resolver. */
public final class PbsSourceNames {
private PbsSourceNames() {}
public static String project(String name) {
var diagnostics = DiagnosticSink.empty();
var tokens = PbsLexer.lex(name, new FileId(0), diagnostics);
if (diagnostics.isEmpty() && tokens.size() == 2
&& tokens.getFirst().kind() == PbsTokenKind.IDENTIFIER
&& tokens.getFirst().lexeme().equals(name)) return name;
return "\"" + name.replace("\\", "\\\\").replace("\"", "\\\"")
.replace("\n", "\\n").replace("\r", "\\r").replace("\t", "\\t") + "\"";
}
/** The ordinary string-literal decoder shared by expressions and project names. */
public static String decodeString(String lexeme) {
if (lexeme.length() < 2) return "";
var raw = lexeme.substring(1, lexeme.length() - 1);
var result = new StringBuilder(raw.length());
for (int i = 0; i < raw.length(); i++) {
char value = raw.charAt(i);
if (value != '\\' || i + 1 >= raw.length()) { result.append(value); continue; }
char next = raw.charAt(++i);
switch (next) {
case 'n' -> result.append('\n');
case 'r' -> result.append('\r');
case 't' -> result.append('\t');
case '"' -> result.append('"');
case '\\' -> result.append('\\');
default -> result.append('\\').append(next); // Lexer owns invalid escapes.
}
}
return result.toString();
}
}
@@ -556,9 +556,9 @@ public final class PbsModuleVisibilityValidator {
private String displayModule(final ModuleRefKey moduleRef) {
if (moduleRef.pathSegments().isEmpty()) {
return "@%s:<root>".formatted(moduleRef.project());
return "@%s:<root>".formatted(p.studio.compiler.pbs.PbsSourceNames.project(moduleRef.project()));
}
return "@%s:%s".formatted(moduleRef.project(), String.join("/", moduleRef.pathSegments().asList()));
return "@%s:%s".formatted(p.studio.compiler.pbs.PbsSourceNames.project(moduleRef.project()), String.join("/", moduleRef.pathSegments().asList()));
}
public record ModuleCoordinates(
@@ -90,8 +90,14 @@ final class PbsDeclarationParser {
PbsAst.ModuleRef parseModuleRef() {
final var at = consume(PbsTokenKind.AT, "Expected '@' in module reference");
final var project = consume(PbsTokenKind.IDENTIFIER, "Expected project identifier in module reference");
consume(PbsTokenKind.COLON, "Expected ':' in module reference");
final var project = cursor.match(PbsTokenKind.STRING_LITERAL) ? cursor.previous()
: consume(PbsTokenKind.IDENTIFIER, "Expected project identifier or quoted name in module reference");
final var projectName = project.kind() == PbsTokenKind.STRING_LITERAL
? p.studio.compiler.pbs.PbsSourceNames.decodeString(project.lexeme()) : project.lexeme();
if (projectName.isBlank()) {
report(project, ParseErrors.E_PARSE_EXPECTED_TOKEN, "Project name must not be blank");
}
consume(PbsTokenKind.COLON, "Expected ':' in module reference; quote non-identifier project names, e.g. @\"game-name\":module");
final var segments = new ArrayList<String>();
final var firstSegment = consume(PbsTokenKind.IDENTIFIER, "Expected module identifier");
segments.add(firstSegment.lexeme());
@@ -101,7 +107,7 @@ final class PbsDeclarationParser {
segments.add(segment.lexeme());
end = segment.end();
}
return new PbsAst.ModuleRef(project.lexeme(), ReadOnlyList.wrap(segments), span(at.start(), end));
return new PbsAst.ModuleRef(projectName, ReadOnlyList.wrap(segments), span(at.start(), end));
}
PbsAst.TopDecl parseDeclareTopDecl(
@@ -36,7 +36,7 @@ final class PbsExprLiteralSupport {
}
if (cursor.match(PbsTokenKind.STRING_LITERAL)) {
final var token = cursor.previous();
return new PbsAst.StringLiteralExpr(unescapeString(token.lexeme()), context.span(token.start(), token.end()));
return new PbsAst.StringLiteralExpr(p.studio.compiler.pbs.PbsSourceNames.decodeString(token.lexeme()), context.span(token.start(), token.end()));
}
return null;
}
@@ -66,28 +66,4 @@ final class PbsExprLiteralSupport {
}
}
private String unescapeString(final String lexeme) {
if (lexeme.length() < 2) {
return "";
}
final var raw = lexeme.substring(1, lexeme.length() - 1);
final var sb = new StringBuilder(raw.length());
for (int i = 0; i < raw.length(); i++) {
final char c = raw.charAt(i);
if (c != '\\' || i + 1 >= raw.length()) {
sb.append(c);
continue;
}
final char next = raw.charAt(++i);
switch (next) {
case 'n' -> sb.append('\n');
case 'r' -> sb.append('\r');
case 't' -> sb.append('\t');
case '"' -> sb.append('"');
case '\\' -> sb.append('\\');
default -> sb.append('\\').append(next);
}
}
return sb.toString();
}
}
@@ -34,7 +34,9 @@ final class PbsTopLevelParser {
if (cursor.match(PbsTokenKind.IMPORT)) {
rejectAttributesBeforeUnsupportedTopDecl(pendingAttributes, "import declarations");
imports.add(declarationParser.parseImport(cursor.previous()));
final var imported = declarationParser.parseImport(cursor.previous());
// Keep the source diagnostic, but do not intern an invalid common identity.
if (!imported.moduleRef().project().isBlank()) imports.add(imported);
continue;
}
@@ -2303,9 +2303,9 @@ public final class PbsEditorialSupportService {
return "";
}
if (moduleRef.pathSegments().isEmpty()) {
return "@%s:<root>".formatted(moduleRef.project());
return "@%s:<root>".formatted(p.studio.compiler.pbs.PbsSourceNames.project(moduleRef.project()));
}
return "@%s:%s".formatted(moduleRef.project(), String.join("/", moduleRef.pathSegments().asList()));
return "@%s:%s".formatted(p.studio.compiler.pbs.PbsSourceNames.project(moduleRef.project()), String.join("/", moduleRef.pathSegments().asList()));
}
private PbsAst.TopDecl cloneTopDeclWithName(
@@ -230,9 +230,9 @@ public class PBSFrontendPhaseService implements FrontendPhaseService {
return "";
}
if (pathSegments == null || pathSegments.isEmpty()) {
return "@" + project;
return "@" + p.studio.compiler.pbs.PbsSourceNames.project(project);
}
return "@" + project + ":" + String.join("/", pathSegments.asList());
return "@" + p.studio.compiler.pbs.PbsSourceNames.project(project) + ":" + String.join("/", pathSegments.asList());
}
public record PbsSemanticReadSurface(
@@ -0,0 +1,107 @@
# PBS production authoring contracts
Owner: compiler/pbs. Target: Game. SDK/stdlib major: 1.
This guide, `cases.json`, and every project below are installed references from
the existing PBS provider. Read this guide as
`pbs:example:game:1:production/GUIDE.md`; project files use the same prefix followed
by `production/projects/<case>/<relative-file>`. This is one extension of the
existing example tree, not a second specification or reference catalogue.
Each project contains its own `prometeu.json`, source and barrel files. Build a
positive project's root with the ordinary compiler pipeline. The dependency
example includes its local dependency and the existing resolver's empty registry.
The metadata in `cases.json` identifies normative reference IDs, expected source
diagnostics/phases and execution classifications. Deliberately invalid projects
are separate from the positive projects and are never built as their modules.
## Authoring patterns
| Contract | Project(s) | Expected observation | Normative reference |
| --- | --- | --- | --- |
| File, module and public visibility | `authoring`, `private-sibling`, `private-overload` | The valid sibling reads admitted `mod` globals; omitted declarations and omitted overloads reject. | `pbs:spec:3` §5.2; `pbs:spec:4` production module conformance |
| Public API with private helpers | `authoring`, `private-helper` | `Box.value()` works from another module, while `Hidden` remains private and cannot be imported. | `pbs:spec:4` §3.4 and production module conformance |
| Shared global/service identity | `authoring`, `equivalent-addresses` | Mutations are observed through the defining API; `Counter` keeps singleton identity; quoted/raw imports share one storage. | `pbs:spec:4`; `pbs:spec:9` |
| Global construction and Init | `authoring`, `global-factory` | Direct `new` constructs private state; file Init makes trace 70/count 1; project Init observes 71 before Frame. Three frames prove Init does not repeat. A global factory rejects. | `pbs:spec:4` §3.4; `pbs:spec:9` §6.1 |
| Strict boolean operators and safe guards | `booleans`, `eager-and-bounds`, `eager-or-bounds` | Every `&&/and/||/or` variant produces ordered trace 12 for both left values. Nested `if` skips unsafe access; eager RHS controls fault. | `pbs:spec:9` §7.1 |
| Optional vacancy versus bounds | `optional`, `bounds-negative`, `bounds-length`, `bounds-empty` | Valid vacancy selects fallback once; a filled position skips it. Invalid indices fault with TRAP_OOB (3), before `else` can help. | `pbs:spec:9` §9; `pbs:spec:14` |
| Exact project-name addressing | `authoring`, `equivalent-addresses`, `escaped-name`, `dependency`, address negatives | Own and dependency names with hyphens work. Quoted/plain names retain canonical identity; escaped names retain exact decoded bytes/characters. | `pbs:spec:3` §6.1; `pbs:spec:5` §3.3–3.4 |
| Current SDK imports | `gfx` | `Gfx.fill_rect` compiles with `Color` from `@core:color`, including quoted reserved project names. | `pbs:spec:5` §5.2; installed `pbs:sdk:game:1:sdk/gfx/main.pbs` and `pbs:sdk:game:1:core/color/main.pbs` |
### Choosing visibility and initialization
Keep construction and its helper types in the defining module, then export a
usable public operation. In `authoring`, the caller obtains a public `Box` from
`getBox()` or `makeBox()` without naming the private `Hidden` type. The state file
constructs its global with supported `new`; the procedural factory is called in
an admitted Init body. The project never invents a placeholder or manually runs
bootstrap again. Read the complete source and barrels together.
Omitting a declaration from the barrel keeps it file-private. `mod` admits
sibling-file access, while `pub` admits other modules. Publishing one overload
does not publish another signature. Helpers do not need to become public because
their implementation participates in a public operation.
### Boolean guards and array fallback
PBS boolean conjunction/disjunction are eager. Both operands execute, left to
right, once each unless an abrupt completion intervenes. Use nested `if` for an
access that must depend on a bounds check. Array `.length` is a long-valued
property; array literals need their existing contextual element type.
`values[index] else fallback()` handles a valid empty position. It does not catch
a trap from an invalid index. The faulting projects deliberately demonstrate
negative, equal-to-length and empty-array accesses, plus false conjunction and
true disjunction whose right operand still executes. A generic fault is not
sufficient: the qualifier requires bounds code 3. Positive assertions deliberately
divide by zero when their expected state/effects are wrong, causing qualification
to fail rather than quietly completing frames.
### Project-name strings
Use `@"zelda-1":inventory` or `@"physics-2d":api`. Existing `@game:state` remains
valid and resolves identically to `@"game":state`. The five ordinary string
escapes are `\\`, `\"`, `\n`, `\r`, `\t`; they are decoded once. No trimming, case
folding, slug conversion, text block, interpolation or path interpretation occurs.
Only the project segment can be quoted. The common manifest/dependency graph
still owns identity and discovery.
Quoting `sdk` or `core` preserves stdlib-only resolution. `@app` means a project
actually named `app`, not a self alias. Unknown decoded names fail resolution;
blank names, invalid escapes and unquoted hyphens are source failures. A matching
frontend version is required for new quoted source; no stdlib-major or runtime
ABI change is implied. Installed qualification also checks generated animation
under `zelda-1`, plus real LSP analysis, dependency navigation and completions.
## Diagnostics and examples
| Diagnostic/outcome | Rule and selected example |
| --- | --- |
| `E_SEM_GLOBAL_UNSUPPORTED_INITIALIZER` | PBS 4 §3.4: `global-factory` rejects; `authoring` shows admitted direct construction and procedural Init. |
| `E_LINK_IMPORT_SYMBOL_NOT_PUBLIC` | PBS 3 visibility/PBS 4: `private-helper` rejects importing Hidden; `authoring` uses its public owner API. |
| `E_SEM_APPLY_NON_CALLABLE_TARGET` | PBS 4: `private-sibling` cannot call a declaration omitted from the barrel. |
| `E_SEM_APPLY_UNRESOLVED_OVERLOAD` | PBS 4: `private-overload` cannot select a non-admitted signature. |
| `E_PARSE_EXPECTED_TOKEN` | PBS 3 §6.1: `blank-name` and `unquoted-hyphen`; use a nonblank quoted project segment. |
| `E_LEX_INVALID_STRING_ESCAPE` | PBS 3 strings: `malformed-escape`; use only the existing five escapes. |
| `E_LINK_IMPORT_MODULE_NOT_FOUND` | PBS 5 resolution: `unknown-name` and `reserved-missing`; quoting does not supply a project or bypass reserved spaces. The existing implementation reports this resolver check in the linking phase. |
| TRAP_OOB / Bounds, code 3 | PBS 14 execution: `bounds-*` and `eager-*-bounds`; this is not a compiler rejection and `else` does not suppress it. |
The current explanation schema has no navigable reference-ID field for these
mappings. This explicit installed guide supplies the links without changing the
public diagnostic schema or having Studio infer semantics from messages.
## What qualification proves
The installed gate reads these references from candidate JARs outside the
checkout, verifies their normative references and compiles every positive and
negative project. It records source/JAR/catalog/PBX/cartridge identities and
preserves expected diagnostic codes and phases. The maintained qualifier then
uses the existing headless protocol harness to execute required artifacts for
three frames or the exact expected fault, and checks worker termination.
Resource discovery, compilation, expected rejection, PBX generation and execution
are separate observations. Gfx requires installed API compilation; graphical
execution and pixel validation are not claimed by this gate. No runtime source
write, new guest test syntax, visual regression or installed runtime distribution
qualification is implied. The frozen 28-case production regression stays separate
and unchanged.
@@ -0,0 +1,323 @@
{
"schemaVersion": 1,
"owner": "compiler/pbs",
"frames": 3,
"cases": [
{
"id": "authoring",
"project": "projects/authoring",
"scenarios": [
"visibility",
"private-helper",
"shared-state",
"initialization"
],
"expectedCompile": "compiled",
"expectedRuntime": "passed",
"references": [
"pbs:spec:4",
"pbs:spec:9",
"pbs:spec:14"
]
},
{
"id": "private-helper",
"project": "projects/private-helper",
"scenarios": [
"visibility",
"private-helper"
],
"expectedCompile": "rejected",
"expectedRuntime": "not-run",
"diagnosticCode": "E_LINK_IMPORT_SYMBOL_NOT_PUBLIC",
"references": [
"pbs:spec:4",
"pbs:spec:9",
"pbs:spec:14"
],
"diagnosticPhase": "linking"
},
{
"id": "private-sibling",
"project": "projects/private-sibling",
"scenarios": [
"visibility"
],
"expectedCompile": "rejected",
"expectedRuntime": "not-run",
"diagnosticCode": "E_SEM_APPLY_NON_CALLABLE_TARGET",
"references": [
"pbs:spec:4",
"pbs:spec:9",
"pbs:spec:14"
],
"diagnosticPhase": "static-semantics"
},
{
"id": "private-overload",
"project": "projects/private-overload",
"scenarios": [
"visibility"
],
"expectedCompile": "rejected",
"expectedRuntime": "not-run",
"diagnosticCode": "E_SEM_APPLY_UNRESOLVED_OVERLOAD",
"references": [
"pbs:spec:4",
"pbs:spec:9",
"pbs:spec:14"
],
"diagnosticPhase": "static-semantics"
},
{
"id": "global-factory",
"project": "projects/global-factory",
"scenarios": [
"initialization"
],
"expectedCompile": "rejected",
"expectedRuntime": "not-run",
"diagnosticCode": "E_SEM_GLOBAL_UNSUPPORTED_INITIALIZER",
"references": [
"pbs:spec:4",
"pbs:spec:9",
"pbs:spec:14"
],
"diagnosticPhase": "static-semantics"
},
{
"id": "booleans",
"project": "projects/booleans",
"scenarios": [
"booleans"
],
"expectedCompile": "compiled",
"expectedRuntime": "passed",
"references": [
"pbs:spec:4",
"pbs:spec:9",
"pbs:spec:14"
]
},
{
"id": "optional",
"project": "projects/optional",
"scenarios": [
"optional-bounds"
],
"expectedCompile": "compiled",
"expectedRuntime": "passed",
"references": [
"pbs:spec:4",
"pbs:spec:9",
"pbs:spec:14"
]
},
{
"id": "bounds-negative",
"project": "projects/bounds-negative",
"scenarios": [
"optional-bounds"
],
"expectedCompile": "compiled",
"expectedRuntime": "fault",
"references": [
"pbs:spec:4",
"pbs:spec:9",
"pbs:spec:14"
],
"faultCode": 3
},
{
"id": "bounds-length",
"project": "projects/bounds-length",
"scenarios": [
"optional-bounds"
],
"expectedCompile": "compiled",
"expectedRuntime": "fault",
"references": [
"pbs:spec:4",
"pbs:spec:9",
"pbs:spec:14"
],
"faultCode": 3
},
{
"id": "bounds-empty",
"project": "projects/bounds-empty",
"scenarios": [
"optional-bounds"
],
"expectedCompile": "compiled",
"expectedRuntime": "fault",
"references": [
"pbs:spec:4",
"pbs:spec:9",
"pbs:spec:14"
],
"faultCode": 3
},
{
"id": "eager-and-bounds",
"project": "projects/eager-and-bounds",
"scenarios": [
"optional-bounds",
"booleans"
],
"expectedCompile": "compiled",
"expectedRuntime": "fault",
"references": [
"pbs:spec:4",
"pbs:spec:9",
"pbs:spec:14"
],
"faultCode": 3
},
{
"id": "eager-or-bounds",
"project": "projects/eager-or-bounds",
"scenarios": [
"optional-bounds",
"booleans"
],
"expectedCompile": "compiled",
"expectedRuntime": "fault",
"references": [
"pbs:spec:4",
"pbs:spec:9",
"pbs:spec:14"
],
"faultCode": 3
},
{
"id": "equivalent-addresses",
"project": "projects/equivalent-addresses",
"scenarios": [
"addressing",
"shared-state"
],
"expectedCompile": "compiled",
"expectedRuntime": "passed",
"references": [
"pbs:spec:3",
"pbs:spec:5"
]
},
{
"id": "escaped-name",
"project": "projects/escaped-name",
"scenarios": [
"addressing"
],
"expectedCompile": "compiled",
"expectedRuntime": "passed",
"references": [
"pbs:spec:3",
"pbs:spec:5"
]
},
{
"id": "dependency",
"project": "projects/dependency",
"scenarios": [
"addressing"
],
"expectedCompile": "compiled",
"expectedRuntime": "passed",
"references": [
"pbs:spec:3",
"pbs:spec:5"
]
},
{
"id": "gfx",
"project": "projects/gfx",
"scenarios": [
"gfx",
"addressing"
],
"expectedCompile": "compiled",
"expectedRuntime": "not-run",
"references": [
"pbs:spec:3",
"pbs:spec:5"
]
},
{
"id": "unknown-name",
"project": "projects/unknown-name",
"scenarios": [
"addressing"
],
"expectedCompile": "rejected",
"expectedRuntime": "not-run",
"diagnosticCode": "E_LINK_IMPORT_MODULE_NOT_FOUND",
"references": [
"pbs:spec:3",
"pbs:spec:5"
],
"diagnosticPhase": "linking"
},
{
"id": "reserved-missing",
"project": "projects/reserved-missing",
"scenarios": [
"addressing"
],
"expectedCompile": "rejected",
"expectedRuntime": "not-run",
"diagnosticCode": "E_LINK_IMPORT_MODULE_NOT_FOUND",
"references": [
"pbs:spec:3",
"pbs:spec:5"
],
"diagnosticPhase": "linking"
},
{
"id": "blank-name",
"project": "projects/blank-name",
"scenarios": [
"addressing"
],
"expectedCompile": "rejected",
"expectedRuntime": "not-run",
"diagnosticCode": "E_PARSE_EXPECTED_TOKEN",
"references": [
"pbs:spec:3",
"pbs:spec:5"
],
"diagnosticPhase": "syntax"
},
{
"id": "unquoted-hyphen",
"project": "projects/unquoted-hyphen",
"scenarios": [
"addressing"
],
"expectedCompile": "rejected",
"expectedRuntime": "not-run",
"diagnosticCode": "E_PARSE_EXPECTED_TOKEN",
"references": [
"pbs:spec:3",
"pbs:spec:5"
],
"diagnosticPhase": "syntax"
},
{
"id": "malformed-escape",
"project": "projects/malformed-escape",
"scenarios": [
"addressing"
],
"expectedCompile": "rejected",
"expectedRuntime": "not-run",
"diagnosticCode": "E_LEX_INVALID_STRING_ESCAPE",
"references": [
"pbs:spec:3",
"pbs:spec:5"
],
"diagnosticPhase": "syntax"
}
]
}
@@ -0,0 +1,8 @@
{
"name": "authoring-demo",
"version": "1.0.0",
"language": "pbs",
"stdlib": "1",
"target": "Game",
"dependencies": []
}
@@ -0,0 +1,18 @@
import { Box, Counter, getBox, makeBox, instance, increment, fileState, sibling } from @"authoring-demo":state;
import { referenceEquals } from @sdk:hash;
declare global frames: int = 0;
declare global ready: int = 0;
[Init] fn initProject() -> void {
if sibling() != 71 || fileState() != 70 { let failure = 1 / 0; }
let created = makeBox();
if created.value() != 7 { let failure = 1 / 0; }
ready = 1;
}
[Frame] fn frame() -> void {
frames += 1;
if ready != 1 || fileState() != 70 || Counter.value() != frames { let failure = 1 / 0; }
if !referenceEquals<Counter>(Counter, instance()) { let failure = 1 / 0; }
increment();
let value = getBox();
if value.value() != 7 { let failure = 1 / 0; }
}
@@ -0,0 +1,10 @@
pub struct Box;
pub service Counter;
pub fn getBox() -> Box;
pub fn makeBox() -> Box;
pub fn instance() -> Counter;
pub fn increment() -> int;
pub fn fileState() -> int;
pub fn sibling() -> int;
mod global count;
mod global fileReady;
@@ -0,0 +1,2 @@
// The two mod globals are admitted across sibling files.
fn sibling() -> int { return count + fileReady; }
@@ -0,0 +1,13 @@
// Hidden and box stay in their defining file.
declare struct Hidden(pub mut value: int);
declare struct Box(hidden: Hidden) { fn value() -> int { return this.hidden.value; } }
declare global box: Box = new Box(new Hidden(7));
declare global count: int = 0;
declare global fileReady: int = 0;
declare service Counter { fn value() -> int { return count; } }
fn getBox() -> Box { return box; }
fn makeBox() -> Box { return new Box(new Hidden(7)); }
fn instance() -> Counter { return Counter; }
fn increment() -> int { count += 1; return count; }
fn fileState() -> int { return fileReady; }
[Init] fn initState() -> void { fileReady = box.value() * 10; count += 1; }
@@ -0,0 +1,8 @@
{
"name": "blank-name",
"version": "1.0.0",
"language": "pbs",
"stdlib": "1",
"target": "Game",
"dependencies": []
}
@@ -0,0 +1,2 @@
import { value } from @" ":state;
[Frame] fn frame() -> void {}
@@ -0,0 +1,8 @@
{
"name": "booleans",
"version": "1.0.0",
"language": "pbs",
"stdlib": "1",
"target": "Game",
"dependencies": []
}
@@ -0,0 +1,33 @@
declare global trace: int = 0;
fn mark(value: bool, digit: int) -> bool { trace = trace * 10 + digit; return value; }
[Frame] fn frame() -> void {
trace = 0;
let observed = mark(true, 1) && mark(true, 2);
if trace != 12 || observed != true { let failure = 1 / 0; }
trace = 0;
let observed = mark(false, 1) && mark(true, 2);
if trace != 12 || observed != false { let failure = 1 / 0; }
trace = 0;
let observed = mark(true, 1) and mark(true, 2);
if trace != 12 || observed != true { let failure = 1 / 0; }
trace = 0;
let observed = mark(false, 1) and mark(true, 2);
if trace != 12 || observed != false { let failure = 1 / 0; }
trace = 0;
let observed = mark(true, 1) || mark(true, 2);
if trace != 12 || observed != true { let failure = 1 / 0; }
trace = 0;
let observed = mark(false, 1) || mark(true, 2);
if trace != 12 || observed != true { let failure = 1 / 0; }
trace = 0;
let observed = mark(true, 1) or mark(true, 2);
if trace != 12 || observed != true { let failure = 1 / 0; }
trace = 0;
let observed = mark(false, 1) or mark(true, 2);
if trace != 12 || observed != true { let failure = 1 / 0; }
let values: array<int> = [42];
let index: long = 1;
if index < values.length {
if (values[index] else 0) != 42 { let failure = 1 / 0; }
}
}
@@ -0,0 +1,8 @@
{
"name": "bounds-empty",
"version": "1.0.0",
"language": "pbs",
"stdlib": "1",
"target": "Game",
"dependencies": []
}
@@ -0,0 +1 @@
[Frame] fn frame() -> void { let values = new array<int>(0); let observed = values[0] else 7; }
@@ -0,0 +1,8 @@
{
"name": "bounds-length",
"version": "1.0.0",
"language": "pbs",
"stdlib": "1",
"target": "Game",
"dependencies": []
}
@@ -0,0 +1 @@
[Frame] fn frame() -> void { let values: array<int> = [42]; let observed = values[1] else 7; }
@@ -0,0 +1,8 @@
{
"name": "bounds-negative",
"version": "1.0.0",
"language": "pbs",
"stdlib": "1",
"target": "Game",
"dependencies": []
}
@@ -0,0 +1 @@
[Frame] fn frame() -> void { let values: array<int> = [42]; let observed = values[-1] else 7; }
@@ -0,0 +1,8 @@
{
"name": "physics-2d",
"version": "1.0.0",
"language": "pbs",
"stdlib": "1",
"target": "Game",
"dependencies": []
}
@@ -0,0 +1,2 @@
import { value } from @"physics-2d":math;
fn answer() -> int { return value(); }
@@ -0,0 +1,12 @@
{
"name": "zelda-1",
"version": "1.0.0",
"language": "pbs",
"stdlib": "1",
"target": "Game",
"dependencies": [
{
"path": "dependency"
}
]
}
@@ -0,0 +1,2 @@
import { answer } from @"physics-2d":api;
[Frame] fn frame() -> void { if answer() != 42 { let failure = 1 / 0; } }
@@ -0,0 +1,8 @@
{
"name": "eager-and-bounds",
"version": "1.0.0",
"language": "pbs",
"stdlib": "1",
"target": "Game",
"dependencies": []
}
@@ -0,0 +1 @@
[Frame] fn frame() -> void { let values: array<int> = [42]; let observed = false && ((values[1] else 7) == 42); }
@@ -0,0 +1,8 @@
{
"name": "eager-or-bounds",
"version": "1.0.0",
"language": "pbs",
"stdlib": "1",
"target": "Game",
"dependencies": []
}
@@ -0,0 +1 @@
[Frame] fn frame() -> void { let values: array<int> = [42]; let observed = true || ((values[1] else 7) == 42); }
@@ -0,0 +1,8 @@
{
"name": "game",
"version": "1.0.0",
"language": "pbs",
"stdlib": "1",
"target": "Game",
"dependencies": []
}
@@ -0,0 +1,5 @@
import { count } from @game:state;
import { count, read } from @"game":state;
import @game:state;
import @"game":state;
[Frame] fn frame() -> void { count += 1; if read() != count { let failure = 1 / 0; } }
@@ -0,0 +1,2 @@
declare global count: int = 0;
fn read() -> int { return count; }
@@ -0,0 +1,8 @@
{
"name": "team\"\\n\n\r\t",
"version": "1.0.0",
"language": "pbs",
"stdlib": "1",
"target": "Game",
"dependencies": []
}
@@ -0,0 +1,2 @@
import { read } from @"team\"\\n\n\r\t":state;
[Frame] fn frame() -> void { if read() != 0 { let failure = 1 / 0; } }
@@ -0,0 +1,2 @@
declare global count: int = 0;
fn read() -> int { return count; }
@@ -0,0 +1,8 @@
{
"name": "gfx",
"version": "1.0.0",
"language": "pbs",
"stdlib": "1",
"target": "Game",
"dependencies": []
}
@@ -0,0 +1,3 @@
import { Gfx } from @"sdk":gfx;
import { Color } from @"core":color;
[Frame] fn frame() -> void { Gfx.fill_rect(0, 0, 8, 8, Color.rgb(255, 0, 0)); }
@@ -0,0 +1,8 @@
{
"name": "global-factory",
"version": "1.0.0",
"language": "pbs",
"stdlib": "1",
"target": "Game",
"dependencies": []
}
@@ -0,0 +1,4 @@
declare struct State(value: int);
fn makeState() -> State { return new State(42); }
declare global state: State = makeState();
[Frame] fn frame() -> void {}
@@ -0,0 +1,8 @@
{
"name": "malformed-escape",
"version": "1.0.0",
"language": "pbs",
"stdlib": "1",
"target": "Game",
"dependencies": []
}
@@ -0,0 +1,2 @@
import { value } from @"bad\q":state;
[Frame] fn frame() -> void {}
@@ -0,0 +1,8 @@
{
"name": "optional",
"version": "1.0.0",
"language": "pbs",
"stdlib": "1",
"target": "Game",
"dependencies": []
}
@@ -0,0 +1,10 @@
declare global calls: int = 0;
fn fallback() -> int { calls += 1; return 7; }
[Frame] fn frame() -> void {
calls = 0;
let values = new array<int>(2);
let vacant = values[0] else fallback();
values[1] = 42;
let filled = values[1] else fallback();
if vacant != 7 || filled != 42 || calls != 1 { let failure = 1 / 0; }
}
@@ -0,0 +1,8 @@
{
"name": "authoring-demo",
"version": "1.0.0",
"language": "pbs",
"stdlib": "1",
"target": "Game",
"dependencies": []
}
@@ -0,0 +1,2 @@
import { Hidden } from @"authoring-demo":state;
[Frame] fn frame() -> void {}
@@ -0,0 +1,10 @@
pub struct Box;
pub service Counter;
pub fn getBox() -> Box;
pub fn makeBox() -> Box;
pub fn instance() -> Counter;
pub fn increment() -> int;
pub fn fileState() -> int;
pub fn sibling() -> int;
mod global count;
mod global fileReady;
@@ -0,0 +1,2 @@
// The two mod globals are admitted across sibling files.
fn sibling() -> int { return count + fileReady; }
@@ -0,0 +1,13 @@
// Hidden and box stay in their defining file.
declare struct Hidden(pub mut value: int);
declare struct Box(hidden: Hidden) { fn value() -> int { return this.hidden.value; } }
declare global box: Box = new Box(new Hidden(7));
declare global count: int = 0;
declare global fileReady: int = 0;
declare service Counter { fn value() -> int { return count; } }
fn getBox() -> Box { return box; }
fn makeBox() -> Box { return new Box(new Hidden(7)); }
fn instance() -> Counter { return Counter; }
fn increment() -> int { count += 1; return count; }
fn fileState() -> int { return fileReady; }
[Init] fn initState() -> void { fileReady = box.value() * 10; count += 1; }
@@ -0,0 +1,8 @@
{
"name": "private-overload",
"version": "1.0.0",
"language": "pbs",
"stdlib": "1",
"target": "Game",
"dependencies": []
}
@@ -0,0 +1,2 @@
pub fn frame() -> void;
mod fn choose(value: int) -> int;
@@ -0,0 +1,2 @@
fn choose(value: int) -> int { return value; }
fn choose(value: bool) -> int { return 42; }
@@ -0,0 +1,8 @@
{
"name": "private-sibling",
"version": "1.0.0",
"language": "pbs",
"stdlib": "1",
"target": "Game",
"dependencies": []
}
@@ -0,0 +1,8 @@
{
"name": "reserved-missing",
"version": "1.0.0",
"language": "pbs",
"stdlib": "1",
"target": "Game",
"dependencies": []
}
@@ -0,0 +1,2 @@
import { value } from @"sdk":counterfeit;
[Frame] fn frame() -> void {}
@@ -0,0 +1,8 @@
{
"name": "unknown-name",
"version": "1.0.0",
"language": "pbs",
"stdlib": "1",
"target": "Game",
"dependencies": []
}
@@ -0,0 +1,2 @@
import { value } from @"missing-project":state;
[Frame] fn frame() -> void {}
@@ -0,0 +1,8 @@
{
"name": "unquoted-hyphen",
"version": "1.0.0",
"language": "pbs",
"stdlib": "1",
"target": "Game",
"dependencies": []
}
@@ -0,0 +1,2 @@
import { value } from @zelda-1:state;
[Frame] fn frame() -> void {}
@@ -1,6 +1,7 @@
package p.studio.compiler;
import org.junit.jupiter.api.Test;
import org.junit.jupiter.params.ParameterizedTest;
import org.junit.jupiter.params.provider.ValueSource;
import org.junit.jupiter.api.io.TempDir;
import p.studio.AppMode;
import p.studio.compiler.messages.FrontendPhaseContext;
@@ -32,8 +33,9 @@ class PBSFrontendModuleCompletionTest {
@TempDir
Path tempDir;
@Test
void moduleRefCompletionListsKnownModulesAndMemberCompletionStays() throws IOException {
@ParameterizedTest
@ValueSource(strings = {"app", "zelda-1", "équipe-1"})
void moduleRefCompletionListsKnownModulesAndMemberCompletionStays(String projectName) throws IOException {
final Path projectRoot = tempDir.resolve("app");
final Path sourceRoot = projectRoot.resolve("src");
final Path moduleA = sourceRoot.resolve("a").resolve("source.pbs");
@@ -47,6 +49,7 @@ class PBSFrontendModuleCompletionTest {
Files.writeString(moduleA.getParent().resolve("mod.barrel"), "pub fn target() -> int;\n");
final String caller = """
import { Log } from @sdk:log;
import { target } from @%s:a;
declare struct Vec() {
fn blend(dx: int, dy: int) -> int { return dx; }
@@ -55,7 +58,7 @@ class PBSFrontendModuleCompletionTest {
fn frame(vec: Vec) -> void {
vec.blend(1, 2);
}
""";
""".formatted(p.studio.compiler.pbs.PbsSourceNames.project(projectName));
Files.writeString(main, caller);
Files.writeString(sourceRoot.resolve("mod.barrel"), """
pub struct Vec();
@@ -66,7 +69,7 @@ class PBSFrontendModuleCompletionTest {
final var fileTable = new FileTable(1);
final ProjectId projectId = projectTable.register(ProjectDescriptor.builder()
.rootPath(projectRoot)
.name("app")
.name(projectName)
.version("1.0.0")
.sourceRoots(ReadOnlyList.wrap(List.of(sourceRoot)))
.build());
@@ -86,7 +89,7 @@ class PBSFrontendModuleCompletionTest {
final var moduleCompletion = service.completion(request, editorialContext, byteOffset(caller, "@sdk:log"));
assertTrue(labels(moduleCompletion).contains("@sdk:log"));
assertTrue(labels(moduleCompletion).contains("@app:a"));
assertTrue(labels(moduleCompletion).contains("@" + p.studio.compiler.pbs.PbsSourceNames.project(projectName) + ":a"));
assertTrue(moduleCompletion.stream().allMatch(candidate -> candidate.kind() == FrontendSymbolKind.MODULE));
final int afterDot = caller.indexOf("vec.") + "vec.".length();
@@ -0,0 +1,47 @@
package p.studio.compiler.pbs.parser;
import org.junit.jupiter.api.Test;
import p.studio.compiler.pbs.PbsSourceNames;
import p.studio.compiler.pbs.lexer.PbsLexer;
import p.studio.compiler.source.diagnostics.DiagnosticSink;
import p.studio.compiler.source.identifiers.FileId;
import java.nio.charset.StandardCharsets;
import static org.junit.jupiter.api.Assertions.*;
class PbsQuotedProjectTest {
@Test void roundTripsProjectIdentityAndUtf8Spans() {
for (var name : new String[]{"game", "zelda-1", "physics-2d", "fn", "équipe-1", "a\\n", "a\"b", "a\nb\rc\td", " padded "}) {
for (var named : new boolean[]{true, false}) {
var source = "// é\nimport " + (named ? "{ X as Y } from " : "") + "@" + PbsSourceNames.project(name) + ":world/items;";
var diagnostics = DiagnosticSink.empty();
var file = new FileId(0);
var ast = PbsParser.parse(PbsLexer.lex(source, file, diagnostics), file, diagnostics);
assertTrue(diagnostics.isEmpty(), name + ": " + diagnostics.asCollection());
var ref = ast.imports().getFirst().moduleRef();
assertEquals(name, ref.project());
assertEquals(java.util.List.of("world", "items"), ref.pathSegments().asList());
assertEquals(source.substring(0, source.indexOf('@')).getBytes(StandardCharsets.UTF_8).length, ref.span().getStart());
assertEquals(source.substring(0, source.indexOf(';')).getBytes(StandardCharsets.UTF_8).length, ref.span().getEnd());
}
}
}
@Test void quotedIdentifierRetainsDecodedName() {
var diagnostics = DiagnosticSink.empty();
var file = new FileId(0);
var ast = PbsParser.parse(PbsLexer.lex("import @\"game\":items;", file, diagnostics), file, diagnostics);
assertTrue(diagnostics.isEmpty());
assertEquals("game", ast.imports().getFirst().moduleRef().project());
}
@Test void rejectsBlankMalformedAndUnquotedHyphenNamesAndQuotedPaths() {
for (var source : new String[]{"import @\"\":src;", "import @\" \\t\":src;", "import @\"bad\\q\":src;",
"import @\"unterminated:src;", "import @zelda-1:src;", "import @game:\"src\";",
"import @\"\"\"game\"\"\":src;"}) {
var diagnostics = DiagnosticSink.empty();
var file = new FileId(0);
PbsParser.parse(PbsLexer.lex(source, file, diagnostics), file, diagnostics);
assertFalse(diagnostics.isEmpty(), source);
}
}
}