Compare commits

..
Author SHA1 Message Date
bquarkz c2112f6ee1 implements PLN-0131
Intrepid/Prometeu/Studio/pipeline/pr-master Build started...
JaCoCo Coverage #### Project Overview No changes detected, that affect the code coverage. * Line Coverage: 62.22% (17996/28921) * Branch Coverage: 52.87% (6986/13213) * Lines of Code: 28921 * Cyclomatic Complexity: 11624 #### Quality Gates Summary Output truncated.
Test / Build skipped: 15, passed: 659
Intrepid/Prometeu/Studio/pipeline/head This commit looks good
Add PBS go-to-definition as hover editorial lookup plus physical
declaration locations on FrontendLanguageService. Empty results stay
honest when the target is not a regular file, including virtual stdlib
paths.

Housekeep DSC-0039 with LSN-0068.
2026-09-21 07:50:14 +01:00
bquarkz 9896e7c657 Merge pull request 'implements PLN-0130' (#24) from dev/multi-frontend-avoid-premature-abstractions into master
JaCoCo Coverage #### Project Overview No changes detected, that affect the code coverage. * Line Coverage: 62.10% (17811/28682) * Branch Coverage: 52.81% (6878/13025) * Lines of Code: 28682 * Cyclomatic Complexity: 11494 #### Quality Gates Summary Output truncated.
Test / Build skipped: 15, passed: 654
Intrepid/Prometeu/Studio/pipeline/head This commit looks good
Reviewed-on: #24
2026-09-19 02:47:17 +00:00
bquarkz 4574aa17c3 implements PLN-0130
Intrepid/Prometeu/Studio/pipeline/pr-master Build started...
JaCoCo Coverage #### Project Overview No changes detected, that affect the code coverage. * Line Coverage: 62.10% (17811/28682) * Branch Coverage: 52.81% (6878/13025) * Lines of Code: 28682 * Cyclomatic Complexity: 11494 #### Quality Gates Summary Output truncated.
Test / Build skipped: 15, passed: 654
Record the multi-frontend simplicity guardrails in an English lesson:
static registry is allowed, new abstractions need a real in-repo
consumer, and plugin-style infrastructure stays forbidden.

Housekeep DSC-0065 with LSN-0067.
2026-09-19 03:44:10 +01:00
bquarkz bb010d565e Merge pull request 'implements PLN-0129' (#23) from dev/multi-frontend-architectural-tests into master
JaCoCo Coverage #### Project Overview No changes detected, that affect the code coverage. * Line Coverage: 62.10% (17811/28682) * Branch Coverage: 52.81% (6878/13025) * Lines of Code: 28682 * Cyclomatic Complexity: 11494 #### Quality Gates Summary Output truncated.
Test / Build skipped: 15, passed: 654
Intrepid/Prometeu/Studio/pipeline/head This commit looks good
Reviewed-on: #23
2026-09-19 02:40:48 +00:00
bquarkz e809ce63d3 implements PLN-0129
JaCoCo Coverage #### Project Overview No changes detected, that affect the code coverage. * Line Coverage: 62.10% (17811/28682) * Branch Coverage: 52.81% (6878/13025) * Lines of Code: 28682 * Cyclomatic Complexity: 11494 #### Quality Gates Summary Output truncated.
Test / Build skipped: 15, passed: 654
Intrepid/Prometeu/Studio/pipeline/head This commit looks good
Intrepid/Prometeu/Studio/pipeline/pr-master This commit looks good
Add ArchUnit guards for Java multi-frontend boundaries in a test-only
module. Identify PBS by frontend-module origin, allow only the registry
as composition root, and lock the wording in specs 19, 20, and 22.

Housekeep DSC-0064 with LSN-0066.
2026-09-19 03:32:43 +01:00
bquarkz 59c0d0c3b4 Merge pull request 'implements PLN-0128' (#22) from dev/multi-frontend-synthetic-test-frontend into master
JaCoCo Coverage #### Project Overview No changes detected, that affect the code coverage. * Line Coverage: 62.10% (17811/28682) * Branch Coverage: 52.81% (6878/13025) * Lines of Code: 28682 * Cyclomatic Complexity: 11494 #### Quality Gates Summary Output truncated.
Test / Build skipped: 15, passed: 653
Intrepid/Prometeu/Studio/pipeline/head This commit looks good
Reviewed-on: #22
2026-09-19 02:10:09 +00:00
bquarkz 79a682b8ec implements PLN-0128
Intrepid/Prometeu/Studio/pipeline/pr-master Build started...
JaCoCo Coverage #### Project Overview No changes detected, that affect the code coverage. * Line Coverage: 62.10% (17811/28682) * Branch Coverage: 52.81% (6878/13025) * Lines of Code: 28682 * Cyclomatic Complexity: 11494 #### Quality Gates Summary Output truncated.
Test / Build skipped: 15, passed: 653
Intrepid/Prometeu/Studio/pipeline/head This commit looks good
Add a test-only synth FrontendProvider that traverses compile() to
verified bytecode without PBS. Expose register/unregister on the static
registry and lock the obligation in specs 23 and 22.

Housekeep DSC-0063 with LSN-0065.
2026-09-19 03:03:37 +01:00
54 changed files with 2024 additions and 528 deletions
+5 -5
View File
@@ -1,7 +1,7 @@
{"type":"meta","next_id":{"DSC":66,"AGD":69,"DEC":49,"PLN":128,"LSN":65,"CLSN":1}} {"type":"meta","next_id":{"DSC":66,"AGD":69,"DEC":53,"PLN":132,"LSN":69,"CLSN":1}}
{"type":"discussion","id":"DSC-0065","status":"open","ticket":"multi-frontend-avoid-premature-abstractions","title":"Evitar abstracoes prematuras na preparacao multi-frontend","created_at":"2026-07-15","updated_at":"2026-07-15","tags":["compiler","compiler-general","studio","frontend","architecture","multi-frontend","simplicity"],"agendas":[{"id":"AGD-0068","file":"AGD-0068-multi-frontend-avoid-premature-abstractions.md","status":"open","created_at":"2026-07-15","updated_at":"2026-07-15"}],"decisions":[],"plans":[],"lessons":[]} {"type":"discussion","id":"DSC-0065","status":"done","ticket":"multi-frontend-avoid-premature-abstractions","title":"Evitar abstracoes prematuras na preparacao multi-frontend","created_at":"2026-07-15","updated_at":"2026-09-19","tags":["compiler","compiler-general","studio","frontend","architecture","multi-frontend","simplicity"],"agendas":[],"decisions":[],"plans":[],"lessons":[{"id":"LSN-0067","file":"discussion/lessons/DSC-0065-multi-frontend-avoid-premature-abstractions/LSN-0067-multi-frontend-phase-rejects-premature-infrastructure.md","status":"done","created_at":"2026-09-19","updated_at":"2026-09-19"}]}
{"type":"discussion","id":"DSC-0064","status":"open","ticket":"multi-frontend-architectural-tests","title":"Testes arquiteturais para fronteiras multi-frontend","created_at":"2026-07-15","updated_at":"2026-07-15","tags":["compiler","compiler-general","studio","frontend","architecture","tests","multi-frontend"],"agendas":[{"id":"AGD-0067","file":"AGD-0067-multi-frontend-architectural-tests.md","status":"open","created_at":"2026-07-15","updated_at":"2026-07-15"}],"decisions":[],"plans":[],"lessons":[]} {"type":"discussion","id":"DSC-0064","status":"done","ticket":"multi-frontend-architectural-tests","title":"Testes arquiteturais para fronteiras multi-frontend","created_at":"2026-07-15","updated_at":"2026-09-19","tags":["compiler","compiler-general","studio","frontend","architecture","tests","multi-frontend"],"agendas":[],"decisions":[],"plans":[],"lessons":[{"id":"LSN-0066","file":"discussion/lessons/DSC-0064-multi-frontend-architectural-tests/LSN-0066-archunit-guards-java-multi-frontend-boundaries.md","status":"done","created_at":"2026-09-19","updated_at":"2026-09-19"}]}
{"type":"discussion","id":"DSC-0063","status":"open","ticket":"multi-frontend-synthetic-test-frontend","title":"Frontend sintetico de teste para provar neutralidade do pipeline","created_at":"2026-07-15","updated_at":"2026-07-15","tags":["compiler","compiler-general","frontend","tests","backend","multi-frontend"],"agendas":[{"id":"AGD-0066","file":"AGD-0066-multi-frontend-synthetic-test-frontend.md","status":"open","created_at":"2026-07-15","updated_at":"2026-07-15"}],"decisions":[],"plans":[],"lessons":[]} {"type":"discussion","id":"DSC-0063","status":"done","ticket":"multi-frontend-synthetic-test-frontend","title":"Frontend sintetico de teste para provar neutralidade do pipeline","created_at":"2026-07-15","updated_at":"2026-09-19","tags":["compiler","compiler-general","frontend","tests","backend","multi-frontend"],"agendas":[],"decisions":[],"plans":[],"lessons":[{"id":"LSN-0065","file":"discussion/lessons/DSC-0063-multi-frontend-synthetic-test-frontend/LSN-0065-synthetic-test-frontend-proves-pipeline-neutrality.md","status":"done","created_at":"2026-09-19","updated_at":"2026-09-19"}]}
{"type":"discussion","id":"DSC-0062","status":"done","ticket":"multi-frontend-pvm-neutrality","title":"Neutralidade da PVM e identificacao PBX independente de PBS","created_at":"2026-07-15","updated_at":"2026-09-18","tags":["vm-arch","runtime","pvm","pbx","compiler","multi-frontend"],"agendas":[],"decisions":[],"plans":[],"lessons":[{"id":"LSN-0061","file":"discussion/lessons/DSC-0062-multi-frontend-pvm-neutrality/LSN-0061-pbx-runtime-boundary.md","status":"done","created_at":"2026-09-18","updated_at":"2026-09-18"}]} {"type":"discussion","id":"DSC-0062","status":"done","ticket":"multi-frontend-pvm-neutrality","title":"Neutralidade da PVM e identificacao PBX independente de PBS","created_at":"2026-07-15","updated_at":"2026-09-18","tags":["vm-arch","runtime","pvm","pbx","compiler","multi-frontend"],"agendas":[],"decisions":[],"plans":[],"lessons":[{"id":"LSN-0061","file":"discussion/lessons/DSC-0062-multi-frontend-pvm-neutrality/LSN-0061-pbx-runtime-boundary.md","status":"done","created_at":"2026-09-18","updated_at":"2026-09-18"}]}
{"type":"discussion","id":"DSC-0061","status":"done","ticket":"multi-frontend-sdk-canonical-definition","title":"Auditoria e centralizacao gradual da definicao canonica do SDK","created_at":"2026-07-15","updated_at":"2026-09-19","tags":["compiler","compiler-general","sdk","stdlib","hostcalls","intrinsics","multi-frontend"],"agendas":[],"decisions":[],"plans":[],"lessons":[{"id":"LSN-0064","file":"discussion/lessons/DSC-0061-multi-frontend-sdk-canonical-definition/LSN-0064-runtime-owns-console-abi-pbs-is-delivery.md","status":"done","created_at":"2026-09-19","updated_at":"2026-09-19"}]} {"type":"discussion","id":"DSC-0061","status":"done","ticket":"multi-frontend-sdk-canonical-definition","title":"Auditoria e centralizacao gradual da definicao canonica do SDK","created_at":"2026-07-15","updated_at":"2026-09-19","tags":["compiler","compiler-general","sdk","stdlib","hostcalls","intrinsics","multi-frontend"],"agendas":[],"decisions":[],"plans":[],"lessons":[{"id":"LSN-0064","file":"discussion/lessons/DSC-0061-multi-frontend-sdk-canonical-definition/LSN-0064-runtime-owns-console-abi-pbs-is-delivery.md","status":"done","created_at":"2026-09-19","updated_at":"2026-09-19"}]}
{"type":"discussion","id":"DSC-0060","status":"done","ticket":"multi-frontend-validation-boundaries","title":"Separar validacoes de linguagem e validacoes de plataforma","created_at":"2026-07-15","updated_at":"2026-09-19","tags":["compiler","compiler-general","compiler-pbs","backend","validation","multi-frontend"],"agendas":[],"decisions":[],"plans":[],"lessons":[{"id":"LSN-0063","file":"discussion/lessons/DSC-0060-multi-frontend-validation-boundaries/LSN-0063-language-vs-platform-validation-ownership.md","status":"done","created_at":"2026-09-19","updated_at":"2026-09-19"}]} {"type":"discussion","id":"DSC-0060","status":"done","ticket":"multi-frontend-validation-boundaries","title":"Separar validacoes de linguagem e validacoes de plataforma","created_at":"2026-07-15","updated_at":"2026-09-19","tags":["compiler","compiler-general","compiler-pbs","backend","validation","multi-frontend"],"agendas":[],"decisions":[],"plans":[],"lessons":[{"id":"LSN-0063","file":"discussion/lessons/DSC-0060-multi-frontend-validation-boundaries/LSN-0063-language-vs-platform-validation-ownership.md","status":"done","created_at":"2026-09-19","updated_at":"2026-09-19"}]}
@@ -25,7 +25,7 @@
{"type":"discussion","id":"DSC-0042","status":"open","ticket":"pbs-lsp-workspace-symbols","title":"PBS LSP Workspace Symbols","created_at":"2026-07-15","updated_at":"2026-07-15","tags":["studio","lsp","vscode","compiler-pbs","editor","workspace-symbols"],"agendas":[{"id":"AGD-0045","file":"AGD-0045-pbs-lsp-workspace-symbols.md","status":"open","created_at":"2026-07-15","updated_at":"2026-07-15"}],"decisions":[],"plans":[],"lessons":[]} {"type":"discussion","id":"DSC-0042","status":"open","ticket":"pbs-lsp-workspace-symbols","title":"PBS LSP Workspace Symbols","created_at":"2026-07-15","updated_at":"2026-07-15","tags":["studio","lsp","vscode","compiler-pbs","editor","workspace-symbols"],"agendas":[{"id":"AGD-0045","file":"AGD-0045-pbs-lsp-workspace-symbols.md","status":"open","created_at":"2026-07-15","updated_at":"2026-07-15"}],"decisions":[],"plans":[],"lessons":[]}
{"type":"discussion","id":"DSC-0041","status":"open","ticket":"pbs-lsp-document-symbols-outline","title":"PBS LSP Document Symbols and Outline","created_at":"2026-07-15","updated_at":"2026-07-15","tags":["studio","lsp","vscode","compiler-pbs","editor","outline","document-symbols"],"agendas":[{"id":"AGD-0044","file":"AGD-0044-pbs-lsp-document-symbols-and-outline.md","status":"open","created_at":"2026-07-15","updated_at":"2026-07-15"}],"decisions":[],"plans":[],"lessons":[]} {"type":"discussion","id":"DSC-0041","status":"open","ticket":"pbs-lsp-document-symbols-outline","title":"PBS LSP Document Symbols and Outline","created_at":"2026-07-15","updated_at":"2026-07-15","tags":["studio","lsp","vscode","compiler-pbs","editor","outline","document-symbols"],"agendas":[{"id":"AGD-0044","file":"AGD-0044-pbs-lsp-document-symbols-and-outline.md","status":"open","created_at":"2026-07-15","updated_at":"2026-07-15"}],"decisions":[],"plans":[],"lessons":[]}
{"type":"discussion","id":"DSC-0040","status":"open","ticket":"pbs-lsp-find-references","title":"PBS LSP Find References","created_at":"2026-07-15","updated_at":"2026-07-15","tags":["studio","lsp","vscode","compiler-pbs","editor","references"],"agendas":[{"id":"AGD-0043","file":"AGD-0043-pbs-lsp-find-references.md","status":"open","created_at":"2026-07-15","updated_at":"2026-07-15"}],"decisions":[],"plans":[],"lessons":[]} {"type":"discussion","id":"DSC-0040","status":"open","ticket":"pbs-lsp-find-references","title":"PBS LSP Find References","created_at":"2026-07-15","updated_at":"2026-07-15","tags":["studio","lsp","vscode","compiler-pbs","editor","references"],"agendas":[{"id":"AGD-0043","file":"AGD-0043-pbs-lsp-find-references.md","status":"open","created_at":"2026-07-15","updated_at":"2026-07-15"}],"decisions":[],"plans":[],"lessons":[]}
{"type":"discussion","id":"DSC-0039","status":"open","ticket":"pbs-lsp-go-to-definition","title":"PBS LSP Go to Definition","created_at":"2026-07-15","updated_at":"2026-07-15","tags":["studio","lsp","vscode","compiler-pbs","editor","definition"],"agendas":[{"id":"AGD-0042","file":"AGD-0042-pbs-lsp-go-to-definition.md","status":"open","created_at":"2026-07-15","updated_at":"2026-07-15"}],"decisions":[],"plans":[],"lessons":[]} {"type":"discussion","id":"DSC-0039","status":"done","ticket":"pbs-lsp-go-to-definition","title":"PBS LSP Go to Definition","created_at":"2026-07-15","updated_at":"2026-09-21","tags":["studio","lsp","vscode","compiler-pbs","editor","definition"],"agendas":[],"decisions":[],"plans":[],"lessons":[{"id":"LSN-0068","file":"discussion/lessons/DSC-0039-pbs-lsp-go-to-definition/LSN-0068-pbs-go-to-definition-uses-editorial-lookup-and-physical-files.md","status":"done","created_at":"2026-09-21","updated_at":"2026-09-21"}]}
{"type":"discussion","id":"DSC-0038","status":"done","ticket":"studio-packer-rgba8888-asset-pipeline","title":"Studio and Packer RGBA8888 Asset Pipeline Alignment","created_at":"2026-05-23","updated_at":"2026-07-14","tags":["studio","packer","assets","glyph-bank","palette","rgba8888","runtime-alignment"],"agendas":[],"decisions":[],"plans":[],"lessons":[{"id":"LSN-0053","file":"discussion/lessons/DSC-0038-studio-packer-rgba8888-asset-pipeline/LSN-0053-rgba8888-is-the-canonical-studio-packer-palette-contract.md","status":"done","created_at":"2026-07-14","updated_at":"2026-07-14"}]} {"type":"discussion","id":"DSC-0038","status":"done","ticket":"studio-packer-rgba8888-asset-pipeline","title":"Studio and Packer RGBA8888 Asset Pipeline Alignment","created_at":"2026-05-23","updated_at":"2026-07-14","tags":["studio","packer","assets","glyph-bank","palette","rgba8888","runtime-alignment"],"agendas":[],"decisions":[],"plans":[],"lessons":[{"id":"LSN-0053","file":"discussion/lessons/DSC-0038-studio-packer-rgba8888-asset-pipeline/LSN-0053-rgba8888-is-the-canonical-studio-packer-palette-contract.md","status":"done","created_at":"2026-07-14","updated_at":"2026-07-14"}]}
{"type":"discussion","id":"DSC-0037","status":"done","ticket":"pbs-autocomplete-parameter-names","title":"PBS autocomplete parameter names for stdlib and method calls","created_at":"2026-05-08","updated_at":"2026-05-14","tags":["compiler-pbs","studio","lsp","autocomplete","signature-help","stdlib"],"agendas":[],"decisions":[],"plans":[],"lessons":[{"id":"LSN-0052","file":"discussion/lessons/DSC-0037-pbs-autocomplete-parameter-names/LSN-0052-canonical-callable-parameter-names-through-pbs-editor-assistance.md","status":"done","created_at":"2026-05-14","updated_at":"2026-05-14"}]} {"type":"discussion","id":"DSC-0037","status":"done","ticket":"pbs-autocomplete-parameter-names","title":"PBS autocomplete parameter names for stdlib and method calls","created_at":"2026-05-08","updated_at":"2026-05-14","tags":["compiler-pbs","studio","lsp","autocomplete","signature-help","stdlib"],"agendas":[],"decisions":[],"plans":[],"lessons":[{"id":"LSN-0052","file":"discussion/lessons/DSC-0037-pbs-autocomplete-parameter-names/LSN-0052-canonical-callable-parameter-names-through-pbs-editor-assistance.md","status":"done","created_at":"2026-05-14","updated_at":"2026-05-14"}]}
{"type":"discussion","id":"DSC-0036","status":"done","ticket":"pbs-symbol-documentation-and-hover-markdown","title":"Modelo de documentacao de simbolos em PBS e consumo markdown no hover","created_at":"2026-05-08","updated_at":"2026-07-15","tags":["compiler","compiler-pbs","studio","lsp","vscode","editor","hover","documentation","markdown"],"agendas":[],"decisions":[],"plans":[],"lessons":[{"id":"LSN-0057","file":"discussion/lessons/DSC-0036-pbs-symbol-documentation-and-hover-markdown/LSN-0057-compiler-owned-pbs-doc-markdown-for-editor-assistance.md","status":"done","created_at":"2026-07-15","updated_at":"2026-07-15"}]} {"type":"discussion","id":"DSC-0036","status":"done","ticket":"pbs-symbol-documentation-and-hover-markdown","title":"Modelo de documentacao de simbolos em PBS e consumo markdown no hover","created_at":"2026-05-08","updated_at":"2026-07-15","tags":["compiler","compiler-pbs","studio","lsp","vscode","editor","hover","documentation","markdown"],"agendas":[],"decisions":[],"plans":[],"lessons":[{"id":"LSN-0057","file":"discussion/lessons/DSC-0036-pbs-symbol-documentation-and-hover-markdown/LSN-0057-compiler-owned-pbs-doc-markdown-for-editor-assistance.md","status":"done","created_at":"2026-07-15","updated_at":"2026-07-15"}]}
@@ -0,0 +1,98 @@
---
id: LSN-0068
ticket: pbs-lsp-go-to-definition
title: PBS go-to-definition uses editorial lookup and physical files
created: 2026-09-21
tags: [studio, lsp, vscode, compiler-pbs, editor, definition]
---
# PBS go-to-definition uses editorial lookup and physical files
## Original Problem
PBS editor assistance already had compiler-backed completion, hover, and signature help (`LSN-0051`). Users still could not jump from a use to a declaration. Wave 1 explicitly deferred `go to definition`.
The remaining LSP navigation family (references, rename, workspace symbols, document links, hierarchy) needed a destination policy before those features could be honest. The risk was shipping a text search, a new `SymbolId` index, or virtual documents for stdlib before a real physical target existed.
## Consolidated Decision
PBS Go to Definition is the LSP projection of **physical declaration locations** on top of the **same editorial lookup hover already uses**.
Durable locks from `DEC-0052`:
1. Resolve the identifier under the cursor through the hover path (locals, parameters, members, imports/supplementals, current-module top-level). Do not use text search or a new usage index.
2. Keep the capability on the existing aggregated `FrontendLanguageService`. Add a default-empty `definition` method and a generic location DTO. Do not add a Definition SPI.
3. Map PBS editorial spans inside `prometeu-frontend-pbs`. Common LSP must not import `p.studio.compiler.pbs.*`.
4. Jump only when `Span.fileId` maps to a **regular filesystem file**. Otherwise return an empty list. Do not create virtual documents, `untitled:` buffers, or synthetic URIs.
5. The destination is the canonical declaration, not the import-alias line. Overloads return every matching location.
6. Advertise `definitionProvider`. Partial coverage is valid. Keywords, source-less builtins, unresolved names, and virtual stdlib paths stay empty; hover is unchanged.
7. Analysis stays request-local, like hover. This discussion does not build references, rename, or snapshot cache.
Spec 23 §8.3 already listed definition as an optional editor capability. It now also states: a definition location must identify a compiler-known physical source file, or the response must be empty.
## Final Implementation
| Layer | What landed |
|---|---|
| PBS editorial | `PbsEditorialSupportService.definition` reuses hover dispatch and attaches declaration `Span`s (`PbsEditorialLocation`). |
| Generic contract | `FrontendDefinitionLocation` (absolute path + offsets) and `FrontendLanguageService.definition` defaulting to `List.of()`. |
| PBS mapping | `PBSFrontendLanguageService` maps `FileId` through `fileTable` and keeps the location only if `Files.isRegularFile(path)`. |
| LSP | `LanguageServiceBridge.definition`, `definitionProvider`, `textDocument/definition`. Compile-only frontends return empty. |
| VS Code | Unchanged thin client. |
Stdlib and SDK modules are still registered under virtual paths such as `/virtual/stdlib/...`. Those handles are not regular files, so F12 on `Gfx.clear` is empty even though hover works. That is the physical-file rule, not a missing lookup.
The location payload (path + span of an already resolved symbol) is reusable later by references (`AGD-0043`) and rename (`AGD-0046`). Those indexes were not built here. Snapshots (`AGD-0051`) remain a later performance discussion, not a prerequisite for this request-local feature.
## Examples
Same-file jump:
```pbs
fn helper() -> int { return 42; }
fn frame() -> void {
helper(); // definition -> helper's declaration in this file
}
```
Aliased import jumps to the original declaration span, not the `import` line:
```pbs
import { Log as Logger } from @sdk:log;
Logger.info("hello");
```
If `@sdk:log` is only a virtual stdlib handle, definition is empty. If a project file owns the declaration and that file exists on disk, definition uses that path.
Builtins stay hover-only:
```pbs
let n: int = 1; // hover describes the builtin; definition is empty
```
## Pitfalls
Do not implement definition as a second name search in `lsp-v1` or in the VS Code extension. It will break on imports, overloads, and members, then be thrown away when references arrive.
Do not open `/virtual/stdlib/...` or invent an `untitled:` document so stdlib F12 “does something”. Empty is the honest result until those sources are real files.
Do not pick the first overload location in the server. Return the full `Location[]`.
Do not wait for snapshot cache before definition. Hover is already request-local; definition follows that shape.
Do not split a new top-level definition service “for future languages”. PBS is a real consumer of the existing language-service surface (`LSN-0067`).
Do not treat this lesson as closing references, rename, outline, workspace symbols, or document links. Those agendas stay open. This lesson only locks the destination policy they can reuse.
## References
- Agenda: `AGD-0042` (Q1–Q6 = A)
- Decision: `DEC-0052`
- Plan: `PLN-0131`
- Spec 23 §8.3 — optional definition capability; physical-file-or-empty
- `LSN-0051` — wave 1 deferred go-to-definition
- `LSN-0058` — generic `FrontendLanguageService` for LSP
- `LSN-0047` — protocol stays in `lsp-v1`; compiler owns semantics
- `LSN-0067` — no SPI or virtual-document host without a real consumer
- Still open: `AGD-0043` references, `AGD-0045` workspace symbols, `AGD-0046` rename, `AGD-0051` snapshots, `AGD-0055` document links, `AGD-0056` hierarchy
@@ -0,0 +1,148 @@
---
id: LSN-0065
ticket: multi-frontend-synthetic-test-frontend
title: Synthetic test frontend proves common pipeline neutrality
created: 2026-09-19
tags: [compiler, compiler-general, frontend, tests, backend, multi-frontend]
---
# Synthetic test frontend proves common pipeline neutrality
## Original Problem
The common pipeline already had `FrontendProvider`, `IRBackend` as the
executable handoff, common lifecycle assembly, and `IRBackend -> IRVM -> PBX`.
Direct construction tests proved the backend could lower a handmade
`IRBackend`. Import guards proved common backend code did not depend on PBS
packages.
That was not enough. Nothing proved that a second provider, resolved by
`languageId`, could enter through `DiscoverPhase` and
`FrontendPhasePipelineStage`, assemble lifecycle, and finish
`BuilderPipelineService.compile()` at verified bytecode without instantiating
PBS, reading `.pbs` files, or loading PBS stdlib.
`CompileOnlyFrontendProvider` already existed as a local test double. It was
not registered, returned an empty `IRBackend`, and never called the pipeline.
It did not close this gap.
## Consolidated Decision
Pipeline neutrality is proved by a **test-only** compile-only
`FrontendProvider`, not by a second product language and not by injecting IR
into compile stages.
Locked shape (former Option A):
- `languageId` is `synth`.
- The provider and `FrontendPhaseService` live only in
`prometeu-build-pipeline` test sources.
- `languageService()` is empty. There is no parser, grammar, semantic
presentation, or stdlib catalog.
- `sourceRoots` is `src`. `allowedExtensions` must not collide with `pbs` /
`barrel`. The fixture must **not** create a source file of that extension.
An empty `src/` directory must still exist because `WireProjectsPhase`
resolves `toRealPath()`.
- The compiler ignores source text and emits one module, one `frame` body
that is a single `RET`, and an `IRLifecycleDeclaration` with exactly one
`FRAME_ROOT` whose origin span is filled.
- The handoff must not declare `FILE_INIT_FRAGMENT` or `PROJECT_INIT`, and
must not pre-materialize wrappers, module-init, or `BOOT_GUARD`. The common
assembler produces `__prometeu.lifecycle.frame_wrapper$mN` and the boot
guard.
- The IR must not contain host bindings, capabilities, intrinsics, PBS types,
PBS stdlib, or `__pbs.` names.
The acceptance path is `compile()` through `VerifyBytecode`. Writing
`program.pbx` is not the criterion. `build()` only adds disk I/O.
Registration stays on the existing static `FrontendRegistryService`.
`register` and `unregister` are public. `unregister` refuses to remove the
default PBS provider and is a no-op for unknown ids. Tests register `synth`
for the duration of the run and unregister in `try/finally`.
`bootstrapDefaults()`, `AppContainer`, and the Studio language catalog must
not register `synth`.
Do not inject a `Registry` into the pipeline, add a `frontends/synth` module,
scan the classpath, or treat a dummy on-disk extension as a language. Do not
replace `LifecycleAssemblerServiceTest`, `LowerToIRVMServiceTest`, or
`IRBackendExecutableContractTest` with this fixture.
A blank `prometeu.json` `language` field still defaults to PBS. The synthetic
project must set `language: synth` explicitly.
## Final Implementation
`FrontendRegistryService.register(FrontendProvider)` is the explicit
registration API. `unregister(String languageId)` removes a non-PBS provider
or no-ops if the id is absent. Duplicate `register` still fails.
`bootstrapDefaults()` still registers only PBS.
The test fixture is:
- `p.studio.compiler.synth.SyntheticFrontendProvider`
- `p.studio.compiler.synth.SyntheticFrontendPhaseService`
`SyntheticFrontendPipelineTest` writes a temporary project
(`language: synth`, `target: Game`, numeric `stdlib`, empty `src/`),
registers the provider, calls `BuilderPipelineService.compile()`, and
asserts:
- the synthetic compiler ran;
- resolved `languageId` is `synth`, not `pbs`;
- diagnostics have no errors;
- in-memory bytecode is non-empty and verified;
- assembled entrypoint is `__prometeu.lifecycle.frame_wrapper$m0`;
- a hidden boot guard is present;
- no `__pbs.` names;
- no `.pbs` / `.barrel` sources were required;
- after `unregister`, `listProviders()` is PBS-only.
Spec 23 section 8.3 records that a compile-only registered provider is a
valid pipeline participant and that the common pipeline must not require PBS
types, PBS sources, or PBS stdlib to emit verified bytecode. Spec 22 row
`G23-8.3` binds that obligation to the synthetic pipeline test.
PBS production code, Studio, and `AppContainer` were not changed.
## Examples
Good:
- register `synth`, compile a temp project with empty `src/`, unregister;
- `FRAME_ROOT` with `FileId(0)` and a non-none span, even with no source file
in `FileTable`;
- assert the synthetic compiler was invoked instead of importing
`PBSFrontendPhaseService` from build-pipeline tests.
Bad:
- omitting `language` in the manifest so discovery silently uses PBS;
- creating `main.dummy` and calling that a second frontend;
- putting the provider under `prometeu-compiler/frontends/`;
- leaving `synth` registered after the test so later tests see two providers;
- using this pipeline test as a substitute for assembler or IRVM unit tests.
## Pitfalls
- `WireProjectsPhase` still needs `src/` on disk. Empty is not the same as
missing.
- Origin span `Span.none()` is rejected by the assembler. Use a real
`FileId` even when no file was loaded.
- `unregister("pbs")` must fail. A cleanup path that blindly unregisters the
resolved language would delete the product default.
- `listProviders()` feeds the Studio catalog. A leaked test registration
would show `synth` as a new-project language.
- Direct `IRBackend` construction tests still own backend-only proofs. The
synthetic frontend owns the registry-plus-pipeline proof. Keep both.
## References
- Decision: `DEC-0049`
- Plan: `PLN-0128`
- Related lessons: `LSN-0055`, `LSN-0056`, `LSN-0059`, `LSN-0062`, `LSN-0061`
- `docs/specs/compiler/23. Compiler Pipeline Entry Points Specification.md`
- `docs/specs/compiler/22. Backend Spec-to-Test Conformance Matrix.md`
- `prometeu-compiler/prometeu-frontend-registry/src/main/java/p/studio/compiler/FrontendRegistryService.java`
- `prometeu-compiler/prometeu-build-pipeline/src/test/java/p/studio/compiler/synth/SyntheticFrontendProvider.java`
- `prometeu-compiler/prometeu-build-pipeline/src/test/java/p/studio/compiler/integration/SyntheticFrontendPipelineTest.java`
@@ -0,0 +1,151 @@
---
id: LSN-0066
ticket: multi-frontend-architectural-tests
title: ArchUnit guards Java multi-frontend boundaries
created: 2026-09-19
tags: [compiler, compiler-general, studio, frontend, architecture, tests, multi-frontend]
---
# ArchUnit guards Java multi-frontend boundaries
## Original Problem
The multi-frontend boundaries already existed in specs and lessons: common
code selects a frontend by `languageId`, `IRBackend` is language-neutral,
lifecycle assembly is common, and PBS is one provider. The automated
protection did not match that model.
The old guards walked Java source and searched for substrings:
- `import p.studio.compiler.pbs`
- `new PBSFrontendPhaseService(`
- `new PbsEditorialSupportService(`
Those checks missed field, signature, and constructor coupling. They also
treated `p.studio.compiler.pbs` as the whole PBS surface. Facades such as
`PBSFrontendProvider`, `PBSDefinitions`, and `PBSFrontendPhaseService` live
in the PBS module but not in that package. `prometeu-app` and
`prometeu-lsp-v1` declared an `implementation` dependency on PBS without
importing any PBS type.
## Consolidated Decision
Java multi-frontend boundaries are enforced by **ArchUnit + JUnit 5**, not by
source substring search, except for the `__pbs.` literal scan that bytecode
cannot see.
Durable locks from DEC-0050:
- ArchUnit is test-only, pinned in `gradle/libs.versions.toml`.
- Rules live in the test-only Gradle project `:prometeu-architecture-tests`.
That project has no production sources. It is not a plugin loader.
- A PBS type is a class whose bytecode originates from
`:prometeu-compiler:frontends:prometeu-frontend-pbs`. Package
`p.studio.compiler.pbs` is not the complete boundary. Name prefixes
`PBS*` / `Pbs*` are not the identity.
- Production may depend on PBS types only in:
- the PBS module itself;
- `prometeu-frontend-registry` / `FrontendRegistryService`, and only on
`PBSFrontendProvider` and `PBSDefinitions`.
- `AppContainer` is not a PBS composition root. It may call
`FrontendRegistryService.bootstrapDefaults()`. It must not instantiate PBS
types.
- `synth` is not in the production allowlist and must not be registered in
`bootstrapDefaults()`.
- Runtime, PVM, and the Rust repository stay out of this discussion
(LSN-0061).
- `IRBackendExecutableContractTest` remains the public-contract shape audit.
ArchUnit covers module-origin dependence.
Do not migrate PBS facades into another package just to make the test
easier. Do not ban the word `PBS` in docs, fixtures, or comments.
## Final Implementation
`:prometeu-architecture-tests` imports production classes under `p.studio`
with `ImportOption.DoNotIncludeTests` and applies three ArchUnit rules:
1. classes outside the PBS module and the registry must not depend on
PBS-module types;
2. registry production may depend only on `PBSFrontendProvider` and
`PBSDefinitions` from that module;
3. frontend-api `p.studio.compiler.models` must not depend on PBS-module
types.
A separate JUnit test walks `build.gradle.kts` files and allows the PBS
project dependency only for:
- `:prometeu-compiler:prometeu-frontend-registry` as `implementation`/`api`;
- `:prometeu-architecture-tests` as `testImplementation` (needed to classify
class origin).
The `__pbs.` source scan moved to
`CommonBackendPbsPrefixScanTest` and still covers `backend/`, `lifecycle/`,
and `workspaces/stages/`.
Gradle graph cleanup:
- `prometeu-app` and `prometeu-lsp-v1` no longer `implementation` PBS.
Runtime classloading of `PBSFrontendProvider` still comes through the
registry's implementation dependency.
- `prometeu-studio` no longer `testImplementation` PBS. No studio test
compiled against PBS types.
Source-walk import/constructor tests were deleted.
`FrontendProviderBoundaryTest` keeps only
`compileOnlyFrontendProviderMayOmitLanguageService`.
Specs 19 §11 and 20 now say common/platform code must not depend on types
from the PBS frontend module. Matrix rows G19-11.6, G20-4.1.2, and G20-4.3.3
point at the ArchUnit rules and the `__pbs.` scan.
## Examples
Good:
- ArchUnit failure names the class that depends on a PBS-module type,
including a facade in package `p.studio.compiler`.
- Registry `bootstrapDefaults()` constructs `PBSFrontendProvider`. That is
the allowed composition root.
- App calls `FrontendRegistryService.bootstrapDefaults()` and has no PBS
project dependency.
Bad:
- Searching source for `import p.studio.compiler.pbs` and calling the
boundary protected.
- Treating `AppContainer` as the place that may `new PBSFrontendProvider()`.
- Identifying PBS by class name prefix, so a future `PbsLike` helper in
common code is banned or a PBS facade is missed.
- Adding ArchUnit to `java-common-conventions` for every module.
## Pitfalls
- Same Java package does not mean same Gradle module.
`FrontendRegistryService` and `PBSFrontendProvider` both sit in
`p.studio.compiler`. Origin is the module path or JAR name.
- `@AnalyzeClasses` classes must not mix `@ArchTest` and Jupiter `@Test` on
the same class. The ArchUnit engine owns `@ArchTest`.
- `DoNotIncludeTests` is required. The architecture-test sources themselves
reference PBS types in order to name the allowlist.
- Removing PBS from app/lsp compile classpath is safe only because registry
still `implementation`s PBS, which is runtime-transitive.
- `testImplementation` of PBS on studio is not a production leak, but if no
studio test needs PBS types it is still a lying graph. The allowlist test
rejects it.
- Do not point ArchUnit at the Rust runtime. `__pbs.` in Java source is a
string contract, not a type dependency.
## References
- Decision: `DEC-0050`
- Plan: `PLN-0129`
- Related lessons: `LSN-0055`, `LSN-0059`, `LSN-0062`, `LSN-0063`,
`LSN-0061`, `LSN-0065`
- `docs/specs/compiler/19. Verification and Safety Checks Specification.md`
- `docs/specs/compiler/20. IRBackend to IRVM Lowering Specification.md`
- `docs/specs/compiler/22. Backend Spec-to-Test Conformance Matrix.md`
- `prometeu-architecture-tests/src/test/java/p/studio/architecture/PbsModuleBoundaryArchTest.java`
- `prometeu-architecture-tests/src/test/java/p/studio/architecture/PbsGradleDependencyAllowlistTest.java`
- `prometeu-compiler/prometeu-frontend-registry/src/main/java/p/studio/compiler/FrontendRegistryService.java`
- `prometeu-compiler/prometeu-frontend-api/src/test/java/p/studio/compiler/models/IRBackendExecutableContractTest.java`
@@ -0,0 +1,167 @@
---
id: LSN-0067
ticket: multi-frontend-avoid-premature-abstractions
title: Multi-frontend phase rejects premature infrastructure
created: 2026-09-19
tags: [compiler, compiler-general, studio, frontend, architecture, multi-frontend, simplicity]
---
# Multi-frontend phase rejects premature infrastructure
## Original Problem
The multi-frontend preparation needed a standing simplicity rule. The original
agenda asked for that rule *before* the other multi-frontend discussions.
Those discussions already closed (DSC-0054 through DSC-0064). The remaining
risk was not a missing plugin platform.
The remaining risk was twofold:
1. using "keep it simple" to put PBS construction back into common compiler,
Studio, LSP, or app code;
2. inventing marketplace, JAR loading, RPC, validator-core, or a generic SPI
"for a future language" that does not exist in this repository.
`FrontendRegistryService` is a static singleton. The original agenda listed
a global service locator as out of scope. Without an explicit exception, a
later change could inject a `Registry` into the pipeline for purity, which
DSC-0063 already refused.
## Consolidated Decision
This is standing policy for *future* work in the current phase: PBS as the
only product frontend, `synth` as a test-only provider, frontends in-repo.
It is not an audit of closed discussions and must not rewrite them.
Durable locks from DEC-0051:
- Implementation of this discussion is the decision plus this lesson. There
is no new spec, no new ArchUnit rule, and no production refactor.
- Spec 23 §2 and §8.3 remain the discovery MUST NOT surface. Do not copy
those sentences into a new spec.
- Architectural tests stay owned by LSN-0066.
### Static registry is allowed
`FrontendRegistryService` as a static singleton, with public `register` and
`unregister` and `bootstrapDefaults()` registering only PBS, is the
composition mechanism of this phase. Treat that as an explicit exception,
not as a banned service locator.
Discovery must not use `ServiceLoader`, classpath scanning, reflection-based
discovery, an external JAR, or runtime plugin installation.
Do not inject a `Registry` into the pipeline, LSP, or `AppContainer`.
`AppContainer` is not a PBS composition root. It may call
`FrontendRegistryService.bootstrapDefaults()`. It must not instantiate PBS
types.
### Real in-repo consumer
A new interface, module, SPI, generator, or framework is allowed only when
a real in-repo consumer exists. In this phase that consumer is one of:
- the PBS product frontend;
- the `synth` test frontend;
- a second product frontend accepted by its own decision.
"For a future language", "for the marketplace", or "when we have plugins"
is not a consumer.
`FrontendProvider`, `IRBackend`, common lifecycle assembly, and test-only
ArchUnit are not premature. They already have consumers.
### Forbidden in this phase
Until a later decision authorizes it with a real consumer, do not introduce:
1. dynamic frontend discovery (plugin, `ServiceLoader`, scan, external JAR,
runtime install);
2. RPC, sockets, a process supervisor, or version negotiation between
compiler and frontend;
3. a marketplace, hot reload, or frontend sandbox;
4. a validator-core or generic validation framework;
5. an SDK schema/generator or `HOSTCALLS.csv` as canonical ABI (LSN-0064);
6. a product module `frontends/synth`;
7. an injected `Registry`, or `AppContainer` as the PBS composition root.
This list is not a monorepo-wide simplicity charter. It does not govern
JavaFX, packer, or LSP protocol design. Owner is `compiler/general`, with
impact on `studio` on the multi-frontend axis.
### Neighbors stay closed
Do not reinterpret, relax, "simplify", or reimplement:
- provider/registry (LSN-0055 / spec 23 §8.3);
- common lifecycle;
- console ABI / PBS delivery;
- `synth`;
- ArchUnit / PBS module identity.
Using this policy to keep `new PBSFrontendPhaseService()` (or equivalent)
in common code is refused. That is PBS recoupling, not simplicity.
A second product frontend needs its own decision. This lesson neither
replaces that decision nor blocks it.
## Final Implementation
No production Java, Gradle, spec, or ArchUnit file changed.
The map above is the implementation. Future compiler/studio plans on this
axis should cite it when they propose a new module, SPI, or discovery
mechanism.
Code that already matches the phase:
- `FrontendProvider` exposes `specification()`, `compiler()`, and optional
`languageService()`;
- `FrontendRegistryService.bootstrapDefaults()` registers PBS only;
- `AppContainer` only calls that bootstrap;
- `synth` lives in build-pipeline test sources;
- ArchUnit lives in `:prometeu-architecture-tests`.
## Examples
Good:
- add a method to `FrontendProvider` because PBS or `synth` cannot compile
or register without it;
- keep `unregister` on the static registry so `synth` tests can clean up;
- reject a proposal to load language JARs from a plugin directory.
Bad:
- inject `Registry` into `BuilderPipelineService` because static state looks
like a service locator;
- create `frontends/synth` as a product module;
- add validator-core "so the next language has somewhere to put checks";
- keep `new PBSFrontendPhaseService()` in pipeline code and call that
simpler than going through the provider.
## Pitfalls
- The original agenda order ("before the other agendas") is historical.
Do not reopen DSC-0054..DSC-0064 to satisfy it.
- Static registry plus explicit `register`/`unregister` is visible. Hidden
`ServiceLoader` discovery is not the same thing.
- A second product frontend *is* a real consumer. Do not use this lesson to
refuse that frontend; use it to refuse infrastructure that frontend does
not yet need.
- Spec 23 already forbids plugin discovery. Do not duplicate it. Do not
treat silence in spec 23 as permission for RPC or validator-core.
- Simplicity does not mean PBS may leak into common modules. LSN-0066 still
owns that boundary.
## References
- Decision: `DEC-0051`
- Plan: `PLN-0130`
- Related lessons: `LSN-0055`, `LSN-0060`, `LSN-0063`, `LSN-0064`,
`LSN-0065`, `LSN-0066`
- `docs/specs/compiler/23. Compiler Pipeline Entry Points Specification.md`
(§2, §8.3)
- `prometeu-compiler/prometeu-frontend-registry/src/main/java/p/studio/compiler/FrontendRegistryService.java`
- `prometeu-compiler/prometeu-frontend-api/src/main/java/p/studio/compiler/services/FrontendProvider.java`
- `prometeu-app/src/main/java/p/studio/AppContainer.java`
@@ -1,62 +0,0 @@
---
id: AGD-0042
ticket: pbs-lsp-go-to-definition
title: PBS LSP Go to Definition
status: open
created: 2026-07-15
resolved:
decision:
tags: [studio, lsp, vscode, compiler-pbs, editor, definition]
---
## Pain
Domain owner: `studio/lsp`
PBS users cannot jump from a symbol use to its declaration, which makes navigation across source files, stdlib imports, services, and generated/editorial surfaces slow and error-prone.
## Context
The current LSP exposes diagnostics, hover, completion, signature help, and semantic tokens. The compiler already builds semantic read surfaces and editorial symbol resolution for hover/completion, but there is no LSP definition capability or stable location mapping exposed to VS Code.
## Open Questions
- [ ] Which symbol categories must be supported in the first definition wave?
- [ ] Should stdlib and generated/supplemental declarations navigate to source files, virtual documents, or remain hover-only?
- [ ] What identity model should connect an editor token to the canonical declaration without relying on text search?
## Options
### Option A - Syntactic location lookup
- **Approach:** Use parser spans and local AST traversal to map the token under cursor to a declaration with matching text.
- **Pro:** Fast to implement and useful for same-file declarations.
- **Con:** Breaks on overloads, imports, stdlib, aliases, and same-name symbols.
- **Maintainability:** Weak; it creates a second navigation model separate from semantic resolution.
### Option B - Semantic identity lookup
- **Approach:** Extend the compiler/editorial surface with resolved declaration locations keyed by symbol identity, then expose `textDocument/definition`.
- **Pro:** Correct for imports, overloads, methods, stdlib-backed declarations, and future references/rename.
- **Con:** Requires explicit location metadata in semantic/editorial surfaces.
- **Maintainability:** Strong; it becomes shared infrastructure for references, rename, hierarchy, and code actions.
## Tradeoffs
The syntactic option is tempting for speed, but it would likely be thrown away once references and rename arrive. The main tradeoff is whether stdlib/supplemental declarations must navigate to physical files immediately or can initially return no location while still supporting project symbols.
## Recommendation
Prefer Option B. Build a reusable semantic location index and implement the first wave for project source declarations, then define a policy for stdlib/supplemental targets.
## Discussion
This should probably be the first navigation agenda to resolve because references, rename, workspace symbols, and hierarchy depend on the same symbol identity/location model.
## Resolution
Ainda em aberto.
## Next Step
Decide the first-wave symbol categories and whether stdlib/supplemental declarations require virtual document support.
@@ -1,77 +0,0 @@
---
id: AGD-0066
ticket: multi-frontend-synthetic-test-frontend
title: Frontend sintetico de teste para provar neutralidade do pipeline
status: open
created: 2026-07-15
resolved:
decision:
tags: [compiler, compiler-general, frontend, tests, backend, multi-frontend]
---
# Agenda - Criar um frontend sintetico de teste
## Objetivo
Domain owner: `compiler/general`.
Discutir um frontend exclusivo de testes que prove que o pipeline comum nao depende implicitamente do PBS.
## Contexto atual
O criterio arquitetural final exige que um frontend sintetico implemente contratos equivalentes a `FrontendProvider`, `FrontendSpec` e `FrontendCompiler`, produza IR comum minima e passe pelo backend ate PBX/verifier.
## Escopo
- Escolher entre frontend totalmente sintetico ou extensao ficticia.
- Definir fixture de IR minima com `frame` vazio.
- Garantir isolamento em testes.
## Fora de escopo
- Expor frontend sintetico no Studio.
- Criar segunda linguagem real.
- Criar parser completo ou grammar dummy complexa.
## Arquivos e componentes a inspecionar
- `prometeu-compiler/prometeu-frontend-registry/...`
- `prometeu-compiler/prometeu-build-pipeline/...`
- testes do build pipeline e backend
- `prometeu-studio/src/main/java/p/studio/projects/...` apenas se a selecao por extensao for exercitada
## Alteracoes propostas
Opcao A: provider sintetico que ignora arquivos e retorna IR minima diretamente.
Opcao B: extensao `.dummy` reconhecida em fixture, com conteudo ignorado ou trivial.
Recomendacao inicial: preferir Opcao A para provar neutralidade do pipeline sem criar outra superficie de linguagem.
## Estrategia de implementacao
Esperar provider/IR/lifecycle estarem suficientemente definidos, entao adicionar fixture de teste que registra provider sintetico e executa pipeline comum sem PBS.
## Testes necessarios
- Provider registrado e resolvido por `languageId`.
- Extensao/source handling testado se a opcao B for escolhida.
- IR comum produzida, lifecycle montado, IRVM gerado, PBX emitido e verificado.
## Criterios de aceitacao
- Teste falha se pipeline comum instanciar PBS implicitamente.
- Synthetic frontend existe apenas em test fixtures.
- PBS nao e afetado.
## Riscos
- Fixture sintetica exercitar caminho feliz pequeno demais e nao proteger acoplamentos reais.
- Virar uma segunda linguagem informal.
## Decisoes que devem ser registradas
- Forma do frontend sintetico.
- Escopo minimo da IR fixture.
- Onde o provider de teste pode ser registrado.
@@ -1,79 +0,0 @@
---
id: AGD-0067
ticket: multi-frontend-architectural-tests
title: Testes arquiteturais para fronteiras multi-frontend
status: open
created: 2026-07-15
resolved:
decision:
tags: [compiler, compiler-general, studio, frontend, architecture, tests, multi-frontend]
---
# Agenda - Criar testes arquiteturais
## Objetivo
Domain owner: `compiler/general`, com impacto em `studio` e `vm-arch`.
Definir testes que protejam fronteiras: backend comum sem PBS, IR comum sem AST PBS, Studio comum sem instanciacao PBS fora do composition root e runtime neutro.
## Contexto atual
O repo ja tem testes Java para backend, bytecode e IRVM. ArchUnit pode ser util, mas o alinhamento proibe adicionar biblioteca arquitetural quando testes simples bastarem.
## Escopo
- Escolher ferramenta minima.
- Definir regras por pacote.
- Adicionar testes que sejam baratos e claros.
## Fora de escopo
- Cobrir toda arquitetura do monorepo.
- Adicionar ArchUnit sem justificativa concreta.
- Bloquear referencias PBS em testes PBS ou no frontend PBS.
## Arquivos e componentes a inspecionar
- `build.gradle.kts` e version catalog se houver.
- `prometeu-compiler/prometeu-build-pipeline/src/test/java/...`
- `prometeu-compiler/frontends/prometeu-frontend-pbs/src/test/java/...`
- `prometeu-studio/src/test/java/...`
- pacotes runtime/PVM quando presentes
## Alteracoes propostas
Opcao A: testes Java/reflection simples para imports, nomes de tipos e packages publicos.
Opcao B: ArchUnit caso a quantidade de regras e modulos justifique.
Recomendacao inicial: comecar com testes simples; reavaliar ArchUnit se as regras virarem frageis.
## Estrategia de implementacao
Definir allowlist de packages PBS, composition root e testes PBS. Escrever verificacoes independentes por dominio para falhas legiveis.
## Testes necessarios
- Backend/common nao importa `frontend.pbs`, `parser.pbs` ou `semantic.pbs`.
- IR comum nao expoe tipos PBS.
- Studio comum nao instancia servicos PBS fora da allowlist.
- Runtime nao usa nomenclatura ou semantica PBS.
## Criterios de aceitacao
- Regras rodam no build local.
- Falhas apontam arquivo/pacote responsavel.
- Excecoes autorizadas estao documentadas.
## Riscos
- Teste textual produzir falso positivo por docs ou fixtures.
- Criar barreira rigida antes de definir provider e lifecycle.
## Decisoes que devem ser registradas
- Ferramenta escolhida.
- Allowlist de packages.
- Ordem de introducao das regras.
@@ -1,77 +0,0 @@
---
id: AGD-0068
ticket: multi-frontend-avoid-premature-abstractions
title: Evitar abstracoes prematuras na preparacao multi-frontend
status: open
created: 2026-07-15
resolved:
decision:
tags: [compiler, compiler-general, studio, frontend, architecture, multi-frontend, simplicity]
---
# Agenda - Evitar abstracoes prematuras
## Objetivo
Domain owner: `compiler/general`, com impacto em `studio`.
Definir limites para a preparacao multi-frontend: remover acoplamento com baixo custo sem construir marketplace, hot reload, RPC, sandbox ou infraestrutura generica antes da necessidade real.
## Contexto atual
O PBS continuara sendo o unico frontend implementado no curto prazo. O objetivo e preparar contratos, fronteiras e testes de neutralidade, nao criar uma plataforma completa de plugins.
## Escopo
- Estabelecer principios para as agendas derivadas.
- Definir o que e explicitamente proibido nesta fase.
- Criar criterio para rejeitar abstracoes sem uso real.
## Fora de escopo
- Plugin marketplace.
- Carregamento dinamico de JARs.
- RPC, sockets, process supervisor ou version negotiation complexa.
- Service locator global.
## Arquivos e componentes a inspecionar
- `prometeu-compiler/prometeu-frontend-registry/...`
- `prometeu-app/src/main/java/p/studio/AppContainer.java`
- `prometeu-studio/src/main/java/p/studio/...`
- planos futuros derivados das discussions multi-frontend
## Alteracoes propostas
Opcao A: registrar esta decisao como guardrail transversal antes das demais.
Opcao B: deixar cada agenda repetir suas restricoes locais.
Recomendacao inicial: criar uma decisao curta e transversal apos discussao, para guiar provider, language services, synthetic frontend e testes arquiteturais.
## Estrategia de implementacao
Transformar o alinhamento em criterios de review: interface pequena, registro explicito, DI/composicao, records imutaveis e testes; rejeitar infra que nao seja exigida pelo PBS ou pelo frontend sintetico de teste.
## Testes necessarios
- Nao ha teste direto para simplicidade, mas plans devem incluir criterio de aceite contra reflection/scanning/RPC quando aplicavel.
- Testes arquiteturais podem proteger contra service locator global ou acoplamentos indevidos.
## Criterios de aceitacao
- Plans derivados nao introduzem infraestrutura de plugin antes da necessidade.
- Registro manual do PBS e suficiente.
- O frontend sintetico prova neutralidade sem virar plataforma externa.
## Riscos
- Usar "evitar abstracao" como desculpa para manter acoplamento PBS.
- Criar contratos tao pequenos que precisem ser quebrados imediatamente.
## Decisoes que devem ser registradas
- Guardrails obrigatorios para esta fase.
- Lista de mecanismos proibidos.
- Criterio para aceitar uma nova abstracao.
@@ -210,4 +210,4 @@ This specification MUST NOT be read as authorizing:
- extracting PBS linking; - extracting PBS linking;
- or reopening lifecycle-assembly ownership. - or reopening lifecycle-assembly ownership.
Platform validators MUST NOT import `p.studio.compiler.pbs` and MUST NOT discover roles from `__pbs.` prefixes. Platform validators MUST NOT depend on types from the PBS frontend module (`prometeu-frontend-pbs`). The package `p.studio.compiler.pbs` is not the complete boundary; facades shipped by that module remain PBS-owned. Platform validators MUST NOT discover roles from `__pbs.` prefixes.
@@ -92,7 +92,7 @@ The declaration MUST represent, using ordered collections and typed ids:
References MUST use `ModuleId`, `FileId`, `CallableId`, a typed role, and source attribution. The public shape MUST NOT expose maps, sets, callbacks, compiler services, or frontend-owned types. References MUST use `ModuleId`, `FileId`, `CallableId`, a typed role, and source attribution. The public shape MUST NOT expose maps, sets, callbacks, compiler services, or frontend-owned types.
`AssembleLifecyclePipelineStage` MUST run after `FrontendPhasePipelineStage` and before `LowerToIRVMPipelineStage`. `LifecycleAssemblerService` is the only owner of derived lifecycle artifacts: module init, project-init wrapper, published frame wrapper, physical entrypoint, and hidden boot guard. Those artifacts MUST use deterministic neutral internal identities. Common code MUST NOT discover roles from `__pbs.*` prefixes or depend on PBS packages. `AssembleLifecyclePipelineStage` MUST run after `FrontendPhasePipelineStage` and before `LowerToIRVMPipelineStage`. `LifecycleAssemblerService` is the only owner of derived lifecycle artifacts: module init, project-init wrapper, published frame wrapper, physical entrypoint, and hidden boot guard. Those artifacts MUST use deterministic neutral internal identities. Common code MUST NOT discover roles from `__pbs.*` prefixes or depend on types from the PBS frontend module (`prometeu-frontend-pbs`). The package `p.studio.compiler.pbs` is not the complete boundary.
The declaration MUST remain available on the assembled `IRBackend` as typed provenance. Downstream inspection MUST use roles, ids, and origins rather than synthetic names. The declaration MUST remain available on the assembled `IRBackend` as typed provenance. Downstream inspection MUST use roles, ids, and origins rather than synthetic names.
@@ -104,7 +104,7 @@ The common backend contract MUST NOT expose or require:
2. PBS parser cursors, parse contexts, parse nodes, or token kinds, 2. PBS parser cursors, parse contexts, parse nodes, or token kinds,
3. PBS semantic validator internals, 3. PBS semantic validator internals,
4. PBS editorial or language-service objects, 4. PBS editorial or language-service objects,
5. or any type under a language frontend package as part of the public backend handoff. 5. or any type from the PBS frontend module (`prometeu-frontend-pbs`) or an equivalent language frontend module as part of the public backend handoff.
## 4.2 Serializable-by-Design Contract Shape ## 4.2 Serializable-by-Design Contract Shape
@@ -45,17 +45,17 @@ to concrete positive/negative test evidence and current status.
| G19-11.3 | Platform diagnostics MUST use `COMMON_*` / `LOWER_IRVM_*` / `MARSHAL_*` and MUST copy origin/span when present. | `ValidationOwnershipSpecTest#spec19MustBeCompilerGeneralAndPublishValidationOwnership`; `LifecycleAssemblerServiceTest#assembleMustRejectMissingFrameRootWithoutRepair` | N/A | pass | Code families and span policy are normative in spec 19 section 11.1. | | G19-11.3 | Platform diagnostics MUST use `COMMON_*` / `LOWER_IRVM_*` / `MARSHAL_*` and MUST copy origin/span when present. | `ValidationOwnershipSpecTest#spec19MustBeCompilerGeneralAndPublishValidationOwnership`; `LifecycleAssemblerServiceTest#assembleMustRejectMissingFrameRootWithoutRepair` | N/A | pass | Code families and span policy are normative in spec 19 section 11.1. |
| G19-11.4 | The same fact MAY exist as a language diagnostic and a platform diagnostic with distinct identities. | `ValidationOwnershipSpecTest#spec19MustBeCompilerGeneralAndPublishValidationOwnership` | N/A | pass | Dual reporting is required when a check reads both source and common contract. | | G19-11.4 | The same fact MAY exist as a language diagnostic and a platform diagnostic with distinct identities. | `ValidationOwnershipSpecTest#spec19MustBeCompilerGeneralAndPublishValidationOwnership` | N/A | pass | Dual reporting is required when a check reads both source and common contract. |
| G19-11.5 | Host admission MUST split source attribute shape from canonical `IRReservedMetadata` identity without moving the PBS validator in this plan. | `ValidationOwnershipSpecTest#spec19MustBeCompilerGeneralAndPublishValidationOwnership` | N/A | pass | Classified as platform; validator remains in the PBS package. | | G19-11.5 | Host admission MUST split source attribute shape from canonical `IRReservedMetadata` identity without moving the PBS validator in this plan. | `ValidationOwnershipSpecTest#spec19MustBeCompilerGeneralAndPublishValidationOwnership` | N/A | pass | Classified as platform; validator remains in the PBS package. |
| G19-11.6 | Platform validators MUST NOT import PBS packages or match `__pbs.` prefixes. | `CommonBackendArchitectureTest#commonBackendMustNotImportPbsFrontendPackages`; `CommonBackendArchitectureTest#commonLifecycleAndBackendMustNotDiscoverRolesFromPbsNamePrefixes` | N/A | pass | Guard covers backend, lifecycle, and all common pipeline stages. | | G19-11.6 | Platform validators MUST NOT depend on PBS frontend module types or match `__pbs.` prefixes. | `PbsModuleBoundaryArchTest#productionOutsideAllowlistMustNotDependOnPbsModuleTypes`; `CommonBackendPbsPrefixScanTest#commonLifecycleAndBackendMustNotDiscoverRolesFromPbsNamePrefixes` | N/A | pass | ArchUnit covers PBS module origin, including facades outside `p.studio.compiler.pbs`; source scan still rejects `__pbs.` in backend, lifecycle, and common pipeline stages. |
| PBS12-11 | PBS diagnostics MUST NOT claim common structural lifecycle/IRVM failures as PBS required coverage. | `ValidationOwnershipSpecTest#pbsDiagnosticsMustNotClaimCommonStructuralFailures` | N/A | pass | PBS spec 12 points those failures at spec 19 section 11 and spec 20. | | PBS12-11 | PBS diagnostics MUST NOT claim common structural lifecycle/IRVM failures as PBS required coverage. | `ValidationOwnershipSpecTest#pbsDiagnosticsMustNotClaimCommonStructuralFailures` | N/A | pass | PBS spec 12 points those failures at spec 19 section 11 and spec 20. |
| G20-4.1.1 | `IRBackend` MUST be the common frontend-to-backend executable handoff. | `LowerToIRVMServiceTest#lowerMustAcceptManuallyConstructedCommonIRBackend` | N/A | pass | Direct backend lowering from manually constructed common IRBackend proves PBS parser/frontend services are not required. | | G20-4.1.1 | `IRBackend` MUST be the common frontend-to-backend executable handoff. | `LowerToIRVMServiceTest#lowerMustAcceptManuallyConstructedCommonIRBackend` | N/A | pass | Direct backend lowering from manually constructed common IRBackend proves PBS parser/frontend services are not required. |
| G20-4.1.2 | Common backend code MUST NOT depend on `p.studio.compiler.pbs`. | `CommonBackendArchitectureTest#commonBackendMustNotImportPbsFrontendPackages` | N/A | pass | Source-level architectural guard rejects PBS frontend imports in common backend packages. | | G20-4.1.2 | Common backend code MUST NOT depend on types from the PBS frontend module. | `PbsModuleBoundaryArchTest#productionOutsideAllowlistMustNotDependOnPbsModuleTypes`; `PbsModuleBoundaryArchTest#irBackendModelsMustNotDependOnPbsModuleTypes` | N/A | pass | ArchUnit rejects PBS-module origin types in common production code, including facades outside `p.studio.compiler.pbs`. |
| G20-4.1.3 | Public `IRBackend` contract MUST NOT expose PBS AST, token, parser, semantic, or editorial types. | `IRBackendExecutableContractTest#publicIRBackendContractMustNotExposePbsTypes` | N/A | pass | Reflection guard covers public contract fields, constructors, methods, and record components. | | G20-4.1.3 | Public `IRBackend` contract MUST NOT expose PBS AST, token, parser, semantic, or editorial types. | `IRBackendExecutableContractTest#publicIRBackendContractMustNotExposePbsTypes` | N/A | pass | Reflection guard covers public contract fields, constructors, methods, and record components. |
| G20-4.2.1 | Public `IRBackend` contract types MUST remain modelable as an acyclic, deterministic data graph. | `IRBackendExecutableContractTest#publicIRBackendContractMustExposeOnlySerializableShapes`; `IRBackendExecutableContractTest#aggregatorMustEmitDeterministicOrderedPublicContractShape` | N/A | pass | Covers public shape guardrails, generic type arguments, ordered aggregate emission, table remapping, and capability de-duplication order. | | G20-4.2.1 | Public `IRBackend` contract types MUST remain modelable as an acyclic, deterministic data graph. | `IRBackendExecutableContractTest#publicIRBackendContractMustExposeOnlySerializableShapes`; `IRBackendExecutableContractTest#aggregatorMustEmitDeterministicOrderedPublicContractShape` | N/A | pass | Covers public shape guardrails, generic type arguments, ordered aggregate emission, table remapping, and capability de-duplication order. |
| G20-4.2.2 | Public `IRBackend` contract types MUST NOT expose callbacks, services, mutable/unordered collection contracts, frontend-owned objects, process-dependent lazy values, cyclic public references, or wire-format commitments. | `IRBackendExecutableContractTest#publicIRBackendContractMustExposeOnlySerializableShapes` | N/A | pass | Reflection guard covers public contract fields, constructors, methods, record components, and generic type arguments. | | G20-4.2.2 | Public `IRBackend` contract types MUST NOT expose callbacks, services, mutable/unordered collection contracts, frontend-owned objects, process-dependent lazy values, cyclic public references, or wire-format commitments. | `IRBackendExecutableContractTest#publicIRBackendContractMustExposeOnlySerializableShapes` | N/A | pass | Reflection guard covers public contract fields, constructors, methods, record components, and generic type arguments. |
| G20-4.2.3 | Public `IRBackend` cross-object references MUST use explicit ids or stable symbolic keys. | `IRBackendExecutableContractTest#publicIRBackendContractAuditMustClassifyAllowedSupportTypes`; `IRBackendExecutableContractTest#publicIRBackendContractMustUseExplicitIdsOrStableKeysForKnownReferences` | N/A | pass | Current audit found no concrete public serialization leak requiring model correction. Existing `FileId`, `ModuleId`, `CallableId`, and `IntrinsicId` remain explicit table-scoped identifiers. | | G20-4.2.3 | Public `IRBackend` cross-object references MUST use explicit ids or stable symbolic keys. | `IRBackendExecutableContractTest#publicIRBackendContractAuditMustClassifyAllowedSupportTypes`; `IRBackendExecutableContractTest#publicIRBackendContractMustUseExplicitIdsOrStableKeysForKnownReferences` | N/A | pass | Current audit found no concrete public serialization leak requiring model correction. Existing `FileId`, `ModuleId`, `CallableId`, and `IntrinsicId` remain explicit table-scoped identifiers. |
| G20-4.3.1 | Executable `IRBackend` MUST carry a typed, ordered, id-based `IRLifecycleDeclaration` as provenance. | `IRBackendExecutableContractTest#aggregatorMustRemapTypedLifecycleReferencesAndPreserveDeclaredModuleOrder`; `LifecycleAssemblerServiceTest#assembleMustMaterializeNeutralLifecycleArtifactsInDeclaredOrder` | `IRBackendExecutableContractTest#aggregatorMustOmitLifecycleDeclarationWhenNoFileContributesOne` | pass | Declaration uses `ReadOnlyList`, typed ids, roles, and source attribution; aggregator remaps ids with explicit module order. | | G20-4.3.1 | Executable `IRBackend` MUST carry a typed, ordered, id-based `IRLifecycleDeclaration` as provenance. | `IRBackendExecutableContractTest#aggregatorMustRemapTypedLifecycleReferencesAndPreserveDeclaredModuleOrder`; `LifecycleAssemblerServiceTest#assembleMustMaterializeNeutralLifecycleArtifactsInDeclaredOrder` | `IRBackendExecutableContractTest#aggregatorMustOmitLifecycleDeclarationWhenNoFileContributesOne` | pass | Declaration uses `ReadOnlyList`, typed ids, roles, and source attribution; aggregator remaps ids with explicit module order. |
| G20-4.3.2 | Missing lifecycle declaration MUST mean a deliberately non-executable handoff and MUST NOT synthesize entrypoints. | `LifecycleAssemblerServiceTest#assembleMustNoOpWhenLifecycleDeclarationIsAbsent`; `AssembleLifecyclePipelineStageTest#runMustNoOpForDeliberatelyNonExecutableHandoff` | N/A | pass | Assembler and stage leave the backend unchanged when the declaration is absent. | | G20-4.3.2 | Missing lifecycle declaration MUST mean a deliberately non-executable handoff and MUST NOT synthesize entrypoints. | `LifecycleAssemblerServiceTest#assembleMustNoOpWhenLifecycleDeclarationIsAbsent`; `AssembleLifecyclePipelineStageTest#runMustNoOpForDeliberatelyNonExecutableHandoff` | N/A | pass | Assembler and stage leave the backend unchanged when the declaration is absent. |
| G20-4.3.3 | Common lifecycle assembly MUST be the exclusive owner of derived artifacts and MUST use neutral identities. | `LifecycleAssemblerServiceTest#assembleMustMaterializeNeutralLifecycleArtifactsInDeclaredOrder`; `CommonBackendArchitectureTest#commonLifecycleAndBackendMustNotDiscoverRolesFromPbsNamePrefixes` | `LifecycleAssemblerServiceTest#assembleMustRejectPreMaterializedDerivedArtifacts` | pass | Derived wrappers and boot guard are common-owned; architecture guard rejects PBS imports and `__pbs.` prefix matching. | | G20-4.3.3 | Common lifecycle assembly MUST be the exclusive owner of derived artifacts and MUST use neutral identities. | `LifecycleAssemblerServiceTest#assembleMustMaterializeNeutralLifecycleArtifactsInDeclaredOrder`; `CommonBackendPbsPrefixScanTest#commonLifecycleAndBackendMustNotDiscoverRolesFromPbsNamePrefixes`; `PbsModuleBoundaryArchTest#productionOutsideAllowlistMustNotDependOnPbsModuleTypes` | `LifecycleAssemblerServiceTest#assembleMustRejectPreMaterializedDerivedArtifacts` | pass | Derived wrappers and boot guard are common-owned; ArchUnit rejects PBS-module types and the source scan rejects `__pbs.` prefix matching. |
| G20-6.2 | `IRVM_EXT` MUST declare structural metadata (`pops/pushes/is_branch/is_terminator`). | `IRVMValidatorTest#validateMustApplyStructuralMetadataForCustomInternalExtension`; `IRVMValidatorTest#validateMustRejectCustomInternalExtensionWhenStructuralMetadataUnderflowsStack`; `IRVMOp` record contract (`pops/pushes/branch/terminator/internal`) | N/A | pass | Dedicated extension fixtures now assert structural metadata is consumed by validation behavior. | | G20-6.2 | `IRVM_EXT` MUST declare structural metadata (`pops/pushes/is_branch/is_terminator`). | `IRVMValidatorTest#validateMustApplyStructuralMetadataForCustomInternalExtension`; `IRVMValidatorTest#validateMustRejectCustomInternalExtensionWhenStructuralMetadataUnderflowsStack`; `IRVMOp` record contract (`pops/pushes/branch/terminator/internal`) | N/A | pass | Dedicated extension fixtures now assert structural metadata is consumed by validation behavior. |
| G20-6.3 | `IRVM_EXT` MUST be eliminable before bytecode emission. | `OptimizeIRVMServiceTest#optimizeDefaultPassesMustEliminateUnreachableInternalExtensionBeforeEmission` | `EmitBytecodePipelineStageTest#runMustFailWhenInternalOpcodesRemain`; `EmitBytecodePipelineStageTest#runMustFailWhenInternalOpcodesRemainEvenWithNonEmptyEmissionPlan`; `IRVMValidatorTest#validateMustRejectInternalOpcodeWhenConfigured` | pass | Optimizer elimination path and emit-stage hard rejection path are both covered. | | G20-6.3 | `IRVM_EXT` MUST be eliminable before bytecode emission. | `OptimizeIRVMServiceTest#optimizeDefaultPassesMustEliminateUnreachableInternalExtensionBeforeEmission` | `EmitBytecodePipelineStageTest#runMustFailWhenInternalOpcodesRemain`; `EmitBytecodePipelineStageTest#runMustFailWhenInternalOpcodesRemainEvenWithNonEmptyEmissionPlan`; `IRVMValidatorTest#validateMustRejectInternalOpcodeWhenConfigured` | pass | Optimizer elimination path and emit-stage hard rejection path are both covered. |
| G20-6.4 | IRVM MUST preserve per-function slot and identity headers. | `IRVMProgramTest#constructorMustRejectModuleAndEmissionPlanMismatch` | `IRVMProgramTest#constructorMustRejectModuleAndEmissionPlanMismatch` | pass | Header mismatch is rejected deterministically. | | G20-6.4 | IRVM MUST preserve per-function slot and identity headers. | `IRVMProgramTest#constructorMustRejectModuleAndEmissionPlanMismatch` | `IRVMProgramTest#constructorMustRejectModuleAndEmissionPlanMismatch` | pass | Header mismatch is rejected deterministically. |
@@ -90,6 +90,7 @@ to concrete positive/negative test evidence and current status.
| G23-6.3 | `build` MUST extend `compile` only with terminal artifact persistence. | `MainProjectPipelineIntegrationTest#buildShouldWriteProgramBytecode`; `BuilderPipelinePublicSurfaceTest#buildResultMustExposeArtifactPathAndCompilePayload` | N/A | pass | Coverage asserts that `build` retains the compile payload and writes the filesystem artifact path expected by callers. | | G23-6.3 | `build` MUST extend `compile` only with terminal artifact persistence. | `MainProjectPipelineIntegrationTest#buildShouldWriteProgramBytecode`; `BuilderPipelinePublicSurfaceTest#buildResultMustExposeArtifactPathAndCompilePayload` | N/A | pass | Coverage asserts that `build` retains the compile payload and writes the filesystem artifact path expected by callers. |
| G23-7.1 | `AnalysisSnapshot` MUST expose the minimum shared analysis contract. | `MainProjectPipelineIntegrationTest#analyzeShouldNotWriteProgramBytecode`; `BuilderPipelinePublicSurfaceTest#analysisSnapshotMustExposeMinimumSharedContract` | N/A | pass | Both executable and structural contract checks now cover the shared minimum analysis payload. | | G23-7.1 | `AnalysisSnapshot` MUST expose the minimum shared analysis contract. | `MainProjectPipelineIntegrationTest#analyzeShouldNotWriteProgramBytecode`; `BuilderPipelinePublicSurfaceTest#analysisSnapshotMustExposeMinimumSharedContract` | N/A | pass | Both executable and structural contract checks now cover the shared minimum analysis payload. |
| G23-8.1 | Caller-specific configs/contexts MUST NOT redefine canonical stage semantics. | N/A | N/A | missing | Requires explicit multi-entrypoint composition tests once non-filesystem contexts are implemented. | | G23-8.1 | Caller-specific configs/contexts MUST NOT redefine canonical stage semantics. | N/A | N/A | missing | Requires explicit multi-entrypoint composition tests once non-filesystem contexts are implemented. |
| G23-8.3 | A compile-only `FrontendProvider` registered by `languageId` MUST traverse `compile()` to verified bytecode without PBS, `.pbs` sources, or PBS stdlib. | `SyntheticFrontendPipelineTest#compileMustEmitVerifiedBytecodeWithoutPbs` | `FrontendRegistryServiceTest#unregisterMustRefuseToRemoveDefaultPbs` | pass | Synthetic `synth` provider is test-only; common pipeline must not require PBS types, PBS sources, or PBS stdlib. |
| G23-9.1 | Legacy public `run` MUST be removed as the normative entrypoint and filesystem-default behavior MUST be expressed through `build`. | `BuilderPipelinePublicSurfaceTest#publicServiceSurfaceMustExposeExplicitEntrypointsAndNoPublicRun`; `MainProjectPipelineIntegrationTest#buildShouldWriteProgramBytecode` | N/A | partial | Public service coverage now proves `run` is no longer public and `build` is the filesystem artifact path, but the CLI composition path is not yet exercised by a dedicated automated test. | | G23-9.1 | Legacy public `run` MUST be removed as the normative entrypoint and filesystem-default behavior MUST be expressed through `build`. | `BuilderPipelinePublicSurfaceTest#publicServiceSurfaceMustExposeExplicitEntrypointsAndNoPublicRun`; `MainProjectPipelineIntegrationTest#buildShouldWriteProgramBytecode` | N/A | partial | Public service coverage now proves `run` is no longer public and `build` is the filesystem artifact path, but the CLI composition path is not yet exercised by a dedicated automated test. |
| PBS13-12.0 | PBS executable lowering MUST emit `IRBackend` satisfying frontend handoff obligations before common backend lowering. | `IRBackendExecutableContractTest` suite; `PBSFrontendPhaseServiceTest#shouldSynthesizePositiveTopic19FixtureAcrossFileInitProjectInitAndFrame` | `LowerToIRVMServiceTest#lowerMustRejectWhenSyntheticWrapperEntrypointIsMissing`; `LowerToIRVMServiceTest#lowerMustRejectWhenHiddenBootGuardIsMissing`; `LowerToIRVMServiceTest#lowerMustRejectWhenSyntheticCallableOriginIsMissing` | pass | Row group `PBS13-12.x` verifies PBS emission into the common handoff; common backend ownership is covered by G20 rows. | | PBS13-12.0 | PBS executable lowering MUST emit `IRBackend` satisfying frontend handoff obligations before common backend lowering. | `IRBackendExecutableContractTest` suite; `PBSFrontendPhaseServiceTest#shouldSynthesizePositiveTopic19FixtureAcrossFileInitProjectInitAndFrame` | `LowerToIRVMServiceTest#lowerMustRejectWhenSyntheticWrapperEntrypointIsMissing`; `LowerToIRVMServiceTest#lowerMustRejectWhenHiddenBootGuardIsMissing`; `LowerToIRVMServiceTest#lowerMustRejectWhenSyntheticCallableOriginIsMissing` | pass | Row group `PBS13-12.x` verifies PBS emission into the common handoff; common backend ownership is covered by G20 rows. |
| PBS13-12.7 | PBS executable lowering MUST emit a typed lifecycle declaration and MUST NOT assemble derived wrappers. | `PBSFrontendPhaseServiceTest#shouldSynthesizePositiveTopic19FixtureAcrossFileInitProjectInitAndFrame`; `PbsFrontendCompilerTest#shouldExposeGlobalsAndTypedLifecycleDeclarationInBackendFile` | N/A | pass | Frontend tests assert declaration roles and the absence of module init, published wrapper, and boot guard. | | PBS13-12.7 | PBS executable lowering MUST emit a typed lifecycle declaration and MUST NOT assemble derived wrappers. | `PBSFrontendPhaseServiceTest#shouldSynthesizePositiveTopic19FixtureAcrossFileInitProjectInitAndFrame`; `PbsFrontendCompilerTest#shouldExposeGlobalsAndTypedLifecycleDeclarationInBackendFile` | N/A | pass | Frontend tests assert declaration roles and the absence of module init, published wrapper, and boot guard. |
@@ -272,6 +272,8 @@ Absent editor capabilities MUST have deterministic fallback behavior at tooling
3. host protocols that can represent unsupported operations SHOULD do so explicitly; 3. host protocols that can represent unsupported operations SHOULD do so explicitly;
4. and absent editor capability MUST NOT be reported as a compiler failure. 4. and absent editor capability MUST NOT be reported as a compiler failure.
When a frontend exposes definition or navigation, each returned location MUST identify a compiler-known physical source file. A resolved symbol without a physical file MUST produce an empty definition response. Tooling MUST NOT require virtual documents, untitled buffers, or synthetic URIs for this capability.
Compiler diagnostics and editor diagnostics are distinct ownership surfaces. Diagnostics returned by `analyze`, `compile`, and `build` are compiler contract output. Editor diagnostics MAY reuse compiler analysis results, live overlays, caches, or cancellation-aware tooling state, but a frontend MUST NOT be required to provide editor diagnostics in order to compile. Compiler diagnostics and editor diagnostics are distinct ownership surfaces. Diagnostics returned by `analyze`, `compile`, and `build` are compiler contract output. Editor diagnostics MAY reuse compiler analysis results, live overlays, caches, or cancellation-aware tooling state, but a frontend MUST NOT be required to provide editor diagnostics in order to compile.
`FrontendSpec` remains the source of static frontend-owned presentation metadata such as semantic vocabularies, host projections, and visual themes. Producing semantic tokens for a live document is an optional editor-facing capability; the existence of static presentation metadata MUST NOT imply that every frontend can provide live semantic-token results. `FrontendSpec` remains the source of static frontend-owned presentation metadata such as semantic vocabularies, host projections, and visual themes. Producing semantic tokens for a live document is an optional editor-facing capability; the existence of static presentation metadata MUST NOT imply that every frontend can provide live semantic-token results.
@@ -284,6 +286,10 @@ Provider registration MUST be explicit in v1. The registry contract MUST NOT use
PBS is the only initial real provider for this contract. PBS MAY be registered by an application composition root, but PBS MUST NOT become an exclusive semantic owner of the shared compiler pipeline. PBS is the only initial real provider for this contract. PBS MAY be registered by an application composition root, but PBS MUST NOT become an exclusive semantic owner of the shared compiler pipeline.
A compile-only `FrontendProvider` registered by `languageId` MUST be a valid participant of `analyze`, `compile`, and `build`. The shared pipeline MUST NOT require PBS frontend types, `.pbs` or `.barrel` sources, or PBS stdlib in order to emit verified bytecode. Test-only frontends MAY exist solely as fixtures. They MUST NOT be product languages, MUST NOT be registered by default bootstrap or Studio composition, and MUST NOT be discovered by plugin scanning, classpath scanning, or external JAR loading.
The frontend registry MUST expose explicit `register` and `unregister` operations. `unregister` MUST refuse to remove the default PBS provider. Lookup of an unknown `languageId` MUST fail explicitly. `unregister` of an unknown `languageId` MUST be a no-op.
## 9. Public Surface Rule ## 9. Public Surface Rule
The shared compiler public surface MUST expose explicit entrypoints equivalent in meaning to: The shared compiler public surface MUST expose explicit entrypoints equivalent in meaning to:
+2
View File
@@ -5,6 +5,7 @@ jackson = "2.18.2"
jacoco = "0.8.12" jacoco = "0.8.12"
lombok = "1.18.32" lombok = "1.18.32"
junit-jupiter = "5.12.1" junit-jupiter = "5.12.1"
archunit = "1.4.2"
slf4j = "2.0.7" slf4j = "2.0.7"
lsp4j = "1.0.0" lsp4j = "1.0.0"
@@ -19,6 +20,7 @@ apache-commons-collections = { group = "org.apache.commons", name = "commons-col
jacoco-core = { group = "org.jacoco", name = "org.jacoco.core", version.ref = "jacoco" } jacoco-core = { group = "org.jacoco", name = "org.jacoco.core", version.ref = "jacoco" }
lombok = { group = "org.projectlombok", name = "lombok", version.ref = "lombok" } lombok = { group = "org.projectlombok", name = "lombok", version.ref = "lombok" }
junit-jupiter = { group = "org.junit.jupiter", name = "junit-jupiter", version.ref = "junit-jupiter" } junit-jupiter = { group = "org.junit.jupiter", name = "junit-jupiter", version.ref = "junit-jupiter" }
archunit-junit5 = { group = "com.tngtech.archunit", name = "archunit-junit5", version.ref = "archunit" }
slf4j-api = { group = "org.slf4j", name = "slf4j-api", version.ref = "slf4j" } slf4j-api = { group = "org.slf4j", name = "slf4j-api", version.ref = "slf4j" }
slf4j-simple = { group = "org.slf4j", name = "slf4j-simple", version.ref = "slf4j" } slf4j-simple = { group = "org.slf4j", name = "slf4j-simple", version.ref = "slf4j" }
lsp4j = { group = "org.eclipse.lsp4j", name = "org.eclipse.lsp4j", version.ref = "lsp4j" } lsp4j = { group = "org.eclipse.lsp4j", name = "org.eclipse.lsp4j", version.ref = "lsp4j" }
-1
View File
@@ -7,7 +7,6 @@ dependencies {
implementation(project(":prometeu-infra")) implementation(project(":prometeu-infra"))
implementation(project(":prometeu-lsp:prometeu-lsp-api")) implementation(project(":prometeu-lsp:prometeu-lsp-api"))
implementation(project(":prometeu-lsp:prometeu-lsp-v1")) implementation(project(":prometeu-lsp:prometeu-lsp-v1"))
implementation(project(":prometeu-compiler:frontends:prometeu-frontend-pbs"))
implementation(project(":prometeu-compiler:prometeu-frontend-registry")) implementation(project(":prometeu-compiler:prometeu-frontend-registry"))
implementation(project(":prometeu-packer:prometeu-packer-api")) implementation(project(":prometeu-packer:prometeu-packer-api"))
implementation(project(":prometeu-packer:prometeu-packer-v1")) implementation(project(":prometeu-packer:prometeu-packer-v1"))
@@ -0,0 +1,23 @@
plugins {
id("gradle.java-library-conventions")
}
dependencies {
testImplementation(libs.archunit.junit5)
testImplementation(project(":prometeu-compiler:frontends:prometeu-frontend-pbs"))
testImplementation(project(":prometeu-compiler:prometeu-frontend-registry"))
testImplementation(project(":prometeu-compiler:prometeu-compiler-core"))
testImplementation(project(":prometeu-compiler:prometeu-frontend-api"))
testImplementation(project(":prometeu-compiler:prometeu-build-pipeline"))
testImplementation(project(":prometeu-compiler:prometeu-deps"))
testImplementation(project(":prometeu-infra"))
testImplementation(project(":prometeu-lsp:prometeu-lsp-api"))
testImplementation(project(":prometeu-lsp:prometeu-lsp-v1"))
testImplementation(project(":prometeu-studio"))
testImplementation(project(":prometeu-app"))
}
tasks.named<JacocoReport>("jacocoTestReport") {
enabled = false
}
@@ -0,0 +1,63 @@
package p.studio.architecture;
import org.junit.jupiter.api.Test;
import java.io.IOException;
import java.nio.file.Files;
import java.nio.file.Path;
import java.util.ArrayList;
import java.util.List;
import static org.junit.jupiter.api.Assertions.assertTrue;
import static org.junit.jupiter.api.Assertions.fail;
class CommonBackendPbsPrefixScanTest {
private static final String COMPILER_SOURCE_ROOT =
"prometeu-compiler/prometeu-build-pipeline/src/main/java/p/studio/compiler";
private static final List<String> GUARDED_RELATIVE_ROOTS = List.of(
"backend",
"lifecycle",
"workspaces/stages");
private static final String FORBIDDEN_PBS_PREFIX = "__pbs.";
@Test
void commonLifecycleAndBackendMustNotDiscoverRolesFromPbsNamePrefixes() throws IOException {
final var violations = new ArrayList<String>();
final var repoRoot = locateRepoRoot();
final var compilerRoot = repoRoot.resolve(COMPILER_SOURCE_ROOT);
for (final var relativeRoot : GUARDED_RELATIVE_ROOTS) {
final var root = compilerRoot.resolve(relativeRoot);
if (!Files.exists(root)) {
fail("guarded source root is missing: " + root);
}
try (final var paths = Files.walk(root)) {
paths.filter(path -> path.toString().endsWith(".java")).forEach(path -> {
try {
if (Files.readString(path).contains(FORBIDDEN_PBS_PREFIX)) {
violations.add(repoRoot.relativize(path).toString());
}
} catch (IOException e) {
throw new IllegalStateException("failed to read source file: " + path, e);
}
});
}
}
assertTrue(
violations.isEmpty(),
"common lifecycle/backend code must not inspect __pbs. prefixes: " + violations);
}
private static Path locateRepoRoot() {
var cursor = Path.of(System.getProperty("user.dir")).toAbsolutePath().normalize();
while (cursor != null) {
final var hasDocs = Files.isDirectory(cursor.resolve("docs/specs/compiler"));
final var hasCompiler = Files.isDirectory(cursor.resolve("prometeu-compiler"));
if (hasDocs && hasCompiler) {
return cursor;
}
cursor = cursor.getParent();
}
fail("could not locate repository root from working directory");
throw new IllegalStateException("unreachable");
}
}
@@ -0,0 +1,22 @@
package p.studio.architecture;
import com.tngtech.archunit.base.DescribedPredicate;
import com.tngtech.archunit.core.domain.JavaClass;
import java.util.Arrays;
import java.util.Set;
import java.util.stream.Collectors;
final class DescribedPredicates {
private DescribedPredicates() {
}
static DescribedPredicate<JavaClass> notBelongingTo(final Class<?>... allowed) {
final Set<String> allowedNames = Arrays.stream(allowed)
.map(Class::getName)
.collect(Collectors.toUnmodifiableSet());
return DescribedPredicate.describe(
"do not belong to " + allowedNames,
javaClass -> !allowedNames.contains(javaClass.getName()));
}
}
@@ -0,0 +1,85 @@
package p.studio.architecture;
import org.junit.jupiter.api.Test;
import java.io.IOException;
import java.nio.file.Files;
import java.nio.file.Path;
import java.util.ArrayList;
import java.util.Map;
import java.util.Set;
import java.util.regex.Pattern;
import static org.junit.jupiter.api.Assertions.assertTrue;
import static org.junit.jupiter.api.Assertions.fail;
class PbsGradleDependencyAllowlistTest {
private static final Pattern PBS_PROJECT_DEP = Pattern.compile(
"(\\w+)\\(\\s*project\\(\\s*\"" + Pattern.quote(PbsModuleOrigins.PBS_GRADLE_PATH) + "\"\\s*\\)");
private static final Map<String, Set<String>> ALLOWED_CONFIGURATIONS = Map.of(
":prometeu-compiler:prometeu-frontend-registry", Set.of("implementation", "api"),
":prometeu-architecture-tests", Set.of("testImplementation"));
@Test
void onlyAllowlistedProjectsMayDependOnThePbsFrontendModule() throws IOException {
final var repoRoot = locateRepoRoot();
final var violations = new ArrayList<String>();
try (final var paths = Files.walk(repoRoot)) {
paths.filter(path -> path.getFileName().toString().equals("build.gradle.kts"))
.filter(path -> !path.toString().contains("/buildSrc/"))
.filter(path -> !path.toString().contains("/build/"))
.forEach(path -> collectViolations(repoRoot, path, violations));
}
assertTrue(violations.isEmpty(), "PBS Gradle project dependency allowlist violated: " + violations);
}
private static void collectViolations(
final Path repoRoot,
final Path buildFile,
final ArrayList<String> violations) {
final var projectPath = toProjectPath(repoRoot, buildFile);
if (PbsModuleOrigins.PBS_GRADLE_PATH.equals(projectPath)) {
return;
}
final String content;
try {
content = Files.readString(buildFile);
} catch (IOException e) {
throw new IllegalStateException("failed to read " + buildFile, e);
}
final var matcher = PBS_PROJECT_DEP.matcher(content);
while (matcher.find()) {
final var configuration = matcher.group(1);
final var allowed = ALLOWED_CONFIGURATIONS.getOrDefault(projectPath, Set.of());
if (!allowed.contains(configuration)) {
violations.add(projectPath + " " + configuration + " " + PbsModuleOrigins.PBS_GRADLE_PATH);
}
}
}
private static String toProjectPath(final Path repoRoot, final Path buildFile) {
final var relative = repoRoot.relativize(buildFile.getParent()).toString().replace('\\', '/');
if (relative.isEmpty() || ".".equals(relative)) {
return ":";
}
return ":" + relative.replace('/', ':');
}
private static Path locateRepoRoot() {
var cursor = Path.of(System.getProperty("user.dir")).toAbsolutePath().normalize();
while (cursor != null) {
final var hasDocs = Files.isDirectory(cursor.resolve("docs/specs/compiler"));
final var hasCompiler = Files.isDirectory(cursor.resolve("prometeu-compiler"));
if (hasDocs && hasCompiler) {
return cursor;
}
cursor = cursor.getParent();
}
fail("could not locate repository root from working directory");
throw new IllegalStateException("unreachable");
}
}
@@ -0,0 +1,43 @@
package p.studio.architecture;
import com.tngtech.archunit.core.importer.ImportOption;
import com.tngtech.archunit.junit.AnalyzeClasses;
import com.tngtech.archunit.junit.ArchTest;
import com.tngtech.archunit.lang.ArchRule;
import p.studio.compiler.PBSDefinitions;
import p.studio.compiler.PBSFrontendProvider;
import static com.tngtech.archunit.lang.syntax.ArchRuleDefinition.noClasses;
import static p.studio.architecture.PbsModuleOrigins.fromFrontendApiModule;
import static p.studio.architecture.PbsModuleOrigins.fromPbsModule;
import static p.studio.architecture.PbsModuleOrigins.fromRegistryModule;
@AnalyzeClasses(packages = "p.studio", importOptions = ImportOption.DoNotIncludeTests.class)
class PbsModuleBoundaryArchTest {
@ArchTest
static final ArchRule productionOutsideAllowlistMustNotDependOnPbsModuleTypes = noClasses()
.that(fromPbsModule().negate())
.and(fromRegistryModule().negate())
.should()
.dependOnClassesThat(fromPbsModule())
.because("DEC-0050: only prometeu-frontend-pbs and prometeu-frontend-registry may depend on PBS module types");
@ArchTest
static final ArchRule registryMustOnlyDependOnPbsProviderFacade = noClasses()
.that(fromRegistryModule())
.should()
.dependOnClassesThat(
fromPbsModule()
.and(DescribedPredicates.notBelongingTo(PBSFrontendProvider.class, PBSDefinitions.class)))
.because("DEC-0050: registry may depend only on PBSFrontendProvider and PBSDefinitions");
@ArchTest
static final ArchRule irBackendModelsMustNotDependOnPbsModuleTypes = noClasses()
.that(fromFrontendApiModule())
.and()
.resideInAPackage("p.studio.compiler.models..")
.should()
.dependOnClassesThat(fromPbsModule())
.because("DEC-0050: public IRBackend contract types must not depend on PBS module types");
}
@@ -0,0 +1,36 @@
package p.studio.architecture;
import com.tngtech.archunit.core.importer.ClassFileImporter;
import com.tngtech.archunit.core.importer.ImportOption;
import org.junit.jupiter.api.Test;
import static org.junit.jupiter.api.Assertions.assertTrue;
import static org.junit.jupiter.api.Assertions.fail;
class PbsModuleClasspathTest {
@Test
void importerMustSeePbsAndRegistryModuleOrigins() {
final var classes = new ClassFileImporter()
.withImportOption(ImportOption.Predefined.DO_NOT_INCLUDE_TESTS)
.importPackages("p.studio");
final var pbsSample = classes.stream()
.filter(PbsModuleOrigins::isPbsModule)
.findFirst();
final var registrySample = classes.stream()
.filter(PbsModuleOrigins::isRegistryModule)
.findFirst();
if (pbsSample.isEmpty() || registrySample.isEmpty()) {
final var uris = classes.stream()
.limit(20)
.map(javaClass -> javaClass.getName() + " -> " + PbsModuleOrigins.sourceUri(javaClass))
.toList();
fail("PBS/registry module origins were not visible to ArchUnit. sample URIs: " + uris);
}
assertTrue(pbsSample.isPresent());
assertTrue(registrySample.isPresent());
}
}
@@ -0,0 +1,60 @@
package p.studio.architecture;
import com.tngtech.archunit.base.DescribedPredicate;
import com.tngtech.archunit.core.domain.JavaClass;
final class PbsModuleOrigins {
static final String PBS_GRADLE_PATH = ":prometeu-compiler:frontends:prometeu-frontend-pbs";
private PbsModuleOrigins() {
}
static boolean isPbsModule(final JavaClass javaClass) {
return uriContains(javaClass, "/prometeu-frontend-pbs/")
|| uriContains(javaClass, "prometeu-frontend-pbs.jar");
}
static boolean isRegistryModule(final JavaClass javaClass) {
return uriContains(javaClass, "/prometeu-frontend-registry/")
|| uriContains(javaClass, "prometeu-frontend-registry.jar");
}
static boolean isFrontendApiModule(final JavaClass javaClass) {
return uriContains(javaClass, "/prometeu-frontend-api/")
|| uriContains(javaClass, "prometeu-frontend-api.jar");
}
static DescribedPredicate<JavaClass> fromPbsModule() {
return DescribedPredicate.describe(
"originate from the PBS frontend module",
PbsModuleOrigins::isPbsModule);
}
static DescribedPredicate<JavaClass> fromRegistryModule() {
return DescribedPredicate.describe(
"originate from the frontend registry module",
PbsModuleOrigins::isRegistryModule);
}
static DescribedPredicate<JavaClass> fromFrontendApiModule() {
return DescribedPredicate.describe(
"originate from the frontend-api module",
PbsModuleOrigins::isFrontendApiModule);
}
static String sourceUri(final JavaClass javaClass) {
return javaClass.getSource()
.map(source -> normalize(source.getUri().toString()))
.orElse("<no source>");
}
private static boolean uriContains(final JavaClass javaClass, final String fragment) {
return javaClass.getSource()
.map(source -> normalize(source.getUri().toString()).contains(fragment))
.orElse(false);
}
private static String normalize(final String uri) {
return uri.replace('\\', '/');
}
}
@@ -6,11 +6,13 @@ import p.studio.compiler.messages.FrontendPhaseContext;
import p.studio.compiler.models.FrontendSemanticToken; import p.studio.compiler.models.FrontendSemanticToken;
import p.studio.compiler.pbs.ast.PbsAst; import p.studio.compiler.pbs.ast.PbsAst;
import p.studio.compiler.pbs.semantics.PbsEditorialCompletionCandidate; import p.studio.compiler.pbs.semantics.PbsEditorialCompletionCandidate;
import p.studio.compiler.pbs.semantics.PbsEditorialLocation;
import p.studio.compiler.pbs.semantics.PbsEditorialResolvedSymbol; import p.studio.compiler.pbs.semantics.PbsEditorialResolvedSymbol;
import p.studio.compiler.pbs.semantics.PbsEditorialSignatureHelp; import p.studio.compiler.pbs.semantics.PbsEditorialSignatureHelp;
import p.studio.compiler.pbs.semantics.PbsEditorialSymbolKind; import p.studio.compiler.pbs.semantics.PbsEditorialSymbolKind;
import p.studio.compiler.pbs.semantics.PbsEditorialSupportService; import p.studio.compiler.pbs.semantics.PbsEditorialSupportService;
import p.studio.compiler.services.FrontendCompletionCandidate; import p.studio.compiler.services.FrontendCompletionCandidate;
import p.studio.compiler.services.FrontendDefinitionLocation;
import p.studio.compiler.services.FrontendDocumentRequest; import p.studio.compiler.services.FrontendDocumentRequest;
import p.studio.compiler.services.FrontendDocumentation; import p.studio.compiler.services.FrontendDocumentation;
import p.studio.compiler.services.FrontendEditorialContext; import p.studio.compiler.services.FrontendEditorialContext;
@@ -20,10 +22,15 @@ import p.studio.compiler.services.FrontendSignature;
import p.studio.compiler.services.FrontendSignatureHelp; import p.studio.compiler.services.FrontendSignatureHelp;
import p.studio.compiler.services.FrontendSymbolKind; import p.studio.compiler.services.FrontendSymbolKind;
import p.studio.compiler.services.PBSFrontendPhaseService; import p.studio.compiler.services.PBSFrontendPhaseService;
import p.studio.compiler.source.Span;
import p.studio.compiler.source.diagnostics.DiagnosticSink; import p.studio.compiler.source.diagnostics.DiagnosticSink;
import p.studio.compiler.source.identifiers.FileId; import p.studio.compiler.source.identifiers.FileId;
import p.studio.compiler.source.tables.FileTableReader;
import p.studio.utilities.structures.ReadOnlyList; import p.studio.utilities.structures.ReadOnlyList;
import java.nio.file.Files;
import java.nio.file.Path;
import java.util.ArrayList;
import java.util.List; import java.util.List;
import java.util.Objects; import java.util.Objects;
import java.util.Optional; import java.util.Optional;
@@ -61,7 +68,8 @@ public final class PBSFrontendLanguageService implements FrontendLanguageService
return Optional.of(new FrontendEditorialContext( return Optional.of(new FrontendEditorialContext(
ast, ast,
semanticReadSurface.supplementalTopDeclsByFile().getOrDefault(fileId, ReadOnlyList.empty()), semanticReadSurface.supplementalTopDeclsByFile().getOrDefault(fileId, ReadOnlyList.empty()),
phaseContext.feSurfaceContext())); phaseContext.feSurfaceContext(),
phaseContext.fileTable));
} }
public List<PbsEditorialCompletionCandidate> completion( public List<PbsEditorialCompletionCandidate> completion(
@@ -167,6 +175,44 @@ public final class PBSFrontendLanguageService implements FrontendLanguageService
.orElseGet(FrontendSignatureHelp::empty); .orElseGet(FrontendSignatureHelp::empty);
} }
public List<PbsEditorialLocation> definition(
final String sourceText,
final PbsAst.File ast,
final ReadOnlyList<PbsAst.TopDecl> supplementalTopDecls,
final FESurfaceContext feSurfaceContext,
final int offset) {
return editorialSupportService.definition(sourceText, ast, supplementalTopDecls, feSurfaceContext, offset);
}
@Override
public List<FrontendDefinitionLocation> definition(
final FrontendDocumentRequest request,
final FrontendEditorialContext editorialContext,
final int offset) {
if (request == null
|| editorialContext == null
|| !(editorialContext.syntaxTree() instanceof PbsAst.File ast)
|| !(editorialContext.supplementalDeclarations() instanceof ReadOnlyList<?> supplementalTopDecls)
|| !(editorialContext.semanticContext() instanceof FESurfaceContext feSurfaceContext)
|| !(editorialContext.sourceFiles() instanceof FileTableReader fileTable)) {
return List.of();
}
@SuppressWarnings("unchecked")
final ReadOnlyList<PbsAst.TopDecl> typedSupplementalTopDecls =
(ReadOnlyList<PbsAst.TopDecl>) supplementalTopDecls;
final ArrayList<FrontendDefinitionLocation> locations = new ArrayList<>();
for (final PbsEditorialLocation location : definition(
request.documentText(),
ast,
typedSupplementalTopDecls,
feSurfaceContext,
offset)) {
toFrontendLocation(location, fileTable).ifPresent(locations::add);
}
return List.copyOf(locations);
}
@Override @Override
public List<FrontendSemanticToken> semanticTokens(final FrontendDocumentRequest request) { public List<FrontendSemanticToken> semanticTokens(final FrontendDocumentRequest request) {
return semanticTokens(request == null ? "" : request.documentText()); return semanticTokens(request == null ? "" : request.documentText());
@@ -213,4 +259,35 @@ public final class PBSFrontendLanguageService implements FrontendLanguageService
private FrontendSymbolKind toFrontendSymbolKind(final PbsEditorialSymbolKind kind) { private FrontendSymbolKind toFrontendSymbolKind(final PbsEditorialSymbolKind kind) {
return FrontendSymbolKind.valueOf(kind.name()); return FrontendSymbolKind.valueOf(kind.name());
} }
private Optional<FrontendDefinitionLocation> toFrontendLocation(
final PbsEditorialLocation location,
final FileTableReader fileTable) {
if (location == null || fileTable == null) {
return Optional.empty();
}
final Span span = location.span();
if (span == null || span.isNone() || span.getFileId() == null || span.getFileId().isNone()) {
return Optional.empty();
}
final var sourceHandle = fileTable.get(span.getFileId());
if (sourceHandle == null || sourceHandle.getCanonPath() == null) {
return Optional.empty();
}
final Path path = sourceHandle.getCanonPath().toAbsolutePath().normalize();
if (!Files.isRegularFile(path)) {
return Optional.empty();
}
return Optional.of(new FrontendDefinitionLocation(
path,
toOffset(span.getStart()),
toOffset(span.getEnd())));
}
private static int toOffset(final long value) {
if (value <= 0L) {
return 0;
}
return (int) Math.min(Integer.MAX_VALUE, value);
}
} }
@@ -0,0 +1,11 @@
package p.studio.compiler.pbs.semantics;
import p.studio.compiler.source.Span;
import java.util.Objects;
public record PbsEditorialLocation(Span span) {
public PbsEditorialLocation {
Objects.requireNonNull(span, "span");
}
}
@@ -74,6 +74,23 @@ public final class PbsEditorialSupportService {
return context.resolveSymbolHover(token.lexeme(), tokenIndex, scopeState); return context.resolveSymbolHover(token.lexeme(), tokenIndex, scopeState);
} }
public List<PbsEditorialLocation> definition(
final String sourceText,
final PbsAst.File ast,
final ReadOnlyList<PbsAst.TopDecl> supplementalTopDecls,
final int offset) {
return definition(sourceText, ast, supplementalTopDecls, FESurfaceContext.empty(), offset);
}
public List<PbsEditorialLocation> definition(
final String sourceText,
final PbsAst.File ast,
final ReadOnlyList<PbsAst.TopDecl> supplementalTopDecls,
final FESurfaceContext feSurfaceContext,
final int offset) {
return buildContext(sourceText, ast, supplementalTopDecls, feSurfaceContext).definitionAt(offset);
}
public Optional<PbsEditorialSignatureHelp> signatureHelp( public Optional<PbsEditorialSignatureHelp> signatureHelp(
final String sourceText, final String sourceText,
final PbsAst.File ast, final PbsAst.File ast,
@@ -610,6 +627,228 @@ public final class PbsEditorialSupportService {
return Optional.empty(); return Optional.empty();
} }
private List<PbsEditorialLocation> definitionAt(final int offset) {
final Integer tokenIndex = identifierTokenIndexAt(offset);
if (tokenIndex == null) {
return List.of();
}
final var scopeState = scopeStateAt(offset);
final var token = token(tokenIndex);
final Integer previousTokenIndex = previousSignificantTokenIndex(tokenIndex);
if (previousTokenIndex != null && token(previousTokenIndex).kind() == PbsTokenKind.DOT) {
final TypeView receiverType = resolveReceiverTypeBeforeDot(previousTokenIndex, scopeState);
return resolveMemberDefinition(receiverType, token.lexeme());
}
return resolveSymbolDefinition(token.lexeme(), tokenIndex, scopeState, offset);
}
private List<PbsEditorialLocation> resolveSymbolDefinition(
final String symbolName,
final int tokenIndex,
final ScopeState scopeState,
final int offset) {
if (scopeState.parameterNames().contains(symbolName)) {
return parameterLocations(symbolName, offset);
}
final Scope.LocalSymbol localSymbol = scopeState.scope().entries().get(symbolName);
if (localSymbol != null) {
return localLocations(symbolName, offset);
}
final Integer previousTokenIndex = previousSignificantTokenIndex(tokenIndex);
if (previousTokenIndex != null && token(previousTokenIndex).kind() == PbsTokenKind.NEW) {
return constructorLocations(resolveTopDeclSymbol(symbolName));
}
final TopDeclSymbol importedSymbol = importedSymbols.get(symbolName);
if (importedSymbol != null) {
return topDeclLocations(importedSymbol);
}
final TopDeclSymbol supplementalSymbol = supplementalSymbols.get(symbolName);
if (supplementalSymbol != null) {
return topDeclLocations(supplementalSymbol);
}
final TopDeclSymbol topLevelSymbol = topLevelSymbols.get(symbolName);
if (topLevelSymbol != null) {
return topDeclLocations(topLevelSymbol);
}
return List.of();
}
private List<PbsEditorialLocation> resolveMemberDefinition(
final TypeView receiverType,
final String memberName) {
if (receiverType == null) {
return List.of();
}
if (receiverType.kind() == Kind.STRUCT) {
final Span fieldSpan = structFieldSpan(receiverType.name(), memberName);
if (fieldSpan != null) {
return locations(fieldSpan);
}
final StructInfo structInfo = model.structs.get(receiverType.name());
if (structInfo == null) {
return List.of();
}
return callableLocations(structInfo.methods().get(memberName));
}
if (receiverType.kind() == Kind.SERVICE || receiverType.kind() == Kind.CONTRACT) {
final Map<String, List<CallableSymbol>> methods = receiverType.kind() == Kind.SERVICE
? Optional.ofNullable(model.services.get(receiverType.name())).map(ServiceInfo::methods).orElse(Map.of())
: Optional.ofNullable(model.contracts.get(receiverType.name())).map(ContractInfo::methods).orElse(Map.of());
return callableLocations(methods.get(memberName));
}
return List.of();
}
private List<PbsEditorialLocation> parameterLocations(
final String symbolName,
final int offset) {
final CallableFrame callableFrame = callableFrameAt(offset);
if (callableFrame == null) {
return List.of();
}
for (final var parameter : callableFrame.parameters()) {
if (symbolName.equals(parameter.name())) {
return locations(parameter.span());
}
}
return List.of();
}
private List<PbsEditorialLocation> localLocations(
final String symbolName,
final int offset) {
final CallableFrame callableFrame = callableFrameAt(offset);
if (callableFrame == null) {
return List.of();
}
return locations(bindingSpan(callableFrame.body(), symbolName, offset, null));
}
private Span bindingSpan(
final PbsAst.Block block,
final String symbolName,
final int offset,
final Span current) {
Span found = current;
for (final var statement : block.statements()) {
if (statement.span().getStart() >= offset) {
break;
}
if (statement instanceof PbsAst.LetStatement letStatement && symbolName.equals(letStatement.name())) {
found = letStatement.nameSpan() == null ? letStatement.span() : letStatement.nameSpan();
}
if (statement.span().contains(offset)) {
if (statement instanceof PbsAst.IfStatement ifStatement) {
if (ifStatement.thenBlock().span().contains(offset)) {
return bindingSpan(ifStatement.thenBlock(), symbolName, offset, found);
}
if (ifStatement.elseBlock() != null && ifStatement.elseBlock().span().contains(offset)) {
return bindingSpan(ifStatement.elseBlock(), symbolName, offset, found);
}
if (ifStatement.elseIf() != null && ifStatement.elseIf().span().contains(offset)) {
final var nestedBlock = new PbsAst.Block(
ReadOnlyList.wrap(List.of(ifStatement.elseIf())),
null,
ifStatement.elseIf().span());
return bindingSpan(nestedBlock, symbolName, offset, found);
}
} else if (statement instanceof PbsAst.ForStatement forStatement) {
Span loopFound = found;
if (symbolName.equals(forStatement.iteratorName())) {
loopFound = forStatement.span();
}
if (forStatement.body().span().contains(offset)) {
return bindingSpan(forStatement.body(), symbolName, offset, loopFound);
}
} else if (statement instanceof PbsAst.WhileStatement whileStatement
&& whileStatement.body().span().contains(offset)) {
return bindingSpan(whileStatement.body(), symbolName, offset, found);
}
return found;
}
}
return found;
}
private List<PbsEditorialLocation> constructorLocations(final TopDeclSymbol topDeclSymbol) {
if (topDeclSymbol == null) {
return List.of();
}
if (topDeclSymbol.decl() instanceof PbsAst.StructDecl structDecl) {
if (structDecl.ctors().isEmpty()) {
return locations(structDecl.span());
}
final ArrayList<Span> ctorSpans = new ArrayList<>();
for (final var ctor : structDecl.ctors()) {
ctorSpans.add(ctor.span());
}
return locations(ctorSpans.toArray(Span[]::new));
}
return topDeclLocations(topDeclSymbol);
}
private List<PbsEditorialLocation> topDeclLocations(final TopDeclSymbol topDeclSymbol) {
if (topDeclSymbol == null) {
return List.of();
}
return locations(topDeclSymbol.decl().span());
}
private List<PbsEditorialLocation> callableLocations(final List<CallableSymbol> callables) {
if (callables == null || callables.isEmpty()) {
return List.of();
}
final ArrayList<Span> spans = new ArrayList<>();
for (final var callable : callables) {
spans.add(callable.span());
}
return locations(spans.toArray(Span[]::new));
}
private Span structFieldSpan(
final String typeName,
final String fieldName) {
final TopDeclSymbol typeSymbol = resolveTopDeclSymbol(typeName);
if (typeSymbol == null) {
return null;
}
if (typeSymbol.decl() instanceof PbsAst.StructDecl structDecl) {
for (final var field : structDecl.fields()) {
if (fieldName.equals(field.name())) {
return field.span();
}
}
}
if (typeSymbol.decl() instanceof PbsAst.BuiltinTypeDecl builtinTypeDecl) {
for (final var field : builtinTypeDecl.fields()) {
if (fieldName.equals(field.name())) {
return field.span();
}
}
}
return null;
}
private List<PbsEditorialLocation> locations(final Span... spans) {
final ArrayList<PbsEditorialLocation> locations = new ArrayList<>();
if (spans == null) {
return List.of();
}
for (final Span span : spans) {
if (hasPhysicalSpan(span)) {
locations.add(new PbsEditorialLocation(span));
}
}
return List.copyOf(locations);
}
private boolean hasPhysicalSpan(final Span span) {
return span != null
&& !span.isNone()
&& span.getFileId() != null
&& !span.getFileId().isNone();
}
private List<PbsEditorialSignature> resolveCallableSignatures( private List<PbsEditorialSignature> resolveCallableSignatures(
final String callableName, final String callableName,
final ScopeState scopeState) { final ScopeState scopeState) {
@@ -265,6 +265,87 @@ final class PbsEditorialSupportServiceTest {
&& candidate.detail().equals("draw_pixel(x: int, y: int, color: int) -> void"))); && candidate.detail().equals("draw_pixel(x: int, y: int, color: int) -> void")));
} }
@Test
void shouldResolveDefinitionForLocalsParametersMembersAndCanonicalImports() {
final var source = """
import { Log as Logger } from @sdk:log;
fn helper(value: int) -> int {
let total = value;
Logger.info("hello");
missingName;
return total;
}
""";
final var ast = parseOrdinary(source);
final var supplementalTopDecls = supplementalTopDecls("""
declare service Log {
fn info(message: str) -> void {
return;
}
}
""");
final var parameter = requireDefinition(source, ast, supplementalTopDecls, "value;");
assertEquals(1, parameter.size());
assertEquals(0, parameter.getFirst().span().getFileId().getId());
assertTrue(parameter.getFirst().span().contains(source.indexOf("value: int")));
final var local = requireDefinition(source, ast, supplementalTopDecls, "total;");
assertEquals(1, local.size());
assertEquals(0, local.getFirst().span().getFileId().getId());
assertTrue(local.getFirst().span().contains(source.indexOf("total = value")));
final var function = requireDefinition(source, ast, supplementalTopDecls, "helper(value");
assertEquals(1, function.size());
assertEquals(0, function.getFirst().span().getFileId().getId());
assertTrue(function.getFirst().span().getStart() <= source.indexOf("fn helper"));
final var imported = requireDefinition(source, ast, supplementalTopDecls, "Logger.info");
assertEquals(1, imported.size());
assertEquals(100, imported.getFirst().span().getFileId().getId());
assertNotEquals(ast.span().getFileId().getId(), imported.getFirst().span().getFileId().getId());
final var member = requireDefinition(source, ast, supplementalTopDecls, "info(");
assertEquals(1, member.size());
assertEquals(100, member.getFirst().span().getFileId().getId());
assertTrue(service.definition(source, ast, supplementalTopDecls, source.indexOf("fn helper")).isEmpty());
assertTrue(service.definition(source, ast, supplementalTopDecls, source.indexOf("int")).isEmpty());
assertTrue(service.definition(source, ast, supplementalTopDecls, source.indexOf("missingName")).isEmpty());
}
@Test
void shouldReturnEveryMatchingDeclarationLocationForOverloadedMembers() {
final var source = """
declare struct Vec() {
fn blend(dx: int) -> int { return dx; }
fn blend(dx: int, dy: int) -> int { return dx; }
}
fn main(vec: Vec) -> void {
vec.blend(1, 2);
}
""";
final var ast = parseOrdinary(source);
final var locations = requireDefinition(source, ast, ReadOnlyList.empty(), "blend(1");
assertEquals(2, locations.size());
assertTrue(locations.getFirst().span().contains(source.indexOf("fn blend(dx: int)")));
assertTrue(locations.get(1).span().contains(source.indexOf("fn blend(dx: int, dy: int)")));
}
private List<PbsEditorialLocation> requireDefinition(
final String source,
final PbsAst.File ast,
final ReadOnlyList<PbsAst.TopDecl> supplementalTopDecls,
final String needle) {
final int offset = source.indexOf(needle);
assertTrue(offset >= 0, "Expected to find needle: " + needle);
final var locations = service.definition(source, ast, supplementalTopDecls, offset);
assertFalse(locations.isEmpty(), "Expected definition for needle: " + needle);
return locations;
}
private PbsEditorialResolvedSymbol requireHover( private PbsEditorialResolvedSymbol requireHover(
final String source, final String source,
final PbsAst.File ast, final PbsAst.File ast,
@@ -0,0 +1,99 @@
package p.studio.compiler.integration;
import org.junit.jupiter.api.Test;
import org.junit.jupiter.api.io.TempDir;
import p.studio.compiler.FrontendRegistryService;
import p.studio.compiler.messages.BuilderPipelineConfig;
import p.studio.compiler.models.BuilderPipelineContext;
import p.studio.compiler.models.IRBackendReader;
import p.studio.compiler.models.IRHiddenGlobalKind;
import p.studio.compiler.synth.SyntheticFrontendProvider;
import p.studio.compiler.workspaces.BuilderPipelineService;
import p.studio.utilities.logs.LogAggregator;
import java.io.IOException;
import java.nio.file.Files;
import java.nio.file.Path;
import static org.junit.jupiter.api.Assertions.assertEquals;
import static org.junit.jupiter.api.Assertions.assertFalse;
import static org.junit.jupiter.api.Assertions.assertNotNull;
import static org.junit.jupiter.api.Assertions.assertTrue;
class SyntheticFrontendPipelineTest {
@TempDir
Path projectRoot;
@Test
void compileMustEmitVerifiedBytecodeWithoutPbs() throws IOException {
writeSyntheticProject();
final var provider = new SyntheticFrontendProvider();
FrontendRegistryService.register(provider);
try {
final var context = BuilderPipelineContext.fromConfig(
new BuilderPipelineConfig(false, projectRoot.toString()));
final var result = BuilderPipelineService.INSTANCE.compile(context, LogAggregator.empty());
assertTrue(provider.syntheticCompiler().invoked(), "synthetic compiler must be the effective frontend");
assertEquals(
SyntheticFrontendProvider.LANGUAGE_ID,
result.analysisSnapshot().frontendSpec().getLanguageId());
assertFalse("pbs".equals(result.analysisSnapshot().frontendSpec().getLanguageId()));
assertTrue(provider.languageService().isEmpty());
assertTrue(
result.diagnostics().stream().noneMatch(issue -> issue.isError()),
result.diagnostics().toString());
assertNotNull(result.bytecodeModule());
assertNotNull(result.bytecodeBytes());
assertTrue(result.bytecodeBytes().length > 0);
final var backend = result.analysisSnapshot().irBackend();
assertEquals("__prometeu.lifecycle.frame_wrapper$m0", backend.getEntryPointCallableName());
assertTrue(backend.getGlobals().stream().anyMatch(global ->
global.hiddenKind() == IRHiddenGlobalKind.BOOT_GUARD
&& "__prometeu.lifecycle.boot_guard$m0".equals(global.name())));
assertNoPbsNames(backend);
assertTrue(noPbsSources(projectRoot));
} finally {
FrontendRegistryService.unregister(SyntheticFrontendProvider.LANGUAGE_ID);
assertEquals(1, FrontendRegistryService.listProviders().size());
assertEquals(
"pbs",
FrontendRegistryService.listProviders().getFirst().specification().getLanguageId());
}
}
private void writeSyntheticProject() throws IOException {
Files.writeString(projectRoot.resolve("prometeu.json"), """
{
"name": "synth-fixture",
"version": "1.0.0",
"language": "synth",
"stdlib": "1",
"target": "Game",
"dependencies": []
}
""");
Files.createDirectory(projectRoot.resolve("src"));
}
private void assertNoPbsNames(final IRBackendReader backend) {
assertFalse(backend.getEntryPointCallableName().contains("__pbs."));
assertTrue(backend.getExecutableFunctions().stream()
.noneMatch(function -> function.callableName().contains("__pbs.")));
assertTrue(backend.getSyntheticFunctions().stream()
.noneMatch(function -> function.callableName().contains("__pbs.")));
assertTrue(backend.getGlobals().stream()
.noneMatch(global -> global.name().contains("__pbs.")));
}
private boolean noPbsSources(final Path root) throws IOException {
try (final var files = Files.walk(root)) {
return files
.filter(Files::isRegularFile)
.map(path -> path.getFileName().toString())
.noneMatch(name -> name.endsWith(".pbs") || name.endsWith(".barrel"));
}
}
}
@@ -95,7 +95,8 @@ class BackendConformanceMatrixSpecTest {
"PBS13-12.7", "PBS13-12.7",
"PBS13-12.8", "PBS13-12.8",
"PBS13-12.9", "PBS13-12.9",
"G23-5.2"); "G23-5.2",
"G23-8.3");
@Test @Test
void matrixMustExistAndContainRequiredRequirementRows() throws IOException { void matrixMustExistAndContainRequiredRequirementRows() throws IOException {
@@ -1,96 +0,0 @@
package p.studio.compiler.specs;
import org.junit.jupiter.api.Test;
import java.io.IOException;
import java.nio.file.Files;
import java.nio.file.Path;
import java.util.ArrayList;
import java.util.List;
import static org.junit.jupiter.api.Assertions.assertTrue;
import static org.junit.jupiter.api.Assertions.fail;
class CommonBackendArchitectureTest {
private static final String COMPILER_SOURCE_ROOT =
"prometeu-compiler/prometeu-build-pipeline/src/main/java/p/studio/compiler";
private static final List<String> GUARDED_RELATIVE_ROOTS = List.of(
"backend",
"lifecycle",
"workspaces/stages");
private static final String FORBIDDEN_PBS_PACKAGE = "p.studio.compiler.pbs";
private static final String FORBIDDEN_PBS_PREFIX = "__pbs.";
@Test
void commonBackendMustNotImportPbsFrontendPackages() throws IOException {
final var violations = new ArrayList<String>();
walkGuardedSources(path -> assertNoPbsImport(path, violations));
assertTrue(
violations.isEmpty(),
"common backend must not import PBS frontend packages: " + violations);
}
@Test
void commonLifecycleAndBackendMustNotDiscoverRolesFromPbsNamePrefixes() throws IOException {
final var violations = new ArrayList<String>();
walkGuardedSources(path -> assertNoPbsPrefixMatching(path, violations));
assertTrue(
violations.isEmpty(),
"common lifecycle/backend code must not inspect __pbs. prefixes: " + violations);
}
private static void walkGuardedSources(final java.util.function.Consumer<Path> consumer) throws IOException {
final var compilerRoot = locateRepoRoot().resolve(COMPILER_SOURCE_ROOT);
for (final var relativeRoot : GUARDED_RELATIVE_ROOTS) {
final var root = compilerRoot.resolve(relativeRoot);
if (Files.isRegularFile(root)) {
consumer.accept(root);
continue;
}
try (final var paths = Files.walk(root)) {
paths.filter(path -> path.toString().endsWith(".java")).forEach(consumer);
}
}
}
private static void assertNoPbsImport(
final Path path,
final ArrayList<String> violations) {
try {
final var content = Files.readString(path);
if (content.contains("import " + FORBIDDEN_PBS_PACKAGE)
|| content.contains("import static " + FORBIDDEN_PBS_PACKAGE)) {
violations.add(locateRepoRoot().relativize(path).toString());
}
} catch (IOException e) {
throw new IllegalStateException("failed to read source file: " + path, e);
}
}
private static void assertNoPbsPrefixMatching(
final Path path,
final ArrayList<String> violations) {
try {
final var content = Files.readString(path);
if (content.contains(FORBIDDEN_PBS_PREFIX)) {
violations.add(locateRepoRoot().relativize(path).toString());
}
} catch (IOException e) {
throw new IllegalStateException("failed to read source file: " + path, e);
}
}
private static Path locateRepoRoot() {
var cursor = Path.of(System.getProperty("user.dir")).toAbsolutePath().normalize();
while (cursor != null) {
final var hasDocs = Files.isDirectory(cursor.resolve("docs/specs/compiler"));
final var hasCompiler = Files.isDirectory(cursor.resolve("prometeu-compiler"));
if (hasDocs && hasCompiler) {
return cursor;
}
cursor = cursor.getParent();
}
fail("could not locate repository root from working directory");
throw new IllegalStateException("unreachable");
}
}
@@ -11,93 +11,11 @@ import p.studio.compiler.source.diagnostics.DiagnosticSink;
import p.studio.utilities.logs.LogAggregator; import p.studio.utilities.logs.LogAggregator;
import p.studio.utilities.structures.ReadOnlySet; import p.studio.utilities.structures.ReadOnlySet;
import java.io.IOException;
import java.nio.file.Files;
import java.nio.file.Path;
import java.util.List;
import static org.junit.jupiter.api.Assertions.assertNotNull; import static org.junit.jupiter.api.Assertions.assertNotNull;
import static org.junit.jupiter.api.Assertions.assertTrue; import static org.junit.jupiter.api.Assertions.assertTrue;
import static org.junit.jupiter.api.Assertions.fail;
class FrontendProviderBoundaryTest { class FrontendProviderBoundaryTest {
@Test
void commonModulesMustNotInstantiatePbsFrontendPhaseServiceDirectly() throws IOException {
final var repoRoot = findRepoRoot(Path.of("").toAbsolutePath().normalize());
final var commonSourceRoots = List.of(
repoRoot.resolve("prometeu-compiler/prometeu-build-pipeline/src/main/java"),
repoRoot.resolve("prometeu-compiler/prometeu-deps/src/main/java"),
repoRoot.resolve("prometeu-studio/src/main/java"),
repoRoot.resolve("prometeu-app/src/main/java"));
for (final var sourceRoot : commonSourceRoots) {
if (!Files.exists(sourceRoot)) {
continue;
}
try (final var files = Files.walk(sourceRoot)) {
final var violations = files
.filter(path -> path.toString().endsWith(".java"))
.filter(path -> contains(path, "new PBSFrontendPhaseService("))
.toList();
if (!violations.isEmpty()) {
fail("common modules must resolve frontend compiler behavior through FrontendProvider: " + violations);
}
}
}
}
@Test
void commonModulesMustNotInstantiatePbsEditorialSupportServiceDirectly() throws IOException {
final var repoRoot = findRepoRoot(Path.of("").toAbsolutePath().normalize());
final var sourceRoots = List.of(
repoRoot.resolve("prometeu-compiler/prometeu-build-pipeline/src/main/java"),
repoRoot.resolve("prometeu-compiler/prometeu-deps/src/main/java"),
repoRoot.resolve("prometeu-lsp/prometeu-lsp-v1/src/main/java"),
repoRoot.resolve("prometeu-studio/src/main/java"),
repoRoot.resolve("prometeu-app/src/main/java"));
for (final var sourceRoot : sourceRoots) {
if (!Files.exists(sourceRoot)) {
continue;
}
try (final var files = Files.walk(sourceRoot)) {
final var violations = files
.filter(path -> path.toString().endsWith(".java"))
.filter(path -> contains(path, "new PbsEditorialSupportService("))
.toList();
if (!violations.isEmpty()) {
fail("common modules must resolve PBS editor behavior through FrontendProvider.languageService(): " + violations);
}
}
}
}
@Test
void commonLspMustNotImportPbsImplementationPackages() throws IOException {
final var repoRoot = findRepoRoot(Path.of("").toAbsolutePath().normalize());
final var sourceRoot = repoRoot.resolve("prometeu-lsp/prometeu-lsp-v1/src/main/java");
final var prohibitedNeedles = List.of(
"p.studio.compiler.PBSFrontendLanguageService",
"p.studio.compiler.services.PBSFrontendPhaseService",
"p.studio.compiler.pbs",
"PbsAst",
"PbsEditorial");
try (final var files = Files.walk(sourceRoot)) {
final var violations = files
.filter(path -> path.toString().endsWith(".java"))
.filter(path -> prohibitedNeedles.stream().anyMatch(needle -> contains(path, needle)))
.toList();
if (!violations.isEmpty()) {
fail("common LSP code must consume generic frontend language-service contracts instead of PBS implementation packages: "
+ violations);
}
}
}
@Test @Test
void compileOnlyFrontendProviderMayOmitLanguageService() { void compileOnlyFrontendProviderMayOmitLanguageService() {
final FrontendProvider provider = new CompileOnlyFrontendProvider(); final FrontendProvider provider = new CompileOnlyFrontendProvider();
@@ -110,26 +28,6 @@ class FrontendProviderBoundaryTest {
BuildingIssueSink.empty())); BuildingIssueSink.empty()));
} }
private boolean contains(final Path path, final String needle) {
try {
return Files.readString(path).contains(needle);
} catch (IOException e) {
throw new IllegalStateException("failed to read " + path, e);
}
}
private Path findRepoRoot(final Path start) {
var current = start;
while (current != null) {
if (Files.exists(current.resolve("settings.gradle.kts"))) {
return current;
}
current = current.getParent();
}
fail("unable to locate repository root from " + start);
return start;
}
private static final class CompileOnlyFrontendProvider implements FrontendProvider { private static final class CompileOnlyFrontendProvider implements FrontendProvider {
private final FrontendSpec specification = FrontendSpec.builder() private final FrontendSpec specification = FrontendSpec.builder()
.languageId("compile-only") .languageId("compile-only")
@@ -43,8 +43,11 @@ class ValidationOwnershipSpecTest {
content.contains("Canonical host-binding identity"), content.contains("Canonical host-binding identity"),
"spec 19 matrix must include the host-admission split"); "spec 19 matrix must include the host-admission split");
assertTrue( assertTrue(
content.contains("MUST NOT import `p.studio.compiler.pbs`"), content.contains("MUST NOT depend on types from the PBS frontend module"),
"spec 19 must forbid PBS imports in platform validators"); "spec 19 must forbid PBS frontend module types in platform validators");
assertTrue(
content.contains("`p.studio.compiler.pbs` is not the complete boundary"),
"spec 19 must not treat package p.studio.compiler.pbs as the complete PBS boundary");
} }
@Test @Test
@@ -0,0 +1,81 @@
package p.studio.compiler.synth;
import p.studio.compiler.messages.BuildingIssueSink;
import p.studio.compiler.messages.FrontendPhaseContext;
import p.studio.compiler.models.IRBackend;
import p.studio.compiler.models.IRBackendExecutableFunction;
import p.studio.compiler.models.IRLifecycleCallableReference;
import p.studio.compiler.models.IRLifecycleCallableRole;
import p.studio.compiler.models.IRLifecycleDeclaration;
import p.studio.compiler.models.IRLifecycleModuleDeclaration;
import p.studio.compiler.services.FrontendPhaseService;
import p.studio.compiler.source.Span;
import p.studio.compiler.source.diagnostics.DiagnosticSink;
import p.studio.compiler.source.identifiers.CallableId;
import p.studio.compiler.source.identifiers.FileId;
import p.studio.compiler.source.identifiers.ModuleId;
import p.studio.compiler.source.tables.CallableSignatureRef;
import p.studio.compiler.source.tables.ModuleReference;
import p.studio.utilities.logs.LogAggregator;
import p.studio.utilities.structures.ReadOnlyList;
import java.util.concurrent.atomic.AtomicBoolean;
public final class SyntheticFrontendPhaseService implements FrontendPhaseService {
private final AtomicBoolean invoked = new AtomicBoolean();
public boolean invoked() {
return invoked.get();
}
@Override
public IRBackend compile(
final FrontendPhaseContext request,
final DiagnosticSink diagnostics,
final LogAggregator logs,
final BuildingIssueSink issues) {
invoked.set(true);
final var moduleId = new ModuleId(0);
final var fileId = new FileId(0);
final var callableId = new CallableId(0);
final var span = new Span(fileId, 0, 1);
final var frame = new IRBackendExecutableFunction(
fileId,
moduleId,
"frame",
callableId,
0,
1,
0,
0,
0,
1,
ReadOnlyList.from(new IRBackendExecutableFunction.Instruction(
IRBackendExecutableFunction.InstructionKind.RET,
"",
null,
null,
span)),
span);
final var frameRoot = new IRLifecycleCallableReference(
moduleId,
fileId,
callableId,
IRLifecycleCallableRole.FRAME_ROOT,
span);
return IRBackend.builder()
.entryPointCallableName("frame")
.entryPointModuleId(moduleId)
.modulePool(ReadOnlyList.from(new ModuleReference("synth", ReadOnlyList.from("main"))))
.callableSignatures(ReadOnlyList.from(
new CallableSignatureRef(moduleId, "frame", 0, "() -> unit")))
.executableFunctions(ReadOnlyList.from(frame))
.lifecycleDeclaration(new IRLifecycleDeclaration(
ReadOnlyList.from(new IRLifecycleModuleDeclaration(moduleId, ReadOnlyList.empty())),
null,
frameRoot))
.build();
}
}
@@ -0,0 +1,31 @@
package p.studio.compiler.synth;
import p.studio.compiler.models.FrontendSpec;
import p.studio.compiler.services.FrontendPhaseService;
import p.studio.compiler.services.FrontendProvider;
import p.studio.utilities.structures.ReadOnlySet;
public final class SyntheticFrontendProvider implements FrontendProvider {
public static final String LANGUAGE_ID = "synth";
private final FrontendSpec specification = FrontendSpec.builder()
.languageId(LANGUAGE_ID)
.allowedExtensions(ReadOnlySet.from("synth"))
.sourceRoots(ReadOnlySet.from("src"))
.build();
private final SyntheticFrontendPhaseService compiler = new SyntheticFrontendPhaseService();
@Override
public FrontendSpec specification() {
return specification;
}
@Override
public FrontendPhaseService compiler() {
return compiler;
}
public SyntheticFrontendPhaseService syntheticCompiler() {
return compiler;
}
}
@@ -0,0 +1,20 @@
package p.studio.compiler.services;
import java.nio.file.Path;
import java.util.Objects;
public record FrontendDefinitionLocation(
Path path,
int startOffset,
int endOffset) {
public FrontendDefinitionLocation {
path = Objects.requireNonNull(path, "path").toAbsolutePath().normalize();
if (startOffset < 0) {
throw new IllegalArgumentException("startOffset must not be negative");
}
if (endOffset < startOffset) {
throw new IllegalArgumentException("endOffset must not be before startOffset");
}
}
}
@@ -3,5 +3,13 @@ package p.studio.compiler.services;
public record FrontendEditorialContext( public record FrontendEditorialContext(
Object syntaxTree, Object syntaxTree,
Object supplementalDeclarations, Object supplementalDeclarations,
Object semanticContext) { Object semanticContext,
Object sourceFiles) {
public FrontendEditorialContext(
final Object syntaxTree,
final Object supplementalDeclarations,
final Object semanticContext) {
this(syntaxTree, supplementalDeclarations, semanticContext, null);
}
} }
@@ -59,4 +59,17 @@ public interface FrontendLanguageService {
final int offset) { final int offset) {
return signatureHelp(request, offset); return signatureHelp(request, offset);
} }
default List<FrontendDefinitionLocation> definition(
final FrontendDocumentRequest request,
final int offset) {
return List.of();
}
default List<FrontendDefinitionLocation> definition(
final FrontendDocumentRequest request,
final FrontendEditorialContext editorialContext,
final int offset) {
return definition(request, offset);
}
} }
@@ -22,6 +22,20 @@ class FrontendLanguageServiceTest {
assertTrue(service.completion(request, 0).isEmpty()); assertTrue(service.completion(request, 0).isEmpty());
assertTrue(service.hover(request, 0).isEmpty()); assertTrue(service.hover(request, 0).isEmpty());
assertEquals(FrontendSignatureHelp.empty(), service.signatureHelp(request, 0)); assertEquals(FrontendSignatureHelp.empty(), service.signatureHelp(request, 0));
assertTrue(service.definition(request, 0).isEmpty());
}
@Test
void definitionLocationRejectsBlankPathAndInvertedOffsets() {
final Path path = Path.of("src/main.pbs").toAbsolutePath();
final var location = new FrontendDefinitionLocation(path, 4, 9);
assertEquals(path.normalize(), location.path());
assertEquals(4, location.startOffset());
assertEquals(9, location.endOffset());
assertThrows(NullPointerException.class, () -> new FrontendDefinitionLocation(null, 0, 1));
assertThrows(IllegalArgumentException.class, () -> new FrontendDefinitionLocation(path, -1, 0));
assertThrows(IllegalArgumentException.class, () -> new FrontendDefinitionLocation(path, 5, 4));
} }
@Test @Test
@@ -62,7 +62,7 @@ public class FrontendRegistryService {
.toList(); .toList();
} }
static void register(final FrontendProvider provider) { public static void register(final FrontendProvider provider) {
final var languageId = provider.specification().getLanguageId(); final var languageId = provider.specification().getLanguageId();
if (FRONTEND_PROVIDERS.containsKey(languageId)) { if (FRONTEND_PROVIDERS.containsKey(languageId)) {
throw new IllegalArgumentException("Duplicate frontend languageId: " + languageId); throw new IllegalArgumentException("Duplicate frontend languageId: " + languageId);
@@ -71,6 +71,16 @@ public class FrontendRegistryService {
FRONTEND_PROVIDERS.put(languageId, provider); FRONTEND_PROVIDERS.put(languageId, provider);
} }
public static void unregister(final String languageId) {
if (languageId == null || languageId.isBlank()) {
return;
}
if (PBSDefinitions.PBS.getLanguageId().equals(languageId)) {
throw new IllegalArgumentException("Cannot unregister the default PBS frontend: " + languageId);
}
FRONTEND_PROVIDERS.remove(languageId);
}
private static void registerIfAbsent(final FrontendProvider provider) { private static void registerIfAbsent(final FrontendProvider provider) {
FRONTEND_PROVIDERS.putIfAbsent(provider.specification().getLanguageId(), provider); FRONTEND_PROVIDERS.putIfAbsent(provider.specification().getLanguageId(), provider);
} }
@@ -1,6 +1,15 @@
package p.studio.compiler; package p.studio.compiler;
import org.junit.jupiter.api.Test; import org.junit.jupiter.api.Test;
import p.studio.compiler.messages.BuildingIssueSink;
import p.studio.compiler.messages.FrontendPhaseContext;
import p.studio.compiler.models.FrontendSpec;
import p.studio.compiler.models.IRBackend;
import p.studio.compiler.services.FrontendPhaseService;
import p.studio.compiler.services.FrontendProvider;
import p.studio.compiler.source.diagnostics.DiagnosticSink;
import p.studio.utilities.logs.LogAggregator;
import p.studio.utilities.structures.ReadOnlySet;
import static org.junit.jupiter.api.Assertions.assertEquals; import static org.junit.jupiter.api.Assertions.assertEquals;
import static org.junit.jupiter.api.Assertions.assertSame; import static org.junit.jupiter.api.Assertions.assertSame;
@@ -41,4 +50,89 @@ class FrontendRegistryServiceTest {
assertEquals(1, providers.size()); assertEquals(1, providers.size());
assertEquals(PBSDefinitions.PBS.getLanguageId(), providers.getFirst().specification().getLanguageId()); assertEquals(PBSDefinitions.PBS.getLanguageId(), providers.getFirst().specification().getLanguageId());
} }
@Test
void registerShouldResolveAndUnregisterTemporaryProvider() {
final var provider = new TemporaryFrontendProvider("registry-temp");
FrontendRegistryService.register(provider);
try {
assertSame(provider, FrontendRegistryService.require("registry-temp"));
assertEquals(2, FrontendRegistryService.listProviders().size());
} finally {
FrontendRegistryService.unregister("registry-temp");
}
assertEquals(1, FrontendRegistryService.listProviders().size());
assertEquals(PBSDefinitions.PBS.getLanguageId(),
FrontendRegistryService.listProviders().getFirst().specification().getLanguageId());
}
@Test
void registerShouldRejectDuplicateLanguageId() {
final var provider = new TemporaryFrontendProvider("registry-dup");
FrontendRegistryService.register(provider);
try {
final var thrown = assertThrows(
IllegalArgumentException.class,
() -> FrontendRegistryService.register(new TemporaryFrontendProvider("registry-dup")));
assertTrue(thrown.getMessage().contains("registry-dup"));
} finally {
FrontendRegistryService.unregister("registry-dup");
}
}
@Test
void unregisterMustRefuseToRemoveDefaultPbs() {
final var thrown = assertThrows(
IllegalArgumentException.class,
() -> FrontendRegistryService.unregister(PBSDefinitions.PBS.getLanguageId()));
assertTrue(thrown.getMessage().contains(PBSDefinitions.PBS.getLanguageId()));
assertEquals(1, FrontendRegistryService.listProviders().size());
assertSame(
PBSDefinitions.PBS,
FrontendRegistryService.require(PBSDefinitions.PBS.getLanguageId()).specification());
}
@Test
void unregisterUnknownLanguageIdMustBeNoOp() {
FrontendRegistryService.unregister(null);
FrontendRegistryService.unregister(" ");
FrontendRegistryService.unregister("unknown-language");
assertEquals(1, FrontendRegistryService.listProviders().size());
assertEquals(PBSDefinitions.PBS.getLanguageId(),
FrontendRegistryService.listProviders().getFirst().specification().getLanguageId());
}
private static final class TemporaryFrontendProvider implements FrontendProvider {
private final FrontendSpec specification;
private TemporaryFrontendProvider(final String languageId) {
this.specification = FrontendSpec.builder()
.languageId(languageId)
.allowedExtensions(ReadOnlySet.from("tmp"))
.sourceRoots(ReadOnlySet.from("src"))
.build();
}
@Override
public FrontendSpec specification() {
return specification;
}
@Override
public FrontendPhaseService compiler() {
return new FrontendPhaseService() {
@Override
public IRBackend compile(
final FrontendPhaseContext request,
final DiagnosticSink diagnostics,
final LogAggregator logs,
final BuildingIssueSink issues) {
return IRBackend.builder().build();
}
};
}
}
} }
@@ -7,7 +7,6 @@ dependencies {
implementation(project(":prometeu-compiler:prometeu-compiler-core")) implementation(project(":prometeu-compiler:prometeu-compiler-core"))
implementation(project(":prometeu-compiler:prometeu-frontend-api")) implementation(project(":prometeu-compiler:prometeu-frontend-api"))
implementation(project(":prometeu-compiler:prometeu-build-pipeline")) implementation(project(":prometeu-compiler:prometeu-build-pipeline"))
implementation(project(":prometeu-compiler:frontends:prometeu-frontend-pbs"))
implementation(project(":prometeu-compiler:prometeu-frontend-registry")) implementation(project(":prometeu-compiler:prometeu-frontend-registry"))
implementation(project(":prometeu-compiler:prometeu-deps")) implementation(project(":prometeu-compiler:prometeu-deps"))
implementation(libs.lsp4j) implementation(libs.lsp4j)
@@ -0,0 +1,15 @@
package p.studio.lsp.messages;
import java.util.List;
public record BaselineDefinition(
List<BaselineDefinitionLocation> locations) {
public BaselineDefinition {
locations = locations == null ? List.of() : List.copyOf(locations);
}
public static BaselineDefinition empty() {
return new BaselineDefinition(List.of());
}
}
@@ -0,0 +1,28 @@
package p.studio.lsp.messages;
import java.util.Objects;
public record BaselineDefinitionLocation(
String uri,
int startLine,
int startCharacter,
int endLine,
int endCharacter) {
public BaselineDefinitionLocation {
uri = requireText(uri, "uri");
if (startLine < 0 || startCharacter < 0 || endLine < 0 || endCharacter < 0) {
throw new IllegalArgumentException("definition range coordinates must not be negative");
}
}
private static String requireText(
final String value,
final String field) {
final String candidate = Objects.requireNonNull(value, field).trim();
if (candidate.isEmpty()) {
throw new IllegalArgumentException(field + " must not be blank");
}
return candidate;
}
}
@@ -10,6 +10,7 @@ public record BaselineServerDescription(
boolean hoverSupported, boolean hoverSupported,
boolean completionSupported, boolean completionSupported,
boolean signatureHelpSupported, boolean signatureHelpSupported,
boolean definitionSupported,
List<String> semanticTokenTypes, List<String> semanticTokenTypes,
List<BaselineSemanticHostProjection> semanticHostProjections, List<BaselineSemanticHostProjection> semanticHostProjections,
List<BaselineVisualTheme> visualThemes, List<BaselineVisualTheme> visualThemes,
@@ -2,6 +2,7 @@ package p.studio.lsp.services;
import p.studio.lsp.messages.BaselineDocumentAnalysis; import p.studio.lsp.messages.BaselineDocumentAnalysis;
import p.studio.lsp.messages.BaselineCompletion; import p.studio.lsp.messages.BaselineCompletion;
import p.studio.lsp.messages.BaselineDefinition;
import p.studio.lsp.messages.BaselineHover; import p.studio.lsp.messages.BaselineHover;
import p.studio.lsp.messages.BaselineSemanticTokens; import p.studio.lsp.messages.BaselineSemanticTokens;
import p.studio.lsp.messages.BaselineSignatureHelp; import p.studio.lsp.messages.BaselineSignatureHelp;
@@ -17,6 +18,8 @@ public interface LanguageServiceBridge {
BaselineHover hover(LspProjectContext context, String documentUri, String text, int line, int character); BaselineHover hover(LspProjectContext context, String documentUri, String text, int line, int character);
BaselineDefinition definition(LspProjectContext context, String documentUri, String text, int line, int character);
BaselineSignatureHelp signatureHelp(LspProjectContext context, String documentUri, String text, int line, int character); BaselineSignatureHelp signatureHelp(LspProjectContext context, String documentUri, String text, int line, int character);
BaselineSemanticTokens semanticTokens(LspProjectContext context, String documentUri, String text); BaselineSemanticTokens semanticTokens(LspProjectContext context, String documentUri, String text);
@@ -5,6 +5,7 @@ import p.studio.compiler.FrontendRegistryService;
import p.studio.compiler.messages.*; import p.studio.compiler.messages.*;
import p.studio.compiler.models.*; import p.studio.compiler.models.*;
import p.studio.compiler.services.FrontendCompletionCandidate; import p.studio.compiler.services.FrontendCompletionCandidate;
import p.studio.compiler.services.FrontendDefinitionLocation;
import p.studio.compiler.services.FrontendDocumentRequest; import p.studio.compiler.services.FrontendDocumentRequest;
import p.studio.compiler.services.FrontendEditorialContext; import p.studio.compiler.services.FrontendEditorialContext;
import p.studio.compiler.services.FrontendHover; import p.studio.compiler.services.FrontendHover;
@@ -21,6 +22,8 @@ import p.studio.lsp.services.LanguageServiceBridge;
import p.studio.utilities.logs.LogAggregator; import p.studio.utilities.logs.LogAggregator;
import java.net.URI; import java.net.URI;
import java.nio.charset.StandardCharsets;
import java.nio.file.Files;
import java.nio.file.Path; import java.nio.file.Path;
import java.util.*; import java.util.*;
import java.util.function.Function; import java.util.function.Function;
@@ -49,6 +52,7 @@ public final class CompilerLanguageServiceBridge implements LanguageServiceBridg
true, true,
true, true,
true, true,
frontendProvider(context).languageService().isPresent(),
presentation.semanticKeys(), presentation.semanticKeys(),
presentation.hostProjections().stream().map(this::mapSemanticHostProjection).toList(), presentation.hostProjections().stream().map(this::mapSemanticHostProjection).toList(),
presentation.themes().stream().map(this::mapVisualTheme).toList(), presentation.themes().stream().map(this::mapVisualTheme).toList(),
@@ -87,13 +91,9 @@ public final class CompilerLanguageServiceBridge implements LanguageServiceBridg
context.projectRoot(), context.projectRoot(),
normalizeDocumentPath(documentUri), normalizeDocumentPath(documentUri),
document.text()); document.text());
final FrontendEditorialContext editorialContext = new FrontendEditorialContext(
document.editorialContext().syntaxTree(),
document.editorialContext().supplementalDeclarations(),
document.editorialContext().semanticContext());
final List<FrontendCompletionCandidate> candidates = languageService.orElseThrow().completion( final List<FrontendCompletionCandidate> candidates = languageService.orElseThrow().completion(
request, request,
editorialContext, document.editorialContext(),
offset); offset);
return new BaselineCompletion( return new BaselineCompletion(
false, false,
@@ -122,19 +122,47 @@ public final class CompilerLanguageServiceBridge implements LanguageServiceBridg
context.projectRoot(), context.projectRoot(),
normalizeDocumentPath(documentUri), normalizeDocumentPath(documentUri),
document.text()); document.text());
final FrontendEditorialContext editorialContext = new FrontendEditorialContext(
document.editorialContext().syntaxTree(),
document.editorialContext().supplementalDeclarations(),
document.editorialContext().semanticContext());
return languageService.orElseThrow().hover( return languageService.orElseThrow().hover(
request, request,
editorialContext, document.editorialContext(),
offset); offset);
}) })
.map(symbol -> new BaselineHover(formatHoverMarkdown(symbol))) .map(symbol -> new BaselineHover(formatHoverMarkdown(symbol)))
.orElseGet(() -> new BaselineHover("No symbol information.")); .orElseGet(() -> new BaselineHover("No symbol information."));
} }
@Override
public BaselineDefinition definition(
final LspProjectContext context,
final String documentUri,
final String text,
final int line,
final int character) {
Objects.requireNonNull(context, "context");
final var provider = frontendProvider(context);
final var languageService = provider.languageService();
if (languageService.isEmpty()) {
return BaselineDefinition.empty();
}
return editorialDocument(context, documentUri, text)
.map(document -> {
final int offset = new DocumentPositionMapper(document.text()).byteOffsetOf(line, character);
final FrontendDocumentRequest request = new FrontendDocumentRequest(
context.projectRoot(),
normalizeDocumentPath(documentUri),
document.text());
final List<FrontendDefinitionLocation> locations = languageService.orElseThrow().definition(
request,
document.editorialContext(),
offset);
return new BaselineDefinition(mapDefinitionLocations(
locations,
request.documentPath(),
document.text()));
})
.orElseGet(BaselineDefinition::empty);
}
@Override @Override
public BaselineSignatureHelp signatureHelp( public BaselineSignatureHelp signatureHelp(
final LspProjectContext context, final LspProjectContext context,
@@ -155,13 +183,9 @@ public final class CompilerLanguageServiceBridge implements LanguageServiceBridg
context.projectRoot(), context.projectRoot(),
normalizeDocumentPath(documentUri), normalizeDocumentPath(documentUri),
document.text()); document.text());
final FrontendEditorialContext editorialContext = new FrontendEditorialContext(
document.editorialContext().syntaxTree(),
document.editorialContext().supplementalDeclarations(),
document.editorialContext().semanticContext());
return languageService.orElseThrow().signatureHelp( return languageService.orElseThrow().signatureHelp(
request, request,
editorialContext, document.editorialContext(),
offset); offset);
}) })
.map(this::mapSignatureHelp) .map(this::mapSignatureHelp)
@@ -418,6 +442,46 @@ public final class CompilerLanguageServiceBridge implements LanguageServiceBridg
}; };
} }
private List<BaselineDefinitionLocation> mapDefinitionLocations(
final List<FrontendDefinitionLocation> locations,
final Path currentDocumentPath,
final String currentDocumentText) {
if (locations == null || locations.isEmpty()) {
return List.of();
}
final ArrayList<BaselineDefinitionLocation> mapped = new ArrayList<>();
for (final FrontendDefinitionLocation location : locations) {
final String targetText = textForDefinitionTarget(location.path(), currentDocumentPath, currentDocumentText);
if (targetText == null) {
continue;
}
final DocumentPositionMapper mapper = new DocumentPositionMapper(targetText);
final DocumentPosition start = mapper.positionOf(location.startOffset());
final DocumentPosition end = mapper.positionOf(location.endOffset());
mapped.add(new BaselineDefinitionLocation(
location.path().toUri().toString(),
start.line(),
start.character(),
end.line(),
end.character()));
}
return List.copyOf(mapped);
}
private String textForDefinitionTarget(
final Path path,
final Path currentDocumentPath,
final String currentDocumentText) {
if (path.equals(currentDocumentPath)) {
return currentDocumentText == null ? "" : currentDocumentText;
}
try {
return Files.readString(path, StandardCharsets.UTF_8);
} catch (final Exception ignored) {
return null;
}
}
private String formatHoverMarkdown(final FrontendHover symbol) { private String formatHoverMarkdown(final FrontendHover symbol) {
final StringBuilder markdown = new StringBuilder(); final StringBuilder markdown = new StringBuilder();
final List<FrontendSignature> signatures = symbol.signatures(); final List<FrontendSignature> signatures = symbol.signatures();
@@ -97,6 +97,20 @@ public final class PrometeuTextDocumentService implements TextDocumentService {
params.getPosition().getCharacter()))); params.getPosition().getCharacter())));
} }
@Override
public CompletableFuture<Either<List<? extends Location>, List<? extends LocationLink>>> definition(
final DefinitionParams params) {
final String uri = params.getTextDocument().getUri();
final String text = documentTextByUri.get(uri);
final List<Location> locations = protocolMessageMapper.mapDefinition(languageServiceBridge.definition(
project,
uri,
text,
params.getPosition().getLine(),
params.getPosition().getCharacter()));
return CompletableFuture.completedFuture(Either.forLeft(locations));
}
@Override @Override
public CompletableFuture<SignatureHelp> signatureHelp(final SignatureHelpParams params) { public CompletableFuture<SignatureHelp> signatureHelp(final SignatureHelpParams params) {
final String uri = params.getTextDocument().getUri(); final String uri = params.getTextDocument().getUri();
@@ -36,6 +36,7 @@ public final class Lsp4jProtocolMessageMapper implements ProtocolMessageMapper {
signatureHelpOptions.setRetriggerCharacters(List.of(",")); signatureHelpOptions.setRetriggerCharacters(List.of(","));
capabilities.setSignatureHelpProvider(signatureHelpOptions); capabilities.setSignatureHelpProvider(signatureHelpOptions);
} }
capabilities.setDefinitionProvider(description.definitionSupported());
final SemanticTokensWithRegistrationOptions semanticTokens = new SemanticTokensWithRegistrationOptions(); final SemanticTokensWithRegistrationOptions semanticTokens = new SemanticTokensWithRegistrationOptions();
semanticTokens.setLegend(new SemanticTokensLegend(description.semanticTokenTypes(), List.of())); semanticTokens.setLegend(new SemanticTokensLegend(description.semanticTokenTypes(), List.of()));
semanticTokens.setFull(true); semanticTokens.setFull(true);
@@ -83,6 +84,20 @@ public final class Lsp4jProtocolMessageMapper implements ProtocolMessageMapper {
return result; return result;
} }
@Override
public List<Location> mapDefinition(final BaselineDefinition definition) {
if (definition == null || definition.locations().isEmpty()) {
return List.of();
}
return definition.locations().stream()
.map(location -> new Location(
location.uri(),
new Range(
new Position(location.startLine(), location.startCharacter()),
new Position(location.endLine(), location.endCharacter()))))
.toList();
}
@Override @Override
public CompletionList mapCompletion(final BaselineCompletion completion) { public CompletionList mapCompletion(final BaselineCompletion completion) {
final CompletionList list = new CompletionList(); final CompletionList list = new CompletionList();
@@ -6,14 +6,18 @@ import org.eclipse.lsp4j.MessageParams;
import org.eclipse.lsp4j.PublishDiagnosticsParams; import org.eclipse.lsp4j.PublishDiagnosticsParams;
import org.eclipse.lsp4j.SignatureHelp; import org.eclipse.lsp4j.SignatureHelp;
import org.eclipse.lsp4j.SemanticTokens; import org.eclipse.lsp4j.SemanticTokens;
import org.eclipse.lsp4j.Location;
import p.studio.lsp.messages.BaselineDocumentAnalysis; import p.studio.lsp.messages.BaselineDocumentAnalysis;
import p.studio.lsp.messages.BaselineCompletion; import p.studio.lsp.messages.BaselineCompletion;
import p.studio.lsp.messages.BaselineDefinition;
import p.studio.lsp.messages.BaselineHover; import p.studio.lsp.messages.BaselineHover;
import p.studio.lsp.messages.BaselineSemanticTokens; import p.studio.lsp.messages.BaselineSemanticTokens;
import p.studio.lsp.messages.BaselineSignatureHelp; import p.studio.lsp.messages.BaselineSignatureHelp;
import p.studio.lsp.messages.BaselineServerDescription; import p.studio.lsp.messages.BaselineServerDescription;
import org.eclipse.lsp4j.CompletionList; import org.eclipse.lsp4j.CompletionList;
import java.util.List;
public interface ProtocolMessageMapper { public interface ProtocolMessageMapper {
InitializeResult mapInitializeResult(BaselineServerDescription description); InitializeResult mapInitializeResult(BaselineServerDescription description);
@@ -23,6 +27,8 @@ public interface ProtocolMessageMapper {
Hover mapHover(BaselineHover hover); Hover mapHover(BaselineHover hover);
List<Location> mapDefinition(BaselineDefinition definition);
CompletionList mapCompletion(BaselineCompletion completion); CompletionList mapCompletion(BaselineCompletion completion);
SignatureHelp mapSignatureHelp(BaselineSignatureHelp signatureHelp); SignatureHelp mapSignatureHelp(BaselineSignatureHelp signatureHelp);
@@ -45,6 +45,9 @@ class CompilerLanguageServiceBridgeTest {
assertEquals(0, signatureHelp.activeSignature()); assertEquals(0, signatureHelp.activeSignature());
assertEquals(0, signatureHelp.activeParameter()); assertEquals(0, signatureHelp.activeParameter());
final var definition = bridge.definition(context, documentUri, "fn main() {}", 0, 0);
assertTrue(definition.locations().isEmpty());
final var semanticTokens = bridge.semanticTokens(context, documentUri, "fn main() {}"); final var semanticTokens = bridge.semanticTokens(context, documentUri, "fn main() {}");
assertTrue(semanticTokens.legend().isEmpty()); assertTrue(semanticTokens.legend().isEmpty());
assertTrue(semanticTokens.tokens().isEmpty()); assertTrue(semanticTokens.tokens().isEmpty());
@@ -309,6 +312,91 @@ class CompilerLanguageServiceBridgeTest {
assertTrue(helper.documentation().contains("- returns `42`")); assertTrue(helper.documentation().contains("- returns `42`"));
} }
@Test
void definitionUsesEditorialLookupAndPhysicalStdlibFiles() {
final Path projectRoot = findRepoRoot(Path.of("").toAbsolutePath().normalize())
.resolve("test-projects")
.resolve("main")
.toAbsolutePath()
.normalize();
final Path documentPath = projectRoot.resolve("src").resolve("main.pbs");
final String overlay = """
import { Gfx } from @sdk:gfx;
declare struct Vec() {
fn blend(dx: int, dy: int) -> int { return dx; }
}
fn helper() -> int { return 42; }
fn frame(vec: Vec) -> void {
helper();
vec.blend(1, 2);
Gfx.clear(5);
let n: int = 1;
n;
}
""";
final CompilerLanguageServiceBridge bridge = new CompilerLanguageServiceBridge();
final LspProjectContext context = new LspProjectContext("main", "pbs", projectRoot);
final DocumentPositionMapper mapper = new DocumentPositionMapper(overlay);
final var helperUse = mapper.positionOf(overlay.indexOf("helper();"));
final var helperDefinition = bridge.definition(
context,
documentPath.toUri().toString(),
overlay,
helperUse.line(),
helperUse.character());
assertEquals(1, helperDefinition.locations().size());
assertEquals(documentPath.toUri().toString(), helperDefinition.locations().getFirst().uri());
assertTrue(helperDefinition.locations().getFirst().startLine() < helperUse.line());
final var blendUse = mapper.positionOf(overlay.indexOf("blend(1"));
final var blendDefinition = bridge.definition(
context,
documentPath.toUri().toString(),
overlay,
blendUse.line(),
blendUse.character());
assertEquals(1, blendDefinition.locations().size());
assertEquals(documentPath.toUri().toString(), blendDefinition.locations().getFirst().uri());
final var clearUse = mapper.positionOf(overlay.indexOf("clear"));
final var clearHover = bridge.hover(
context,
documentPath.toUri().toString(),
overlay,
clearUse.line(),
clearUse.character());
assertTrue(clearHover.markdown().contains("clear(color:"));
final var clearDefinition = bridge.definition(
context,
documentPath.toUri().toString(),
overlay,
clearUse.line(),
clearUse.character());
assertTrue(
clearDefinition.locations().isEmpty(),
"stdlib is loaded from a virtual path, so definition stays empty until a physical file exists");
final var builtinUse = mapper.positionOf(overlay.indexOf("int = 1"));
final var builtinHover = bridge.hover(
context,
documentPath.toUri().toString(),
overlay,
builtinUse.line(),
builtinUse.character());
assertTrue(builtinHover.markdown().contains("builtin"));
final var builtinDefinition = bridge.definition(
context,
documentPath.toUri().toString(),
overlay,
builtinUse.line(),
builtinUse.character());
assertTrue(builtinDefinition.locations().isEmpty());
}
@Test @Test
void describeServerPublishesFrontendVisualThemes() { void describeServerPublishesFrontendVisualThemes() {
final CompilerLanguageServiceBridge bridge = new CompilerLanguageServiceBridge(); final CompilerLanguageServiceBridge bridge = new CompilerLanguageServiceBridge();
@@ -319,6 +407,7 @@ class CompilerLanguageServiceBridgeTest {
assertEquals("pbs-default", description.activeVisualThemeId()); assertEquals("pbs-default", description.activeVisualThemeId());
assertTrue(description.completionSupported()); assertTrue(description.completionSupported());
assertTrue(description.signatureHelpSupported()); assertTrue(description.signatureHelpSupported());
assertTrue(description.definitionSupported());
assertEquals(1, description.semanticHostProjections().size()); assertEquals(1, description.semanticHostProjections().size());
assertEquals("vscode", description.semanticHostProjections().getFirst().hostId()); assertEquals("vscode", description.semanticHostProjections().getFirst().hostId());
assertTrue(description.semanticHostProjections().getFirst().tokenProjections().stream() assertTrue(description.semanticHostProjections().getFirst().tokenProjections().stream()
@@ -15,6 +15,7 @@ import org.junit.jupiter.api.Test;
import p.studio.lsp.messages.BaselineCompletion; import p.studio.lsp.messages.BaselineCompletion;
import p.studio.lsp.messages.BaselineCompletionItem; import p.studio.lsp.messages.BaselineCompletionItem;
import p.studio.lsp.messages.BaselineCompletionItemKind; import p.studio.lsp.messages.BaselineCompletionItemKind;
import p.studio.lsp.messages.BaselineDefinition;
import p.studio.lsp.messages.BaselineDocumentAnalysis; import p.studio.lsp.messages.BaselineDocumentAnalysis;
import p.studio.lsp.messages.BaselineEditorPalette; import p.studio.lsp.messages.BaselineEditorPalette;
import p.studio.lsp.messages.BaselineHover; import p.studio.lsp.messages.BaselineHover;
@@ -98,6 +99,7 @@ class PrometeuLanguageServerTest {
true, true,
true, true,
true, true,
true,
List.of(), List.of(),
List.of(new BaselineSemanticHostProjection( List.of(new BaselineSemanticHostProjection(
"vscode", "vscode",
@@ -145,6 +147,16 @@ class PrometeuLanguageServerTest {
return new BaselineHover("hover"); return new BaselineHover("hover");
} }
@Override
public BaselineDefinition definition(
final LspProjectContext project,
final String documentUri,
final String text,
final int line,
final int character) {
return BaselineDefinition.empty();
}
@Override @Override
public BaselineSignatureHelp signatureHelp( public BaselineSignatureHelp signatureHelp(
final LspProjectContext project, final LspProjectContext project,
@@ -191,6 +203,11 @@ class PrometeuLanguageServerTest {
throw new UnsupportedOperationException(); throw new UnsupportedOperationException();
} }
@Override
public java.util.List<org.eclipse.lsp4j.Location> mapDefinition(final BaselineDefinition definition) {
throw new UnsupportedOperationException();
}
@Override @Override
public org.eclipse.lsp4j.CompletionList mapCompletion(final BaselineCompletion completion) { public org.eclipse.lsp4j.CompletionList mapCompletion(final BaselineCompletion completion) {
throw new UnsupportedOperationException(); throw new UnsupportedOperationException();
@@ -3,9 +3,11 @@ package p.studio.lsp.services.protocol;
import org.eclipse.lsp4j.CompletionItem; import org.eclipse.lsp4j.CompletionItem;
import org.eclipse.lsp4j.CompletionList; import org.eclipse.lsp4j.CompletionList;
import org.eclipse.lsp4j.CompletionParams; import org.eclipse.lsp4j.CompletionParams;
import org.eclipse.lsp4j.DefinitionParams;
import org.eclipse.lsp4j.DidOpenTextDocumentParams; import org.eclipse.lsp4j.DidOpenTextDocumentParams;
import org.eclipse.lsp4j.Hover; import org.eclipse.lsp4j.Hover;
import org.eclipse.lsp4j.HoverParams; import org.eclipse.lsp4j.HoverParams;
import org.eclipse.lsp4j.Location;
import org.eclipse.lsp4j.MarkupContent; import org.eclipse.lsp4j.MarkupContent;
import org.eclipse.lsp4j.Position; import org.eclipse.lsp4j.Position;
import org.eclipse.lsp4j.SignatureHelp; import org.eclipse.lsp4j.SignatureHelp;
@@ -16,6 +18,8 @@ import org.junit.jupiter.api.Test;
import p.studio.lsp.messages.BaselineCompletion; import p.studio.lsp.messages.BaselineCompletion;
import p.studio.lsp.messages.BaselineCompletionItem; import p.studio.lsp.messages.BaselineCompletionItem;
import p.studio.lsp.messages.BaselineCompletionItemKind; import p.studio.lsp.messages.BaselineCompletionItemKind;
import p.studio.lsp.messages.BaselineDefinition;
import p.studio.lsp.messages.BaselineDefinitionLocation;
import p.studio.lsp.messages.BaselineDocumentAnalysis; import p.studio.lsp.messages.BaselineDocumentAnalysis;
import p.studio.lsp.messages.BaselineHover; import p.studio.lsp.messages.BaselineHover;
import p.studio.lsp.messages.BaselineSemanticTokens; import p.studio.lsp.messages.BaselineSemanticTokens;
@@ -77,6 +81,14 @@ final class PrometeuTextDocumentServiceTest {
assertEquals(1, bridge.lastSignatureHelpLine); assertEquals(1, bridge.lastSignatureHelpLine);
assertEquals(6, bridge.lastSignatureHelpCharacter); assertEquals(6, bridge.lastSignatureHelpCharacter);
assertTrue(mapper.mappedSignatureHelp.signatures().getFirst().label().contains("demo")); assertTrue(mapper.mappedSignatureHelp.signatures().getFirst().label().contains("demo"));
final var definition = service.definition(new DefinitionParams(
new TextDocumentIdentifier(uri),
new Position(1, 2))).join();
assertSame(mapper.definitionLocations, definition.getLeft());
assertEquals(text, bridge.lastDefinitionText);
assertEquals(1, bridge.lastDefinitionLine);
assertEquals(2, bridge.lastDefinitionCharacter);
} }
private static final class RecordingBridge implements LanguageServiceBridge { private static final class RecordingBridge implements LanguageServiceBridge {
@@ -84,6 +96,9 @@ final class PrometeuTextDocumentServiceTest {
private int lastCompletionLine; private int lastCompletionLine;
private int lastCompletionCharacter; private int lastCompletionCharacter;
private String lastHoverText; private String lastHoverText;
private String lastDefinitionText;
private int lastDefinitionLine;
private int lastDefinitionCharacter;
private String lastSignatureHelpText; private String lastSignatureHelpText;
private int lastSignatureHelpLine; private int lastSignatureHelpLine;
private int lastSignatureHelpCharacter; private int lastSignatureHelpCharacter;
@@ -123,6 +138,19 @@ final class PrometeuTextDocumentServiceTest {
return new BaselineHover("hover"); return new BaselineHover("hover");
} }
@Override
public BaselineDefinition definition(
final LspProjectContext context,
final String documentUri,
final String text,
final int line,
final int character) {
lastDefinitionText = text;
lastDefinitionLine = line;
lastDefinitionCharacter = character;
return new BaselineDefinition(List.of(new BaselineDefinitionLocation(documentUri, 0, 0, 0, 6)));
}
@Override @Override
public BaselineSignatureHelp signatureHelp( public BaselineSignatureHelp signatureHelp(
final LspProjectContext context, final LspProjectContext context,
@@ -151,6 +179,7 @@ final class PrometeuTextDocumentServiceTest {
private static final class RecordingMapper implements ProtocolMessageMapper { private static final class RecordingMapper implements ProtocolMessageMapper {
private final CompletionList completionList = new CompletionList(false, List.of(new CompletionItem("demo"))); private final CompletionList completionList = new CompletionList(false, List.of(new CompletionItem("demo")));
private final SignatureHelp signatureHelp = new SignatureHelp(); private final SignatureHelp signatureHelp = new SignatureHelp();
private final List<Location> definitionLocations = List.of();
private BaselineSignatureHelp mappedSignatureHelp; private BaselineSignatureHelp mappedSignatureHelp;
@Override @Override
@@ -178,6 +207,11 @@ final class PrometeuTextDocumentServiceTest {
return new Hover(content); return new Hover(content);
} }
@Override
public List<Location> mapDefinition(final BaselineDefinition definition) {
return definitionLocations;
}
@Override @Override
public CompletionList mapCompletion(final BaselineCompletion completion) { public CompletionList mapCompletion(final BaselineCompletion completion) {
return completionList; return completionList;
@@ -6,6 +6,8 @@ import org.junit.jupiter.api.Test;
import p.studio.lsp.messages.BaselineCompletion; import p.studio.lsp.messages.BaselineCompletion;
import p.studio.lsp.messages.BaselineCompletionItem; import p.studio.lsp.messages.BaselineCompletionItem;
import p.studio.lsp.messages.BaselineCompletionItemKind; import p.studio.lsp.messages.BaselineCompletionItemKind;
import p.studio.lsp.messages.BaselineDefinition;
import p.studio.lsp.messages.BaselineDefinitionLocation;
import p.studio.lsp.messages.BaselineEditorPalette; import p.studio.lsp.messages.BaselineEditorPalette;
import p.studio.lsp.messages.BaselineSemanticHostProjection; import p.studio.lsp.messages.BaselineSemanticHostProjection;
import p.studio.lsp.messages.BaselineSemanticHostProjectionEntry; import p.studio.lsp.messages.BaselineSemanticHostProjectionEntry;
@@ -35,6 +37,7 @@ final class Lsp4jProtocolMessageMapperTest {
true, true,
true, true,
true, true,
true,
List.of("demo-keyword"), List.of("demo-keyword"),
List.of(new BaselineSemanticHostProjection( List.of(new BaselineSemanticHostProjection(
"vscode", "vscode",
@@ -55,6 +58,7 @@ final class Lsp4jProtocolMessageMapperTest {
assertEquals(List.of("."), result.getCapabilities().getCompletionProvider().getTriggerCharacters()); assertEquals(List.of("."), result.getCapabilities().getCompletionProvider().getTriggerCharacters());
assertEquals(List.of("(", ","), result.getCapabilities().getSignatureHelpProvider().getTriggerCharacters()); assertEquals(List.of("(", ","), result.getCapabilities().getSignatureHelpProvider().getTriggerCharacters());
assertEquals(Boolean.TRUE, result.getCapabilities().getDefinitionProvider().getLeft());
final var experimental = assertInstanceOf(Map.class, result.getCapabilities().getExperimental()); final var experimental = assertInstanceOf(Map.class, result.getCapabilities().getExperimental());
final var semanticPayload = assertInstanceOf(Map.class, experimental.get("prometeuSemanticHostProjections")); final var semanticPayload = assertInstanceOf(Map.class, experimental.get("prometeuSemanticHostProjections"));
@@ -104,4 +108,17 @@ final class Lsp4jProtocolMessageMapperTest {
assertEquals("left: int", signatureHelp.getSignatures().getFirst().getParameters().getFirst().getLabel().getLeft()); assertEquals("left: int", signatureHelp.getSignatures().getFirst().getParameters().getFirst().getLabel().getLeft());
assertEquals(1, signatureHelp.getActiveParameter()); assertEquals(1, signatureHelp.getActiveParameter());
} }
@Test
void definitionMapsPhysicalFileLocations() {
final var mapper = new Lsp4jProtocolMessageMapper();
final var locations = mapper.mapDefinition(new BaselineDefinition(List.of(
new BaselineDefinitionLocation("file:///tmp/demo.pbs", 2, 3, 2, 9))));
assertEquals(1, locations.size());
assertEquals("file:///tmp/demo.pbs", locations.getFirst().getUri());
assertEquals(2, locations.getFirst().getRange().getStart().getLine());
assertEquals(3, locations.getFirst().getRange().getStart().getCharacter());
assertEquals(9, locations.getFirst().getRange().getEnd().getCharacter());
assertTrue(mapper.mapDefinition(BaselineDefinition.empty()).isEmpty());
}
} }
-1
View File
@@ -14,7 +14,6 @@ dependencies {
implementation(libs.javafx.controls) implementation(libs.javafx.controls)
implementation(libs.javafx.fxml) implementation(libs.javafx.fxml)
implementation(libs.richtextfx) implementation(libs.richtextfx)
testImplementation(project(":prometeu-compiler:frontends:prometeu-frontend-pbs"))
testImplementation(project(":prometeu-packer:prometeu-packer-v1")) testImplementation(project(":prometeu-packer:prometeu-packer-v1"))
} }
+2
View File
@@ -22,3 +22,5 @@ include("prometeu-compiler:prometeu-frontend-registry")
include("prometeu-studio") include("prometeu-studio")
include("prometeu-app") include("prometeu-app")
include("prometeu-architecture-tests")