Compare commits
15
Commits
| Author | SHA1 | Date | |
|---|---|---|---|
|
|
ae891262e1
|
||
|
|
6f45f4f205 | ||
|
|
65d2d40310
|
||
|
|
fa21a029ae | ||
|
|
12e2a4edcc
|
||
|
|
78d10cf03c | ||
|
|
5d3d48e802
|
||
|
|
331ad752d1 | ||
|
|
9458312d73
|
||
|
|
4b72b2a0dd | ||
|
|
c2112f6ee1
|
||
|
|
9896e7c657 | ||
|
|
4574aa17c3
|
||
|
|
bb010d565e | ||
|
|
e809ce63d3
|
@@ -1,6 +1,6 @@
|
|||||||
{"type":"meta","next_id":{"DSC":66,"AGD":69,"DEC":50,"PLN":129,"LSN":66,"CLSN":1}}
|
{"type":"meta","next_id":{"DSC":66,"AGD":69,"DEC":58,"PLN":137,"LSN":74,"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":"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-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"}]}
|
||||||
@@ -20,12 +20,12 @@
|
|||||||
{"type":"discussion","id":"DSC-0047","status":"open","ticket":"pbs-lsp-semantic-tokens-semantic-classification","title":"PBS LSP Semantic Token Classification","created_at":"2026-07-15","updated_at":"2026-07-15","tags":["studio","lsp","vscode","compiler-pbs","editor","semantic-tokens"],"agendas":[{"id":"AGD-0050","file":"AGD-0050-pbs-lsp-semantic-token-classification.md","status":"open","created_at":"2026-07-15","updated_at":"2026-07-15"}],"decisions":[],"plans":[],"lessons":[]}
|
{"type":"discussion","id":"DSC-0047","status":"open","ticket":"pbs-lsp-semantic-tokens-semantic-classification","title":"PBS LSP Semantic Token Classification","created_at":"2026-07-15","updated_at":"2026-07-15","tags":["studio","lsp","vscode","compiler-pbs","editor","semantic-tokens"],"agendas":[{"id":"AGD-0050","file":"AGD-0050-pbs-lsp-semantic-token-classification.md","status":"open","created_at":"2026-07-15","updated_at":"2026-07-15"}],"decisions":[],"plans":[],"lessons":[]}
|
||||||
{"type":"discussion","id":"DSC-0046","status":"open","ticket":"pbs-lsp-import-assistance","title":"PBS LSP Import Assistance","created_at":"2026-07-15","updated_at":"2026-07-15","tags":["studio","lsp","vscode","compiler-pbs","editor","imports","completion"],"agendas":[{"id":"AGD-0049","file":"AGD-0049-pbs-lsp-import-assistance.md","status":"open","created_at":"2026-07-15","updated_at":"2026-07-15"}],"decisions":[],"plans":[],"lessons":[]}
|
{"type":"discussion","id":"DSC-0046","status":"open","ticket":"pbs-lsp-import-assistance","title":"PBS LSP Import Assistance","created_at":"2026-07-15","updated_at":"2026-07-15","tags":["studio","lsp","vscode","compiler-pbs","editor","imports","completion"],"agendas":[{"id":"AGD-0049","file":"AGD-0049-pbs-lsp-import-assistance.md","status":"open","created_at":"2026-07-15","updated_at":"2026-07-15"}],"decisions":[],"plans":[],"lessons":[]}
|
||||||
{"type":"discussion","id":"DSC-0045","status":"open","ticket":"pbs-lsp-formatting","title":"PBS LSP Formatting","created_at":"2026-07-15","updated_at":"2026-07-15","tags":["studio","lsp","vscode","compiler-pbs","editor","formatting"],"agendas":[{"id":"AGD-0048","file":"AGD-0048-pbs-lsp-formatting.md","status":"open","created_at":"2026-07-15","updated_at":"2026-07-15"}],"decisions":[],"plans":[],"lessons":[]}
|
{"type":"discussion","id":"DSC-0045","status":"open","ticket":"pbs-lsp-formatting","title":"PBS LSP Formatting","created_at":"2026-07-15","updated_at":"2026-07-15","tags":["studio","lsp","vscode","compiler-pbs","editor","formatting"],"agendas":[{"id":"AGD-0048","file":"AGD-0048-pbs-lsp-formatting.md","status":"open","created_at":"2026-07-15","updated_at":"2026-07-15"}],"decisions":[],"plans":[],"lessons":[]}
|
||||||
{"type":"discussion","id":"DSC-0044","status":"open","ticket":"pbs-lsp-code-actions","title":"PBS LSP Code Actions and Quick Fixes","created_at":"2026-07-15","updated_at":"2026-07-15","tags":["studio","lsp","vscode","compiler-pbs","editor","code-actions","quick-fix"],"agendas":[{"id":"AGD-0047","file":"AGD-0047-pbs-lsp-code-actions-and-quick-fixes.md","status":"open","created_at":"2026-07-15","updated_at":"2026-07-15"}],"decisions":[],"plans":[],"lessons":[]}
|
{"type":"discussion","id":"DSC-0044","status":"done","ticket":"pbs-lsp-code-actions","title":"PBS LSP Code Actions and Quick Fixes","created_at":"2026-07-15","updated_at":"2026-09-22","tags":["studio","lsp","vscode","compiler-pbs","editor","code-actions","quick-fix"],"agendas":[],"decisions":[],"plans":[],"lessons":[{"id":"LSN-0073","file":"discussion/lessons/DSC-0044-pbs-lsp-code-actions/LSN-0073-pbs-quick-fixes-are-frontend-repairs-transported-by-the-lsp.md","status":"done","created_at":"2026-09-22","updated_at":"2026-09-22"}]}
|
||||||
{"type":"discussion","id":"DSC-0043","status":"open","ticket":"pbs-lsp-rename-symbol","title":"PBS LSP Rename Symbol","created_at":"2026-07-15","updated_at":"2026-07-15","tags":["studio","lsp","vscode","compiler-pbs","editor","rename"],"agendas":[{"id":"AGD-0046","file":"AGD-0046-pbs-lsp-rename-symbol.md","status":"open","created_at":"2026-07-15","updated_at":"2026-07-15"}],"decisions":[],"plans":[],"lessons":[]}
|
{"type":"discussion","id":"DSC-0043","status":"done","ticket":"pbs-lsp-rename-symbol","title":"PBS LSP Rename Symbol","created_at":"2026-07-15","updated_at":"2026-09-22","tags":["studio","lsp","vscode","compiler-pbs","editor","rename"],"agendas":[],"decisions":[],"plans":[],"lessons":[{"id":"LSN-0072","file":"discussion/lessons/DSC-0043-pbs-lsp-rename-symbol/LSN-0072-pbs-rename-is-a-validated-physical-workspace-edit.md","status":"done","created_at":"2026-09-22","updated_at":"2026-09-22"}]}
|
||||||
{"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":"done","ticket":"pbs-lsp-workspace-symbols","title":"PBS LSP Workspace Symbols","created_at":"2026-07-15","updated_at":"2026-09-21","tags":["studio","lsp","vscode","compiler-pbs","editor","workspace-symbols"],"agendas":[],"decisions":[],"plans":[],"lessons":[{"id":"LSN-0071","file":"discussion/lessons/DSC-0042-pbs-lsp-workspace-symbols/LSN-0071-pbs-workspace-symbols-are-a-physical-named-declaration-search.md","status":"done","created_at":"2026-09-21","updated_at":"2026-09-21"}]}
|
||||||
{"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":"done","ticket":"pbs-lsp-document-symbols-outline","title":"PBS LSP Document Symbols and Outline","created_at":"2026-07-15","updated_at":"2026-09-21","tags":["studio","lsp","vscode","compiler-pbs","editor","outline","document-symbols"],"agendas":[],"decisions":[],"plans":[],"lessons":[{"id":"LSN-0070","file":"discussion/lessons/DSC-0041-pbs-lsp-document-symbols-outline/LSN-0070-pbs-outline-is-an-ast-backed-document-symbol-tree.md","status":"done","created_at":"2026-09-21","updated_at":"2026-09-21"}]}
|
||||||
{"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":"done","ticket":"pbs-lsp-find-references","title":"PBS LSP Find References","created_at":"2026-07-15","updated_at":"2026-09-21","tags":["studio","lsp","vscode","compiler-pbs","editor","references"],"agendas":[],"decisions":[],"plans":[],"lessons":[{"id":"LSN-0069","file":"discussion/lessons/DSC-0040-pbs-lsp-find-references/LSN-0069-pbs-find-references-is-the-physical-inverse-of-definition.md","status":"done","created_at":"2026-09-21","updated_at":"2026-09-21"}]}
|
||||||
{"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"}]}
|
||||||
|
|||||||
+98
@@ -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
|
||||||
+111
@@ -0,0 +1,111 @@
|
|||||||
|
---
|
||||||
|
id: LSN-0069
|
||||||
|
ticket: pbs-lsp-find-references
|
||||||
|
title: PBS find-references is the physical inverse of definition
|
||||||
|
created: 2026-09-21
|
||||||
|
tags: [studio, lsp, vscode, compiler-pbs, editor, references]
|
||||||
|
---
|
||||||
|
|
||||||
|
# PBS find-references is the physical inverse of definition
|
||||||
|
|
||||||
|
## Original Problem
|
||||||
|
|
||||||
|
PBS already had compiler-backed completion, hover, signature help, and go-to-definition (`LSN-0051`, `LSN-0068`). Users still could not ask where a resolved symbol is used. Text search confuses overloads, shadowing, members, comments, and coincidental names. Rename (`AGD-0046`) and hierarchy (`AGD-0056`) need an honest usage list before they exist.
|
||||||
|
|
||||||
|
The risk was inventing a `SymbolId` / `RefIndex`, waiting for snapshot cache (`AGD-0051`), or listing uses of stdlib APIs whose declarations are still virtual paths.
|
||||||
|
|
||||||
|
## Consolidated Decision
|
||||||
|
|
||||||
|
PBS Find References is the LSP projection of **physical usage sites** of the **same identity definition already returns**.
|
||||||
|
|
||||||
|
Durable locks from `DEC-0053` (AGD-0043 Q1–Q6 = A):
|
||||||
|
|
||||||
|
1. Resolve the cursor through the definition path (locals, parameters, members, imports/supplementals, current-module top-level). Identity is that physical declaration-location set. Do not text-search. Do not add `SymbolId` or a persistent `RefIndex`.
|
||||||
|
2. A site is a usage when its definition locations intersect the cursor identity. Overloads follow that intersection.
|
||||||
|
3. If definition at the same offset is empty, references is empty.
|
||||||
|
4. Walk regular `fileTable` files from the current `analyze()` surface. Do not scan `/virtual/stdlib` or other non-regular handles.
|
||||||
|
5. Keep the capability on the existing aggregated `FrontendLanguageService`. Reuse `FrontendDefinitionLocation`. Map PBS spans in `prometeu-frontend-pbs`. Common LSP must not import `p.studio.compiler.pbs.*`. No References SPI.
|
||||||
|
6. Honor LSP `includeDeclaration` in the server: union usage sites with definition locations when the host asks and the declaration is a regular file. No read/write classification.
|
||||||
|
7. Advertise `referencesProvider`. Partial coverage is valid. Analysis stays request-local. This discussion does not build rename, hierarchy, workspace symbols, virtual documents, or snapshot cache.
|
||||||
|
|
||||||
|
Spec 23 §8.3 now also states: a references location must identify a compiler-known physical source file; empty definition implies empty references; `includeDeclaration` must not invent a virtual location.
|
||||||
|
|
||||||
|
## Final Implementation
|
||||||
|
|
||||||
|
| Layer | What landed |
|
||||||
|
|---|---|
|
||||||
|
| PBS editorial | `PbsEditorialSupportService.references` walks `IDENTIFIER` tokens and keeps sites whose `definition` locations intersect the cursor identity (`FileId` + start + end). |
|
||||||
|
| Generic contract | `FrontendLanguageService.references` defaults to `List.of()`. `FrontendEditorialContext.projectSurface` carries the PBS semantic read surface so the walk can see `astByFile`. |
|
||||||
|
| PBS mapping | `PBSFrontendLanguageService` requires a non-empty physical definition set, skips non-regular files, and maps surviving spans through the same `Files.isRegularFile` helper as definition. |
|
||||||
|
| LSP | `referencesProvider`, `textDocument/references`. The bridge applies `includeDeclaration` by unioning `references` with `definition`. Compile-only frontends stay empty. |
|
||||||
|
| VS Code | Unchanged thin client. |
|
||||||
|
|
||||||
|
Stdlib and SDK modules remain virtual (`/virtual/stdlib/...`). Shift+F12 on `Gfx.clear` is empty, matching F12. Hover is unchanged.
|
||||||
|
|
||||||
|
Local binding names are not usage sites: definition at `let total` is empty because the name is not yet in scope. The use `return total` matches. `includeDeclaration` adds the declaration span from definition, not a second name search.
|
||||||
|
|
||||||
|
## Examples
|
||||||
|
|
||||||
|
Same-file function uses, including the declaring identifier (top-level names resolve to themselves):
|
||||||
|
|
||||||
|
```pbs
|
||||||
|
fn helper() -> int { return 42; }
|
||||||
|
|
||||||
|
fn frame() -> void {
|
||||||
|
helper();
|
||||||
|
helper();
|
||||||
|
// helper // not a reference
|
||||||
|
let text = "helper"; // not a reference
|
||||||
|
}
|
||||||
|
```
|
||||||
|
|
||||||
|
Imported project (or otherwise physical) symbols collect uses in the importing file. Identity is the foreign declaration span.
|
||||||
|
|
||||||
|
```pbs
|
||||||
|
import { Log as Logger } from @sdk:log;
|
||||||
|
Logger.info("a");
|
||||||
|
Logger.info("b");
|
||||||
|
```
|
||||||
|
|
||||||
|
If `@sdk:log` is only a virtual handle, definition is empty, so references is empty.
|
||||||
|
|
||||||
|
Builtins stay hover-only:
|
||||||
|
|
||||||
|
```pbs
|
||||||
|
let n: int = 1; // hover works; references is empty
|
||||||
|
```
|
||||||
|
|
||||||
|
`includeDeclaration=true` adds the canonical declaration location on top of identifier usage sites. `false` returns usages only.
|
||||||
|
|
||||||
|
## Pitfalls
|
||||||
|
|
||||||
|
Do not implement find-references as workspace text search in `lsp-v1` or in the VS Code extension. It will lie about overloads, members, and imports, then poison rename.
|
||||||
|
|
||||||
|
Do not add a `SymbolId` index “for rename later”. Definition already gave the key: physical declaration locations. Rename can consume this list once it has its own decision.
|
||||||
|
|
||||||
|
Do not wait for snapshot cache. The LSP already reanalyzes on each editorial request. Snapshots (`AGD-0051`) can make the walk cheaper without changing the contract.
|
||||||
|
|
||||||
|
Do not treat empty stdlib references as a missing feature. Virtual paths are not regular files. Empty is the honest result until those sources live on disk.
|
||||||
|
|
||||||
|
Do not expect `let total` to appear as a usage of `total`. Inverse-of-definition only keeps identifier sites that themselves resolve. The declaration span arrives through `includeDeclaration`.
|
||||||
|
|
||||||
|
Do not put `includeDeclaration` into PBS types. It is a host flag applied in the LSP bridge.
|
||||||
|
|
||||||
|
Do not scan `/virtual/stdlib` to “find more uses”. That reopens virtual documents.
|
||||||
|
|
||||||
|
Do not split a References SPI “for future languages”. PBS is a real consumer of `FrontendLanguageService` (`LSN-0067`).
|
||||||
|
|
||||||
|
Do not treat this lesson as closing rename, snapshots, workspace symbols, document links, or hierarchy.
|
||||||
|
|
||||||
|
## References
|
||||||
|
|
||||||
|
- Agenda: `AGD-0043` (Q1–Q6 = A)
|
||||||
|
- Decision: `DEC-0053`
|
||||||
|
- Plan: `PLN-0132`
|
||||||
|
- Spec 23 §8.3 — optional navigation; physical-file-or-empty; empty definition implies empty references
|
||||||
|
- `LSN-0068` — definition identity this feature inverts
|
||||||
|
- `LSN-0051` — wave 1 deferred navigation
|
||||||
|
- `LSN-0058` — generic `FrontendLanguageService` for LSP
|
||||||
|
- `LSN-0047` — protocol stays in `lsp-v1`; compiler owns semantics
|
||||||
|
- `LSN-0067` — no SPI without a real in-repo consumer
|
||||||
|
- Still open: `AGD-0046` rename, `AGD-0045` workspace symbols, `AGD-0051` snapshots, `AGD-0055` document links, `AGD-0056` hierarchy
|
||||||
+141
@@ -0,0 +1,141 @@
|
|||||||
|
---
|
||||||
|
id: LSN-0070
|
||||||
|
ticket: pbs-lsp-document-symbols-outline
|
||||||
|
title: PBS outline is an AST-backed document-symbol tree
|
||||||
|
created: 2026-09-21
|
||||||
|
tags: [studio, lsp, vscode, compiler-pbs, editor, outline, document-symbols]
|
||||||
|
---
|
||||||
|
|
||||||
|
# PBS outline is an AST-backed document-symbol tree
|
||||||
|
|
||||||
|
## Original Problem
|
||||||
|
|
||||||
|
PBS already had compiler-backed completion, hover, signature help, go-to-definition (`LSN-0068`), and find-references (`LSN-0069`). VS Code Outline stayed empty. Long `.pbs` files had to be scanned by hand.
|
||||||
|
|
||||||
|
The risk was building outline from semantic success (so the tree vanishes while typing), flattening to `SymbolInformation`, inventing a Document Symbol SPI, or stuffing workspace search and folding into the same payload.
|
||||||
|
|
||||||
|
## Consolidated Decision
|
||||||
|
|
||||||
|
PBS Document Symbols is the LSP projection of the **named declaration tree of the open `.pbs` file**, with the **recovered AST as backbone**.
|
||||||
|
|
||||||
|
Durable locks from `DEC-0054` (AGD-0044 Q1 A, Q2 AST tree, Q3 A, Q4 A, Q5 A, Q6 `.pbs`-only, Q7 existing kinds):
|
||||||
|
|
||||||
|
1. Presence, hierarchy, and ranges come from the document AST. Kind and `detail` may use cheap semantic enrichment. Semantics must not drop a named declaration still in the syntax tree, and must not require full analysis.
|
||||||
|
2. Named `TopDecl` plus syntactic members:
|
||||||
|
- `fn` → Function, no children;
|
||||||
|
- `declare struct` → Struct, children: fields, `ctor`s, methods;
|
||||||
|
- `declare service` → Service, children: methods;
|
||||||
|
- `declare contract` → Contract, children: signatures as methods;
|
||||||
|
- `declare host` → Host, children: signatures;
|
||||||
|
- `declare builtin type` → Builtin type, children: projection fields and signatures;
|
||||||
|
- `declare enum` → Enum, children: cases;
|
||||||
|
- `declare error` → Error, children: labels;
|
||||||
|
- `declare callback` → Callback, no children;
|
||||||
|
- `declare global` / `const` → Global / Const, no children;
|
||||||
|
- `implements Contract for Owner` → top-level Contract named `contractName`, `detail` = owner name, children: methods.
|
||||||
|
Locals, parameters, `this`, imports, and comments stay out. Private fields stay in. Overloads stay siblings. Host and builtin type appear only if the open file declares them.
|
||||||
|
3. Recovered AST is enough. Unnamed `InvalidDecl` is omitted. Named decls survive later semantic errors. No `PbsAst.File` → empty list. Do not invent nodes from text or token pairs.
|
||||||
|
4. Keep the capability on aggregated `FrontendLanguageService.documentSymbols` (default empty) plus a hierarchical DTO (`name`, `kind`, optional `detail`, range offsets, selection offsets, `children`). No file path on the DTO. PBS builds the tree in `prometeu-frontend-pbs`. Common LSP must not import `p.studio.compiler.pbs.*`. No Document Symbol SPI.
|
||||||
|
5. Advertise `documentSymbolProvider`. Payload is hierarchical `DocumentSymbol`, not flat `SymbolInformation`. `range` is the declaration span. `selectionRange` is the name span only if the AST already has one; this wave reuses the declaration span. Do not scan tokens for identifier spans. VS Code stays a thin client.
|
||||||
|
6. First wave is the current `.pbs` only. Out: imported supplementals, `mod.barrel`, locals, parameters, imports, comments, virtual documents, workspace symbols, folding, rename, snapshot cache. Server order is AST declaration order, not alphabetical.
|
||||||
|
7. Reuse `FrontendSymbolKind` / `PbsEditorialSymbolKind`. LSP projects to the closest host `SymbolKind`. Name is the identifier. `detail` may carry the AST signature (`(a: int) -> int`). Attributes such as `[Init]` do not enter the name.
|
||||||
|
|
||||||
|
Outline does not jump to another file. The physical-file destination policy of definition/references is not the outline policy.
|
||||||
|
|
||||||
|
Spec 23 §8.3 now also states: document symbols are the named declaration tree of the requested document; recovered syntax is enough; a missing syntax tree is empty; this is not a workspace index, folding ranges, or a foreign-file navigation list.
|
||||||
|
|
||||||
|
## Final Implementation
|
||||||
|
|
||||||
|
| Layer | What landed |
|
||||||
|
|---|---|
|
||||||
|
| PBS editorial | `PbsAstDocumentSymbols` walks `PbsAst.File.topDecls` in source order. `PbsEditorialSupportService.documentSymbols` delegates to that walk. |
|
||||||
|
| Generic contract | `FrontendLanguageService.documentSymbols` defaults to `List.of()`. `FrontendDocumentSymbol` is hierarchical and pathless. |
|
||||||
|
| PBS mapping | `PBSFrontendLanguageService` requires `editorialContext.syntaxTree()` to be `PbsAst.File`. Barrels and unknown trees stay empty. Kinds map with `valueOf(kind.name())`. |
|
||||||
|
| LSP | `documentSymbolProvider`, `textDocument/documentSymbol`, hierarchical `DocumentSymbol`. Nested enum/error children project to `EnumMember`. Compile-only frontends stay empty. |
|
||||||
|
| VS Code | Unchanged thin client. |
|
||||||
|
|
||||||
|
`mod.barrel` is assembled as `BarrelFile`, not `PbsAst.File`, so `astByFile` has no barrel outline. Empty is the honest first-wave result.
|
||||||
|
|
||||||
|
Error case labels have no per-label span in the AST. Children reuse the parent `ErrorDecl` span rather than scanning tokens.
|
||||||
|
|
||||||
|
## Examples
|
||||||
|
|
||||||
|
Outline of a file is the declarations in that file, not imports or locals:
|
||||||
|
|
||||||
|
```pbs
|
||||||
|
import { Log } from @sdk:log;
|
||||||
|
|
||||||
|
fn helper() -> int { return 42; }
|
||||||
|
|
||||||
|
fn frame() -> void {
|
||||||
|
let local = 1;
|
||||||
|
helper(local);
|
||||||
|
}
|
||||||
|
```
|
||||||
|
|
||||||
|
Outline: `helper`, `frame`. Not `Log`, not `local`.
|
||||||
|
|
||||||
|
Struct members and overloads as siblings:
|
||||||
|
|
||||||
|
```pbs
|
||||||
|
declare struct Vec(x: int) {
|
||||||
|
ctor make(x: int) { return; }
|
||||||
|
fn blend(dx: int, dy: int) -> int { return dx; }
|
||||||
|
}
|
||||||
|
|
||||||
|
fn helper() -> int { return 42; }
|
||||||
|
fn helper(value: int) -> int { return value; }
|
||||||
|
```
|
||||||
|
|
||||||
|
Outline: `Vec` (`x`, `make`, `blend`), then two `helper` siblings. Private field `x` is present. `detail` on `blend` is `(dx: int, dy: int) -> int`.
|
||||||
|
|
||||||
|
Recovered parse keeps the named decl:
|
||||||
|
|
||||||
|
```pbs
|
||||||
|
declare ;
|
||||||
|
fn ok() -> int { return 1; }
|
||||||
|
```
|
||||||
|
|
||||||
|
Outline: `ok`. The unnamed `InvalidDecl` is omitted.
|
||||||
|
|
||||||
|
`[Init] fn init()` still names the symbol `init`.
|
||||||
|
|
||||||
|
`implements TickLike for Point` is a top-level node named `TickLike` with detail `Point`.
|
||||||
|
|
||||||
|
## Pitfalls
|
||||||
|
|
||||||
|
Do not wait for semantic analysis to succeed before showing outline. The tree must survive broken intermediate edits.
|
||||||
|
|
||||||
|
Do not omit private fields because they are not in `mod.barrel`. Outline is for the author of this file.
|
||||||
|
|
||||||
|
Do not collapse overloads. AST identity forbids merging declaration sets.
|
||||||
|
|
||||||
|
Do not walk `File.imports` or supplemental imported `TopDecl`s. Those symbols are not declared in this document.
|
||||||
|
|
||||||
|
Do not implement outline for `mod.barrel` in this contract. Barrel AST is a different root. Empty is correct until a later decision.
|
||||||
|
|
||||||
|
Do not scan tokens to invent a tighter `selectionRange`. This wave uses the declaration span.
|
||||||
|
|
||||||
|
Do not put a file path on `FrontendDocumentSymbol`. The host already has the document URI. Outline is not go-to-definition.
|
||||||
|
|
||||||
|
Do not reuse the physical-file jump rule of `LSN-0068` as an outline destination policy. Clicking outline stays inside the buffer.
|
||||||
|
|
||||||
|
Do not overload document symbols with folding or scope guides (`LSN-0034`, `AGD-0053`).
|
||||||
|
|
||||||
|
Do not split a Document Symbol SPI “for future languages”. PBS is a real consumer of `FrontendLanguageService` (`LSN-0067`).
|
||||||
|
|
||||||
|
Do not treat this lesson as closing workspace symbols, folding, rename, document links, or hierarchy.
|
||||||
|
|
||||||
|
## References
|
||||||
|
|
||||||
|
- Agenda: `AGD-0044` (Q1 A, Q2 AST tree, Q3 A, Q4 A, Q5 A, Q6 `.pbs`-only, Q7 existing kinds)
|
||||||
|
- Decision: `DEC-0054`
|
||||||
|
- Plan: `PLN-0133`
|
||||||
|
- Spec 23 §8.3 — optional document symbols; recovered AST tree of the requested document
|
||||||
|
- `LSN-0068` — definition is a jump; outline is not
|
||||||
|
- `LSN-0069` — references invert definition identity
|
||||||
|
- `LSN-0034` — do not overload document symbols with structural anchors
|
||||||
|
- `LSN-0058` — generic `FrontendLanguageService` for LSP
|
||||||
|
- `LSN-0047` — protocol stays in `lsp-v1`; compiler owns semantics
|
||||||
|
- `LSN-0067` — no SPI without a real in-repo consumer
|
||||||
|
- Still open: `AGD-0045` workspace symbols, `AGD-0046` rename, `AGD-0051` snapshots, `AGD-0053` folding, `AGD-0055` document links, `AGD-0056` hierarchy
|
||||||
+149
@@ -0,0 +1,149 @@
|
|||||||
|
---
|
||||||
|
id: LSN-0071
|
||||||
|
ticket: pbs-lsp-workspace-symbols
|
||||||
|
title: PBS workspace symbols are a physical named-declaration search
|
||||||
|
created: 2026-09-21
|
||||||
|
tags: [studio, lsp, vscode, compiler-pbs, editor, workspace-symbols]
|
||||||
|
---
|
||||||
|
|
||||||
|
# PBS workspace symbols are a physical named-declaration search
|
||||||
|
|
||||||
|
## Original Problem
|
||||||
|
|
||||||
|
PBS already had compiler-backed completion, hover, signature help, go-to-definition (`LSN-0068`), find-references (`LSN-0069`), and an AST-backed outline of the open `.pbs` file (`LSN-0070`). VS Code workspace search (`Ctrl+T` / `workspace/symbol`) stayed empty.
|
||||||
|
|
||||||
|
The risk was treating workspace symbols as a second outline, inventing a `SymbolId` index, waiting for snapshot cache (`AGD-0051`), or returning stdlib/SDK hits whose declarations are still virtual paths (`/virtual/stdlib`). Workspace symbols is a jump. Outline is not.
|
||||||
|
|
||||||
|
## Consolidated Decision
|
||||||
|
|
||||||
|
PBS Workspace Symbols is the LSP projection of a **flat named-declaration search** over **regular filesystem files** of the current analysis, flattening the **same outline set** and using the **same physical-file destination policy** as definition.
|
||||||
|
|
||||||
|
Durable locks from `DEC-0055` (AGD-0045 Q1 A, Q2 A, Q3 A, Q4 A, Q5 A, Q6 first-wave exclusions):
|
||||||
|
|
||||||
|
1. Emit only declarations whose `fileTable` handle is a regular filesystem file. Virtual stdlib/SDK, including `/virtual/stdlib`, is omitted. Do not invent virtual documents, `untitled:` buffers, or synthetic URIs.
|
||||||
|
2. `workspace/symbol` does not require an open text document. The server obtains the project analysis surface (`astByFile` / `projectSurface`) from `analyze()`. Missing surface → empty list.
|
||||||
|
3. The set is the flatten, file by file, of the named-declaration tree locked by outline (`LSN-0070`):
|
||||||
|
- `fn` → Function;
|
||||||
|
- `declare struct` → Struct plus fields, `ctor`s, methods;
|
||||||
|
- `declare service` → Service plus methods;
|
||||||
|
- `declare contract` → Contract plus signatures;
|
||||||
|
- `declare host` → Host plus signatures;
|
||||||
|
- `declare builtin type` → Builtin type plus projection fields and signatures;
|
||||||
|
- `declare enum` → Enum plus cases;
|
||||||
|
- `declare error` → Error plus labels;
|
||||||
|
- `declare callback` → Callback;
|
||||||
|
- `declare global` / `const` → Global / Const;
|
||||||
|
- `implements Contract for Owner` → `contractName`, kind CONTRACT, `detail` = owner, plus methods.
|
||||||
|
Locals, parameters, `this`, imports, and comments stay out. Private fields stay in. Overloads stay sibling hits. Unnamed `InvalidDecl` is omitted. Named decls survive later semantic errors.
|
||||||
|
4. First wave is `.pbs` whose recovered root is `PbsAst.File`. `mod.barrel` (`BarrelFile`) stays empty. Presence, name, kind, `detail`, and spans come from recovered AST. Do not invent nodes from text search.
|
||||||
|
5. Query is a case-insensitive substring of `name` only. Blank query returns the full first-wave corpus. Do not match `detail`, path, `containerName`, or qualified `Vec.blend`. No fuzzy ranking, no `top N`. After the filter, order is stable by name, then path, then start offset.
|
||||||
|
6. `containerName` is the parent name for members and empty for top-level declarations. `detail` may repeat the outline AST signature. Attributes such as `[Init]` do not enter the name.
|
||||||
|
7. Keep the capability on aggregated `FrontendLanguageService`. Add `workspaceSymbols` (default empty) plus a flat DTO with `name`, `kind`, optional `detail`, `containerName`, absolute path, and offsets. Do not reuse pathless `FrontendDocumentSymbol`. PBS flattens in `prometeu-frontend-pbs`. Common LSP must not import `p.studio.compiler.pbs.*`. No Workspace Symbol SPI, `SymbolId`, `RefIndex`, or snapshot cache.
|
||||||
|
8. Advertise `workspaceSymbolProvider` when the frontend exposes a language service. Payload is flat `SymbolInformation`. Do not emit hierarchical `DocumentSymbol` on this request. Compile-only frontends stay empty. VS Code stays a thin client.
|
||||||
|
|
||||||
|
Spec 23 §8.3 now also states: workspace symbols are a flat search of named declarations in compiler-known physical source files of the current analysis; recovered syntax is enough; a missing analysis surface is empty; the request must not require an open document; a declaration without a physical file is omitted; this is not outline, folding, a persistent index, or navigation to virtual locations.
|
||||||
|
|
||||||
|
## Final Implementation
|
||||||
|
|
||||||
|
| Layer | What landed |
|
||||||
|
|---|---|
|
||||||
|
| PBS editorial | `PbsAstWorkspaceSymbols` flattens `PbsAstDocumentSymbols` and filters by name. `PbsEditorialSupportService.workspaceSymbols(ast, query)` delegates to that flatten. |
|
||||||
|
| Generic contract | `FrontendWorkspaceRequest` (`projectRoot`, `query`). `FrontendWorkspaceSymbol` carries path. `FrontendLanguageService.workspaceSymbols` defaults to `List.of()`. `prepareEditorialContext(FrontendPhaseContext)` defaults to empty so a workspace request can obtain project surface without a `FileId`. |
|
||||||
|
| PBS mapping | Project-level `prepareEditorialContext` attaches `fileTable` + `astByFile`. Regular `PbsAst.File` entries are flattened; non-regular handles are skipped. Results sort by name, path, offset. |
|
||||||
|
| LSP | `workspaceSymbolProvider`, `workspace/symbol` on `PrometeuWorkspaceService` (no document URI). `CompilerLanguageServiceBridge` analyzes the project with an empty overlay map. Mapper emits flat `SymbolInformation`. Nested enum/error hits with a container project to `EnumMember`. Compile-only frontends stay empty. |
|
||||||
|
| VS Code | Unchanged thin client. |
|
||||||
|
|
||||||
|
`workspace/symbol` in this wave reads the project on disk. Unsaved editor overlays are not shared into the search. Empty is honest until a later overlay/snapshot decision.
|
||||||
|
|
||||||
|
`mod.barrel` is still `BarrelFile`, not `PbsAst.File`. Empty barrel hits are the honest first-wave result.
|
||||||
|
|
||||||
|
Error case labels still have no per-label span. Flattened children reuse the parent `ErrorDecl` span, same as outline.
|
||||||
|
|
||||||
|
## Examples
|
||||||
|
|
||||||
|
Workspace search of a project file is the flatten of that file's outline, not imports or locals:
|
||||||
|
|
||||||
|
```pbs
|
||||||
|
import { Log } from @sdk:log;
|
||||||
|
|
||||||
|
fn helper() -> int { return 42; }
|
||||||
|
|
||||||
|
fn frame() -> void {
|
||||||
|
let local = 1;
|
||||||
|
helper(local);
|
||||||
|
}
|
||||||
|
```
|
||||||
|
|
||||||
|
Query `frame` → `frame`. Query `helper` → `helper`. Query empty → `helper`, `frame` (plus other physical decls), sorted. Not `Log`, not `local`.
|
||||||
|
|
||||||
|
Members keep a container; overloads stay siblings:
|
||||||
|
|
||||||
|
```pbs
|
||||||
|
declare struct Vec(x: int) {
|
||||||
|
ctor make(x: int) { return; }
|
||||||
|
fn blend(dx: int, dy: int) -> int { return dx; }
|
||||||
|
}
|
||||||
|
|
||||||
|
fn helper() -> int { return 42; }
|
||||||
|
fn helper(value: int) -> int { return value; }
|
||||||
|
```
|
||||||
|
|
||||||
|
Query `blend` → method `blend` with `containerName` `Vec`. Query `helper` → two hits. Query `Vec.blend` → empty (this wave matches `name` only).
|
||||||
|
|
||||||
|
Stdlib remains hover-only while the handle is virtual:
|
||||||
|
|
||||||
|
```pbs
|
||||||
|
import { Gfx } from @sdk:gfx;
|
||||||
|
Gfx.clear(0);
|
||||||
|
```
|
||||||
|
|
||||||
|
Query `Gfx` is empty. F12 on `Gfx.clear` is already empty (`LSN-0068`). Workspace search does not reopen that jump.
|
||||||
|
|
||||||
|
Recovered parse keeps the named decl:
|
||||||
|
|
||||||
|
```pbs
|
||||||
|
declare ;
|
||||||
|
fn ok() -> int { return 1; }
|
||||||
|
```
|
||||||
|
|
||||||
|
Query empty → `ok`. The unnamed `InvalidDecl` is omitted.
|
||||||
|
|
||||||
|
`[Init] fn init()` still names the symbol `init`.
|
||||||
|
|
||||||
|
## Pitfalls
|
||||||
|
|
||||||
|
Do not implement workspace symbols as workspace text search in `lsp-v1` or in the VS Code extension. It will lie about overloads, members, and imports.
|
||||||
|
|
||||||
|
Do not reuse `FrontendDocumentSymbol`. Outline is pathless because the host already has the document URI. Workspace symbols is a jump and must carry a path.
|
||||||
|
|
||||||
|
Do not require an open editor buffer to answer `workspace/symbol`. Analyze the project and walk `astByFile`.
|
||||||
|
|
||||||
|
Do not include `/virtual/stdlib` so Ctrl+T on `Gfx` “does something”. Empty is the honest result until those sources are regular files.
|
||||||
|
|
||||||
|
Do not wait for snapshot cache. References already walks the current analysis request-locally. Snapshots (`AGD-0051`) can make the walk cheaper without changing this contract.
|
||||||
|
|
||||||
|
Do not add a `SymbolId` index “for rename later”. Outline already named the declarations; definition already named the destination.
|
||||||
|
|
||||||
|
Do not match `containerName`, path, or `Vec.blend` in this wave. The query is a substring of `name`.
|
||||||
|
|
||||||
|
Do not emit hierarchical `DocumentSymbol` on `workspace/symbol`. That payload is outline.
|
||||||
|
|
||||||
|
Do not treat unsaved overlay absence as a missing feature of this contract. First-wave analysis is the project on disk.
|
||||||
|
|
||||||
|
Do not split a Workspace Symbol SPI “for future languages”. PBS is a real consumer of `FrontendLanguageService` (`LSN-0067`).
|
||||||
|
|
||||||
|
Do not treat this lesson as closing rename, snapshots, folding, document links, or hierarchy.
|
||||||
|
|
||||||
|
## References
|
||||||
|
|
||||||
|
- Agenda: `AGD-0045` (Q1 A, Q2 A, Q3 A, Q4 A, Q5 A, Q6 first-wave exclusions)
|
||||||
|
- Decision: `DEC-0055`
|
||||||
|
- Plan: `PLN-0134`
|
||||||
|
- Spec 23 §8.3 — optional workspace symbols; physical-file-or-omit; no open document required
|
||||||
|
- `LSN-0070` — outline set this feature flattens
|
||||||
|
- `LSN-0068` — physical-file destination this feature reuses
|
||||||
|
- `LSN-0069` — project `astByFile` walk already exists for references
|
||||||
|
- `LSN-0058` — generic `FrontendLanguageService` for LSP
|
||||||
|
- `LSN-0047` — protocol stays in `lsp-v1`; compiler owns semantics
|
||||||
|
- `LSN-0067` — no SPI without a real in-repo consumer
|
||||||
|
- Still open: `AGD-0046` rename, `AGD-0051` snapshots, `AGD-0053` folding, `AGD-0055` document links, `AGD-0056` hierarchy
|
||||||
+128
@@ -0,0 +1,128 @@
|
|||||||
|
---
|
||||||
|
id: LSN-0072
|
||||||
|
ticket: pbs-lsp-rename-symbol
|
||||||
|
title: PBS rename is a validated physical workspace edit
|
||||||
|
created: 2026-09-22
|
||||||
|
tags: [studio, lsp, vscode, compiler-pbs, editor, rename]
|
||||||
|
---
|
||||||
|
|
||||||
|
# PBS rename is a validated physical workspace edit
|
||||||
|
|
||||||
|
## Original Problem
|
||||||
|
|
||||||
|
PBS already had compiler-backed completion, hover, signature help, go-to-definition (`LSN-0068`), find-references (`LSN-0069`), outline (`LSN-0070`), and workspace symbols (`LSN-0071`). Users still could not rename a symbol through the editor. Manual text edits miss uses or rewrite unrelated overloads, comments, strings, and same-name declarations.
|
||||||
|
|
||||||
|
The risk was a file-local rename, a lexeme replace, a new `SymbolId` / `RefIndex`, snapshot cache (`AGD-0051`) as a prerequisite, virtual stdlib documents, or a successful empty `WorkspaceEdit` that pretends the symbol changed.
|
||||||
|
|
||||||
|
## Consolidated Decision
|
||||||
|
|
||||||
|
PBS Rename Symbol is the LSP projection of a **validated `WorkspaceEdit`** over **physical identifier spans** of the **same identity definition already returns**.
|
||||||
|
|
||||||
|
Durable locks from `DEC-0056` (AGD-0046 Q1–Q6 = A):
|
||||||
|
|
||||||
|
1. Identity is the physical declaration-location set from definition. Do not text-search. Do not add `SymbolId` or a persistent `RefIndex`.
|
||||||
|
2. Sites are identifier tokens whose definition intersects that identity, plus identifier-sized declaration name spans. Overloads of the same name in the same owner rewrite together. Members rewrite only that member. Comments, strings, and homonyms of another identity stay.
|
||||||
|
3. Walk regular `fileTable` files of the current `analyze()` surface. Omit `/virtual/stdlib` and other non-regular handles. Every edit location must be a compiler-known physical source file.
|
||||||
|
4. Refuse when physical identity is empty: builtins, virtual stdlib/SDK, unresolved names, keywords, comments, strings, `this`, `Self`. Refuse `mod.barrel`. Refuse `declare error` case labels that have no per-label span.
|
||||||
|
5. Exception: a local or parameter name span is renameable even when definition at that offset is empty. Identity becomes that name span; uses are identifiers whose definition intersects it.
|
||||||
|
6. Refuse when the cursor lexeme is an import alias (`item.alias()` distinct from `item.name()`), including uses of that alias. Do not follow alias definition and rewrite the export. Export rename happens only when the cursor writes the original name. Export rewrite must not change `as Alias` tokens or uses that spell a differing alias.
|
||||||
|
7. `prepareRename` validates the cursor and returns the identifier range, or null. `rename` also validates the new name: PBS identifier, not a keyword, no collision in the same binding space (top-level `fn`/`service`/`global`/`const`, local/param in the same scope, field in the same struct, method in the same owner, case in the same enum), ignoring rewritten sites and the overload set. Failure is an LSP error. Never return a successful empty `WorkspaceEdit`. The server does not write files and does not rename paths.
|
||||||
|
8. Keep the capability on aggregated `FrontendLanguageService`. `prepareRename` defaults empty; `rename` defaults unsupported. PBS maps in `prometeu-frontend-pbs`. Common LSP must not import `p.studio.compiler.pbs.*`. No Rename SPI. Advertise `renameProvider` with `prepareProvider`. Compile-only stays unsupported. VS Code stays a thin client.
|
||||||
|
|
||||||
|
Spec 23 §8.3 now also states: rename is a validated workspace edit of identifier spans in compiler-known physical source files; identity is definition; local/param name spans remain renameable; alias, virtual, and error-label cursors refuse; invalid names and collisions are protocol errors, not empty success; the server does not write files; `prepareProvider` is advertised when rename is exposed.
|
||||||
|
|
||||||
|
## Final Implementation
|
||||||
|
|
||||||
|
| Layer | What landed |
|
||||||
|
|---|---|
|
||||||
|
| PBS editorial | `PbsEditorialSupportService.planRename` builds identity from definition or local/param name span, refuses aliases and error labels, walks `IDENTIFIER` tokens whose definition intersects identity and whose lexeme is the original name, then validates identifier/keyword/collision. |
|
||||||
|
| Generic contract | `FrontendLanguageService.prepareRename` defaults empty. `rename` defaults `FrontendRenameResult.unsupported()`. `FrontendRenameEdit` is path + offsets + `newText`. Applied results reject an empty edit list. |
|
||||||
|
| PBS mapping | `PBSFrontendLanguageService` reuses `projectDocuments` and `toFrontendLocation`. Empty physical identity is refuse, even if editorial sites exist on virtual handles. |
|
||||||
|
| LSP | `renameSupported`, `prepareRename`, `rename`. Mapper advertises `RenameOptions.prepareProvider`. Refused rename is `ResponseErrorException`, not an empty `WorkspaceEdit`. Compile-only does not advertise. |
|
||||||
|
| VS Code | Unchanged thin client. |
|
||||||
|
|
||||||
|
Stdlib and SDK modules remain virtual (`/virtual/stdlib/...`). F2 on `Gfx.clear` is refused, matching empty F12 / Shift+F12. Hover is unchanged.
|
||||||
|
|
||||||
|
`let total` at the binding itself still has empty definition. Rename uses the name span as identity so F2 on the binding works.
|
||||||
|
|
||||||
|
## Examples
|
||||||
|
|
||||||
|
Same-file function, including overloads and the declaring identifier. Comment and string stay:
|
||||||
|
|
||||||
|
```pbs
|
||||||
|
fn helper() -> int { return 1; }
|
||||||
|
fn helper(value: int) -> int { return value; }
|
||||||
|
|
||||||
|
fn frame() -> void {
|
||||||
|
helper();
|
||||||
|
helper(2);
|
||||||
|
// helper
|
||||||
|
let text = "helper";
|
||||||
|
}
|
||||||
|
```
|
||||||
|
|
||||||
|
F2 on `helper` → `aid` rewrites both declarations and both calls.
|
||||||
|
|
||||||
|
Local name span:
|
||||||
|
|
||||||
|
```pbs
|
||||||
|
fn frame() -> void {
|
||||||
|
let total = 1;
|
||||||
|
return total;
|
||||||
|
}
|
||||||
|
```
|
||||||
|
|
||||||
|
F2 on `let total` or on the use rewrites both identifier sites.
|
||||||
|
|
||||||
|
Alias is refused. Export rename keeps the local alias:
|
||||||
|
|
||||||
|
```pbs
|
||||||
|
import { Log as Logger } from @sdk:log;
|
||||||
|
Logger.info("a");
|
||||||
|
```
|
||||||
|
|
||||||
|
F2 on `Logger` or `Logger.info` is refused. F2 on a physical `Log` declaration rewrites the original name and `import { Log as Logger }`, and leaves `Logger` / `Logger.info`.
|
||||||
|
|
||||||
|
Builtins and virtual stdlib stay hover-only:
|
||||||
|
|
||||||
|
```pbs
|
||||||
|
let n: int = 1;
|
||||||
|
Gfx.clear(5);
|
||||||
|
```
|
||||||
|
|
||||||
|
Invalid new names (`fn`, `1ab`) and collisions (`helper` → existing `frame`) fail with an LSP error.
|
||||||
|
|
||||||
|
## Pitfalls
|
||||||
|
|
||||||
|
Do not implement rename as workspace text search in `lsp-v1` or in the VS Code extension. It will rewrite comments, strings, overloads of another identity, and import aliases.
|
||||||
|
|
||||||
|
Do not follow definition through an import alias. `Logger` currently resolves to `Log`'s span; a blind inverse-of-definition rename would rewrite the export.
|
||||||
|
|
||||||
|
Do not return a successful empty `WorkspaceEdit` for a refused cursor. The editor will treat that as “renamed”.
|
||||||
|
|
||||||
|
Do not skip the local/param name-span exception. F2 on `let total` is the common case, and definition there is empty.
|
||||||
|
|
||||||
|
Do not rewrite `declare error` case labels by using the parent `ErrorDecl` span. Those labels have no per-label span.
|
||||||
|
|
||||||
|
Do not wait for snapshot cache. Rename reuses the request-local walk already used by references.
|
||||||
|
|
||||||
|
Do not treat empty/refused stdlib rename as a missing feature. Virtual paths are not regular files.
|
||||||
|
|
||||||
|
Do not split a Rename SPI “for future languages”. PBS is a real consumer of `FrontendLanguageService` (`LSN-0067`).
|
||||||
|
|
||||||
|
Do not treat this lesson as closing snapshots, folding, document links, hierarchy, code actions, formatting, file rename, or local-alias rename.
|
||||||
|
|
||||||
|
## References
|
||||||
|
|
||||||
|
- Agenda: `AGD-0046` (Q1–Q6 = A)
|
||||||
|
- Decision: `DEC-0056`
|
||||||
|
- Plan: `PLN-0135`
|
||||||
|
- Spec 23 §8.3 — optional rename; physical-file-or-empty; alias refuse; error instead of empty success; `prepareProvider`
|
||||||
|
- Spec: `docs/specs/compiler-languages/pbs/3. Core Syntax Specification.md` §4.3–4.4
|
||||||
|
- `LSN-0068` — definition identity this feature writes
|
||||||
|
- `LSN-0069` — physical inverse that supplies usage sites
|
||||||
|
- `LSN-0051` — wave 1 deferred rename
|
||||||
|
- `LSN-0058` — generic `FrontendLanguageService` for LSP
|
||||||
|
- `LSN-0047` — protocol stays in `lsp-v1`; compiler owns semantics
|
||||||
|
- `LSN-0067` — no SPI without a real in-repo consumer
|
||||||
|
- Still open: `AGD-0051` snapshots, `AGD-0053` folding, `AGD-0055` document links, `AGD-0056` hierarchy
|
||||||
+130
@@ -0,0 +1,130 @@
|
|||||||
|
---
|
||||||
|
id: LSN-0073
|
||||||
|
ticket: pbs-lsp-code-actions
|
||||||
|
title: PBS quick fixes are frontend repairs transported by the LSP
|
||||||
|
created: 2026-09-22
|
||||||
|
tags: [studio, lsp, vscode, compiler-pbs, editor, code-actions, quick-fix]
|
||||||
|
---
|
||||||
|
|
||||||
|
# PBS quick fixes are frontend repairs transported by the LSP
|
||||||
|
|
||||||
|
## Original Problem
|
||||||
|
|
||||||
|
PBS diagnostics already reach the editor, but the server did not advertise `codeActionProvider`. A user could see a duplicate attribute or a bad `InitAllowed` and still had to repair it by hand.
|
||||||
|
|
||||||
|
The tempting shortcut was a code-to-edit table in the LSP. That shortcut does not work. Compiler `Diagnostic` values carry a stable code, phase, template, placeholders, span, and related locations, but the reserved-attribute reports use the short constructor: empty placeholders, and the English sentence is the only fine discriminator. `E_SEM_MALFORMED_RESERVED_ATTRIBUTE` covers Doc without `markdown`, a wrong payload, empty markdown, an unknown argument, `InitAllowed` with arguments, an out-of-range `AssetLowering`, and a bad `Host` shape. A switch on the code cannot pick a safe edit without reading the message. Diagnostic wording is rendering, not identity. Code actions are an optional editorial capability: the frontend owns the meaning, and the LSP transports it.
|
||||||
|
|
||||||
|
## Consolidated Decision
|
||||||
|
|
||||||
|
PBS quick fix is one `WorkspaceEdit` tied to one diagnostic of the requested physical document. The frontend produces the repair from the syntax tree. The LSP does not invent it.
|
||||||
|
|
||||||
|
Durable locks from `DEC-0057` (AGD-0047: scope A, producer B, residence B, first wave C):
|
||||||
|
|
||||||
|
1. This wave is quick fix only. No organize-imports, source action, refactor, function or struct stub, code lens, or server command.
|
||||||
|
2. The server does not write files. The client applies the edit.
|
||||||
|
3. Each repair names the stable diagnostic code, the primary span of that diagnostic, and exactly one local text edit. The LSP must not keep a code-to-edit table and must not read the diagnostic message to build the edit.
|
||||||
|
4. The repair is computed on `textDocument/codeAction` from the current document analysis. It is not a required field of compiler `Diagnostic`, and it is not published inside `publishDiagnostics`, including `data`.
|
||||||
|
5. `publishDiagnostics` carries the stable compiler code on `Diagnostic.code` so the client can echo it. Source, severity, message, and related information stay as they were. Those presentation questions remain with `AGD-0054`.
|
||||||
|
6. A repair is returned only when the request context contains a diagnostic with the same code and the same primary range. An empty diagnostic list returns an empty action list. An `only` filter that does not include quick fix returns an empty action list.
|
||||||
|
7. Each item is a QuickFix `CodeAction`, not a `Command`. The edit touches one file, the requested physical document, and contains one `TextEdit`. There is no lazy resolve.
|
||||||
|
8. A path that is not a compiler-known regular file, including `/virtual/stdlib`, gets no edit.
|
||||||
|
9. If the frontend does not expose the capability, the server does not advertise `codeActionProvider`. A request that arrives anyway returns an empty list, not a protocol error. Absence of a fix is not a refused cursor.
|
||||||
|
10. PBS exposes the capability. Another frontend does not gain it merely by having a language service.
|
||||||
|
11. The first wave is two shapes, not three diagnostic codes.
|
||||||
|
- For every extra reserved attribute the declaration validator already reports as `E_SEM_DUPLICATE_RESERVED_ATTRIBUTE`, delete exactly that occurrence's span. Do not delete the first occurrence, the declaration, or neighboring whitespace.
|
||||||
|
- For an `InitAllowed` attribute with a non-empty argument list on a host signature, the shape the validator reports as `E_SEM_MALFORMED_RESERVED_ATTRIBUTE` when the file is an interface module, replace that attribute span with `[InitAllowed]`. Do not emit that repair for any other attribute that shares the code. `[InitAllowed()]` is not diagnosed today and gets no repair.
|
||||||
|
12. Nothing else gets a quick fix in this wave. In particular: inserting `[Doc(markdown = """""")]` or any other Doc rewrite, inserting an empty or incomplete `[Host]` or `[BuiltinType]`, `W_SEM_IGNORED_VALUE`, unresolved imports, an invalid reserved-attribute target, parse errors, unresolved overloads, and method stubs.
|
||||||
|
|
||||||
|
`AGD-0048` still owns formatting. `AGD-0049` still owns import assistance and organize-imports. `AGD-0054` still owns range, related locations, and diagnostic presentation. The PBS diagnostics spec does not gain a mandatory remediation field.
|
||||||
|
|
||||||
|
Spec 23 §8.3 now states the shared contract: code actions are quick fixes only; the frontend produces each repair from the document syntax; tooling transports it and does not parse the message or switch on codes; the published diagnostic carries the stable code; a repair is returned only for a matching context diagnostic; the edit is one physical file; the server does not write files, return a command, or require resolve; a missing capability is an empty list, not an error; virtual documents get no edit.
|
||||||
|
|
||||||
|
## Final Implementation
|
||||||
|
|
||||||
|
| Layer | What landed |
|
||||||
|
|---|---|
|
||||||
|
| PBS repairs | `PbsQuickFixCollector` walks the same attribute surfaces as `PbsDeclarationSemanticsValidator`, including the interface-module gate. Duplicate reserved attributes become an empty replacement of the extra span. The first `InitAllowed` with arguments on an interface host signature becomes `[InitAllowed]`. |
|
||||||
|
| Source kind | `PbsSemanticReadSurface.sourceKindByFile` records the kind used to parse each file. A missing kind means project rules, so a project `declare host` does not pretend the validator emitted the interface-only `InitAllowed` diagnostic. |
|
||||||
|
| Generic contract | `FrontendLanguageService.codeActionsSupported` defaults false. `codeActions` defaults empty. `FrontendCodeAction` is title, diagnostic code, path, offsets, and `newText`. Empty `newText` is a deletion and is allowed. |
|
||||||
|
| PBS mapping | `PBSFrontendLanguageService` exposes the capability and returns repairs only for the requested regular file. `/virtual/stdlib` fails `Files.isRegularFile` and produces nothing. |
|
||||||
|
| LSP | `BaselineDocumentIssue.code` is copied onto `Diagnostic.code`. `data` stays unset. The bridge drops repairs whose code and range do not match a context diagnostic. `PrometeuTextDocumentService.codeAction` honors the quick-fix `only` filter and never fails the request for “no fix”. |
|
||||||
|
| Protocol | `codeActionProvider` is `CodeActionOptions` with kind `quickfix` and `resolveProvider` false, and only when the frontend reports support. Mapped actions are `CodeAction` values with a `WorkspaceEdit`. They are not `Command`s. |
|
||||||
|
|
||||||
|
Titles are `Remove duplicate reserved attribute` and `Remove InitAllowed arguments`.
|
||||||
|
|
||||||
|
## Examples
|
||||||
|
|
||||||
|
Duplicate `Doc` on a project file. The first copy stays. Each later copy is deleted at its own span:
|
||||||
|
|
||||||
|
```pbs
|
||||||
|
[Doc(markdown = """
|
||||||
|
First.
|
||||||
|
""")]
|
||||||
|
[Doc(markdown = """
|
||||||
|
Second.
|
||||||
|
""")]
|
||||||
|
fn duplicated() -> void { return; }
|
||||||
|
```
|
||||||
|
|
||||||
|
The quick fix removes the second attribute and leaves `First.`. A context diagnostic with the same range but code `E_SEM_MALFORMED_RESERVED_ATTRIBUTE` produces no action. An empty diagnostic list produces no action.
|
||||||
|
|
||||||
|
Malformed or empty Doc is visible and not repairable here:
|
||||||
|
|
||||||
|
```pbs
|
||||||
|
[Doc(text = """
|
||||||
|
Wrong argument.
|
||||||
|
""")]
|
||||||
|
fn malformed() -> void { return; }
|
||||||
|
```
|
||||||
|
|
||||||
|
`InitAllowed` with arguments is repaired only on an interface-module host signature:
|
||||||
|
|
||||||
|
```pbs
|
||||||
|
declare host Gfx {
|
||||||
|
[Host(module = "gfx2d", name = "clear", version = 1)]
|
||||||
|
[InitAllowed(flag = 1)]
|
||||||
|
fn clear() -> void;
|
||||||
|
|
||||||
|
[Host(module = "gfx2d", name = "fill", version = 1)]
|
||||||
|
[InitAllowed()]
|
||||||
|
fn fill() -> void;
|
||||||
|
}
|
||||||
|
```
|
||||||
|
|
||||||
|
`clear` becomes `[InitAllowed]`. `fill` is already valid to the validator, so `[InitAllowed()]` is left alone. The same `InitAllowed(flag = 1)` inside a project file does not get that repair, because the validator does not emit the malformed-attribute diagnostic there.
|
||||||
|
|
||||||
|
The same collector deletes the extra copy of `BuiltinType`, `IntrinsicCall`, `BuiltinConst`, `Host`, and `AssetLowering` when the validator reports `E_SEM_DUPLICATE_RESERVED_ATTRIBUTE` for that surface. A malformed `Host` that merely shares the malformed-attribute code gets no edit.
|
||||||
|
|
||||||
|
## Pitfalls
|
||||||
|
|
||||||
|
Do not choose the edit in `prometeu-lsp` by switching on `E_SEM_MALFORMED_RESERVED_ATTRIBUTE` or by parsing the English message. The code is too coarse, and the message is not the identity.
|
||||||
|
|
||||||
|
Do not store the repair on compiler `Diagnostic` or in `Diagnostic.data`. Compilation and quick fix stay different surfaces. The published code exists so the client can echo it back.
|
||||||
|
|
||||||
|
Do not match on `Diagnostic.source` as if it were the long-term identity field. Today the bridge still copies the code into `source` for the existing presentation. The code-action match uses `Diagnostic.code`. `AGD-0054` may change `source` later.
|
||||||
|
|
||||||
|
Do not delete the first duplicate, and do not trim the whitespace around the deleted span. That cleanup is formatting and belongs to `AGD-0048`.
|
||||||
|
|
||||||
|
Do not insert `[Doc(markdown = """""")]`, an empty `[Host]`, or an empty `[BuiltinType]`. Those edits trade one diagnostic for another, or invent a declaration.
|
||||||
|
|
||||||
|
Do not treat `W_SEM_IGNORED_VALUE` as a source edit. Discard exists in lowering, not as PBS syntax.
|
||||||
|
|
||||||
|
Do not offer the `InitAllowed` rewrite for `[InitAllowed()]` or for a project file. The validator does not diagnose those shapes as “arguments not allowed”, so there is no diagnostic to attach.
|
||||||
|
|
||||||
|
Do not return a protocol error when there is no fix. Rename refuses a bad cursor with an error. Quick fix answers “nothing to do” with an empty list.
|
||||||
|
|
||||||
|
Do not advertise `codeActionProvider` for every frontend that has a language service. The default capability is unsupported.
|
||||||
|
|
||||||
|
Do not treat this lesson as closing formatting, import assistance, diagnostic presentation, snapshots, folding, document links, or hierarchy.
|
||||||
|
|
||||||
|
## References
|
||||||
|
|
||||||
|
- Agenda: `AGD-0047` (scope A, producer B, residence B, first wave C)
|
||||||
|
- Decision: `DEC-0057`
|
||||||
|
- Plan: `PLN-0136`
|
||||||
|
- Spec 23 §8.3 — optional code actions; frontend-owned repair; match by code and range; empty list when unsupported
|
||||||
|
- Spec: `docs/specs/compiler-languages/pbs/12. Diagnostics Specification.md` — wording is not identity; remediation stays outside the v1 diagnostic minimum
|
||||||
|
- `LSN-0056` — code actions are an optional editorial capability
|
||||||
|
- `LSN-0058` — generic `FrontendLanguageService` for the LSP
|
||||||
|
- `LSN-0067` — no new editorial SPI without a real consumer; PBS implements the existing language service
|
||||||
|
- Still open: `AGD-0048` formatting, `AGD-0049` import assistance, `AGD-0054` diagnostics UX, `AGD-0051` snapshots, `AGD-0056` hierarchy
|
||||||
+151
@@ -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`
|
||||||
+167
@@ -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,62 +0,0 @@
|
|||||||
---
|
|
||||||
id: AGD-0043
|
|
||||||
ticket: pbs-lsp-find-references
|
|
||||||
title: PBS LSP Find References
|
|
||||||
status: open
|
|
||||||
created: 2026-07-15
|
|
||||||
resolved:
|
|
||||||
decision:
|
|
||||||
tags: [studio, lsp, vscode, compiler-pbs, editor, references]
|
|
||||||
---
|
|
||||||
|
|
||||||
## Pain
|
|
||||||
|
|
||||||
Domain owner: `studio/lsp`
|
|
||||||
|
|
||||||
PBS users cannot ask where a symbol is used, so changes to functions, services, structs, constants, and stdlib-facing APIs require manual search that confuses overloads and unrelated text matches.
|
|
||||||
|
|
||||||
## Context
|
|
||||||
|
|
||||||
Completion and hover already resolve symbols in local editor context, but the LSP does not expose references and the compiler/editorial layer does not yet provide project-wide usage locations keyed by semantic identity.
|
|
||||||
|
|
||||||
## Open Questions
|
|
||||||
|
|
||||||
- [ ] Which declarations need reference tracking first: local functions, methods, types, constants, imports, stdlib symbols, or all of them?
|
|
||||||
- [ ] How should overloads and same-name symbols in different scopes be disambiguated?
|
|
||||||
- [ ] Should references include declarations, write/read classification, or only usage sites in the first wave?
|
|
||||||
|
|
||||||
## Options
|
|
||||||
|
|
||||||
### Option A - Text search with filters
|
|
||||||
|
|
||||||
- **Approach:** Search workspace text for the selected identifier and filter obvious false positives by token kind.
|
|
||||||
- **Pro:** Simple and fast for early demos.
|
|
||||||
- **Con:** Incorrect for overloads, scope, shadowing, fields, methods, imports, and generated/stdlib surfaces.
|
|
||||||
- **Maintainability:** Poor; later semantic references would duplicate and replace it.
|
|
||||||
|
|
||||||
### Option B - Semantic usage index
|
|
||||||
|
|
||||||
- **Approach:** During semantic analysis, emit definition and usage sites tied to stable symbol identities and expose `textDocument/references`.
|
|
||||||
- **Pro:** Correct foundation for rename, call hierarchy, diagnostics UX, and code actions.
|
|
||||||
- **Con:** Requires compiler-facing usage modeling and careful invalidation.
|
|
||||||
- **Maintainability:** Strong; one source of truth for all symbol usage features.
|
|
||||||
|
|
||||||
## Tradeoffs
|
|
||||||
|
|
||||||
Reference accuracy matters more than early breadth. False positives are worse than missing unsupported categories because users will trust rename and references for safe edits.
|
|
||||||
|
|
||||||
## Recommendation
|
|
||||||
|
|
||||||
Prefer Option B, but scope the first wave to project-owned declarations whose identity is already resolved reliably.
|
|
||||||
|
|
||||||
## Discussion
|
|
||||||
|
|
||||||
References should follow go-to-definition because both need the same identity and location model.
|
|
||||||
|
|
||||||
## Resolution
|
|
||||||
|
|
||||||
Ainda em aberto.
|
|
||||||
|
|
||||||
## Next Step
|
|
||||||
|
|
||||||
Define first-wave symbol categories and whether declarations are included in reference results.
|
|
||||||
@@ -1,62 +0,0 @@
|
|||||||
---
|
|
||||||
id: AGD-0044
|
|
||||||
ticket: pbs-lsp-document-symbols-outline
|
|
||||||
title: PBS LSP Document Symbols and Outline
|
|
||||||
status: open
|
|
||||||
created: 2026-07-15
|
|
||||||
resolved:
|
|
||||||
decision:
|
|
||||||
tags: [studio, lsp, vscode, compiler-pbs, editor, outline, document-symbols]
|
|
||||||
---
|
|
||||||
|
|
||||||
## Pain
|
|
||||||
|
|
||||||
Domain owner: `studio/lsp`
|
|
||||||
|
|
||||||
PBS files do not populate a reliable VS Code outline, forcing users to navigate long source files manually instead of scanning declarations and members structurally.
|
|
||||||
|
|
||||||
## Context
|
|
||||||
|
|
||||||
The parser and semantic surfaces know top-level declarations and many member declarations. The LSP currently does not announce documentSymbolProvider and does not map PBS declarations to DocumentSymbol or SymbolInformation payloads.
|
|
||||||
|
|
||||||
## Open Questions
|
|
||||||
|
|
||||||
- [ ] Should the first outline be syntactic, semantic, or hybrid?
|
|
||||||
- [ ] Which hierarchy should be shown for structs, services, hosts, contracts, builtin types, enums, and methods?
|
|
||||||
- [ ] How should invalid or partially parsed files contribute to outline during editing?
|
|
||||||
|
|
||||||
## Options
|
|
||||||
|
|
||||||
### Option A - AST-only outline
|
|
||||||
|
|
||||||
- **Approach:** Map parsed declarations and member spans directly to LSP `DocumentSymbol`.
|
|
||||||
- **Pro:** Works even when semantic analysis is incomplete and gives immediate editor value.
|
|
||||||
- **Con:** Cannot classify every symbol with semantic precision.
|
|
||||||
- **Maintainability:** Good if kept as structural outline, not overloaded with semantic behavior.
|
|
||||||
|
|
||||||
### Option B - Semantic outline
|
|
||||||
|
|
||||||
- **Approach:** Build outline from semantic symbols after analysis.
|
|
||||||
- **Pro:** More accurate kinds and can hide invalid/unresolved surfaces.
|
|
||||||
- **Con:** More fragile during active editing and depends on full semantic success.
|
|
||||||
- **Maintainability:** Good for final precision, but heavier than needed for outline.
|
|
||||||
|
|
||||||
## Tradeoffs
|
|
||||||
|
|
||||||
Outline should remain available during broken intermediate edits. Semantic precision is useful, but not at the cost of disappearing structure while typing.
|
|
||||||
|
|
||||||
## Recommendation
|
|
||||||
|
|
||||||
Prefer Option A with semantic enrichment where available. Use AST spans as the stable backbone.
|
|
||||||
|
|
||||||
## Discussion
|
|
||||||
|
|
||||||
Document symbols are relatively independent and can be implemented before definition/references.
|
|
||||||
|
|
||||||
## Resolution
|
|
||||||
|
|
||||||
Ainda em aberto.
|
|
||||||
|
|
||||||
## Next Step
|
|
||||||
|
|
||||||
Decide hierarchy and symbol kinds for PBS declarations and members.
|
|
||||||
@@ -1,62 +0,0 @@
|
|||||||
---
|
|
||||||
id: AGD-0045
|
|
||||||
ticket: pbs-lsp-workspace-symbols
|
|
||||||
title: PBS LSP Workspace Symbols
|
|
||||||
status: open
|
|
||||||
created: 2026-07-15
|
|
||||||
resolved:
|
|
||||||
decision:
|
|
||||||
tags: [studio, lsp, vscode, compiler-pbs, editor, workspace-symbols]
|
|
||||||
---
|
|
||||||
|
|
||||||
## Pain
|
|
||||||
|
|
||||||
Domain owner: `studio/lsp`
|
|
||||||
|
|
||||||
VS Code cannot search PBS symbols across the workspace, so users cannot quickly jump to functions, services, structs, constants, or stdlib-exposed APIs by name.
|
|
||||||
|
|
||||||
## Context
|
|
||||||
|
|
||||||
Document-level editorial features exist, but the LSP does not announce workspaceSymbolProvider and the compiler pipeline does not expose a project-wide symbol index designed for editor queries.
|
|
||||||
|
|
||||||
## Open Questions
|
|
||||||
|
|
||||||
- [ ] Should workspace symbols include only project files or also imported stdlib and SDK surfaces?
|
|
||||||
- [ ] What symbol kinds and ranking should be returned for duplicate names or overloads?
|
|
||||||
- [ ] Should the symbol index be cached from analysis snapshots or rebuilt per request in the first implementation?
|
|
||||||
|
|
||||||
## Options
|
|
||||||
|
|
||||||
### Option A - Project source index only
|
|
||||||
|
|
||||||
- **Approach:** Index project-owned declarations from analysis snapshots and expose `workspace/symbol`.
|
|
||||||
- **Pro:** Clear ownership and physical locations.
|
|
||||||
- **Con:** Does not help users discover stdlib/SDK symbols.
|
|
||||||
- **Maintainability:** Strong as a first wave.
|
|
||||||
|
|
||||||
### Option B - Project plus stdlib index
|
|
||||||
|
|
||||||
- **Approach:** Include project declarations and imported stdlib/SDK surfaces in the workspace symbol result set.
|
|
||||||
- **Pro:** Better discovery, especially for new users.
|
|
||||||
- **Con:** Requires a navigation policy for stdlib source or virtual targets.
|
|
||||||
- **Maintainability:** Good if stdlib target handling is solved; awkward otherwise.
|
|
||||||
|
|
||||||
## Tradeoffs
|
|
||||||
|
|
||||||
Workspace symbols are partly navigation and partly discovery. Including stdlib too early can create broken jumps if target locations are not defined.
|
|
||||||
|
|
||||||
## Recommendation
|
|
||||||
|
|
||||||
Prefer Option A first, then add stdlib once definition has a target policy.
|
|
||||||
|
|
||||||
## Discussion
|
|
||||||
|
|
||||||
This should follow document symbols and the semantic location/index work.
|
|
||||||
|
|
||||||
## Resolution
|
|
||||||
|
|
||||||
Ainda em aberto.
|
|
||||||
|
|
||||||
## Next Step
|
|
||||||
|
|
||||||
Decide whether first-wave workspace search includes stdlib or project-only symbols.
|
|
||||||
@@ -1,62 +0,0 @@
|
|||||||
---
|
|
||||||
id: AGD-0046
|
|
||||||
ticket: pbs-lsp-rename-symbol
|
|
||||||
title: PBS LSP Rename Symbol
|
|
||||||
status: open
|
|
||||||
created: 2026-07-15
|
|
||||||
resolved:
|
|
||||||
decision:
|
|
||||||
tags: [studio, lsp, vscode, compiler-pbs, editor, rename]
|
|
||||||
---
|
|
||||||
|
|
||||||
## Pain
|
|
||||||
|
|
||||||
Domain owner: `studio/lsp`
|
|
||||||
|
|
||||||
PBS users cannot safely rename a symbol through the editor, so they must edit text manually and risk missing references or changing unrelated overloads and same-name declarations.
|
|
||||||
|
|
||||||
## Context
|
|
||||||
|
|
||||||
Rename requires the same semantic identity and reference machinery needed by definition/references, plus workspace edits and conflict detection. The current LSP does not announce renameProvider.
|
|
||||||
|
|
||||||
## Open Questions
|
|
||||||
|
|
||||||
- [ ] Which symbols should be renameable in the first wave, and which should be protected such as stdlib, generated, host, or builtin declarations?
|
|
||||||
- [ ] How should rename handle overloads, member methods, imports, and labels with the same text?
|
|
||||||
- [ ] What validation should run before returning a WorkspaceEdit?
|
|
||||||
|
|
||||||
## Options
|
|
||||||
|
|
||||||
### Option A - Local file rename
|
|
||||||
|
|
||||||
- **Approach:** Rename only references in the current file using local semantic resolution.
|
|
||||||
- **Pro:** Smaller blast radius and easier conflict handling.
|
|
||||||
- **Con:** Incomplete for imported symbols and project-wide APIs.
|
|
||||||
- **Maintainability:** Acceptable only if explicitly presented as limited.
|
|
||||||
|
|
||||||
### Option B - Workspace semantic rename
|
|
||||||
|
|
||||||
- **Approach:** Use a project-wide reference index and return a `WorkspaceEdit` for all usage and declaration sites.
|
|
||||||
- **Pro:** Matches user expectations for editor rename.
|
|
||||||
- **Con:** Requires reliable references, collision checks, and write-safety across files.
|
|
||||||
- **Maintainability:** Strong once references exist.
|
|
||||||
|
|
||||||
## Tradeoffs
|
|
||||||
|
|
||||||
Rename is high trust. A partial or text-based rename can corrupt code silently, so scope must be explicit and conservative.
|
|
||||||
|
|
||||||
## Recommendation
|
|
||||||
|
|
||||||
Prefer Option B after semantic references are implemented. If delivered earlier, ship only a clearly limited local rename.
|
|
||||||
|
|
||||||
## Discussion
|
|
||||||
|
|
||||||
Do not implement rename before definition/references are resolved.
|
|
||||||
|
|
||||||
## Resolution
|
|
||||||
|
|
||||||
Ainda em aberto.
|
|
||||||
|
|
||||||
## Next Step
|
|
||||||
|
|
||||||
Decide whether rename waits for workspace references or ships a limited local-only wave.
|
|
||||||
@@ -1,62 +0,0 @@
|
|||||||
---
|
|
||||||
id: AGD-0047
|
|
||||||
ticket: pbs-lsp-code-actions
|
|
||||||
title: PBS LSP Code Actions and Quick Fixes
|
|
||||||
status: open
|
|
||||||
created: 2026-07-15
|
|
||||||
resolved:
|
|
||||||
decision:
|
|
||||||
tags: [studio, lsp, vscode, compiler-pbs, editor, code-actions, quick-fix]
|
|
||||||
---
|
|
||||||
|
|
||||||
## Pain
|
|
||||||
|
|
||||||
Domain owner: `studio/lsp`
|
|
||||||
|
|
||||||
PBS diagnostics are visible, but users do not get actionable quick fixes for common compiler/editor problems, making simple repairs slower than necessary.
|
|
||||||
|
|
||||||
## Context
|
|
||||||
|
|
||||||
The LSP maps diagnostics but does not announce codeActionProvider. Compiler diagnostics already carry codes and ranges, but not every diagnostic has enough structured repair data to generate safe edits.
|
|
||||||
|
|
||||||
## Open Questions
|
|
||||||
|
|
||||||
- [ ] Which diagnostics should receive quick fixes first?
|
|
||||||
- [ ] Should code actions be produced from diagnostic codes only, or from structured compiler repair hints?
|
|
||||||
- [ ] How should imports, reserved attributes, missing methods, and invalid Doc shapes be prioritized?
|
|
||||||
|
|
||||||
## Options
|
|
||||||
|
|
||||||
### Option A - Diagnostic-code quick fixes
|
|
||||||
|
|
||||||
- **Approach:** Map known diagnostic codes to simple edits in the LSP layer.
|
|
||||||
- **Pro:** Fast for a small set of obvious repairs.
|
|
||||||
- **Con:** Couples fixes to diagnostic text/ranges and can become brittle.
|
|
||||||
- **Maintainability:** Moderate if limited to trivial edits.
|
|
||||||
|
|
||||||
### Option B - Compiler repair hints
|
|
||||||
|
|
||||||
- **Approach:** Extend diagnostics with structured repair metadata and let the LSP map hints to code actions.
|
|
||||||
- **Pro:** Keeps product logic close to compiler knowledge.
|
|
||||||
- **Con:** Requires a new diagnostic/repair contract.
|
|
||||||
- **Maintainability:** Strong for non-trivial fixes and future frontends.
|
|
||||||
|
|
||||||
## Tradeoffs
|
|
||||||
|
|
||||||
Quick fixes are only useful if safe. Simple code-based fixes can ship first, but imports and generated stubs need stronger compiler context.
|
|
||||||
|
|
||||||
## Recommendation
|
|
||||||
|
|
||||||
Prefer Option B as the target design, with Option A allowed only for a small bootstrap set of unambiguous repairs.
|
|
||||||
|
|
||||||
## Discussion
|
|
||||||
|
|
||||||
This should follow diagnostics UX and import assistance for the first high-value fixes.
|
|
||||||
|
|
||||||
## Resolution
|
|
||||||
|
|
||||||
Ainda em aberto.
|
|
||||||
|
|
||||||
## Next Step
|
|
||||||
|
|
||||||
Pick the first three diagnostic codes eligible for safe quick fixes.
|
|
||||||
@@ -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. |
|
||||||
|
|||||||
@@ -272,6 +272,18 @@ 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.
|
||||||
|
|
||||||
|
When a frontend exposes find-references, each returned usage or declaration location MUST identify a compiler-known physical source file. A cursor offset whose definition response is empty MUST produce an empty references response. Host `includeDeclaration` MAY add the canonical declaration location only when that declaration is a compiler-known physical source file; it MUST NOT invent a virtual, untitled, or synthetic location.
|
||||||
|
|
||||||
|
When a frontend exposes document symbols or outline, the result MUST be the named declaration tree of the requested document. Presence, hierarchy, and ranges MUST come from that document's recovered syntax tree. Semantic success MUST NOT be required. Semantic enrichment MUST NOT drop a named declaration that the syntax tree still exposes. A missing syntax tree MUST produce an empty list. Document symbols MUST NOT be a workspace symbol index, folding ranges, or a navigation list of foreign files.
|
||||||
|
|
||||||
|
When a frontend exposes workspace symbols, the result MUST be a flat search of named declarations whose locations identify compiler-known physical source files of the current analysis. Presence, names, kinds, details, and ranges MUST come from the recovered syntax of those files. Semantic success MUST NOT be required. Semantic enrichment MUST NOT drop a named declaration that the syntax tree still exposes. A missing analysis surface MUST produce an empty list. The workspace-symbol request MUST NOT require an open text document. A declaration without a compiler-known physical file MUST be omitted. Tooling MUST NOT require virtual documents, untitled buffers, or synthetic URIs for this capability. Workspace symbols MUST NOT be a document outline, folding ranges, a persistent symbol index, or a navigation list of virtual locations.
|
||||||
|
|
||||||
|
When a frontend exposes rename, the result MUST be a validated workspace edit of identifier spans whose locations identify compiler-known physical source files. Identity MUST be the physical declaration locations that definition returns at the cursor. A local or parameter name span MUST still be renameable when definition at that offset is empty. Each rewritten location MUST identify a compiler-known physical source file. A cursor that is not renameable, including builtins, virtual paths, unresolved names, keywords, comments, strings, import aliases and uses of those aliases, error case labels without their own span, and barrel files, MUST produce a protocol error or a null prepareRename result. Tooling MUST NOT return a successful empty workspace edit for a refused cursor or an invalid new name. The new name MUST be a language identifier that is not a keyword and MUST NOT collide in the same binding space, ignoring the sites being rewritten and the overload set being renamed. The server MUST NOT write files and MUST NOT rename file paths. Host prepareRename MUST advertise a prepareProvider when rename is exposed. Tooling MUST NOT require virtual documents, untitled buffers, or synthetic URIs for this capability.
|
||||||
|
|
||||||
|
When a frontend exposes code actions, the result MUST be quick fixes only: one workspace edit tied to a diagnostic of the requested physical document. The frontend MUST produce each repair from that document's syntax. Each repair MUST name the stable diagnostic code, the primary span, and exactly one local text edit. Tooling MUST transport that repair. Tooling MUST NOT choose the edit by parsing the diagnostic message or by a diagnostic-code table. A repair MUST NOT be a required field of compiler diagnostics and MUST NOT be published inside diagnostic data. The published diagnostic MUST carry the stable code so a later code-action request can match it. A repair MUST be returned only when the request context contains a diagnostic with the same code and the same primary range. An empty diagnostic context MUST produce an empty list. The edit MUST change only the requested physical source file. The server MUST NOT write files, MUST NOT return a command, and MUST NOT require a resolve round trip. A missing code-action capability MUST NOT advertise code actions and MUST produce an empty list rather than a protocol error. Virtual, untitled, or synthetic documents MUST NOT receive an edit. Code actions MUST NOT include organize-imports, source actions, refactors, or generated stubs unless a future accepted decision says so.
|
||||||
|
|
||||||
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.
|
||||||
|
|||||||
@@ -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" }
|
||||||
|
|||||||
@@ -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
|
||||||
|
}
|
||||||
+63
@@ -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");
|
||||||
|
}
|
||||||
|
}
|
||||||
+22
@@ -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()));
|
||||||
|
}
|
||||||
|
}
|
||||||
+85
@@ -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");
|
||||||
|
}
|
||||||
|
}
|
||||||
+43
@@ -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");
|
||||||
|
}
|
||||||
+36
@@ -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('\\', '/');
|
||||||
|
}
|
||||||
|
}
|
||||||
+447
-1
@@ -6,12 +6,26 @@ 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.PbsEditorialDocumentSymbol;
|
||||||
|
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.pbs.semantics.PbsEditorialSupportService.EditorialDocument;
|
||||||
|
import p.studio.compiler.models.SourceKind;
|
||||||
|
import p.studio.compiler.pbs.semantics.PbsEditorialRename;
|
||||||
|
import p.studio.compiler.pbs.semantics.PbsEditorialWorkspaceSymbol;
|
||||||
|
import p.studio.compiler.pbs.semantics.PbsQuickFix;
|
||||||
|
import p.studio.compiler.pbs.semantics.PbsQuickFixCollector;
|
||||||
|
import p.studio.compiler.services.PBSFrontendPhaseService.PbsSemanticReadSurface;
|
||||||
|
import p.studio.compiler.services.FrontendCodeAction;
|
||||||
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.FrontendDocumentSymbol;
|
||||||
|
import p.studio.compiler.services.FrontendRenameEdit;
|
||||||
|
import p.studio.compiler.services.FrontendRenameResult;
|
||||||
import p.studio.compiler.services.FrontendDocumentation;
|
import p.studio.compiler.services.FrontendDocumentation;
|
||||||
import p.studio.compiler.services.FrontendEditorialContext;
|
import p.studio.compiler.services.FrontendEditorialContext;
|
||||||
import p.studio.compiler.services.FrontendHover;
|
import p.studio.compiler.services.FrontendHover;
|
||||||
@@ -19,11 +33,20 @@ import p.studio.compiler.services.FrontendLanguageService;
|
|||||||
import p.studio.compiler.services.FrontendSignature;
|
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.FrontendWorkspaceRequest;
|
||||||
|
import p.studio.compiler.services.FrontendWorkspaceSymbol;
|
||||||
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.Comparator;
|
||||||
|
import java.util.LinkedHashMap;
|
||||||
import java.util.List;
|
import java.util.List;
|
||||||
import java.util.Objects;
|
import java.util.Objects;
|
||||||
import java.util.Optional;
|
import java.util.Optional;
|
||||||
@@ -43,6 +66,23 @@ public final class PBSFrontendLanguageService implements FrontendLanguageService
|
|||||||
this.semanticTokenProvider = Objects.requireNonNull(semanticTokenProvider, "semanticTokenProvider");
|
this.semanticTokenProvider = Objects.requireNonNull(semanticTokenProvider, "semanticTokenProvider");
|
||||||
}
|
}
|
||||||
|
|
||||||
|
@Override
|
||||||
|
public Optional<FrontendEditorialContext> prepareEditorialContext(final FrontendPhaseContext phaseContext) {
|
||||||
|
if (phaseContext == null) {
|
||||||
|
return Optional.empty();
|
||||||
|
}
|
||||||
|
final var semanticReadSurface = PBSFrontendPhaseService.semanticReadSurface(
|
||||||
|
phaseContext,
|
||||||
|
DiagnosticSink.empty(),
|
||||||
|
BuildingIssueSink.empty());
|
||||||
|
return Optional.of(new FrontendEditorialContext(
|
||||||
|
null,
|
||||||
|
ReadOnlyList.empty(),
|
||||||
|
phaseContext.feSurfaceContext(),
|
||||||
|
phaseContext.fileTable,
|
||||||
|
semanticReadSurface));
|
||||||
|
}
|
||||||
|
|
||||||
@Override
|
@Override
|
||||||
public Optional<FrontendEditorialContext> prepareEditorialContext(
|
public Optional<FrontendEditorialContext> prepareEditorialContext(
|
||||||
final FrontendPhaseContext phaseContext,
|
final FrontendPhaseContext phaseContext,
|
||||||
@@ -61,7 +101,9 @@ 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,
|
||||||
|
semanticReadSurface));
|
||||||
}
|
}
|
||||||
|
|
||||||
public List<PbsEditorialCompletionCandidate> completion(
|
public List<PbsEditorialCompletionCandidate> completion(
|
||||||
@@ -167,6 +209,272 @@ 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
|
||||||
|
public List<FrontendDefinitionLocation> references(
|
||||||
|
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 List<PbsEditorialLocation> editorialIdentity = definition(
|
||||||
|
request.documentText(),
|
||||||
|
ast,
|
||||||
|
typedSupplementalTopDecls,
|
||||||
|
feSurfaceContext,
|
||||||
|
offset);
|
||||||
|
final ArrayList<PbsEditorialLocation> physicalIdentity = new ArrayList<>();
|
||||||
|
for (final PbsEditorialLocation location : editorialIdentity) {
|
||||||
|
if (toFrontendLocation(location, fileTable).isPresent()) {
|
||||||
|
physicalIdentity.add(location);
|
||||||
|
}
|
||||||
|
}
|
||||||
|
if (physicalIdentity.isEmpty()) {
|
||||||
|
return List.of();
|
||||||
|
}
|
||||||
|
|
||||||
|
final EditorialDocument cursorDocument = new EditorialDocument(
|
||||||
|
request.documentText(),
|
||||||
|
ast,
|
||||||
|
typedSupplementalTopDecls,
|
||||||
|
feSurfaceContext);
|
||||||
|
final List<PbsEditorialLocation> usages = editorialSupportService.references(
|
||||||
|
cursorDocument,
|
||||||
|
offset,
|
||||||
|
projectDocuments(request, editorialContext, cursorDocument, fileTable));
|
||||||
|
final LinkedHashMap<String, FrontendDefinitionLocation> mapped = new LinkedHashMap<>();
|
||||||
|
for (final PbsEditorialLocation usage : usages) {
|
||||||
|
toFrontendLocation(usage, fileTable).ifPresent(location ->
|
||||||
|
mapped.putIfAbsent(frontendLocationKey(location), location));
|
||||||
|
}
|
||||||
|
return List.copyOf(mapped.values());
|
||||||
|
}
|
||||||
|
|
||||||
|
@Override
|
||||||
|
public List<FrontendDocumentSymbol> documentSymbols(
|
||||||
|
final FrontendDocumentRequest request,
|
||||||
|
final FrontendEditorialContext editorialContext) {
|
||||||
|
if (editorialContext == null || !(editorialContext.syntaxTree() instanceof PbsAst.File ast)) {
|
||||||
|
return List.of();
|
||||||
|
}
|
||||||
|
return editorialSupportService.documentSymbols(ast).stream()
|
||||||
|
.map(this::toFrontendDocumentSymbol)
|
||||||
|
.toList();
|
||||||
|
}
|
||||||
|
|
||||||
|
@Override
|
||||||
|
public List<FrontendWorkspaceSymbol> workspaceSymbols(
|
||||||
|
final FrontendWorkspaceRequest request,
|
||||||
|
final FrontendEditorialContext editorialContext) {
|
||||||
|
if (request == null
|
||||||
|
|| editorialContext == null
|
||||||
|
|| !(editorialContext.sourceFiles() instanceof FileTableReader fileTable)
|
||||||
|
|| !(editorialContext.projectSurface() instanceof PbsSemanticReadSurface surface)
|
||||||
|
|| surface.astByFile() == null
|
||||||
|
|| surface.astByFile().isEmpty()) {
|
||||||
|
return List.of();
|
||||||
|
}
|
||||||
|
final ArrayList<FrontendWorkspaceSymbol> symbols = new ArrayList<>();
|
||||||
|
for (final var entry : surface.astByFile().entrySet()) {
|
||||||
|
final Path path = pathForRegularSource(entry.getKey(), fileTable);
|
||||||
|
if (path == null) {
|
||||||
|
continue;
|
||||||
|
}
|
||||||
|
final PbsAst.File fileAst = entry.getValue();
|
||||||
|
if (fileAst == null) {
|
||||||
|
continue;
|
||||||
|
}
|
||||||
|
for (final PbsEditorialWorkspaceSymbol symbol : editorialSupportService.workspaceSymbols(
|
||||||
|
fileAst,
|
||||||
|
request.query())) {
|
||||||
|
toFrontendWorkspaceSymbol(symbol, path).ifPresent(symbols::add);
|
||||||
|
}
|
||||||
|
}
|
||||||
|
symbols.sort(Comparator
|
||||||
|
.comparing(FrontendWorkspaceSymbol::name, String.CASE_INSENSITIVE_ORDER)
|
||||||
|
.thenComparing(symbol -> symbol.path().toString())
|
||||||
|
.thenComparingInt(FrontendWorkspaceSymbol::startOffset));
|
||||||
|
return List.copyOf(symbols);
|
||||||
|
}
|
||||||
|
|
||||||
|
@Override
|
||||||
|
public Optional<FrontendDefinitionLocation> prepareRename(
|
||||||
|
final FrontendDocumentRequest request,
|
||||||
|
final FrontendEditorialContext editorialContext,
|
||||||
|
final int offset) {
|
||||||
|
final PbsEditorialRename planned = editorialRename(request, editorialContext, offset, null);
|
||||||
|
if (planned == null || !planned.allowed()) {
|
||||||
|
return Optional.empty();
|
||||||
|
}
|
||||||
|
if (!(editorialContext.sourceFiles() instanceof FileTableReader fileTable)) {
|
||||||
|
return Optional.empty();
|
||||||
|
}
|
||||||
|
if (physicalIdentity(planned, fileTable).isEmpty()) {
|
||||||
|
return Optional.empty();
|
||||||
|
}
|
||||||
|
return toFrontendLocation(planned.placeholder(), fileTable);
|
||||||
|
}
|
||||||
|
|
||||||
|
@Override
|
||||||
|
public FrontendRenameResult rename(
|
||||||
|
final FrontendDocumentRequest request,
|
||||||
|
final FrontendEditorialContext editorialContext,
|
||||||
|
final int offset,
|
||||||
|
final String newName) {
|
||||||
|
if (newName == null) {
|
||||||
|
return FrontendRenameResult.refused("invalid identifier");
|
||||||
|
}
|
||||||
|
final PbsEditorialRename planned = editorialRename(request, editorialContext, offset, newName);
|
||||||
|
if (planned == null) {
|
||||||
|
return FrontendRenameResult.refused("not renameable");
|
||||||
|
}
|
||||||
|
if (!planned.allowed()) {
|
||||||
|
return FrontendRenameResult.refused(planned.refusal());
|
||||||
|
}
|
||||||
|
if (!(editorialContext.sourceFiles() instanceof FileTableReader fileTable)) {
|
||||||
|
return FrontendRenameResult.refused("not renameable");
|
||||||
|
}
|
||||||
|
if (physicalIdentity(planned, fileTable).isEmpty()) {
|
||||||
|
return FrontendRenameResult.refused("not renameable");
|
||||||
|
}
|
||||||
|
final LinkedHashMap<String, FrontendRenameEdit> edits = new LinkedHashMap<>();
|
||||||
|
for (final PbsEditorialLocation site : planned.sites()) {
|
||||||
|
toFrontendLocation(site, fileTable).ifPresent(location ->
|
||||||
|
edits.putIfAbsent(
|
||||||
|
frontendLocationKey(location),
|
||||||
|
new FrontendRenameEdit(
|
||||||
|
location.path(),
|
||||||
|
location.startOffset(),
|
||||||
|
location.endOffset(),
|
||||||
|
newName)));
|
||||||
|
}
|
||||||
|
if (edits.isEmpty()) {
|
||||||
|
return FrontendRenameResult.refused("not renameable");
|
||||||
|
}
|
||||||
|
return FrontendRenameResult.applied(List.copyOf(edits.values()));
|
||||||
|
}
|
||||||
|
|
||||||
|
@Override
|
||||||
|
public boolean codeActionsSupported() {
|
||||||
|
return true;
|
||||||
|
}
|
||||||
|
|
||||||
|
@Override
|
||||||
|
public List<FrontendCodeAction> codeActions(
|
||||||
|
final FrontendDocumentRequest request,
|
||||||
|
final FrontendEditorialContext editorialContext) {
|
||||||
|
if (request == null
|
||||||
|
|| editorialContext == null
|
||||||
|
|| !(editorialContext.syntaxTree() instanceof PbsAst.File ast)
|
||||||
|
|| !(editorialContext.sourceFiles() instanceof FileTableReader fileTable)) {
|
||||||
|
return List.of();
|
||||||
|
}
|
||||||
|
final FileId fileId = ast.span() == null ? null : ast.span().getFileId();
|
||||||
|
final Path path = pathForRegularSource(fileId, fileTable);
|
||||||
|
if (path == null || !path.equals(request.documentPath().toAbsolutePath().normalize())) {
|
||||||
|
return List.of();
|
||||||
|
}
|
||||||
|
final boolean interfaceModule = editorialContext.projectSurface() instanceof PbsSemanticReadSurface surface
|
||||||
|
&& surface.sourceKindByFile() != null
|
||||||
|
&& surface.sourceKindByFile().get(fileId) == SourceKind.SDK_INTERFACE;
|
||||||
|
final ArrayList<FrontendCodeAction> actions = new ArrayList<>();
|
||||||
|
for (final PbsQuickFix repair : PbsQuickFixCollector.collect(ast, interfaceModule)) {
|
||||||
|
actions.add(new FrontendCodeAction(
|
||||||
|
repair.title(),
|
||||||
|
repair.diagnosticCode(),
|
||||||
|
path,
|
||||||
|
repair.startOffset(),
|
||||||
|
repair.endOffset(),
|
||||||
|
repair.newText()));
|
||||||
|
}
|
||||||
|
return List.copyOf(actions);
|
||||||
|
}
|
||||||
|
|
||||||
|
private PbsEditorialRename editorialRename(
|
||||||
|
final FrontendDocumentRequest request,
|
||||||
|
final FrontendEditorialContext editorialContext,
|
||||||
|
final int offset,
|
||||||
|
final String newName) {
|
||||||
|
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 null;
|
||||||
|
}
|
||||||
|
@SuppressWarnings("unchecked")
|
||||||
|
final ReadOnlyList<PbsAst.TopDecl> typedSupplementalTopDecls =
|
||||||
|
(ReadOnlyList<PbsAst.TopDecl>) supplementalTopDecls;
|
||||||
|
final EditorialDocument cursorDocument = new EditorialDocument(
|
||||||
|
request.documentText(),
|
||||||
|
ast,
|
||||||
|
typedSupplementalTopDecls,
|
||||||
|
feSurfaceContext);
|
||||||
|
return editorialSupportService.rename(
|
||||||
|
cursorDocument,
|
||||||
|
offset,
|
||||||
|
newName,
|
||||||
|
projectDocuments(request, editorialContext, cursorDocument, fileTable));
|
||||||
|
}
|
||||||
|
|
||||||
|
private List<FrontendDefinitionLocation> physicalIdentity(
|
||||||
|
final PbsEditorialRename planned,
|
||||||
|
final FileTableReader fileTable) {
|
||||||
|
final ArrayList<FrontendDefinitionLocation> locations = new ArrayList<>();
|
||||||
|
for (final PbsEditorialLocation location : planned.identity()) {
|
||||||
|
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 +521,142 @@ 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<FrontendWorkspaceSymbol> toFrontendWorkspaceSymbol(
|
||||||
|
final PbsEditorialWorkspaceSymbol symbol,
|
||||||
|
final Path path) {
|
||||||
|
if (symbol == null || path == null || symbol.span() == null || symbol.span().isNone()) {
|
||||||
|
return Optional.empty();
|
||||||
|
}
|
||||||
|
return Optional.of(new FrontendWorkspaceSymbol(
|
||||||
|
symbol.name(),
|
||||||
|
toFrontendSymbolKind(symbol.kind()),
|
||||||
|
symbol.detail(),
|
||||||
|
symbol.containerName(),
|
||||||
|
path,
|
||||||
|
toOffset(symbol.span().getStart()),
|
||||||
|
toOffset(symbol.span().getEnd())));
|
||||||
|
}
|
||||||
|
|
||||||
|
private FrontendDocumentSymbol toFrontendDocumentSymbol(final PbsEditorialDocumentSymbol symbol) {
|
||||||
|
final int start = toOffset(symbol.span().getStart());
|
||||||
|
final int end = toOffset(symbol.span().getEnd());
|
||||||
|
return new FrontendDocumentSymbol(
|
||||||
|
symbol.name(),
|
||||||
|
toFrontendSymbolKind(symbol.kind()),
|
||||||
|
symbol.detail(),
|
||||||
|
start,
|
||||||
|
end,
|
||||||
|
start,
|
||||||
|
end,
|
||||||
|
symbol.children().stream().map(this::toFrontendDocumentSymbol).toList());
|
||||||
|
}
|
||||||
|
|
||||||
|
private List<EditorialDocument> projectDocuments(
|
||||||
|
final FrontendDocumentRequest request,
|
||||||
|
final FrontendEditorialContext editorialContext,
|
||||||
|
final EditorialDocument cursorDocument,
|
||||||
|
final FileTableReader fileTable) {
|
||||||
|
if (!(editorialContext.projectSurface() instanceof PbsSemanticReadSurface surface)
|
||||||
|
|| surface.astByFile() == null
|
||||||
|
|| surface.astByFile().isEmpty()) {
|
||||||
|
return List.of(cursorDocument);
|
||||||
|
}
|
||||||
|
final ArrayList<EditorialDocument> documents = new ArrayList<>();
|
||||||
|
for (final var entry : surface.astByFile().entrySet()) {
|
||||||
|
if (!isRegularSource(entry.getKey(), fileTable)) {
|
||||||
|
continue;
|
||||||
|
}
|
||||||
|
final PbsAst.File fileAst = entry.getValue();
|
||||||
|
if (fileAst == null) {
|
||||||
|
continue;
|
||||||
|
}
|
||||||
|
final ReadOnlyList<PbsAst.TopDecl> fileSupplementals = fileAst == cursorDocument.ast()
|
||||||
|
? cursorDocument.supplementalTopDecls()
|
||||||
|
: surface.supplementalTopDeclsByFile().getOrDefault(entry.getKey(), ReadOnlyList.empty());
|
||||||
|
documents.add(new EditorialDocument(
|
||||||
|
textForFile(entry.getKey(), fileTable, request),
|
||||||
|
fileAst,
|
||||||
|
fileSupplementals,
|
||||||
|
cursorDocument.feSurfaceContext()));
|
||||||
|
}
|
||||||
|
if (documents.isEmpty()) {
|
||||||
|
return List.of(cursorDocument);
|
||||||
|
}
|
||||||
|
return List.copyOf(documents);
|
||||||
|
}
|
||||||
|
|
||||||
|
private Path pathForRegularSource(
|
||||||
|
final FileId fileId,
|
||||||
|
final FileTableReader fileTable) {
|
||||||
|
if (!isRegularSource(fileId, fileTable)) {
|
||||||
|
return null;
|
||||||
|
}
|
||||||
|
return fileTable.get(fileId).getCanonPath().toAbsolutePath().normalize();
|
||||||
|
}
|
||||||
|
|
||||||
|
private boolean isRegularSource(
|
||||||
|
final FileId fileId,
|
||||||
|
final FileTableReader fileTable) {
|
||||||
|
if (fileId == null || fileId.isNone() || fileTable == null) {
|
||||||
|
return false;
|
||||||
|
}
|
||||||
|
final var sourceHandle = fileTable.get(fileId);
|
||||||
|
if (sourceHandle == null || sourceHandle.getCanonPath() == null) {
|
||||||
|
return false;
|
||||||
|
}
|
||||||
|
return Files.isRegularFile(sourceHandle.getCanonPath().toAbsolutePath().normalize());
|
||||||
|
}
|
||||||
|
|
||||||
|
private String textForFile(
|
||||||
|
final FileId fileId,
|
||||||
|
final FileTableReader fileTable,
|
||||||
|
final FrontendDocumentRequest request) {
|
||||||
|
final var sourceHandle = fileTable.get(fileId);
|
||||||
|
if (sourceHandle == null || sourceHandle.getCanonPath() == null) {
|
||||||
|
return "";
|
||||||
|
}
|
||||||
|
final Path path = sourceHandle.getCanonPath().toAbsolutePath().normalize();
|
||||||
|
if (request != null
|
||||||
|
&& request.documentPath() != null
|
||||||
|
&& path.equals(request.documentPath().toAbsolutePath().normalize())) {
|
||||||
|
return request.documentText() == null ? "" : request.documentText();
|
||||||
|
}
|
||||||
|
return sourceHandle.readUtf8().orElse("");
|
||||||
|
}
|
||||||
|
|
||||||
|
private static String frontendLocationKey(final FrontendDefinitionLocation location) {
|
||||||
|
return location.path() + ":" + location.startOffset() + ":" + location.endOffset();
|
||||||
|
}
|
||||||
|
|
||||||
|
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);
|
||||||
|
}
|
||||||
}
|
}
|
||||||
|
|||||||
+26
@@ -46,6 +46,32 @@ public final class PbsLexer {
|
|||||||
return lexer.lexInternal();
|
return lexer.lexInternal();
|
||||||
}
|
}
|
||||||
|
|
||||||
|
public static boolean isKeyword(final String text) {
|
||||||
|
return text != null && KEYWORDS.containsKey(text);
|
||||||
|
}
|
||||||
|
|
||||||
|
public static boolean isIdentifierLexeme(final String text) {
|
||||||
|
if (text == null || text.isEmpty() || isKeyword(text)) {
|
||||||
|
return false;
|
||||||
|
}
|
||||||
|
int index = 0;
|
||||||
|
final int first = text.codePointAt(0);
|
||||||
|
if (!(first == '_' || Character.isAlphabetic(first))) {
|
||||||
|
return false;
|
||||||
|
}
|
||||||
|
index += Character.charCount(first);
|
||||||
|
while (index < text.length()) {
|
||||||
|
final int codePoint = text.codePointAt(index);
|
||||||
|
if (!(codePoint == '_'
|
||||||
|
|| Character.isAlphabetic(codePoint)
|
||||||
|
|| Character.isDigit(codePoint))) {
|
||||||
|
return false;
|
||||||
|
}
|
||||||
|
index += Character.charCount(codePoint);
|
||||||
|
}
|
||||||
|
return true;
|
||||||
|
}
|
||||||
|
|
||||||
private ReadOnlyList<PbsToken> lexInternal() {
|
private ReadOnlyList<PbsToken> lexInternal() {
|
||||||
while (!isAtEnd() || state != LexerState.DEFAULT) {
|
while (!isAtEnd() || state != LexerState.DEFAULT) {
|
||||||
switch (state) {
|
switch (state) {
|
||||||
|
|||||||
+321
@@ -0,0 +1,321 @@
|
|||||||
|
package p.studio.compiler.pbs.semantics;
|
||||||
|
|
||||||
|
import p.studio.compiler.pbs.ast.PbsAst;
|
||||||
|
import p.studio.compiler.source.Span;
|
||||||
|
import p.studio.utilities.structures.ReadOnlyList;
|
||||||
|
|
||||||
|
import java.util.ArrayList;
|
||||||
|
import java.util.List;
|
||||||
|
import java.util.Optional;
|
||||||
|
|
||||||
|
final class PbsAstDocumentSymbols {
|
||||||
|
private PbsAstDocumentSymbols() {
|
||||||
|
}
|
||||||
|
|
||||||
|
static List<PbsEditorialDocumentSymbol> list(final PbsAst.File ast) {
|
||||||
|
if (ast == null || ast.topDecls() == null) {
|
||||||
|
return List.of();
|
||||||
|
}
|
||||||
|
final ArrayList<PbsEditorialDocumentSymbol> symbols = new ArrayList<>();
|
||||||
|
for (final PbsAst.TopDecl topDecl : ast.topDecls()) {
|
||||||
|
symbolFor(topDecl).ifPresent(symbols::add);
|
||||||
|
}
|
||||||
|
return List.copyOf(symbols);
|
||||||
|
}
|
||||||
|
|
||||||
|
private static Optional<PbsEditorialDocumentSymbol> symbolFor(final PbsAst.TopDecl topDecl) {
|
||||||
|
if (topDecl instanceof PbsAst.FunctionDecl functionDecl) {
|
||||||
|
return callableSymbol(
|
||||||
|
functionDecl.name(),
|
||||||
|
PbsEditorialSymbolKind.FUNCTION,
|
||||||
|
functionDecl.parameters(),
|
||||||
|
functionDecl.returnKind(),
|
||||||
|
functionDecl.returnType(),
|
||||||
|
functionDecl.resultErrorType(),
|
||||||
|
functionDecl.span());
|
||||||
|
}
|
||||||
|
if (topDecl instanceof PbsAst.StructDecl structDecl) {
|
||||||
|
return structSymbol(structDecl);
|
||||||
|
}
|
||||||
|
if (topDecl instanceof PbsAst.ServiceDecl serviceDecl) {
|
||||||
|
return namedSymbol(
|
||||||
|
serviceDecl.name(),
|
||||||
|
PbsEditorialSymbolKind.SERVICE,
|
||||||
|
"",
|
||||||
|
serviceDecl.span(),
|
||||||
|
methodSymbols(serviceDecl.methods()));
|
||||||
|
}
|
||||||
|
if (topDecl instanceof PbsAst.ContractDecl contractDecl) {
|
||||||
|
return namedSymbol(
|
||||||
|
contractDecl.name(),
|
||||||
|
PbsEditorialSymbolKind.CONTRACT,
|
||||||
|
"",
|
||||||
|
contractDecl.span(),
|
||||||
|
signatureSymbols(contractDecl.signatures()));
|
||||||
|
}
|
||||||
|
if (topDecl instanceof PbsAst.HostDecl hostDecl) {
|
||||||
|
return namedSymbol(
|
||||||
|
hostDecl.name(),
|
||||||
|
PbsEditorialSymbolKind.HOST,
|
||||||
|
"",
|
||||||
|
hostDecl.span(),
|
||||||
|
signatureSymbols(hostDecl.signatures()));
|
||||||
|
}
|
||||||
|
if (topDecl instanceof PbsAst.BuiltinTypeDecl builtinTypeDecl) {
|
||||||
|
return builtinTypeSymbol(builtinTypeDecl);
|
||||||
|
}
|
||||||
|
if (topDecl instanceof PbsAst.EnumDecl enumDecl) {
|
||||||
|
return enumSymbol(enumDecl);
|
||||||
|
}
|
||||||
|
if (topDecl instanceof PbsAst.ErrorDecl errorDecl) {
|
||||||
|
return errorSymbol(errorDecl);
|
||||||
|
}
|
||||||
|
if (topDecl instanceof PbsAst.CallbackDecl callbackDecl) {
|
||||||
|
return callableSymbol(
|
||||||
|
callbackDecl.name(),
|
||||||
|
PbsEditorialSymbolKind.CALLBACK,
|
||||||
|
callbackDecl.parameters(),
|
||||||
|
callbackDecl.returnKind(),
|
||||||
|
callbackDecl.returnType(),
|
||||||
|
callbackDecl.resultErrorType(),
|
||||||
|
callbackDecl.span());
|
||||||
|
}
|
||||||
|
if (topDecl instanceof PbsAst.GlobalDecl globalDecl) {
|
||||||
|
return namedSymbol(
|
||||||
|
globalDecl.name(),
|
||||||
|
PbsEditorialSymbolKind.GLOBAL,
|
||||||
|
formatTypeRef(globalDecl.explicitType()),
|
||||||
|
globalDecl.span(),
|
||||||
|
List.of());
|
||||||
|
}
|
||||||
|
if (topDecl instanceof PbsAst.ConstDecl constDecl) {
|
||||||
|
return namedSymbol(
|
||||||
|
constDecl.name(),
|
||||||
|
PbsEditorialSymbolKind.CONST,
|
||||||
|
formatTypeRef(constDecl.explicitType()),
|
||||||
|
constDecl.span(),
|
||||||
|
List.of());
|
||||||
|
}
|
||||||
|
if (topDecl instanceof PbsAst.ImplementsDecl implementsDecl) {
|
||||||
|
return namedSymbol(
|
||||||
|
implementsDecl.contractName(),
|
||||||
|
PbsEditorialSymbolKind.CONTRACT,
|
||||||
|
implementsDecl.ownerName() == null ? "" : implementsDecl.ownerName(),
|
||||||
|
implementsDecl.span(),
|
||||||
|
methodSymbols(implementsDecl.methods()));
|
||||||
|
}
|
||||||
|
return Optional.empty();
|
||||||
|
}
|
||||||
|
|
||||||
|
private static Optional<PbsEditorialDocumentSymbol> structSymbol(final PbsAst.StructDecl structDecl) {
|
||||||
|
final ArrayList<PbsEditorialDocumentSymbol> children = new ArrayList<>();
|
||||||
|
for (final PbsAst.StructField field : structDecl.fields()) {
|
||||||
|
namedSymbol(
|
||||||
|
field.name(),
|
||||||
|
PbsEditorialSymbolKind.FIELD,
|
||||||
|
formatTypeRef(field.typeRef()),
|
||||||
|
field.span(),
|
||||||
|
List.of()).ifPresent(children::add);
|
||||||
|
}
|
||||||
|
for (final PbsAst.CtorDecl ctorDecl : structDecl.ctors()) {
|
||||||
|
namedSymbol(
|
||||||
|
ctorDecl.name(),
|
||||||
|
PbsEditorialSymbolKind.CONSTRUCTOR,
|
||||||
|
ctorDetail(ctorDecl.parameters()),
|
||||||
|
ctorDecl.span(),
|
||||||
|
List.of()).ifPresent(children::add);
|
||||||
|
}
|
||||||
|
children.addAll(methodSymbols(structDecl.methods()));
|
||||||
|
return namedSymbol(
|
||||||
|
structDecl.name(),
|
||||||
|
PbsEditorialSymbolKind.STRUCT,
|
||||||
|
"",
|
||||||
|
structDecl.span(),
|
||||||
|
children);
|
||||||
|
}
|
||||||
|
|
||||||
|
private static Optional<PbsEditorialDocumentSymbol> builtinTypeSymbol(final PbsAst.BuiltinTypeDecl builtinTypeDecl) {
|
||||||
|
final ArrayList<PbsEditorialDocumentSymbol> children = new ArrayList<>();
|
||||||
|
for (final PbsAst.BuiltinFieldDecl field : builtinTypeDecl.fields()) {
|
||||||
|
namedSymbol(
|
||||||
|
field.name(),
|
||||||
|
PbsEditorialSymbolKind.FIELD,
|
||||||
|
formatTypeRef(field.typeRef()),
|
||||||
|
field.span(),
|
||||||
|
List.of()).ifPresent(children::add);
|
||||||
|
}
|
||||||
|
children.addAll(signatureSymbols(builtinTypeDecl.signatures()));
|
||||||
|
return namedSymbol(
|
||||||
|
builtinTypeDecl.name(),
|
||||||
|
PbsEditorialSymbolKind.BUILTIN_TYPE,
|
||||||
|
"",
|
||||||
|
builtinTypeDecl.span(),
|
||||||
|
children);
|
||||||
|
}
|
||||||
|
|
||||||
|
private static Optional<PbsEditorialDocumentSymbol> enumSymbol(final PbsAst.EnumDecl enumDecl) {
|
||||||
|
final ArrayList<PbsEditorialDocumentSymbol> children = new ArrayList<>();
|
||||||
|
for (final PbsAst.EnumCase enumCase : enumDecl.cases()) {
|
||||||
|
final String detail = enumCase.explicitValue() == null ? "" : String.valueOf(enumCase.explicitValue());
|
||||||
|
namedSymbol(
|
||||||
|
enumCase.name(),
|
||||||
|
PbsEditorialSymbolKind.ENUM,
|
||||||
|
detail,
|
||||||
|
enumCase.span(),
|
||||||
|
List.of()).ifPresent(children::add);
|
||||||
|
}
|
||||||
|
return namedSymbol(
|
||||||
|
enumDecl.name(),
|
||||||
|
PbsEditorialSymbolKind.ENUM,
|
||||||
|
"",
|
||||||
|
enumDecl.span(),
|
||||||
|
children);
|
||||||
|
}
|
||||||
|
|
||||||
|
private static Optional<PbsEditorialDocumentSymbol> errorSymbol(final PbsAst.ErrorDecl errorDecl) {
|
||||||
|
final ArrayList<PbsEditorialDocumentSymbol> children = new ArrayList<>();
|
||||||
|
for (final String label : errorDecl.cases()) {
|
||||||
|
namedSymbol(
|
||||||
|
label,
|
||||||
|
PbsEditorialSymbolKind.ERROR,
|
||||||
|
"",
|
||||||
|
errorDecl.span(),
|
||||||
|
List.of()).ifPresent(children::add);
|
||||||
|
}
|
||||||
|
return namedSymbol(
|
||||||
|
errorDecl.name(),
|
||||||
|
PbsEditorialSymbolKind.ERROR,
|
||||||
|
"",
|
||||||
|
errorDecl.span(),
|
||||||
|
children);
|
||||||
|
}
|
||||||
|
|
||||||
|
private static List<PbsEditorialDocumentSymbol> methodSymbols(final ReadOnlyList<PbsAst.FunctionDecl> methods) {
|
||||||
|
if (methods == null || methods.isEmpty()) {
|
||||||
|
return List.of();
|
||||||
|
}
|
||||||
|
final ArrayList<PbsEditorialDocumentSymbol> symbols = new ArrayList<>();
|
||||||
|
for (final PbsAst.FunctionDecl method : methods) {
|
||||||
|
callableSymbol(
|
||||||
|
method.name(),
|
||||||
|
PbsEditorialSymbolKind.METHOD,
|
||||||
|
method.parameters(),
|
||||||
|
method.returnKind(),
|
||||||
|
method.returnType(),
|
||||||
|
method.resultErrorType(),
|
||||||
|
method.span()).ifPresent(symbols::add);
|
||||||
|
}
|
||||||
|
return symbols;
|
||||||
|
}
|
||||||
|
|
||||||
|
private static List<PbsEditorialDocumentSymbol> signatureSymbols(
|
||||||
|
final ReadOnlyList<PbsAst.FunctionSignature> signatures) {
|
||||||
|
if (signatures == null || signatures.isEmpty()) {
|
||||||
|
return List.of();
|
||||||
|
}
|
||||||
|
final ArrayList<PbsEditorialDocumentSymbol> symbols = new ArrayList<>();
|
||||||
|
for (final PbsAst.FunctionSignature signature : signatures) {
|
||||||
|
callableSymbol(
|
||||||
|
signature.name(),
|
||||||
|
PbsEditorialSymbolKind.METHOD,
|
||||||
|
signature.parameters(),
|
||||||
|
signature.returnKind(),
|
||||||
|
signature.returnType(),
|
||||||
|
signature.resultErrorType(),
|
||||||
|
signature.span()).ifPresent(symbols::add);
|
||||||
|
}
|
||||||
|
return symbols;
|
||||||
|
}
|
||||||
|
|
||||||
|
private static Optional<PbsEditorialDocumentSymbol> callableSymbol(
|
||||||
|
final String name,
|
||||||
|
final PbsEditorialSymbolKind kind,
|
||||||
|
final ReadOnlyList<PbsAst.Parameter> parameters,
|
||||||
|
final PbsAst.ReturnKind returnKind,
|
||||||
|
final PbsAst.TypeRef returnType,
|
||||||
|
final PbsAst.TypeRef resultErrorType,
|
||||||
|
final Span span) {
|
||||||
|
return namedSymbol(
|
||||||
|
name,
|
||||||
|
kind,
|
||||||
|
callableDetail(parameters, returnKind, returnType, resultErrorType),
|
||||||
|
span,
|
||||||
|
List.of());
|
||||||
|
}
|
||||||
|
|
||||||
|
private static Optional<PbsEditorialDocumentSymbol> namedSymbol(
|
||||||
|
final String name,
|
||||||
|
final PbsEditorialSymbolKind kind,
|
||||||
|
final String detail,
|
||||||
|
final Span span,
|
||||||
|
final List<PbsEditorialDocumentSymbol> children) {
|
||||||
|
if (name == null || name.isBlank() || span == null || span.isNone()) {
|
||||||
|
return Optional.empty();
|
||||||
|
}
|
||||||
|
return Optional.of(new PbsEditorialDocumentSymbol(name, kind, detail, span, children));
|
||||||
|
}
|
||||||
|
|
||||||
|
private static String callableDetail(
|
||||||
|
final ReadOnlyList<PbsAst.Parameter> parameters,
|
||||||
|
final PbsAst.ReturnKind returnKind,
|
||||||
|
final PbsAst.TypeRef returnType,
|
||||||
|
final PbsAst.TypeRef resultErrorType) {
|
||||||
|
return "(" + formatParameters(parameters) + ") -> " + formatReturn(returnKind, returnType, resultErrorType);
|
||||||
|
}
|
||||||
|
|
||||||
|
private static String ctorDetail(final ReadOnlyList<PbsAst.Parameter> parameters) {
|
||||||
|
return "(" + formatParameters(parameters) + ")";
|
||||||
|
}
|
||||||
|
|
||||||
|
private static String formatParameters(final ReadOnlyList<PbsAst.Parameter> parameters) {
|
||||||
|
if (parameters == null || parameters.isEmpty()) {
|
||||||
|
return "";
|
||||||
|
}
|
||||||
|
final ArrayList<String> parts = new ArrayList<>(parameters.size());
|
||||||
|
for (final PbsAst.Parameter parameter : parameters) {
|
||||||
|
parts.add(parameter.name() + ": " + formatTypeRef(parameter.typeRef()));
|
||||||
|
}
|
||||||
|
return String.join(", ", parts);
|
||||||
|
}
|
||||||
|
|
||||||
|
private static String formatReturn(
|
||||||
|
final PbsAst.ReturnKind returnKind,
|
||||||
|
final PbsAst.TypeRef returnType,
|
||||||
|
final PbsAst.TypeRef resultErrorType) {
|
||||||
|
if (returnKind == null) {
|
||||||
|
return formatTypeRef(returnType);
|
||||||
|
}
|
||||||
|
return switch (returnKind) {
|
||||||
|
case INFERRED_UNIT, EXPLICIT_UNIT -> "void";
|
||||||
|
case PLAIN -> formatTypeRef(returnType);
|
||||||
|
case RESULT -> {
|
||||||
|
final String errorType = formatTypeRef(resultErrorType);
|
||||||
|
if (returnType == null || returnType.kind() == PbsAst.TypeRefKind.UNIT) {
|
||||||
|
yield "result<" + errorType + ">";
|
||||||
|
}
|
||||||
|
yield "result<" + errorType + "> " + formatTypeRef(returnType);
|
||||||
|
}
|
||||||
|
};
|
||||||
|
}
|
||||||
|
|
||||||
|
private static String formatTypeRef(final PbsAst.TypeRef typeRef) {
|
||||||
|
if (typeRef == null) {
|
||||||
|
return "void";
|
||||||
|
}
|
||||||
|
return switch (typeRef.kind()) {
|
||||||
|
case UNIT -> typeRef.name() == null || typeRef.name().isBlank() ? "void" : typeRef.name();
|
||||||
|
case SELF -> "Self";
|
||||||
|
case SIMPLE -> typeRef.name() == null ? "void" : typeRef.name();
|
||||||
|
case OPTIONAL -> "optional " + formatTypeRef(typeRef.inner());
|
||||||
|
case GROUP -> "(" + formatTypeRef(typeRef.inner()) + ")";
|
||||||
|
case NAMED_TUPLE -> {
|
||||||
|
final ArrayList<String> fields = new ArrayList<>(typeRef.fields().size());
|
||||||
|
for (final var field : typeRef.fields()) {
|
||||||
|
fields.add(field.label() + ": " + formatTypeRef(field.typeRef()));
|
||||||
|
}
|
||||||
|
yield "(" + String.join(", ", fields) + ")";
|
||||||
|
}
|
||||||
|
case ERROR -> "unknown";
|
||||||
|
};
|
||||||
|
}
|
||||||
|
}
|
||||||
+55
@@ -0,0 +1,55 @@
|
|||||||
|
package p.studio.compiler.pbs.semantics;
|
||||||
|
|
||||||
|
import p.studio.compiler.pbs.ast.PbsAst;
|
||||||
|
|
||||||
|
import java.util.ArrayList;
|
||||||
|
import java.util.List;
|
||||||
|
import java.util.Locale;
|
||||||
|
|
||||||
|
final class PbsAstWorkspaceSymbols {
|
||||||
|
private PbsAstWorkspaceSymbols() {
|
||||||
|
}
|
||||||
|
|
||||||
|
static List<PbsEditorialWorkspaceSymbol> list(
|
||||||
|
final PbsAst.File ast,
|
||||||
|
final String query) {
|
||||||
|
if (ast == null) {
|
||||||
|
return List.of();
|
||||||
|
}
|
||||||
|
final ArrayList<PbsEditorialWorkspaceSymbol> symbols = new ArrayList<>();
|
||||||
|
for (final PbsEditorialDocumentSymbol topDecl : PbsAstDocumentSymbols.list(ast)) {
|
||||||
|
flatten(topDecl, "", query, symbols);
|
||||||
|
}
|
||||||
|
return List.copyOf(symbols);
|
||||||
|
}
|
||||||
|
|
||||||
|
private static void flatten(
|
||||||
|
final PbsEditorialDocumentSymbol symbol,
|
||||||
|
final String containerName,
|
||||||
|
final String query,
|
||||||
|
final ArrayList<PbsEditorialWorkspaceSymbol> symbols) {
|
||||||
|
if (matches(symbol.name(), query)) {
|
||||||
|
symbols.add(new PbsEditorialWorkspaceSymbol(
|
||||||
|
symbol.name(),
|
||||||
|
symbol.kind(),
|
||||||
|
symbol.detail(),
|
||||||
|
containerName,
|
||||||
|
symbol.span()));
|
||||||
|
}
|
||||||
|
for (final PbsEditorialDocumentSymbol child : symbol.children()) {
|
||||||
|
flatten(child, symbol.name(), query, symbols);
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
static boolean matches(
|
||||||
|
final String name,
|
||||||
|
final String query) {
|
||||||
|
if (name == null || name.isBlank()) {
|
||||||
|
return false;
|
||||||
|
}
|
||||||
|
if (query == null || query.isBlank()) {
|
||||||
|
return true;
|
||||||
|
}
|
||||||
|
return name.toLowerCase(Locale.ROOT).contains(query.trim().toLowerCase(Locale.ROOT));
|
||||||
|
}
|
||||||
|
}
|
||||||
+22
@@ -0,0 +1,22 @@
|
|||||||
|
package p.studio.compiler.pbs.semantics;
|
||||||
|
|
||||||
|
import p.studio.compiler.source.Span;
|
||||||
|
|
||||||
|
import java.util.List;
|
||||||
|
import java.util.Objects;
|
||||||
|
|
||||||
|
public record PbsEditorialDocumentSymbol(
|
||||||
|
String name,
|
||||||
|
PbsEditorialSymbolKind kind,
|
||||||
|
String detail,
|
||||||
|
Span span,
|
||||||
|
List<PbsEditorialDocumentSymbol> children) {
|
||||||
|
|
||||||
|
public PbsEditorialDocumentSymbol {
|
||||||
|
name = Objects.requireNonNull(name, "name").trim();
|
||||||
|
kind = Objects.requireNonNull(kind, "kind");
|
||||||
|
detail = detail == null ? "" : detail;
|
||||||
|
span = Objects.requireNonNull(span, "span");
|
||||||
|
children = children == null ? List.of() : List.copyOf(children);
|
||||||
|
}
|
||||||
|
}
|
||||||
+11
@@ -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");
|
||||||
|
}
|
||||||
|
}
|
||||||
+40
@@ -0,0 +1,40 @@
|
|||||||
|
package p.studio.compiler.pbs.semantics;
|
||||||
|
|
||||||
|
import java.util.List;
|
||||||
|
import java.util.Objects;
|
||||||
|
|
||||||
|
public record PbsEditorialRename(
|
||||||
|
String refusal,
|
||||||
|
PbsEditorialLocation placeholder,
|
||||||
|
List<PbsEditorialLocation> identity,
|
||||||
|
List<PbsEditorialLocation> sites) {
|
||||||
|
|
||||||
|
public PbsEditorialRename {
|
||||||
|
refusal = refusal == null ? "" : refusal;
|
||||||
|
identity = identity == null ? List.of() : List.copyOf(identity);
|
||||||
|
sites = sites == null ? List.of() : List.copyOf(sites);
|
||||||
|
}
|
||||||
|
|
||||||
|
public static PbsEditorialRename refused(final String reason) {
|
||||||
|
return new PbsEditorialRename(
|
||||||
|
reason == null || reason.isBlank() ? "not renameable" : reason,
|
||||||
|
null,
|
||||||
|
List.of(),
|
||||||
|
List.of());
|
||||||
|
}
|
||||||
|
|
||||||
|
public static PbsEditorialRename applied(
|
||||||
|
final PbsEditorialLocation placeholder,
|
||||||
|
final List<PbsEditorialLocation> identity,
|
||||||
|
final List<PbsEditorialLocation> sites) {
|
||||||
|
return new PbsEditorialRename(
|
||||||
|
"",
|
||||||
|
Objects.requireNonNull(placeholder, "placeholder"),
|
||||||
|
identity,
|
||||||
|
sites);
|
||||||
|
}
|
||||||
|
|
||||||
|
public boolean allowed() {
|
||||||
|
return refusal.isBlank() && placeholder != null && !identity.isEmpty() && !sites.isEmpty();
|
||||||
|
}
|
||||||
|
}
|
||||||
+835
@@ -74,6 +74,157 @@ public final class PbsEditorialSupportService {
|
|||||||
return context.resolveSymbolHover(token.lexeme(), tokenIndex, scopeState);
|
return context.resolveSymbolHover(token.lexeme(), tokenIndex, scopeState);
|
||||||
}
|
}
|
||||||
|
|
||||||
|
public List<PbsEditorialDocumentSymbol> documentSymbols(final PbsAst.File ast) {
|
||||||
|
return PbsAstDocumentSymbols.list(ast);
|
||||||
|
}
|
||||||
|
|
||||||
|
public List<PbsEditorialWorkspaceSymbol> workspaceSymbols(
|
||||||
|
final PbsAst.File ast,
|
||||||
|
final String query) {
|
||||||
|
return PbsAstWorkspaceSymbols.list(ast, query);
|
||||||
|
}
|
||||||
|
|
||||||
|
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 List<PbsEditorialLocation> references(
|
||||||
|
final String sourceText,
|
||||||
|
final PbsAst.File ast,
|
||||||
|
final ReadOnlyList<PbsAst.TopDecl> supplementalTopDecls,
|
||||||
|
final int offset) {
|
||||||
|
return references(sourceText, ast, supplementalTopDecls, FESurfaceContext.empty(), offset);
|
||||||
|
}
|
||||||
|
|
||||||
|
public List<PbsEditorialLocation> references(
|
||||||
|
final String sourceText,
|
||||||
|
final PbsAst.File ast,
|
||||||
|
final ReadOnlyList<PbsAst.TopDecl> supplementalTopDecls,
|
||||||
|
final FESurfaceContext feSurfaceContext,
|
||||||
|
final int offset) {
|
||||||
|
final EditorialDocument cursor = new EditorialDocument(sourceText, ast, supplementalTopDecls, feSurfaceContext);
|
||||||
|
return references(cursor, offset, List.of(cursor));
|
||||||
|
}
|
||||||
|
|
||||||
|
public List<PbsEditorialLocation> references(
|
||||||
|
final EditorialDocument cursorDocument,
|
||||||
|
final int offset,
|
||||||
|
final List<EditorialDocument> projectDocuments) {
|
||||||
|
if (cursorDocument == null) {
|
||||||
|
return List.of();
|
||||||
|
}
|
||||||
|
final List<PbsEditorialLocation> identity = definition(
|
||||||
|
cursorDocument.sourceText(),
|
||||||
|
cursorDocument.ast(),
|
||||||
|
cursorDocument.supplementalTopDecls(),
|
||||||
|
cursorDocument.feSurfaceContext(),
|
||||||
|
offset);
|
||||||
|
if (identity.isEmpty()) {
|
||||||
|
return List.of();
|
||||||
|
}
|
||||||
|
final Set<String> identityKeys = locationKeys(identity);
|
||||||
|
final LinkedHashMap<String, PbsEditorialLocation> usages = new LinkedHashMap<>();
|
||||||
|
final List<EditorialDocument> documents = projectDocuments == null || projectDocuments.isEmpty()
|
||||||
|
? List.of(cursorDocument)
|
||||||
|
: projectDocuments;
|
||||||
|
for (final EditorialDocument document : documents) {
|
||||||
|
if (document == null || document.ast() == null) {
|
||||||
|
continue;
|
||||||
|
}
|
||||||
|
for (final PbsEditorialLocation usage : buildContext(
|
||||||
|
document.sourceText(),
|
||||||
|
document.ast(),
|
||||||
|
document.supplementalTopDecls(),
|
||||||
|
document.feSurfaceContext()).usagesMatching(identityKeys)) {
|
||||||
|
usages.putIfAbsent(locationKey(usage.span()), usage);
|
||||||
|
}
|
||||||
|
}
|
||||||
|
return List.copyOf(usages.values());
|
||||||
|
}
|
||||||
|
|
||||||
|
public Optional<PbsEditorialLocation> prepareRename(
|
||||||
|
final String sourceText,
|
||||||
|
final PbsAst.File ast,
|
||||||
|
final ReadOnlyList<PbsAst.TopDecl> supplementalTopDecls,
|
||||||
|
final int offset) {
|
||||||
|
return prepareRename(sourceText, ast, supplementalTopDecls, FESurfaceContext.empty(), offset);
|
||||||
|
}
|
||||||
|
|
||||||
|
public Optional<PbsEditorialLocation> prepareRename(
|
||||||
|
final String sourceText,
|
||||||
|
final PbsAst.File ast,
|
||||||
|
final ReadOnlyList<PbsAst.TopDecl> supplementalTopDecls,
|
||||||
|
final FESurfaceContext feSurfaceContext,
|
||||||
|
final int offset) {
|
||||||
|
final EditorialDocument cursor = new EditorialDocument(sourceText, ast, supplementalTopDecls, feSurfaceContext);
|
||||||
|
return prepareRename(cursor, offset, List.of(cursor));
|
||||||
|
}
|
||||||
|
|
||||||
|
public Optional<PbsEditorialLocation> prepareRename(
|
||||||
|
final EditorialDocument cursorDocument,
|
||||||
|
final int offset,
|
||||||
|
final List<EditorialDocument> projectDocuments) {
|
||||||
|
final PbsEditorialRename planned = planRename(cursorDocument, offset, projectDocuments, null);
|
||||||
|
if (!planned.allowed()) {
|
||||||
|
return Optional.empty();
|
||||||
|
}
|
||||||
|
return Optional.of(planned.placeholder());
|
||||||
|
}
|
||||||
|
|
||||||
|
public PbsEditorialRename rename(
|
||||||
|
final String sourceText,
|
||||||
|
final PbsAst.File ast,
|
||||||
|
final ReadOnlyList<PbsAst.TopDecl> supplementalTopDecls,
|
||||||
|
final int offset,
|
||||||
|
final String newName) {
|
||||||
|
return rename(sourceText, ast, supplementalTopDecls, FESurfaceContext.empty(), offset, newName);
|
||||||
|
}
|
||||||
|
|
||||||
|
public PbsEditorialRename rename(
|
||||||
|
final String sourceText,
|
||||||
|
final PbsAst.File ast,
|
||||||
|
final ReadOnlyList<PbsAst.TopDecl> supplementalTopDecls,
|
||||||
|
final FESurfaceContext feSurfaceContext,
|
||||||
|
final int offset,
|
||||||
|
final String newName) {
|
||||||
|
final EditorialDocument cursor = new EditorialDocument(sourceText, ast, supplementalTopDecls, feSurfaceContext);
|
||||||
|
return rename(cursor, offset, newName, List.of(cursor));
|
||||||
|
}
|
||||||
|
|
||||||
|
public PbsEditorialRename rename(
|
||||||
|
final EditorialDocument cursorDocument,
|
||||||
|
final int offset,
|
||||||
|
final String newName,
|
||||||
|
final List<EditorialDocument> projectDocuments) {
|
||||||
|
return planRename(cursorDocument, offset, projectDocuments, newName);
|
||||||
|
}
|
||||||
|
|
||||||
|
public record EditorialDocument(
|
||||||
|
String sourceText,
|
||||||
|
PbsAst.File ast,
|
||||||
|
ReadOnlyList<PbsAst.TopDecl> supplementalTopDecls,
|
||||||
|
FESurfaceContext feSurfaceContext) {
|
||||||
|
public EditorialDocument {
|
||||||
|
sourceText = sourceText == null ? "" : sourceText;
|
||||||
|
Objects.requireNonNull(ast, "ast");
|
||||||
|
supplementalTopDecls = supplementalTopDecls == null ? ReadOnlyList.empty() : supplementalTopDecls;
|
||||||
|
feSurfaceContext = feSurfaceContext == null ? FESurfaceContext.empty() : feSurfaceContext;
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
public Optional<PbsEditorialSignatureHelp> signatureHelp(
|
public Optional<PbsEditorialSignatureHelp> signatureHelp(
|
||||||
final String sourceText,
|
final String sourceText,
|
||||||
final PbsAst.File ast,
|
final PbsAst.File ast,
|
||||||
@@ -108,6 +259,76 @@ public final class PbsEditorialSupportService {
|
|||||||
return Optional.of(new PbsEditorialSignatureHelp(signatures, 0, callSite.activeParameter()));
|
return Optional.of(new PbsEditorialSignatureHelp(signatures, 0, callSite.activeParameter()));
|
||||||
}
|
}
|
||||||
|
|
||||||
|
private PbsEditorialRename planRename(
|
||||||
|
final EditorialDocument cursorDocument,
|
||||||
|
final int offset,
|
||||||
|
final List<EditorialDocument> projectDocuments,
|
||||||
|
final String newName) {
|
||||||
|
if (cursorDocument == null || cursorDocument.ast() == null) {
|
||||||
|
return PbsEditorialRename.refused("not renameable");
|
||||||
|
}
|
||||||
|
final DocumentContext cursor = buildContext(
|
||||||
|
cursorDocument.sourceText(),
|
||||||
|
cursorDocument.ast(),
|
||||||
|
cursorDocument.supplementalTopDecls(),
|
||||||
|
cursorDocument.feSurfaceContext());
|
||||||
|
final RenameCursor renameCursor = cursor.renameCursorAt(offset);
|
||||||
|
if (renameCursor.refusal() != null) {
|
||||||
|
return PbsEditorialRename.refused(renameCursor.refusal());
|
||||||
|
}
|
||||||
|
if (newName != null) {
|
||||||
|
if (!PbsLexer.isIdentifierLexeme(newName)) {
|
||||||
|
return PbsEditorialRename.refused("invalid identifier");
|
||||||
|
}
|
||||||
|
if (cursor.collides(newName, renameCursor)) {
|
||||||
|
return PbsEditorialRename.refused("name collision");
|
||||||
|
}
|
||||||
|
}
|
||||||
|
final List<EditorialDocument> documents = projectDocuments == null || projectDocuments.isEmpty()
|
||||||
|
? List.of(cursorDocument)
|
||||||
|
: projectDocuments;
|
||||||
|
final LinkedHashMap<String, PbsEditorialLocation> sites = new LinkedHashMap<>();
|
||||||
|
sites.putIfAbsent(locationKey(renameCursor.placeholder().span()), renameCursor.placeholder());
|
||||||
|
final Set<String> identityKeys = locationKeys(renameCursor.identity());
|
||||||
|
for (final EditorialDocument document : documents) {
|
||||||
|
if (document == null || document.ast() == null) {
|
||||||
|
continue;
|
||||||
|
}
|
||||||
|
final DocumentContext documentContext = buildContext(
|
||||||
|
document.sourceText(),
|
||||||
|
document.ast(),
|
||||||
|
document.supplementalTopDecls(),
|
||||||
|
document.feSurfaceContext());
|
||||||
|
for (final PbsEditorialLocation site : documentContext.renameSitesMatching(
|
||||||
|
identityKeys,
|
||||||
|
renameCursor.originalName())) {
|
||||||
|
sites.putIfAbsent(locationKey(site.span()), site);
|
||||||
|
}
|
||||||
|
final FileId documentFileId = document.ast().span() == null
|
||||||
|
? FileId.none()
|
||||||
|
: document.ast().span().getFileId();
|
||||||
|
for (final PbsEditorialLocation location : renameCursor.identity()) {
|
||||||
|
if (location == null || location.span() == null || location.span().isNone()) {
|
||||||
|
continue;
|
||||||
|
}
|
||||||
|
if (location.span().length() != renameCursor.originalName().length()) {
|
||||||
|
continue;
|
||||||
|
}
|
||||||
|
if (location.span().getFileId() == null || !location.span().getFileId().equals(documentFileId)) {
|
||||||
|
continue;
|
||||||
|
}
|
||||||
|
sites.putIfAbsent(locationKey(location.span()), location);
|
||||||
|
}
|
||||||
|
}
|
||||||
|
if (sites.isEmpty()) {
|
||||||
|
return PbsEditorialRename.refused("not renameable");
|
||||||
|
}
|
||||||
|
return PbsEditorialRename.applied(
|
||||||
|
renameCursor.placeholder(),
|
||||||
|
renameCursor.identity(),
|
||||||
|
List.copyOf(sites.values()));
|
||||||
|
}
|
||||||
|
|
||||||
private DocumentContext buildContext(
|
private DocumentContext buildContext(
|
||||||
final String sourceText,
|
final String sourceText,
|
||||||
final PbsAst.File ast,
|
final PbsAst.File ast,
|
||||||
@@ -116,6 +337,25 @@ public final class PbsEditorialSupportService {
|
|||||||
return new DocumentContext(sourceText, ast, supplementalTopDecls, feSurfaceContext);
|
return new DocumentContext(sourceText, ast, supplementalTopDecls, feSurfaceContext);
|
||||||
}
|
}
|
||||||
|
|
||||||
|
private static Set<String> locationKeys(final List<PbsEditorialLocation> locations) {
|
||||||
|
final LinkedHashSet<String> keys = new LinkedHashSet<>();
|
||||||
|
if (locations == null) {
|
||||||
|
return Set.of();
|
||||||
|
}
|
||||||
|
for (final PbsEditorialLocation location : locations) {
|
||||||
|
if (location != null && location.span() != null) {
|
||||||
|
keys.add(locationKey(location.span()));
|
||||||
|
}
|
||||||
|
}
|
||||||
|
return Set.copyOf(keys);
|
||||||
|
}
|
||||||
|
|
||||||
|
private static String locationKey(final Span span) {
|
||||||
|
final FileId fileId = span.getFileId();
|
||||||
|
final int fileNumber = fileId == null ? -1 : fileId.getId();
|
||||||
|
return fileNumber + ":" + span.getStart() + ":" + span.getEnd();
|
||||||
|
}
|
||||||
|
|
||||||
private static final class DocumentContext {
|
private static final class DocumentContext {
|
||||||
private final String sourceText;
|
private final String sourceText;
|
||||||
private final PbsAst.File ast;
|
private final PbsAst.File ast;
|
||||||
@@ -610,6 +850,264 @@ 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> usagesMatching(final Set<String> identityKeys) {
|
||||||
|
if (identityKeys == null || identityKeys.isEmpty()) {
|
||||||
|
return List.of();
|
||||||
|
}
|
||||||
|
final FileId fileId = ast.span() == null ? FileId.none() : ast.span().getFileId();
|
||||||
|
final LinkedHashMap<String, PbsEditorialLocation> usages = new LinkedHashMap<>();
|
||||||
|
for (final PbsToken token : tokens) {
|
||||||
|
if (token.kind() != PbsTokenKind.IDENTIFIER) {
|
||||||
|
continue;
|
||||||
|
}
|
||||||
|
if (!intersects(definitionAt(token.start()), identityKeys)) {
|
||||||
|
continue;
|
||||||
|
}
|
||||||
|
final Span usageSpan = new Span(fileId, token.start(), token.end());
|
||||||
|
if (!hasPhysicalSpan(usageSpan)) {
|
||||||
|
continue;
|
||||||
|
}
|
||||||
|
usages.putIfAbsent(locationKey(usageSpan), new PbsEditorialLocation(usageSpan));
|
||||||
|
}
|
||||||
|
return List.copyOf(usages.values());
|
||||||
|
}
|
||||||
|
|
||||||
|
private boolean intersects(
|
||||||
|
final List<PbsEditorialLocation> locations,
|
||||||
|
final Set<String> identityKeys) {
|
||||||
|
if (locations == null || locations.isEmpty()) {
|
||||||
|
return false;
|
||||||
|
}
|
||||||
|
for (final PbsEditorialLocation location : locations) {
|
||||||
|
if (location != null && location.span() != null && identityKeys.contains(locationKey(location.span()))) {
|
||||||
|
return true;
|
||||||
|
}
|
||||||
|
}
|
||||||
|
return false;
|
||||||
|
}
|
||||||
|
|
||||||
|
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) {
|
||||||
@@ -1128,6 +1626,332 @@ public final class PbsEditorialSupportService {
|
|||||||
throw new IndexOutOfBoundsException("No significant token at index " + significantIndex);
|
throw new IndexOutOfBoundsException("No significant token at index " + significantIndex);
|
||||||
}
|
}
|
||||||
|
|
||||||
|
private RenameCursor renameCursorAt(final int offset) {
|
||||||
|
final Integer tokenIndex = identifierTokenIndexAt(offset);
|
||||||
|
if (tokenIndex == null) {
|
||||||
|
return RenameCursor.refused("not an identifier");
|
||||||
|
}
|
||||||
|
final PbsToken token = token(tokenIndex);
|
||||||
|
final String lexeme = token.lexeme();
|
||||||
|
if (isImportAliasLexeme(lexeme)) {
|
||||||
|
return RenameCursor.refused("import alias");
|
||||||
|
}
|
||||||
|
List<PbsEditorialLocation> identity = definitionAt(offset);
|
||||||
|
if (identity.isEmpty()) {
|
||||||
|
identity = localLocations(lexeme, offset);
|
||||||
|
}
|
||||||
|
if (identity.isEmpty()) {
|
||||||
|
identity = parameterLocations(lexeme, offset);
|
||||||
|
}
|
||||||
|
if (isErrorCaseLabel(lexeme, offset, identity)) {
|
||||||
|
return RenameCursor.refused("error case label");
|
||||||
|
}
|
||||||
|
if (identity.isEmpty()) {
|
||||||
|
return RenameCursor.refused("not renameable");
|
||||||
|
}
|
||||||
|
final FileId fileId = ast.span() == null ? FileId.none() : ast.span().getFileId();
|
||||||
|
final Span placeholderSpan = new Span(fileId, token.start(), token.end());
|
||||||
|
if (!hasPhysicalSpan(placeholderSpan)) {
|
||||||
|
return RenameCursor.refused("not renameable");
|
||||||
|
}
|
||||||
|
return new RenameCursor(
|
||||||
|
lexeme,
|
||||||
|
new PbsEditorialLocation(placeholderSpan),
|
||||||
|
identity,
|
||||||
|
null);
|
||||||
|
}
|
||||||
|
|
||||||
|
private List<PbsEditorialLocation> renameSitesMatching(
|
||||||
|
final Set<String> identityKeys,
|
||||||
|
final String originalName) {
|
||||||
|
if (identityKeys == null || identityKeys.isEmpty() || originalName == null || originalName.isBlank()) {
|
||||||
|
return List.of();
|
||||||
|
}
|
||||||
|
final FileId fileId = ast.span() == null ? FileId.none() : ast.span().getFileId();
|
||||||
|
final LinkedHashMap<String, PbsEditorialLocation> sites = new LinkedHashMap<>();
|
||||||
|
for (final PbsToken token : tokens) {
|
||||||
|
if (token.kind() != PbsTokenKind.IDENTIFIER || !originalName.equals(token.lexeme())) {
|
||||||
|
continue;
|
||||||
|
}
|
||||||
|
if (isImportAliasLexeme(token.lexeme())) {
|
||||||
|
continue;
|
||||||
|
}
|
||||||
|
if (!intersects(definitionAt(token.start()), identityKeys)) {
|
||||||
|
continue;
|
||||||
|
}
|
||||||
|
final Span usageSpan = new Span(fileId, token.start(), token.end());
|
||||||
|
if (!hasPhysicalSpan(usageSpan)) {
|
||||||
|
continue;
|
||||||
|
}
|
||||||
|
sites.putIfAbsent(locationKey(usageSpan), new PbsEditorialLocation(usageSpan));
|
||||||
|
}
|
||||||
|
return List.copyOf(sites.values());
|
||||||
|
}
|
||||||
|
|
||||||
|
private boolean isImportAliasLexeme(final String lexeme) {
|
||||||
|
if (lexeme == null || lexeme.isBlank()) {
|
||||||
|
return false;
|
||||||
|
}
|
||||||
|
for (final var importDecl : ast.imports()) {
|
||||||
|
for (final var item : importDecl.items()) {
|
||||||
|
if (item.alias() == null || item.alias().isBlank()) {
|
||||||
|
continue;
|
||||||
|
}
|
||||||
|
if (lexeme.equals(item.alias()) && !item.alias().equals(item.name())) {
|
||||||
|
return true;
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
|
return false;
|
||||||
|
}
|
||||||
|
|
||||||
|
private boolean isErrorCaseLabel(
|
||||||
|
final String lexeme,
|
||||||
|
final int offset,
|
||||||
|
final List<PbsEditorialLocation> identity) {
|
||||||
|
if (lexeme == null || lexeme.isBlank()) {
|
||||||
|
return false;
|
||||||
|
}
|
||||||
|
for (final var topDecl : ast.topDecls()) {
|
||||||
|
if (!(topDecl instanceof PbsAst.ErrorDecl errorDecl)) {
|
||||||
|
continue;
|
||||||
|
}
|
||||||
|
if (lexeme.equals(errorDecl.name()) || !errorDecl.cases().asList().contains(lexeme)) {
|
||||||
|
continue;
|
||||||
|
}
|
||||||
|
if (errorDecl.span() != null && errorDecl.span().contains(offset)) {
|
||||||
|
return true;
|
||||||
|
}
|
||||||
|
final String errorKey = locationKey(errorDecl.span());
|
||||||
|
for (final PbsEditorialLocation location : identity) {
|
||||||
|
if (location != null && location.span() != null && errorKey.equals(locationKey(location.span()))) {
|
||||||
|
return true;
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
|
return false;
|
||||||
|
}
|
||||||
|
|
||||||
|
private boolean collides(
|
||||||
|
final String newName,
|
||||||
|
final RenameCursor renameCursor) {
|
||||||
|
if (newName == null || newName.equals(renameCursor.originalName())) {
|
||||||
|
return false;
|
||||||
|
}
|
||||||
|
if (isLocalOrParameterIdentity(renameCursor)) {
|
||||||
|
return localBindingNames((int) renameCursor.placeholder().span().getStart()).contains(newName);
|
||||||
|
}
|
||||||
|
if (isStructFieldIdentity(renameCursor)) {
|
||||||
|
return structFieldNames(renameCursor).contains(newName);
|
||||||
|
}
|
||||||
|
if (isMethodIdentity(renameCursor)) {
|
||||||
|
return methodNames(renameCursor).contains(newName);
|
||||||
|
}
|
||||||
|
if (isEnumCaseIdentity(renameCursor)) {
|
||||||
|
return enumCaseNames(renameCursor).contains(newName);
|
||||||
|
}
|
||||||
|
return topLevelBindingNames().contains(newName);
|
||||||
|
}
|
||||||
|
|
||||||
|
private boolean isLocalOrParameterIdentity(final RenameCursor renameCursor) {
|
||||||
|
final Set<String> keys = locationKeys(renameCursor.identity());
|
||||||
|
for (final var topDecl : ast.topDecls()) {
|
||||||
|
if (!(topDecl instanceof PbsAst.FunctionDecl functionDecl) || functionDecl.body() == null) {
|
||||||
|
continue;
|
||||||
|
}
|
||||||
|
for (final var parameter : functionDecl.parameters()) {
|
||||||
|
if (keys.contains(locationKey(parameter.span()))) {
|
||||||
|
return true;
|
||||||
|
}
|
||||||
|
}
|
||||||
|
if (containsLetNameSpan(functionDecl.body(), keys)) {
|
||||||
|
return true;
|
||||||
|
}
|
||||||
|
}
|
||||||
|
for (final var topDecl : ast.topDecls()) {
|
||||||
|
if (!(topDecl instanceof PbsAst.StructDecl structDecl)) {
|
||||||
|
continue;
|
||||||
|
}
|
||||||
|
for (final var method : structDecl.methods()) {
|
||||||
|
if (method.body() == null) {
|
||||||
|
continue;
|
||||||
|
}
|
||||||
|
for (final var parameter : method.parameters()) {
|
||||||
|
if (keys.contains(locationKey(parameter.span()))) {
|
||||||
|
return true;
|
||||||
|
}
|
||||||
|
}
|
||||||
|
if (containsLetNameSpan(method.body(), keys)) {
|
||||||
|
return true;
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
|
return false;
|
||||||
|
}
|
||||||
|
|
||||||
|
private boolean containsLetNameSpan(
|
||||||
|
final PbsAst.Block block,
|
||||||
|
final Set<String> keys) {
|
||||||
|
if (block == null) {
|
||||||
|
return false;
|
||||||
|
}
|
||||||
|
for (final var statement : block.statements()) {
|
||||||
|
if (statement instanceof PbsAst.LetStatement letStatement
|
||||||
|
&& letStatement.nameSpan() != null
|
||||||
|
&& keys.contains(locationKey(letStatement.nameSpan()))) {
|
||||||
|
return true;
|
||||||
|
}
|
||||||
|
if (statement instanceof PbsAst.IfStatement ifStatement) {
|
||||||
|
if (containsLetNameSpan(ifStatement.thenBlock(), keys)
|
||||||
|
|| containsLetNameSpan(ifStatement.elseBlock(), keys)) {
|
||||||
|
return true;
|
||||||
|
}
|
||||||
|
} else if (statement instanceof PbsAst.ForStatement forStatement) {
|
||||||
|
if (containsLetNameSpan(forStatement.body(), keys)) {
|
||||||
|
return true;
|
||||||
|
}
|
||||||
|
} else if (statement instanceof PbsAst.WhileStatement whileStatement
|
||||||
|
&& containsLetNameSpan(whileStatement.body(), keys)) {
|
||||||
|
return true;
|
||||||
|
}
|
||||||
|
}
|
||||||
|
return false;
|
||||||
|
}
|
||||||
|
|
||||||
|
private Set<String> localBindingNames(final int offset) {
|
||||||
|
final LinkedHashSet<String> names = new LinkedHashSet<>();
|
||||||
|
final CallableFrame frame = callableFrameAt(offset);
|
||||||
|
if (frame == null) {
|
||||||
|
return Set.of();
|
||||||
|
}
|
||||||
|
names.addAll(frame.parameterNames());
|
||||||
|
collectLetNames(frame.body(), names);
|
||||||
|
return names;
|
||||||
|
}
|
||||||
|
|
||||||
|
private void collectLetNames(
|
||||||
|
final PbsAst.Block block,
|
||||||
|
final Set<String> names) {
|
||||||
|
if (block == null) {
|
||||||
|
return;
|
||||||
|
}
|
||||||
|
for (final var statement : block.statements()) {
|
||||||
|
if (statement instanceof PbsAst.LetStatement letStatement) {
|
||||||
|
names.add(letStatement.name());
|
||||||
|
} else if (statement instanceof PbsAst.IfStatement ifStatement) {
|
||||||
|
collectLetNames(ifStatement.thenBlock(), names);
|
||||||
|
collectLetNames(ifStatement.elseBlock(), names);
|
||||||
|
} else if (statement instanceof PbsAst.ForStatement forStatement) {
|
||||||
|
names.add(forStatement.iteratorName());
|
||||||
|
collectLetNames(forStatement.body(), names);
|
||||||
|
} else if (statement instanceof PbsAst.WhileStatement whileStatement) {
|
||||||
|
collectLetNames(whileStatement.body(), names);
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
private boolean isStructFieldIdentity(final RenameCursor renameCursor) {
|
||||||
|
return !structFieldNames(renameCursor).isEmpty()
|
||||||
|
&& structFieldIdentityMatch(renameCursor);
|
||||||
|
}
|
||||||
|
|
||||||
|
private boolean structFieldIdentityMatch(final RenameCursor renameCursor) {
|
||||||
|
final Set<String> keys = locationKeys(renameCursor.identity());
|
||||||
|
for (final var topDecl : ast.topDecls()) {
|
||||||
|
if (!(topDecl instanceof PbsAst.StructDecl structDecl)) {
|
||||||
|
continue;
|
||||||
|
}
|
||||||
|
for (final var field : structDecl.fields()) {
|
||||||
|
if (keys.contains(locationKey(field.span()))) {
|
||||||
|
return true;
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
|
return false;
|
||||||
|
}
|
||||||
|
|
||||||
|
private Set<String> structFieldNames(final RenameCursor renameCursor) {
|
||||||
|
final Set<String> keys = locationKeys(renameCursor.identity());
|
||||||
|
for (final var topDecl : ast.topDecls()) {
|
||||||
|
if (!(topDecl instanceof PbsAst.StructDecl structDecl)) {
|
||||||
|
continue;
|
||||||
|
}
|
||||||
|
for (final var field : structDecl.fields()) {
|
||||||
|
if (keys.contains(locationKey(field.span()))) {
|
||||||
|
final LinkedHashSet<String> names = new LinkedHashSet<>();
|
||||||
|
for (final var sibling : structDecl.fields()) {
|
||||||
|
names.add(sibling.name());
|
||||||
|
}
|
||||||
|
return names;
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
|
return Set.of();
|
||||||
|
}
|
||||||
|
|
||||||
|
private boolean isMethodIdentity(final RenameCursor renameCursor) {
|
||||||
|
return !methodNames(renameCursor).isEmpty();
|
||||||
|
}
|
||||||
|
|
||||||
|
private Set<String> methodNames(final RenameCursor renameCursor) {
|
||||||
|
final Set<String> keys = locationKeys(renameCursor.identity());
|
||||||
|
for (final var topDecl : ast.topDecls()) {
|
||||||
|
if (!(topDecl instanceof PbsAst.StructDecl structDecl)) {
|
||||||
|
continue;
|
||||||
|
}
|
||||||
|
for (final var method : structDecl.methods()) {
|
||||||
|
if (keys.contains(locationKey(method.span()))) {
|
||||||
|
final LinkedHashSet<String> names = new LinkedHashSet<>();
|
||||||
|
for (final var sibling : structDecl.methods()) {
|
||||||
|
names.add(sibling.name());
|
||||||
|
}
|
||||||
|
return names;
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
|
return Set.of();
|
||||||
|
}
|
||||||
|
|
||||||
|
private boolean isEnumCaseIdentity(final RenameCursor renameCursor) {
|
||||||
|
return !enumCaseNames(renameCursor).isEmpty();
|
||||||
|
}
|
||||||
|
|
||||||
|
private Set<String> enumCaseNames(final RenameCursor renameCursor) {
|
||||||
|
final Set<String> keys = locationKeys(renameCursor.identity());
|
||||||
|
for (final var topDecl : ast.topDecls()) {
|
||||||
|
if (!(topDecl instanceof PbsAst.EnumDecl enumDecl)) {
|
||||||
|
continue;
|
||||||
|
}
|
||||||
|
for (final var enumCase : enumDecl.cases()) {
|
||||||
|
if (keys.contains(locationKey(enumCase.span()))) {
|
||||||
|
final LinkedHashSet<String> names = new LinkedHashSet<>();
|
||||||
|
for (final var sibling : enumDecl.cases()) {
|
||||||
|
names.add(sibling.name());
|
||||||
|
}
|
||||||
|
return names;
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
|
return Set.of();
|
||||||
|
}
|
||||||
|
|
||||||
|
private Set<String> topLevelBindingNames() {
|
||||||
|
final LinkedHashSet<String> names = new LinkedHashSet<>();
|
||||||
|
for (final var topDecl : ast.topDecls()) {
|
||||||
|
if (topDecl instanceof PbsAst.FunctionDecl functionDecl) {
|
||||||
|
names.add(functionDecl.name());
|
||||||
|
} else if (topDecl instanceof PbsAst.ServiceDecl serviceDecl) {
|
||||||
|
names.add(serviceDecl.name());
|
||||||
|
} else if (topDecl instanceof PbsAst.GlobalDecl globalDecl) {
|
||||||
|
names.add(globalDecl.name());
|
||||||
|
} else if (topDecl instanceof PbsAst.ConstDecl constDecl) {
|
||||||
|
names.add(constDecl.name());
|
||||||
|
}
|
||||||
|
}
|
||||||
|
names.addAll(importedSymbols.keySet());
|
||||||
|
return names;
|
||||||
|
}
|
||||||
|
|
||||||
private PbsToken token(final int index) {
|
private PbsToken token(final int index) {
|
||||||
return tokens.get(index);
|
return tokens.get(index);
|
||||||
}
|
}
|
||||||
@@ -1336,6 +2160,17 @@ public final class PbsEditorialSupportService {
|
|||||||
String origin) {
|
String origin) {
|
||||||
}
|
}
|
||||||
|
|
||||||
|
private record RenameCursor(
|
||||||
|
String originalName,
|
||||||
|
PbsEditorialLocation placeholder,
|
||||||
|
List<PbsEditorialLocation> identity,
|
||||||
|
String refusal) {
|
||||||
|
|
||||||
|
private static RenameCursor refused(final String reason) {
|
||||||
|
return new RenameCursor("", null, List.of(), reason);
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
private record CallableFrame(
|
private record CallableFrame(
|
||||||
ReadOnlyList<PbsAst.Parameter> parameters,
|
ReadOnlyList<PbsAst.Parameter> parameters,
|
||||||
PbsAst.Block body,
|
PbsAst.Block body,
|
||||||
|
|||||||
+21
@@ -0,0 +1,21 @@
|
|||||||
|
package p.studio.compiler.pbs.semantics;
|
||||||
|
|
||||||
|
import p.studio.compiler.source.Span;
|
||||||
|
|
||||||
|
import java.util.Objects;
|
||||||
|
|
||||||
|
public record PbsEditorialWorkspaceSymbol(
|
||||||
|
String name,
|
||||||
|
PbsEditorialSymbolKind kind,
|
||||||
|
String detail,
|
||||||
|
String containerName,
|
||||||
|
Span span) {
|
||||||
|
|
||||||
|
public PbsEditorialWorkspaceSymbol {
|
||||||
|
name = Objects.requireNonNull(name, "name").trim();
|
||||||
|
kind = Objects.requireNonNull(kind, "kind");
|
||||||
|
detail = detail == null ? "" : detail;
|
||||||
|
containerName = containerName == null ? "" : containerName.trim();
|
||||||
|
span = Objects.requireNonNull(span, "span");
|
||||||
|
}
|
||||||
|
}
|
||||||
+33
@@ -0,0 +1,33 @@
|
|||||||
|
package p.studio.compiler.pbs.semantics;
|
||||||
|
|
||||||
|
import java.util.Objects;
|
||||||
|
|
||||||
|
public record PbsQuickFix(
|
||||||
|
String diagnosticCode,
|
||||||
|
int startOffset,
|
||||||
|
int endOffset,
|
||||||
|
String newText,
|
||||||
|
String title) {
|
||||||
|
|
||||||
|
public PbsQuickFix {
|
||||||
|
diagnosticCode = requireText(diagnosticCode, "diagnosticCode");
|
||||||
|
title = requireText(title, "title");
|
||||||
|
if (startOffset < 0) {
|
||||||
|
throw new IllegalArgumentException("startOffset must not be negative");
|
||||||
|
}
|
||||||
|
if (endOffset < startOffset) {
|
||||||
|
throw new IllegalArgumentException("endOffset must not be before startOffset");
|
||||||
|
}
|
||||||
|
newText = Objects.requireNonNull(newText, "newText");
|
||||||
|
}
|
||||||
|
|
||||||
|
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;
|
||||||
|
}
|
||||||
|
}
|
||||||
+148
@@ -0,0 +1,148 @@
|
|||||||
|
package p.studio.compiler.pbs.semantics;
|
||||||
|
|
||||||
|
import p.studio.compiler.pbs.ast.PbsAst;
|
||||||
|
import p.studio.compiler.source.Span;
|
||||||
|
import p.studio.utilities.structures.ReadOnlyList;
|
||||||
|
|
||||||
|
import java.util.ArrayList;
|
||||||
|
import java.util.Comparator;
|
||||||
|
import java.util.List;
|
||||||
|
|
||||||
|
public final class PbsQuickFixCollector {
|
||||||
|
static final String REMOVE_DUPLICATE_TITLE = "Remove duplicate reserved attribute";
|
||||||
|
static final String REMOVE_INIT_ALLOWED_ARGUMENTS_TITLE = "Remove InitAllowed arguments";
|
||||||
|
private static final String INIT_ALLOWED_REPLACEMENT = "[InitAllowed]";
|
||||||
|
|
||||||
|
private PbsQuickFixCollector() {
|
||||||
|
}
|
||||||
|
|
||||||
|
public static List<PbsQuickFix> collect(
|
||||||
|
final PbsAst.File ast,
|
||||||
|
final boolean interfaceModule) {
|
||||||
|
if (ast == null) {
|
||||||
|
return List.of();
|
||||||
|
}
|
||||||
|
final ArrayList<PbsQuickFix> repairs = new ArrayList<>();
|
||||||
|
for (final PbsAst.TopDecl topDecl : ast.topDecls()) {
|
||||||
|
switch (topDecl) {
|
||||||
|
case PbsAst.FunctionDecl functionDecl -> duplicateDoc(functionDecl.attributes(), repairs);
|
||||||
|
case PbsAst.StructDecl structDecl -> {
|
||||||
|
duplicateDoc(structDecl.attributes(), repairs);
|
||||||
|
for (final PbsAst.FunctionDecl method : structDecl.methods()) {
|
||||||
|
duplicateDoc(method.attributes(), repairs);
|
||||||
|
}
|
||||||
|
}
|
||||||
|
case PbsAst.ServiceDecl serviceDecl -> {
|
||||||
|
duplicateDoc(serviceDecl.attributes(), repairs);
|
||||||
|
for (final PbsAst.FunctionDecl method : serviceDecl.methods()) {
|
||||||
|
duplicateDoc(method.attributes(), repairs);
|
||||||
|
}
|
||||||
|
}
|
||||||
|
case PbsAst.ContractDecl contractDecl -> {
|
||||||
|
duplicateDoc(contractDecl.attributes(), repairs);
|
||||||
|
if (interfaceModule) {
|
||||||
|
for (final PbsAst.FunctionSignature signature : contractDecl.signatures()) {
|
||||||
|
duplicateDoc(signature.attributes(), repairs);
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
|
case PbsAst.HostDecl hostDecl -> {
|
||||||
|
duplicateDoc(hostDecl.attributes(), repairs);
|
||||||
|
if (interfaceModule) {
|
||||||
|
for (final PbsAst.FunctionSignature signature : hostDecl.signatures()) {
|
||||||
|
collectHostSignature(signature, repairs);
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
|
case PbsAst.BuiltinTypeDecl builtinTypeDecl -> {
|
||||||
|
if (interfaceModule) {
|
||||||
|
duplicateDoc(builtinTypeDecl.attributes(), repairs);
|
||||||
|
duplicateNamed(builtinTypeDecl.attributes(), "BuiltinType", repairs);
|
||||||
|
for (final PbsAst.FunctionSignature signature : builtinTypeDecl.signatures()) {
|
||||||
|
duplicateDoc(signature.attributes(), repairs);
|
||||||
|
duplicateNamed(signature.attributes(), "IntrinsicCall", repairs);
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
|
case PbsAst.ErrorDecl errorDecl -> duplicateDoc(errorDecl.attributes(), repairs);
|
||||||
|
case PbsAst.EnumDecl enumDecl -> duplicateDoc(enumDecl.attributes(), repairs);
|
||||||
|
case PbsAst.CallbackDecl callbackDecl -> duplicateDoc(callbackDecl.attributes(), repairs);
|
||||||
|
case PbsAst.ConstDecl constDecl -> {
|
||||||
|
duplicateDoc(constDecl.attributes(), repairs);
|
||||||
|
duplicateNamed(constDecl.attributes(), "BuiltinConst", repairs);
|
||||||
|
}
|
||||||
|
default -> {
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
|
repairs.sort(Comparator
|
||||||
|
.comparingInt(PbsQuickFix::startOffset)
|
||||||
|
.thenComparingInt(PbsQuickFix::endOffset)
|
||||||
|
.thenComparing(PbsQuickFix::diagnosticCode));
|
||||||
|
return List.copyOf(repairs);
|
||||||
|
}
|
||||||
|
|
||||||
|
private static void collectHostSignature(
|
||||||
|
final PbsAst.FunctionSignature signature,
|
||||||
|
final List<PbsQuickFix> repairs) {
|
||||||
|
duplicateDoc(signature.attributes(), repairs);
|
||||||
|
duplicateNamed(signature.attributes(), "Host", repairs);
|
||||||
|
duplicateNamed(signature.attributes(), "InitAllowed", repairs);
|
||||||
|
duplicateNamed(signature.attributes(), "AssetLowering", repairs);
|
||||||
|
final List<PbsAst.Attribute> initAllowed = named(signature.attributes(), "InitAllowed");
|
||||||
|
if (!initAllowed.isEmpty() && !initAllowed.getFirst().arguments().isEmpty()) {
|
||||||
|
add(repairs, initAllowed.getFirst(), PbsSemanticsErrors.E_SEM_MALFORMED_RESERVED_ATTRIBUTE.name(),
|
||||||
|
INIT_ALLOWED_REPLACEMENT, REMOVE_INIT_ALLOWED_ARGUMENTS_TITLE);
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
private static void duplicateDoc(
|
||||||
|
final ReadOnlyList<PbsAst.Attribute> attributes,
|
||||||
|
final List<PbsQuickFix> repairs) {
|
||||||
|
duplicateNamed(attributes, "Doc", repairs);
|
||||||
|
}
|
||||||
|
|
||||||
|
private static void duplicateNamed(
|
||||||
|
final ReadOnlyList<PbsAst.Attribute> attributes,
|
||||||
|
final String name,
|
||||||
|
final List<PbsQuickFix> repairs) {
|
||||||
|
final List<PbsAst.Attribute> matches = named(attributes, name);
|
||||||
|
for (int index = 1; index < matches.size(); index++) {
|
||||||
|
add(repairs, matches.get(index), PbsSemanticsErrors.E_SEM_DUPLICATE_RESERVED_ATTRIBUTE.name(),
|
||||||
|
"", REMOVE_DUPLICATE_TITLE);
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
private static List<PbsAst.Attribute> named(
|
||||||
|
final ReadOnlyList<PbsAst.Attribute> attributes,
|
||||||
|
final String name) {
|
||||||
|
final ArrayList<PbsAst.Attribute> matches = new ArrayList<>();
|
||||||
|
if (attributes == null) {
|
||||||
|
return matches;
|
||||||
|
}
|
||||||
|
for (final PbsAst.Attribute attribute : attributes) {
|
||||||
|
if (name.equals(attribute.name())) {
|
||||||
|
matches.add(attribute);
|
||||||
|
}
|
||||||
|
}
|
||||||
|
return matches;
|
||||||
|
}
|
||||||
|
|
||||||
|
private static void add(
|
||||||
|
final List<PbsQuickFix> repairs,
|
||||||
|
final PbsAst.Attribute attribute,
|
||||||
|
final String code,
|
||||||
|
final String newText,
|
||||||
|
final String title) {
|
||||||
|
if (attribute == null || attribute.span() == null || attribute.span().isNone()) {
|
||||||
|
return;
|
||||||
|
}
|
||||||
|
final Span span = attribute.span();
|
||||||
|
final long start = span.getStart();
|
||||||
|
final long end = span.getEnd();
|
||||||
|
if (start < 0 || end < start || end > Integer.MAX_VALUE) {
|
||||||
|
return;
|
||||||
|
}
|
||||||
|
repairs.add(new PbsQuickFix(code, (int) start, (int) end, newText, title));
|
||||||
|
}
|
||||||
|
}
|
||||||
+9
-2
@@ -5,6 +5,7 @@ import p.studio.compiler.messages.BuildingIssueSink;
|
|||||||
import p.studio.compiler.messages.FESurfaceContext;
|
import p.studio.compiler.messages.FESurfaceContext;
|
||||||
import p.studio.compiler.messages.FrontendPhaseContext;
|
import p.studio.compiler.messages.FrontendPhaseContext;
|
||||||
import p.studio.compiler.models.IRBackend;
|
import p.studio.compiler.models.IRBackend;
|
||||||
|
import p.studio.compiler.models.SourceKind;
|
||||||
import p.studio.compiler.pbs.PbsFrontendCompiler;
|
import p.studio.compiler.pbs.PbsFrontendCompiler;
|
||||||
import p.studio.compiler.pbs.PbsReservedMetadataExtractor;
|
import p.studio.compiler.pbs.PbsReservedMetadataExtractor;
|
||||||
import p.studio.compiler.pbs.semantics.PbsFlowSemanticsValidator;
|
import p.studio.compiler.pbs.semantics.PbsFlowSemanticsValidator;
|
||||||
@@ -127,11 +128,15 @@ public class PBSFrontendPhaseService implements FrontendPhaseService {
|
|||||||
final Map<FileId, p.studio.compiler.pbs.ast.PbsAst.File> astByFile = new LinkedHashMap<>();
|
final Map<FileId, p.studio.compiler.pbs.ast.PbsAst.File> astByFile = new LinkedHashMap<>();
|
||||||
final Map<FileId, ReadOnlyList<p.studio.compiler.pbs.ast.PbsAst.TopDecl>> supplementalTopDeclsByFile = new LinkedHashMap<>();
|
final Map<FileId, ReadOnlyList<p.studio.compiler.pbs.ast.PbsAst.TopDecl>> supplementalTopDeclsByFile = new LinkedHashMap<>();
|
||||||
final Map<FileId, ReadOnlyList<PbsInlineHintSurface>> inlineHintsByFile = new LinkedHashMap<>();
|
final Map<FileId, ReadOnlyList<PbsInlineHintSurface>> inlineHintsByFile = new LinkedHashMap<>();
|
||||||
|
final Map<FileId, SourceKind> sourceKindByFile = new LinkedHashMap<>();
|
||||||
for (final var entry : importedSemanticContexts.entrySet()) {
|
for (final var entry : importedSemanticContexts.entrySet()) {
|
||||||
supplementalTopDeclsByFile.put(entry.getKey(), entry.getValue().supplementalTopDecls());
|
supplementalTopDeclsByFile.put(entry.getKey(), entry.getValue().supplementalTopDecls());
|
||||||
}
|
}
|
||||||
for (final var parsedSourceFile : assembly.parsedSourceFiles()) {
|
for (final var parsedSourceFile : assembly.parsedSourceFiles()) {
|
||||||
astByFile.put(parsedSourceFile.fileId(), parsedSourceFile.ast());
|
astByFile.put(parsedSourceFile.fileId(), parsedSourceFile.ast());
|
||||||
|
sourceKindByFile.put(
|
||||||
|
parsedSourceFile.fileId(),
|
||||||
|
parsedSourceFile.sourceKind() == null ? SourceKind.PROJECT : parsedSourceFile.sourceKind());
|
||||||
final var importedSemanticContext = importedSemanticContexts.getOrDefault(
|
final var importedSemanticContext = importedSemanticContexts.getOrDefault(
|
||||||
parsedSourceFile.fileId(),
|
parsedSourceFile.fileId(),
|
||||||
PbsImportedSemanticContext.empty());
|
PbsImportedSemanticContext.empty());
|
||||||
@@ -147,13 +152,15 @@ public class PBSFrontendPhaseService implements FrontendPhaseService {
|
|||||||
return new PbsSemanticReadSurface(
|
return new PbsSemanticReadSurface(
|
||||||
Map.copyOf(astByFile),
|
Map.copyOf(astByFile),
|
||||||
Map.copyOf(supplementalTopDeclsByFile),
|
Map.copyOf(supplementalTopDeclsByFile),
|
||||||
Map.copyOf(inlineHintsByFile));
|
Map.copyOf(inlineHintsByFile),
|
||||||
|
Map.copyOf(sourceKindByFile));
|
||||||
}
|
}
|
||||||
|
|
||||||
public record PbsSemanticReadSurface(
|
public record PbsSemanticReadSurface(
|
||||||
Map<FileId, p.studio.compiler.pbs.ast.PbsAst.File> astByFile,
|
Map<FileId, p.studio.compiler.pbs.ast.PbsAst.File> astByFile,
|
||||||
Map<FileId, ReadOnlyList<p.studio.compiler.pbs.ast.PbsAst.TopDecl>> supplementalTopDeclsByFile,
|
Map<FileId, ReadOnlyList<p.studio.compiler.pbs.ast.PbsAst.TopDecl>> supplementalTopDeclsByFile,
|
||||||
Map<FileId, ReadOnlyList<PbsInlineHintSurface>> inlineHintsByFile) {
|
Map<FileId, ReadOnlyList<PbsInlineHintSurface>> inlineHintsByFile,
|
||||||
|
Map<FileId, SourceKind> sourceKindByFile) {
|
||||||
}
|
}
|
||||||
|
|
||||||
private IRBackend mergeCompiledSources(
|
private IRBackend mergeCompiledSources(
|
||||||
|
|||||||
+8
@@ -8,6 +8,7 @@ import java.nio.charset.StandardCharsets;
|
|||||||
import java.util.List;
|
import java.util.List;
|
||||||
|
|
||||||
import static org.junit.jupiter.api.Assertions.assertEquals;
|
import static org.junit.jupiter.api.Assertions.assertEquals;
|
||||||
|
import static org.junit.jupiter.api.Assertions.assertFalse;
|
||||||
import static org.junit.jupiter.api.Assertions.assertTrue;
|
import static org.junit.jupiter.api.Assertions.assertTrue;
|
||||||
|
|
||||||
class PbsLexerTest {
|
class PbsLexerTest {
|
||||||
@@ -34,6 +35,13 @@ class PbsLexerTest {
|
|||||||
.kind());
|
.kind());
|
||||||
assertEquals(PbsTokenKind.EOF, tokens.getLast().kind());
|
assertEquals(PbsTokenKind.EOF, tokens.getLast().kind());
|
||||||
assertTrue(diagnostics.isEmpty(), "Lexer should not report diagnostics for valid input");
|
assertTrue(diagnostics.isEmpty(), "Lexer should not report diagnostics for valid input");
|
||||||
|
assertTrue(PbsLexer.isKeyword("fn"));
|
||||||
|
assertTrue(PbsLexer.isKeyword("step"));
|
||||||
|
assertTrue(PbsLexer.isIdentifierLexeme("helper"));
|
||||||
|
assertTrue(PbsLexer.isIdentifierLexeme("_value"));
|
||||||
|
assertFalse(PbsLexer.isIdentifierLexeme("fn"));
|
||||||
|
assertFalse(PbsLexer.isIdentifierLexeme("1ab"));
|
||||||
|
assertFalse(PbsLexer.isIdentifierLexeme(""));
|
||||||
}
|
}
|
||||||
|
|
||||||
@Test
|
@Test
|
||||||
|
|||||||
+487
@@ -265,6 +265,473 @@ 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)")));
|
||||||
|
}
|
||||||
|
|
||||||
|
@Test
|
||||||
|
void shouldCollectSameFileReferencesForPhysicalSymbolsAndSkipTrivia() {
|
||||||
|
final var source = """
|
||||||
|
fn helper(value: int) -> int {
|
||||||
|
let total = value;
|
||||||
|
return total;
|
||||||
|
}
|
||||||
|
|
||||||
|
fn frame() -> void {
|
||||||
|
helper(1);
|
||||||
|
helper(2);
|
||||||
|
// helper
|
||||||
|
let text = "helper";
|
||||||
|
missingName;
|
||||||
|
}
|
||||||
|
""";
|
||||||
|
final var ast = parseOrdinary(source);
|
||||||
|
|
||||||
|
final var helperRefs = service.references(source, ast, ReadOnlyList.empty(), source.indexOf("helper(1)"));
|
||||||
|
assertEquals(3, helperRefs.size(), helperRefs.toString());
|
||||||
|
assertTrue(helperRefs.stream().anyMatch(location -> location.span().contains(source.indexOf("helper(value"))));
|
||||||
|
assertTrue(helperRefs.stream().anyMatch(location -> location.span().contains(source.indexOf("helper(1)"))));
|
||||||
|
assertTrue(helperRefs.stream().anyMatch(location -> location.span().contains(source.indexOf("helper(2)"))));
|
||||||
|
assertTrue(helperRefs.stream().noneMatch(location -> location.span().contains(source.indexOf("// helper"))));
|
||||||
|
assertTrue(helperRefs.stream().noneMatch(location -> location.span().contains(source.indexOf("\"helper\""))));
|
||||||
|
|
||||||
|
final var parameterRefs = service.references(source, ast, ReadOnlyList.empty(), source.indexOf("value;"));
|
||||||
|
assertEquals(2, parameterRefs.size());
|
||||||
|
assertTrue(parameterRefs.stream().anyMatch(location -> location.span().contains(source.indexOf("value: int"))));
|
||||||
|
assertTrue(parameterRefs.stream().anyMatch(location -> location.span().contains(source.indexOf("value;"))));
|
||||||
|
|
||||||
|
final var localRefs = service.references(source, ast, ReadOnlyList.empty(), source.indexOf("total;"));
|
||||||
|
assertEquals(1, localRefs.size());
|
||||||
|
assertTrue(localRefs.getFirst().span().contains(source.indexOf("total;")));
|
||||||
|
assertTrue(service.definition(source, ast, ReadOnlyList.empty(), source.indexOf("total = value")).isEmpty());
|
||||||
|
|
||||||
|
assertTrue(service.references(source, ast, ReadOnlyList.empty(), source.indexOf("fn helper")).isEmpty());
|
||||||
|
assertTrue(service.references(source, ast, ReadOnlyList.empty(), source.indexOf("int")).isEmpty());
|
||||||
|
assertTrue(service.references(source, ast, ReadOnlyList.empty(), source.indexOf("missingName")).isEmpty());
|
||||||
|
}
|
||||||
|
|
||||||
|
@Test
|
||||||
|
void shouldCollectImportedAndOverloadedReferencesByDefinitionIntersection() {
|
||||||
|
final var importedSource = """
|
||||||
|
declare service Log {
|
||||||
|
fn info(message: str) -> void {
|
||||||
|
return;
|
||||||
|
}
|
||||||
|
}
|
||||||
|
""";
|
||||||
|
final var importedAst = parseInterface(importedSource, new FileId(100));
|
||||||
|
final var source = """
|
||||||
|
import { Log as Logger } from @sdk:log;
|
||||||
|
|
||||||
|
declare struct Vec() {
|
||||||
|
fn blend(dx: int) -> int { return dx; }
|
||||||
|
fn blend(dx: int, dy: int) -> int { return dx; }
|
||||||
|
}
|
||||||
|
|
||||||
|
fn frame(vec: Vec) -> void {
|
||||||
|
Logger.info("a");
|
||||||
|
Logger.info("b");
|
||||||
|
vec.blend(1, 2);
|
||||||
|
}
|
||||||
|
""";
|
||||||
|
final var ast = parseOrdinary(source);
|
||||||
|
final var supplementalTopDecls = importedAst.topDecls();
|
||||||
|
|
||||||
|
final var infoRefs = service.references(
|
||||||
|
new PbsEditorialSupportService.EditorialDocument(source, ast, supplementalTopDecls, null),
|
||||||
|
source.indexOf("info(\"a\")"),
|
||||||
|
List.of(
|
||||||
|
new PbsEditorialSupportService.EditorialDocument(source, ast, supplementalTopDecls, null),
|
||||||
|
new PbsEditorialSupportService.EditorialDocument(
|
||||||
|
importedSource,
|
||||||
|
importedAst,
|
||||||
|
ReadOnlyList.empty(),
|
||||||
|
null)));
|
||||||
|
assertEquals(2, infoRefs.stream().filter(location -> location.span().getFileId().getId() == 0).count());
|
||||||
|
assertTrue(infoRefs.stream().anyMatch(location -> location.span().contains(source.indexOf("info(\"a\")"))));
|
||||||
|
assertTrue(infoRefs.stream().anyMatch(location -> location.span().contains(source.indexOf("info(\"b\")"))));
|
||||||
|
|
||||||
|
final var blendRefs = service.references(source, ast, supplementalTopDecls, source.indexOf("blend(1"));
|
||||||
|
assertTrue(blendRefs.stream().anyMatch(location -> location.span().contains(source.indexOf("blend(1"))));
|
||||||
|
final var blendIdentity = service.definition(source, ast, supplementalTopDecls, source.indexOf("blend(1"));
|
||||||
|
assertEquals(2, blendIdentity.size());
|
||||||
|
}
|
||||||
|
|
||||||
|
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;
|
||||||
|
}
|
||||||
|
|
||||||
|
@Test
|
||||||
|
void shouldBuildAstBackedOutlineHierarchyAndKeepOverloadsAsSiblings() {
|
||||||
|
final var source = """
|
||||||
|
import { Log } from @sdk:log;
|
||||||
|
|
||||||
|
[Init]
|
||||||
|
fn init() -> void { return; }
|
||||||
|
fn helper(a: int) -> int { return a; }
|
||||||
|
fn helper(a: int, b: int) -> int { return a; }
|
||||||
|
declare struct Point(x: int, pub y: int) {
|
||||||
|
ctor make(x: int) { return; }
|
||||||
|
fn run() -> void { return; }
|
||||||
|
}
|
||||||
|
declare contract TickLike { fn tick(dt: int) -> void; }
|
||||||
|
declare service Physics { fn tick() -> void { return; } }
|
||||||
|
declare error Io { NotFound; Busy; }
|
||||||
|
declare enum Mode(Idle = 0, Run = 1);
|
||||||
|
declare callback OnClick(x: int) -> result<Io> int;
|
||||||
|
declare global STATE: int = 10;
|
||||||
|
declare const LIMIT: int = 10;
|
||||||
|
implements TickLike for Point using s { fn tick(dt: int) -> void { return; } }
|
||||||
|
|
||||||
|
fn frame() -> void {
|
||||||
|
let local = 1;
|
||||||
|
helper(local);
|
||||||
|
}
|
||||||
|
""";
|
||||||
|
final var ast = parseOrdinary(source);
|
||||||
|
final var symbols = service.documentSymbols(ast);
|
||||||
|
|
||||||
|
assertEquals(List.of(
|
||||||
|
"init",
|
||||||
|
"helper",
|
||||||
|
"helper",
|
||||||
|
"Point",
|
||||||
|
"TickLike",
|
||||||
|
"Physics",
|
||||||
|
"Io",
|
||||||
|
"Mode",
|
||||||
|
"OnClick",
|
||||||
|
"STATE",
|
||||||
|
"LIMIT",
|
||||||
|
"TickLike",
|
||||||
|
"frame"), names(symbols));
|
||||||
|
assertTrue(symbols.stream().noneMatch(symbol -> symbol.name().equals("Log") || symbol.name().equals("local")));
|
||||||
|
assertTrue(symbols.getFirst().name().equals("init"));
|
||||||
|
assertFalse(symbols.getFirst().name().contains("Init"));
|
||||||
|
assertEquals("(a: int) -> int", symbols.get(1).detail());
|
||||||
|
assertEquals("(a: int, b: int) -> int", symbols.get(2).detail());
|
||||||
|
|
||||||
|
final var point = requireNamed(symbols, "Point");
|
||||||
|
assertEquals(PbsEditorialSymbolKind.STRUCT, point.kind());
|
||||||
|
assertEquals(List.of("x", "y", "make", "run"), names(point.children()));
|
||||||
|
assertEquals(PbsEditorialSymbolKind.FIELD, point.children().getFirst().kind());
|
||||||
|
assertEquals("int", point.children().getFirst().detail());
|
||||||
|
assertEquals(PbsEditorialSymbolKind.CONSTRUCTOR, point.children().get(2).kind());
|
||||||
|
assertEquals("(x: int)", point.children().get(2).detail());
|
||||||
|
assertEquals(PbsEditorialSymbolKind.METHOD, point.children().get(3).kind());
|
||||||
|
|
||||||
|
final var contract = symbols.get(4);
|
||||||
|
assertEquals(PbsEditorialSymbolKind.CONTRACT, contract.kind());
|
||||||
|
assertEquals(List.of("tick"), names(contract.children()));
|
||||||
|
assertEquals("(dt: int) -> void", contract.children().getFirst().detail());
|
||||||
|
|
||||||
|
final var physics = requireNamed(symbols, "Physics");
|
||||||
|
assertEquals(PbsEditorialSymbolKind.SERVICE, physics.kind());
|
||||||
|
assertEquals(List.of("tick"), names(physics.children()));
|
||||||
|
|
||||||
|
final var error = requireNamed(symbols, "Io");
|
||||||
|
assertEquals(PbsEditorialSymbolKind.ERROR, error.kind());
|
||||||
|
assertEquals(List.of("NotFound", "Busy"), names(error.children()));
|
||||||
|
|
||||||
|
final var mode = requireNamed(symbols, "Mode");
|
||||||
|
assertEquals(PbsEditorialSymbolKind.ENUM, mode.kind());
|
||||||
|
assertEquals(List.of("Idle", "Run"), names(mode.children()));
|
||||||
|
assertEquals("0", mode.children().getFirst().detail());
|
||||||
|
|
||||||
|
final var callback = requireNamed(symbols, "OnClick");
|
||||||
|
assertEquals(PbsEditorialSymbolKind.CALLBACK, callback.kind());
|
||||||
|
assertEquals("(x: int) -> result<Io> int", callback.detail());
|
||||||
|
|
||||||
|
assertEquals(PbsEditorialSymbolKind.GLOBAL, requireNamed(symbols, "STATE").kind());
|
||||||
|
assertEquals("int", requireNamed(symbols, "STATE").detail());
|
||||||
|
assertEquals(PbsEditorialSymbolKind.CONST, requireNamed(symbols, "LIMIT").kind());
|
||||||
|
|
||||||
|
final var implementsSymbol = symbols.get(11);
|
||||||
|
assertEquals("TickLike", implementsSymbol.name());
|
||||||
|
assertEquals("Point", implementsSymbol.detail());
|
||||||
|
assertEquals(PbsEditorialSymbolKind.CONTRACT, implementsSymbol.kind());
|
||||||
|
assertEquals(List.of("tick"), names(implementsSymbol.children()));
|
||||||
|
}
|
||||||
|
|
||||||
|
@Test
|
||||||
|
void shouldFlattenOutlineMembersForWorkspaceSearchAndFilterByName() {
|
||||||
|
final var source = """
|
||||||
|
import { Log } from @sdk:log;
|
||||||
|
|
||||||
|
declare struct Vec(x: int) {
|
||||||
|
ctor make(x: int) { return; }
|
||||||
|
fn blend(dx: int, dy: int) -> int { return dx; }
|
||||||
|
}
|
||||||
|
|
||||||
|
fn helper() -> int { return 42; }
|
||||||
|
fn helper(value: int) -> int { return value; }
|
||||||
|
|
||||||
|
fn frame() -> void {
|
||||||
|
let local = 1;
|
||||||
|
helper(local);
|
||||||
|
}
|
||||||
|
""";
|
||||||
|
final var ast = parseOrdinary(source);
|
||||||
|
final var all = service.workspaceSymbols(ast, "");
|
||||||
|
assertEquals(List.of(
|
||||||
|
"Vec",
|
||||||
|
"x",
|
||||||
|
"make",
|
||||||
|
"blend",
|
||||||
|
"helper",
|
||||||
|
"helper",
|
||||||
|
"frame"), all.stream().map(PbsEditorialWorkspaceSymbol::name).toList());
|
||||||
|
assertEquals("", all.getFirst().containerName());
|
||||||
|
assertEquals("Vec", all.stream().filter(symbol -> symbol.name().equals("blend")).findFirst().orElseThrow().containerName());
|
||||||
|
assertEquals("Vec", all.stream().filter(symbol -> symbol.name().equals("x")).findFirst().orElseThrow().containerName());
|
||||||
|
assertTrue(all.stream().noneMatch(symbol -> symbol.name().equals("Log") || symbol.name().equals("local")));
|
||||||
|
|
||||||
|
final var blendHits = service.workspaceSymbols(ast, "BLEND");
|
||||||
|
assertEquals(List.of("blend"), blendHits.stream().map(PbsEditorialWorkspaceSymbol::name).toList());
|
||||||
|
assertEquals("Vec", blendHits.getFirst().containerName());
|
||||||
|
|
||||||
|
final var helperHits = service.workspaceSymbols(ast, "helper");
|
||||||
|
assertEquals(2, helperHits.size());
|
||||||
|
assertNotEquals(helperHits.getFirst().detail(), helperHits.get(1).detail());
|
||||||
|
|
||||||
|
final var qualifiedMiss = service.workspaceSymbols(ast, "Vec.blend");
|
||||||
|
assertTrue(qualifiedMiss.isEmpty());
|
||||||
|
}
|
||||||
|
|
||||||
|
@Test
|
||||||
|
void shouldOmitInvalidDeclarationsAndKeepNamedDeclsFromRecoveredAst() {
|
||||||
|
final var source = """
|
||||||
|
declare ;
|
||||||
|
fn ok() -> int { return 1; }
|
||||||
|
""";
|
||||||
|
final var ast = parseAllowingErrors(source);
|
||||||
|
final var symbols = service.documentSymbols(ast);
|
||||||
|
assertEquals(List.of("ok"), names(symbols));
|
||||||
|
assertEquals(PbsEditorialSymbolKind.FUNCTION, symbols.getFirst().kind());
|
||||||
|
final var workspaceSymbols = service.workspaceSymbols(ast, "");
|
||||||
|
assertEquals(List.of("ok"), workspaceSymbols.stream().map(PbsEditorialWorkspaceSymbol::name).toList());
|
||||||
|
}
|
||||||
|
|
||||||
|
@Test
|
||||||
|
void shouldOutlineHostAndBuiltinTypeDeclarationsFromInterfaceModules() {
|
||||||
|
final var source = """
|
||||||
|
declare host Gfx {
|
||||||
|
fn clear(color: int) -> void;
|
||||||
|
}
|
||||||
|
declare builtin type Color(
|
||||||
|
pub r: int
|
||||||
|
) {
|
||||||
|
fn pack() -> int;
|
||||||
|
}
|
||||||
|
""";
|
||||||
|
final var ast = parseInterface(source, new FileId(0));
|
||||||
|
final var symbols = service.documentSymbols(ast);
|
||||||
|
assertEquals(List.of("Gfx", "Color"), names(symbols));
|
||||||
|
assertEquals(PbsEditorialSymbolKind.HOST, symbols.getFirst().kind());
|
||||||
|
assertEquals(List.of("clear"), names(symbols.getFirst().children()));
|
||||||
|
assertEquals(PbsEditorialSymbolKind.BUILTIN_TYPE, symbols.get(1).kind());
|
||||||
|
assertEquals(List.of("r", "pack"), names(symbols.get(1).children()));
|
||||||
|
}
|
||||||
|
|
||||||
|
@Test
|
||||||
|
void renameRewritesPhysicalFunctionSitesAndSkipsCommentsStringsAndCollisions() {
|
||||||
|
final var source = """
|
||||||
|
fn helper() -> int { return 1; }
|
||||||
|
|
||||||
|
fn helper(value: int) -> int { return value; }
|
||||||
|
|
||||||
|
fn frame() -> void {
|
||||||
|
helper();
|
||||||
|
helper(2);
|
||||||
|
// helper
|
||||||
|
let text = "helper";
|
||||||
|
}
|
||||||
|
""";
|
||||||
|
final var ast = parseOrdinary(source);
|
||||||
|
final var renamed = service.rename(source, ast, ReadOnlyList.empty(), source.indexOf("helper();"), "aid");
|
||||||
|
assertTrue(renamed.allowed(), renamed.refusal());
|
||||||
|
assertEquals(4, renamed.sites().size(), renamed.sites().toString());
|
||||||
|
assertTrue(service.prepareRename(source, ast, ReadOnlyList.empty(), source.indexOf("helper();")).isPresent());
|
||||||
|
|
||||||
|
final var keyword = service.rename(source, ast, ReadOnlyList.empty(), source.indexOf("helper();"), "fn");
|
||||||
|
assertFalse(keyword.allowed());
|
||||||
|
assertEquals("invalid identifier", keyword.refusal());
|
||||||
|
|
||||||
|
final var collision = service.rename(source, ast, ReadOnlyList.empty(), source.indexOf("helper();"), "frame");
|
||||||
|
assertFalse(collision.allowed());
|
||||||
|
assertEquals("name collision", collision.refusal());
|
||||||
|
}
|
||||||
|
|
||||||
|
@Test
|
||||||
|
void renameAllowsLocalNameSpanAndRefusesAliasBuiltinAndErrorLabel() {
|
||||||
|
final var source = """
|
||||||
|
import { Log as Logger } from @sdk:log;
|
||||||
|
|
||||||
|
declare error Boom {
|
||||||
|
Missing;
|
||||||
|
}
|
||||||
|
|
||||||
|
fn frame() -> void {
|
||||||
|
let total = 1;
|
||||||
|
Logger.info("x");
|
||||||
|
let n: int = total;
|
||||||
|
n;
|
||||||
|
}
|
||||||
|
""";
|
||||||
|
final var ast = parseOrdinary(source);
|
||||||
|
final var supplemental = supplementalTopDecls("""
|
||||||
|
declare service Log {
|
||||||
|
fn info(message: str) -> void {
|
||||||
|
return;
|
||||||
|
}
|
||||||
|
}
|
||||||
|
""");
|
||||||
|
|
||||||
|
final var local = service.rename(
|
||||||
|
source,
|
||||||
|
ast,
|
||||||
|
supplemental,
|
||||||
|
source.indexOf("total ="),
|
||||||
|
"sum");
|
||||||
|
assertTrue(local.allowed(), local.refusal());
|
||||||
|
assertEquals(2, local.sites().size(), local.sites().toString());
|
||||||
|
|
||||||
|
final var alias = service.prepareRename(
|
||||||
|
source,
|
||||||
|
ast,
|
||||||
|
supplemental,
|
||||||
|
source.indexOf("Logger.info"));
|
||||||
|
assertTrue(alias.isEmpty());
|
||||||
|
|
||||||
|
final var builtin = service.prepareRename(
|
||||||
|
source,
|
||||||
|
ast,
|
||||||
|
supplemental,
|
||||||
|
source.indexOf("int = total"));
|
||||||
|
assertTrue(builtin.isEmpty());
|
||||||
|
|
||||||
|
final var errorLabel = service.prepareRename(
|
||||||
|
source,
|
||||||
|
ast,
|
||||||
|
supplemental,
|
||||||
|
source.indexOf("Missing"));
|
||||||
|
assertTrue(errorLabel.isEmpty());
|
||||||
|
}
|
||||||
|
|
||||||
|
@Test
|
||||||
|
void renameOfExportDoesNotRewriteDifferingAlias() {
|
||||||
|
final var exporter = """
|
||||||
|
fn helper() -> int { return 1; }
|
||||||
|
""";
|
||||||
|
final var importer = """
|
||||||
|
import { helper as aid } from @sdk:log;
|
||||||
|
|
||||||
|
fn frame() -> void {
|
||||||
|
aid();
|
||||||
|
}
|
||||||
|
""";
|
||||||
|
final var exporterAst = parse(exporter, new FileId(1), PbsParser.ParseMode.ORDINARY);
|
||||||
|
final var importerAst = parseOrdinary(importer);
|
||||||
|
final var exporterDoc = new PbsEditorialSupportService.EditorialDocument(
|
||||||
|
exporter,
|
||||||
|
exporterAst,
|
||||||
|
ReadOnlyList.empty(),
|
||||||
|
p.studio.compiler.messages.FESurfaceContext.empty());
|
||||||
|
final var importerDoc = new PbsEditorialSupportService.EditorialDocument(
|
||||||
|
importer,
|
||||||
|
importerAst,
|
||||||
|
exporterAst.topDecls(),
|
||||||
|
p.studio.compiler.messages.FESurfaceContext.empty());
|
||||||
|
final var renamed = service.rename(
|
||||||
|
exporterDoc,
|
||||||
|
exporter.indexOf("helper"),
|
||||||
|
"renamed",
|
||||||
|
List.of(exporterDoc, importerDoc));
|
||||||
|
assertTrue(renamed.allowed(), renamed.refusal());
|
||||||
|
assertEquals(2, renamed.sites().size(), renamed.sites().toString());
|
||||||
|
assertTrue(renamed.sites().stream().anyMatch(site ->
|
||||||
|
site.span().getFileId().equals(exporterAst.span().getFileId())));
|
||||||
|
assertTrue(renamed.sites().stream().anyMatch(site ->
|
||||||
|
site.span().getFileId().equals(importerAst.span().getFileId())));
|
||||||
|
final int aliasUse = importer.indexOf("aid();");
|
||||||
|
assertTrue(renamed.sites().stream().noneMatch(site ->
|
||||||
|
site.span().getFileId().equals(importerAst.span().getFileId())
|
||||||
|
&& site.span().getStart() == aliasUse));
|
||||||
|
}
|
||||||
|
|
||||||
private PbsEditorialResolvedSymbol requireHover(
|
private PbsEditorialResolvedSymbol requireHover(
|
||||||
final String source,
|
final String source,
|
||||||
final PbsAst.File ast,
|
final PbsAst.File ast,
|
||||||
@@ -286,6 +753,26 @@ final class PbsEditorialSupportServiceTest {
|
|||||||
return ReadOnlyList.wrap(topDecls);
|
return ReadOnlyList.wrap(topDecls);
|
||||||
}
|
}
|
||||||
|
|
||||||
|
private List<String> names(final List<PbsEditorialDocumentSymbol> symbols) {
|
||||||
|
return symbols.stream().map(PbsEditorialDocumentSymbol::name).toList();
|
||||||
|
}
|
||||||
|
|
||||||
|
private PbsEditorialDocumentSymbol requireNamed(
|
||||||
|
final List<PbsEditorialDocumentSymbol> symbols,
|
||||||
|
final String name) {
|
||||||
|
return symbols.stream()
|
||||||
|
.filter(symbol -> symbol.name().equals(name))
|
||||||
|
.findFirst()
|
||||||
|
.orElseThrow(() -> new AssertionError("missing symbol: " + name + " in " + names(symbols)));
|
||||||
|
}
|
||||||
|
|
||||||
|
private PbsAst.File parseAllowingErrors(final String source) {
|
||||||
|
final var diagnostics = DiagnosticSink.empty();
|
||||||
|
final var fileId = new FileId(0);
|
||||||
|
final var tokens = PbsLexer.lex(source, fileId, diagnostics);
|
||||||
|
return PbsParser.parse(tokens, fileId, diagnostics, PbsParser.ParseMode.ORDINARY);
|
||||||
|
}
|
||||||
|
|
||||||
private PbsAst.File parseOrdinary(final String source) {
|
private PbsAst.File parseOrdinary(final String source) {
|
||||||
return parse(source, new FileId(0), PbsParser.ParseMode.ORDINARY);
|
return parse(source, new FileId(0), PbsParser.ParseMode.ORDINARY);
|
||||||
}
|
}
|
||||||
|
|||||||
+234
@@ -0,0 +1,234 @@
|
|||||||
|
package p.studio.compiler.pbs.semantics;
|
||||||
|
|
||||||
|
import org.junit.jupiter.api.Test;
|
||||||
|
import p.studio.compiler.models.SourceKind;
|
||||||
|
import p.studio.compiler.pbs.ast.PbsAst;
|
||||||
|
import p.studio.compiler.pbs.lexer.PbsLexer;
|
||||||
|
import p.studio.compiler.pbs.parser.PbsParser;
|
||||||
|
import p.studio.compiler.source.diagnostics.Diagnostic;
|
||||||
|
import p.studio.compiler.source.diagnostics.DiagnosticSink;
|
||||||
|
import p.studio.compiler.source.identifiers.FileId;
|
||||||
|
import p.studio.compiler.source.tables.NameTable;
|
||||||
|
|
||||||
|
import java.util.Comparator;
|
||||||
|
import java.util.List;
|
||||||
|
|
||||||
|
import static org.junit.jupiter.api.Assertions.assertEquals;
|
||||||
|
import static org.junit.jupiter.api.Assertions.assertFalse;
|
||||||
|
import static org.junit.jupiter.api.Assertions.assertTrue;
|
||||||
|
|
||||||
|
class PbsQuickFixCollectorTest {
|
||||||
|
|
||||||
|
@Test
|
||||||
|
void duplicateDocRepairsMatchValidatorSpansAndKeepTheFirstCopy() {
|
||||||
|
final var parsed = parse("""
|
||||||
|
[Doc(markdown = \"""
|
||||||
|
First.
|
||||||
|
\""")]
|
||||||
|
[Doc(markdown = \"""
|
||||||
|
Second.
|
||||||
|
\""")]
|
||||||
|
[Doc(markdown = \"""
|
||||||
|
Third.
|
||||||
|
\""")]
|
||||||
|
fn duplicated() -> void { return; }
|
||||||
|
|
||||||
|
declare struct Player(x: int) {
|
||||||
|
[Doc(markdown = \"""
|
||||||
|
Kept.
|
||||||
|
\""")]
|
||||||
|
[Doc(markdown = \"""
|
||||||
|
Extra method.
|
||||||
|
\""")]
|
||||||
|
fn update() -> void { return; }
|
||||||
|
}
|
||||||
|
""", SourceKind.PROJECT);
|
||||||
|
|
||||||
|
final var duplicates = diagnostics(parsed, PbsSemanticsErrors.E_SEM_DUPLICATE_RESERVED_ATTRIBUTE.name());
|
||||||
|
assertEquals(3, duplicates.size(), parsed.diagnostics().stream().map(Diagnostic::getMessage).toList().toString());
|
||||||
|
assertEquals(3, parsed.repairs().size());
|
||||||
|
assertTrue(parsed.repairs().stream().allMatch(repair ->
|
||||||
|
repair.newText().isEmpty()
|
||||||
|
&& repair.title().equals(PbsQuickFixCollector.REMOVE_DUPLICATE_TITLE)
|
||||||
|
&& repair.diagnosticCode().equals(PbsSemanticsErrors.E_SEM_DUPLICATE_RESERVED_ATTRIBUTE.name())));
|
||||||
|
assertRepairsMatchDiagnostics(parsed);
|
||||||
|
|
||||||
|
final String edited = apply(parsed.source(), parsed.repairs());
|
||||||
|
assertTrue(edited.contains("First."));
|
||||||
|
assertTrue(edited.contains("Kept."));
|
||||||
|
assertFalse(edited.contains("Second."));
|
||||||
|
assertFalse(edited.contains("Third."));
|
||||||
|
assertFalse(edited.contains("Extra method."));
|
||||||
|
}
|
||||||
|
|
||||||
|
@Test
|
||||||
|
void malformedAndEmptyDocProduceNoRepair() {
|
||||||
|
final var parsed = parse("""
|
||||||
|
[Doc(text = \"""
|
||||||
|
Wrong argument.
|
||||||
|
\""")]
|
||||||
|
fn malformed() -> void { return; }
|
||||||
|
|
||||||
|
[Doc(markdown = \"""
|
||||||
|
|
||||||
|
\""")]
|
||||||
|
fn empty() -> void { return; }
|
||||||
|
|
||||||
|
[InitAllowed(flag = 1)]
|
||||||
|
fn frame() -> void { return; }
|
||||||
|
""", SourceKind.PROJECT);
|
||||||
|
|
||||||
|
assertTrue(diagnostics(parsed, PbsSemanticsErrors.E_SEM_MALFORMED_RESERVED_ATTRIBUTE.name()).size() >= 2);
|
||||||
|
assertTrue(parsed.repairs().isEmpty(), parsed.repairs().toString());
|
||||||
|
}
|
||||||
|
|
||||||
|
@Test
|
||||||
|
void initAllowedArgumentsAreRewrittenOnlyForInterfaceHostSignatures() {
|
||||||
|
final var parsed = parse("""
|
||||||
|
declare host Gfx {
|
||||||
|
[Host(module = "gfx2d", name = "clear", version = 1)]
|
||||||
|
[InitAllowed(flag = 1)]
|
||||||
|
fn clear() -> void;
|
||||||
|
|
||||||
|
[Host(module = "gfx2d", name = "fill", version = 1)]
|
||||||
|
[InitAllowed()]
|
||||||
|
fn fill() -> void;
|
||||||
|
|
||||||
|
[Host(module = "gfx2d", name = "blit", version = 1)]
|
||||||
|
[InitAllowed]
|
||||||
|
fn blit() -> void;
|
||||||
|
|
||||||
|
[Host(module = "gfx2d")]
|
||||||
|
fn broken() -> void;
|
||||||
|
|
||||||
|
[Host(module = "gfx2d", name = "copy", version = 1)]
|
||||||
|
[Host(module = "gfx2d", name = "copy", version = 1)]
|
||||||
|
fn copy() -> void;
|
||||||
|
}
|
||||||
|
""", SourceKind.SDK_INTERFACE);
|
||||||
|
|
||||||
|
final var argumentRepairs = parsed.repairs().stream()
|
||||||
|
.filter(repair -> repair.newText().equals("[InitAllowed]"))
|
||||||
|
.toList();
|
||||||
|
assertEquals(1, argumentRepairs.size(), parsed.repairs().toString());
|
||||||
|
assertEquals(PbsSemanticsErrors.E_SEM_MALFORMED_RESERVED_ATTRIBUTE.name(), argumentRepairs.getFirst().diagnosticCode());
|
||||||
|
assertEquals(PbsQuickFixCollector.REMOVE_INIT_ALLOWED_ARGUMENTS_TITLE, argumentRepairs.getFirst().title());
|
||||||
|
assertRepairsMatchDiagnostics(parsed);
|
||||||
|
|
||||||
|
final var duplicateRepairs = parsed.repairs().stream()
|
||||||
|
.filter(repair -> repair.diagnosticCode().equals(PbsSemanticsErrors.E_SEM_DUPLICATE_RESERVED_ATTRIBUTE.name()))
|
||||||
|
.toList();
|
||||||
|
assertEquals(1, duplicateRepairs.size());
|
||||||
|
assertTrue(duplicateRepairs.getFirst().newText().isEmpty());
|
||||||
|
|
||||||
|
final String edited = apply(parsed.source(), parsed.repairs());
|
||||||
|
assertTrue(edited.contains("[InitAllowed]\n"));
|
||||||
|
assertFalse(edited.contains("flag = 1"));
|
||||||
|
assertTrue(edited.contains("[InitAllowed()]"));
|
||||||
|
assertEquals(1, count(edited, "[Host(module = \"gfx2d\", name = \"copy\", version = 1)]"));
|
||||||
|
|
||||||
|
final var projectHost = parse("""
|
||||||
|
declare host Gfx {
|
||||||
|
[Host(module = "gfx2d", name = "clear", version = 1)]
|
||||||
|
[InitAllowed(flag = 1)]
|
||||||
|
fn clear() -> void;
|
||||||
|
}
|
||||||
|
""", SourceKind.PROJECT);
|
||||||
|
assertTrue(projectHost.repairs().stream().noneMatch(repair -> repair.newText().equals("[InitAllowed]")));
|
||||||
|
}
|
||||||
|
|
||||||
|
@Test
|
||||||
|
void builtinConstTypeIntrinsicAndAssetLoweringDuplicatesAreDeleted() {
|
||||||
|
final var parsed = parse("""
|
||||||
|
[BuiltinType(name = "Color", version = 1)]
|
||||||
|
[BuiltinType(name = "Color", version = 1)]
|
||||||
|
declare builtin type Color(
|
||||||
|
pub raw: int
|
||||||
|
) {
|
||||||
|
[IntrinsicCall(name = "width", version = 1)]
|
||||||
|
[IntrinsicCall(name = "width", version = 1)]
|
||||||
|
fn width() -> int;
|
||||||
|
}
|
||||||
|
[BuiltinConst(target = "Color", name = "white", version = 1)]
|
||||||
|
[BuiltinConst(target = "Color", name = "white", version = 1)]
|
||||||
|
declare const WHITE: Color;
|
||||||
|
declare host LowAssets {
|
||||||
|
[Host(module = "asset", name = "load", version = 1)]
|
||||||
|
[AssetLowering(param = 0)]
|
||||||
|
[AssetLowering(param = 0)]
|
||||||
|
fn load(addressable: int) -> void;
|
||||||
|
}
|
||||||
|
""", SourceKind.SDK_INTERFACE);
|
||||||
|
|
||||||
|
assertEquals(4, parsed.repairs().size(), parsed.repairs().toString());
|
||||||
|
assertTrue(parsed.repairs().stream().allMatch(repair ->
|
||||||
|
repair.newText().isEmpty()
|
||||||
|
&& repair.diagnosticCode().equals(PbsSemanticsErrors.E_SEM_DUPLICATE_RESERVED_ATTRIBUTE.name())));
|
||||||
|
assertRepairsMatchDiagnostics(parsed);
|
||||||
|
final String edited = apply(parsed.source(), parsed.repairs());
|
||||||
|
assertEquals(1, count(edited, "[BuiltinType(name = \"Color\", version = 1)]"));
|
||||||
|
assertEquals(1, count(edited, "[IntrinsicCall(name = \"width\", version = 1)]"));
|
||||||
|
assertEquals(1, count(edited, "[BuiltinConst(target = \"Color\", name = \"white\", version = 1)]"));
|
||||||
|
assertEquals(1, count(edited, "[AssetLowering(param = 0)]"));
|
||||||
|
}
|
||||||
|
|
||||||
|
private static Parsed parse(final String source, final SourceKind sourceKind) {
|
||||||
|
final var diagnostics = DiagnosticSink.empty();
|
||||||
|
final var fileId = new FileId(0);
|
||||||
|
final var tokens = PbsLexer.lex(source, fileId, diagnostics);
|
||||||
|
final var parseMode = sourceKind == SourceKind.SDK_INTERFACE
|
||||||
|
? PbsParser.ParseMode.INTERFACE_MODULE
|
||||||
|
: PbsParser.ParseMode.ORDINARY;
|
||||||
|
final PbsAst.File ast = PbsParser.parse(tokens, fileId, diagnostics, parseMode);
|
||||||
|
new PbsDeclarationSemanticsValidator(new NameTable()).validate(ast, sourceKind, diagnostics);
|
||||||
|
return new Parsed(
|
||||||
|
source,
|
||||||
|
diagnostics,
|
||||||
|
PbsQuickFixCollector.collect(ast, sourceKind == SourceKind.SDK_INTERFACE));
|
||||||
|
}
|
||||||
|
|
||||||
|
private static List<Diagnostic> diagnostics(final Parsed parsed, final String code) {
|
||||||
|
return parsed.diagnostics().stream().filter(diagnostic -> diagnostic.getCode().equals(code)).toList();
|
||||||
|
}
|
||||||
|
|
||||||
|
private static void assertRepairsMatchDiagnostics(final Parsed parsed) {
|
||||||
|
for (final PbsQuickFix repair : parsed.repairs()) {
|
||||||
|
assertTrue(parsed.diagnostics().stream().anyMatch(diagnostic ->
|
||||||
|
diagnostic.getCode().equals(repair.diagnosticCode())
|
||||||
|
&& diagnostic.getSpan().getStart() == repair.startOffset()
|
||||||
|
&& diagnostic.getSpan().getEnd() == repair.endOffset()),
|
||||||
|
repair + " missing from " + parsed.diagnostics());
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
private static String apply(final String source, final List<PbsQuickFix> repairs) {
|
||||||
|
final var ordered = repairs.stream()
|
||||||
|
.sorted(Comparator.comparingInt(PbsQuickFix::startOffset).reversed())
|
||||||
|
.toList();
|
||||||
|
String current = source;
|
||||||
|
for (final PbsQuickFix repair : ordered) {
|
||||||
|
current = current.substring(0, repair.startOffset()) + repair.newText() + current.substring(repair.endOffset());
|
||||||
|
}
|
||||||
|
return current;
|
||||||
|
}
|
||||||
|
|
||||||
|
private static int count(final String source, final String needle) {
|
||||||
|
int count = 0;
|
||||||
|
int from = 0;
|
||||||
|
while (from <= source.length()) {
|
||||||
|
final int found = source.indexOf(needle, from);
|
||||||
|
if (found < 0) {
|
||||||
|
return count;
|
||||||
|
}
|
||||||
|
count += 1;
|
||||||
|
from = found + needle.length();
|
||||||
|
}
|
||||||
|
return count;
|
||||||
|
}
|
||||||
|
|
||||||
|
private record Parsed(
|
||||||
|
String source,
|
||||||
|
DiagnosticSink diagnostics,
|
||||||
|
List<PbsQuickFix> repairs) {
|
||||||
|
}
|
||||||
|
}
|
||||||
-96
@@ -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");
|
|
||||||
}
|
|
||||||
}
|
|
||||||
-102
@@ -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")
|
||||||
|
|||||||
+5
-2
@@ -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
|
||||||
|
|||||||
+36
@@ -0,0 +1,36 @@
|
|||||||
|
package p.studio.compiler.services;
|
||||||
|
|
||||||
|
import java.nio.file.Path;
|
||||||
|
import java.util.Objects;
|
||||||
|
|
||||||
|
public record FrontendCodeAction(
|
||||||
|
String title,
|
||||||
|
String diagnosticCode,
|
||||||
|
Path path,
|
||||||
|
int startOffset,
|
||||||
|
int endOffset,
|
||||||
|
String newText) {
|
||||||
|
|
||||||
|
public FrontendCodeAction {
|
||||||
|
title = requireText(title, "title");
|
||||||
|
diagnosticCode = requireText(diagnosticCode, "diagnosticCode");
|
||||||
|
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");
|
||||||
|
}
|
||||||
|
newText = Objects.requireNonNull(newText, "newText");
|
||||||
|
}
|
||||||
|
|
||||||
|
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;
|
||||||
|
}
|
||||||
|
}
|
||||||
+20
@@ -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");
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
+44
@@ -0,0 +1,44 @@
|
|||||||
|
package p.studio.compiler.services;
|
||||||
|
|
||||||
|
import java.util.List;
|
||||||
|
import java.util.Objects;
|
||||||
|
|
||||||
|
public record FrontendDocumentSymbol(
|
||||||
|
String name,
|
||||||
|
FrontendSymbolKind kind,
|
||||||
|
String detail,
|
||||||
|
int rangeStart,
|
||||||
|
int rangeEnd,
|
||||||
|
int selectionStart,
|
||||||
|
int selectionEnd,
|
||||||
|
List<FrontendDocumentSymbol> children) {
|
||||||
|
|
||||||
|
public FrontendDocumentSymbol {
|
||||||
|
name = requireText(name, "name");
|
||||||
|
kind = Objects.requireNonNull(kind, "kind");
|
||||||
|
detail = detail == null ? "" : detail.trim();
|
||||||
|
if (rangeStart < 0) {
|
||||||
|
throw new IllegalArgumentException("rangeStart must not be negative");
|
||||||
|
}
|
||||||
|
if (rangeEnd < rangeStart) {
|
||||||
|
throw new IllegalArgumentException("rangeEnd must not be before rangeStart");
|
||||||
|
}
|
||||||
|
if (selectionStart < 0) {
|
||||||
|
throw new IllegalArgumentException("selectionStart must not be negative");
|
||||||
|
}
|
||||||
|
if (selectionEnd < selectionStart) {
|
||||||
|
throw new IllegalArgumentException("selectionEnd must not be before selectionStart");
|
||||||
|
}
|
||||||
|
children = children == null ? List.of() : List.copyOf(children);
|
||||||
|
}
|
||||||
|
|
||||||
|
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;
|
||||||
|
}
|
||||||
|
}
|
||||||
+18
-1
@@ -3,5 +3,22 @@ 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,
|
||||||
|
Object projectSurface) {
|
||||||
|
|
||||||
|
public FrontendEditorialContext(
|
||||||
|
final Object syntaxTree,
|
||||||
|
final Object supplementalDeclarations,
|
||||||
|
final Object semanticContext) {
|
||||||
|
this(syntaxTree, supplementalDeclarations, semanticContext, null, null);
|
||||||
|
}
|
||||||
|
|
||||||
|
public FrontendEditorialContext(
|
||||||
|
final Object syntaxTree,
|
||||||
|
final Object supplementalDeclarations,
|
||||||
|
final Object semanticContext,
|
||||||
|
final Object sourceFiles) {
|
||||||
|
this(syntaxTree, supplementalDeclarations, semanticContext, sourceFiles, null);
|
||||||
|
}
|
||||||
}
|
}
|
||||||
|
|||||||
+93
@@ -11,6 +11,11 @@ import java.util.Optional;
|
|||||||
* Optional frontend-owned editor services.
|
* Optional frontend-owned editor services.
|
||||||
*/
|
*/
|
||||||
public interface FrontendLanguageService {
|
public interface FrontendLanguageService {
|
||||||
|
default Optional<FrontendEditorialContext> prepareEditorialContext(
|
||||||
|
final FrontendPhaseContext phaseContext) {
|
||||||
|
return Optional.empty();
|
||||||
|
}
|
||||||
|
|
||||||
default Optional<FrontendEditorialContext> prepareEditorialContext(
|
default Optional<FrontendEditorialContext> prepareEditorialContext(
|
||||||
final FrontendPhaseContext phaseContext,
|
final FrontendPhaseContext phaseContext,
|
||||||
final FileId fileId) {
|
final FileId fileId) {
|
||||||
@@ -59,4 +64,92 @@ 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);
|
||||||
|
}
|
||||||
|
|
||||||
|
default List<FrontendDefinitionLocation> references(
|
||||||
|
final FrontendDocumentRequest request,
|
||||||
|
final int offset) {
|
||||||
|
return List.of();
|
||||||
|
}
|
||||||
|
|
||||||
|
default List<FrontendDefinitionLocation> references(
|
||||||
|
final FrontendDocumentRequest request,
|
||||||
|
final FrontendEditorialContext editorialContext,
|
||||||
|
final int offset) {
|
||||||
|
return references(request, offset);
|
||||||
|
}
|
||||||
|
|
||||||
|
default List<FrontendDocumentSymbol> documentSymbols(final FrontendDocumentRequest request) {
|
||||||
|
return List.of();
|
||||||
|
}
|
||||||
|
|
||||||
|
default List<FrontendDocumentSymbol> documentSymbols(
|
||||||
|
final FrontendDocumentRequest request,
|
||||||
|
final FrontendEditorialContext editorialContext) {
|
||||||
|
return documentSymbols(request);
|
||||||
|
}
|
||||||
|
|
||||||
|
default List<FrontendWorkspaceSymbol> workspaceSymbols(final FrontendWorkspaceRequest request) {
|
||||||
|
return List.of();
|
||||||
|
}
|
||||||
|
|
||||||
|
default List<FrontendWorkspaceSymbol> workspaceSymbols(
|
||||||
|
final FrontendWorkspaceRequest request,
|
||||||
|
final FrontendEditorialContext editorialContext) {
|
||||||
|
return workspaceSymbols(request);
|
||||||
|
}
|
||||||
|
|
||||||
|
default Optional<FrontendDefinitionLocation> prepareRename(
|
||||||
|
final FrontendDocumentRequest request,
|
||||||
|
final int offset) {
|
||||||
|
return Optional.empty();
|
||||||
|
}
|
||||||
|
|
||||||
|
default Optional<FrontendDefinitionLocation> prepareRename(
|
||||||
|
final FrontendDocumentRequest request,
|
||||||
|
final FrontendEditorialContext editorialContext,
|
||||||
|
final int offset) {
|
||||||
|
return prepareRename(request, offset);
|
||||||
|
}
|
||||||
|
|
||||||
|
default FrontendRenameResult rename(
|
||||||
|
final FrontendDocumentRequest request,
|
||||||
|
final int offset,
|
||||||
|
final String newName) {
|
||||||
|
return FrontendRenameResult.unsupported();
|
||||||
|
}
|
||||||
|
|
||||||
|
default FrontendRenameResult rename(
|
||||||
|
final FrontendDocumentRequest request,
|
||||||
|
final FrontendEditorialContext editorialContext,
|
||||||
|
final int offset,
|
||||||
|
final String newName) {
|
||||||
|
return rename(request, offset, newName);
|
||||||
|
}
|
||||||
|
|
||||||
|
default boolean codeActionsSupported() {
|
||||||
|
return false;
|
||||||
|
}
|
||||||
|
|
||||||
|
default List<FrontendCodeAction> codeActions(final FrontendDocumentRequest request) {
|
||||||
|
return List.of();
|
||||||
|
}
|
||||||
|
|
||||||
|
default List<FrontendCodeAction> codeActions(
|
||||||
|
final FrontendDocumentRequest request,
|
||||||
|
final FrontendEditorialContext editorialContext) {
|
||||||
|
return codeActions(request);
|
||||||
|
}
|
||||||
}
|
}
|
||||||
|
|||||||
+22
@@ -0,0 +1,22 @@
|
|||||||
|
package p.studio.compiler.services;
|
||||||
|
|
||||||
|
import java.nio.file.Path;
|
||||||
|
import java.util.Objects;
|
||||||
|
|
||||||
|
public record FrontendRenameEdit(
|
||||||
|
Path path,
|
||||||
|
int startOffset,
|
||||||
|
int endOffset,
|
||||||
|
String newText) {
|
||||||
|
|
||||||
|
public FrontendRenameEdit {
|
||||||
|
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");
|
||||||
|
}
|
||||||
|
newText = Objects.requireNonNull(newText, "newText");
|
||||||
|
}
|
||||||
|
}
|
||||||
+45
@@ -0,0 +1,45 @@
|
|||||||
|
package p.studio.compiler.services;
|
||||||
|
|
||||||
|
import java.util.List;
|
||||||
|
import java.util.Objects;
|
||||||
|
|
||||||
|
public record FrontendRenameResult(
|
||||||
|
Status status,
|
||||||
|
String message,
|
||||||
|
List<FrontendRenameEdit> edits) {
|
||||||
|
|
||||||
|
public enum Status {
|
||||||
|
UNSUPPORTED,
|
||||||
|
REFUSED,
|
||||||
|
APPLIED
|
||||||
|
}
|
||||||
|
|
||||||
|
public FrontendRenameResult {
|
||||||
|
status = Objects.requireNonNull(status, "status");
|
||||||
|
message = message == null ? "" : message.trim();
|
||||||
|
edits = edits == null ? List.of() : List.copyOf(edits);
|
||||||
|
if (status == Status.APPLIED && edits.isEmpty()) {
|
||||||
|
throw new IllegalArgumentException("applied rename must include at least one edit");
|
||||||
|
}
|
||||||
|
if (status != Status.APPLIED && !edits.isEmpty()) {
|
||||||
|
throw new IllegalArgumentException("refused or unsupported rename must not include edits");
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
public static FrontendRenameResult unsupported() {
|
||||||
|
return new FrontendRenameResult(Status.UNSUPPORTED, "unsupported", List.of());
|
||||||
|
}
|
||||||
|
|
||||||
|
public static FrontendRenameResult refused(final String message) {
|
||||||
|
final String reason = message == null || message.isBlank() ? "not renameable" : message.trim();
|
||||||
|
return new FrontendRenameResult(Status.REFUSED, reason, List.of());
|
||||||
|
}
|
||||||
|
|
||||||
|
public static FrontendRenameResult applied(final List<FrontendRenameEdit> edits) {
|
||||||
|
return new FrontendRenameResult(Status.APPLIED, "", edits);
|
||||||
|
}
|
||||||
|
|
||||||
|
public boolean applied() {
|
||||||
|
return status == Status.APPLIED;
|
||||||
|
}
|
||||||
|
}
|
||||||
+14
@@ -0,0 +1,14 @@
|
|||||||
|
package p.studio.compiler.services;
|
||||||
|
|
||||||
|
import java.nio.file.Path;
|
||||||
|
import java.util.Objects;
|
||||||
|
|
||||||
|
public record FrontendWorkspaceRequest(
|
||||||
|
Path projectRoot,
|
||||||
|
String query) {
|
||||||
|
|
||||||
|
public FrontendWorkspaceRequest {
|
||||||
|
projectRoot = Objects.requireNonNull(projectRoot, "projectRoot").toAbsolutePath().normalize();
|
||||||
|
query = query == null ? "" : query;
|
||||||
|
}
|
||||||
|
}
|
||||||
+38
@@ -0,0 +1,38 @@
|
|||||||
|
package p.studio.compiler.services;
|
||||||
|
|
||||||
|
import java.nio.file.Path;
|
||||||
|
import java.util.Objects;
|
||||||
|
|
||||||
|
public record FrontendWorkspaceSymbol(
|
||||||
|
String name,
|
||||||
|
FrontendSymbolKind kind,
|
||||||
|
String detail,
|
||||||
|
String containerName,
|
||||||
|
Path path,
|
||||||
|
int startOffset,
|
||||||
|
int endOffset) {
|
||||||
|
|
||||||
|
public FrontendWorkspaceSymbol {
|
||||||
|
name = requireText(name, "name");
|
||||||
|
kind = Objects.requireNonNull(kind, "kind");
|
||||||
|
detail = detail == null ? "" : detail.trim();
|
||||||
|
containerName = containerName == null ? "" : containerName.trim();
|
||||||
|
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");
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
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;
|
||||||
|
}
|
||||||
|
}
|
||||||
+166
@@ -22,6 +22,172 @@ 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());
|
||||||
|
assertTrue(service.references(request, 0).isEmpty());
|
||||||
|
assertTrue(service.documentSymbols(request).isEmpty());
|
||||||
|
assertTrue(service.workspaceSymbols(new FrontendWorkspaceRequest(Path.of("."), "frame")).isEmpty());
|
||||||
|
assertTrue(service.prepareEditorialContext(null).isEmpty());
|
||||||
|
assertTrue(service.prepareRename(request, 0).isEmpty());
|
||||||
|
assertEquals(FrontendRenameResult.Status.UNSUPPORTED, service.rename(request, 0, "renamed").status());
|
||||||
|
assertTrue(service.rename(request, 0, "renamed").edits().isEmpty());
|
||||||
|
assertFalse(service.codeActionsSupported());
|
||||||
|
assertTrue(service.codeActions(request).isEmpty());
|
||||||
|
assertTrue(service.codeActions(request, null).isEmpty());
|
||||||
|
}
|
||||||
|
|
||||||
|
@Test
|
||||||
|
void codeActionAllowsEmptyReplacementAndRejectsBlankIdentity() {
|
||||||
|
final Path path = Path.of("src/main.pbs").toAbsolutePath();
|
||||||
|
final var action = new FrontendCodeAction(
|
||||||
|
" Remove duplicate reserved attribute ",
|
||||||
|
" E_SEM_DUPLICATE_RESERVED_ATTRIBUTE ",
|
||||||
|
path,
|
||||||
|
4,
|
||||||
|
12,
|
||||||
|
"");
|
||||||
|
assertEquals("Remove duplicate reserved attribute", action.title());
|
||||||
|
assertEquals("E_SEM_DUPLICATE_RESERVED_ATTRIBUTE", action.diagnosticCode());
|
||||||
|
assertEquals("", action.newText());
|
||||||
|
assertThrows(IllegalArgumentException.class, () -> new FrontendCodeAction(
|
||||||
|
" ",
|
||||||
|
"E_SEM_DUPLICATE_RESERVED_ATTRIBUTE",
|
||||||
|
path,
|
||||||
|
0,
|
||||||
|
1,
|
||||||
|
""));
|
||||||
|
assertThrows(NullPointerException.class, () -> new FrontendCodeAction(
|
||||||
|
"Remove duplicate reserved attribute",
|
||||||
|
"E_SEM_DUPLICATE_RESERVED_ATTRIBUTE",
|
||||||
|
path,
|
||||||
|
0,
|
||||||
|
1,
|
||||||
|
null));
|
||||||
|
}
|
||||||
|
|
||||||
|
@Test
|
||||||
|
void documentSymbolRejectsBlankNameAndInvertedRangesAndCopiesChildren() {
|
||||||
|
final var child = new FrontendDocumentSymbol(
|
||||||
|
"x",
|
||||||
|
FrontendSymbolKind.FIELD,
|
||||||
|
"int",
|
||||||
|
10,
|
||||||
|
16,
|
||||||
|
10,
|
||||||
|
16,
|
||||||
|
List.of());
|
||||||
|
final var symbol = new FrontendDocumentSymbol(
|
||||||
|
" Point ",
|
||||||
|
FrontendSymbolKind.STRUCT,
|
||||||
|
" ",
|
||||||
|
0,
|
||||||
|
20,
|
||||||
|
8,
|
||||||
|
13,
|
||||||
|
List.of(child));
|
||||||
|
assertEquals("Point", symbol.name());
|
||||||
|
assertEquals("", symbol.detail());
|
||||||
|
assertEquals(1, symbol.children().size());
|
||||||
|
assertEquals("x", symbol.children().getFirst().name());
|
||||||
|
assertThrows(UnsupportedOperationException.class, () -> symbol.children().add(child));
|
||||||
|
assertThrows(IllegalArgumentException.class, () -> new FrontendDocumentSymbol(
|
||||||
|
" ",
|
||||||
|
FrontendSymbolKind.FUNCTION,
|
||||||
|
"",
|
||||||
|
0,
|
||||||
|
1,
|
||||||
|
0,
|
||||||
|
1,
|
||||||
|
List.of()));
|
||||||
|
assertThrows(IllegalArgumentException.class, () -> new FrontendDocumentSymbol(
|
||||||
|
"fn",
|
||||||
|
FrontendSymbolKind.FUNCTION,
|
||||||
|
"",
|
||||||
|
-1,
|
||||||
|
1,
|
||||||
|
0,
|
||||||
|
1,
|
||||||
|
List.of()));
|
||||||
|
assertThrows(IllegalArgumentException.class, () -> new FrontendDocumentSymbol(
|
||||||
|
"fn",
|
||||||
|
FrontendSymbolKind.FUNCTION,
|
||||||
|
"",
|
||||||
|
5,
|
||||||
|
4,
|
||||||
|
0,
|
||||||
|
1,
|
||||||
|
List.of()));
|
||||||
|
assertThrows(IllegalArgumentException.class, () -> new FrontendDocumentSymbol(
|
||||||
|
"fn",
|
||||||
|
FrontendSymbolKind.FUNCTION,
|
||||||
|
"",
|
||||||
|
0,
|
||||||
|
1,
|
||||||
|
3,
|
||||||
|
2,
|
||||||
|
List.of()));
|
||||||
|
}
|
||||||
|
|
||||||
|
@Test
|
||||||
|
void workspaceSymbolNormalizesOptionalTextAndRejectsBlankNameOrInvertedOffsets() {
|
||||||
|
final Path path = Path.of("src/main.pbs").toAbsolutePath();
|
||||||
|
final var symbol = new FrontendWorkspaceSymbol(
|
||||||
|
" blend ",
|
||||||
|
FrontendSymbolKind.METHOD,
|
||||||
|
" (dx: int) -> int ",
|
||||||
|
" Vec ",
|
||||||
|
path,
|
||||||
|
4,
|
||||||
|
9);
|
||||||
|
assertEquals("blend", symbol.name());
|
||||||
|
assertEquals("(dx: int) -> int", symbol.detail());
|
||||||
|
assertEquals("Vec", symbol.containerName());
|
||||||
|
assertEquals(path.normalize(), symbol.path());
|
||||||
|
|
||||||
|
assertThrows(IllegalArgumentException.class, () -> new FrontendWorkspaceSymbol(
|
||||||
|
" ",
|
||||||
|
FrontendSymbolKind.FUNCTION,
|
||||||
|
"",
|
||||||
|
"",
|
||||||
|
path,
|
||||||
|
0,
|
||||||
|
1));
|
||||||
|
assertThrows(NullPointerException.class, () -> new FrontendWorkspaceSymbol(
|
||||||
|
"fn",
|
||||||
|
FrontendSymbolKind.FUNCTION,
|
||||||
|
"",
|
||||||
|
"",
|
||||||
|
null,
|
||||||
|
0,
|
||||||
|
1));
|
||||||
|
assertThrows(IllegalArgumentException.class, () -> new FrontendWorkspaceSymbol(
|
||||||
|
"fn",
|
||||||
|
FrontendSymbolKind.FUNCTION,
|
||||||
|
"",
|
||||||
|
"",
|
||||||
|
path,
|
||||||
|
-1,
|
||||||
|
0));
|
||||||
|
assertThrows(IllegalArgumentException.class, () -> new FrontendWorkspaceSymbol(
|
||||||
|
"fn",
|
||||||
|
FrontendSymbolKind.FUNCTION,
|
||||||
|
"",
|
||||||
|
"",
|
||||||
|
path,
|
||||||
|
5,
|
||||||
|
4));
|
||||||
|
}
|
||||||
|
|
||||||
|
@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
|
||||||
|
|||||||
@@ -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)
|
||||||
|
|||||||
+34
@@ -0,0 +1,34 @@
|
|||||||
|
package p.studio.lsp.messages;
|
||||||
|
|
||||||
|
import java.util.Objects;
|
||||||
|
|
||||||
|
public record BaselineCodeAction(
|
||||||
|
String title,
|
||||||
|
String diagnosticCode,
|
||||||
|
String uri,
|
||||||
|
int startLine,
|
||||||
|
int startCharacter,
|
||||||
|
int endLine,
|
||||||
|
int endCharacter,
|
||||||
|
String newText) {
|
||||||
|
|
||||||
|
public BaselineCodeAction {
|
||||||
|
title = requireText(title, "title");
|
||||||
|
diagnosticCode = requireText(diagnosticCode, "diagnosticCode");
|
||||||
|
uri = requireText(uri, "uri");
|
||||||
|
if (startLine < 0 || startCharacter < 0 || endLine < 0 || endCharacter < 0) {
|
||||||
|
throw new IllegalArgumentException("code action range coordinates must not be negative");
|
||||||
|
}
|
||||||
|
newText = Objects.requireNonNull(newText, "newText");
|
||||||
|
}
|
||||||
|
|
||||||
|
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;
|
||||||
|
}
|
||||||
|
}
|
||||||
+16
@@ -0,0 +1,16 @@
|
|||||||
|
package p.studio.lsp.messages;
|
||||||
|
|
||||||
|
public record BaselineCodeActionDiagnostic(
|
||||||
|
String code,
|
||||||
|
int startLine,
|
||||||
|
int startCharacter,
|
||||||
|
int endLine,
|
||||||
|
int endCharacter) {
|
||||||
|
|
||||||
|
public BaselineCodeActionDiagnostic {
|
||||||
|
code = code == null ? "" : code.trim();
|
||||||
|
if (startLine < 0 || startCharacter < 0 || endLine < 0 || endCharacter < 0) {
|
||||||
|
throw new IllegalArgumentException("diagnostic range coordinates must not be negative");
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
+13
@@ -0,0 +1,13 @@
|
|||||||
|
package p.studio.lsp.messages;
|
||||||
|
|
||||||
|
import java.util.List;
|
||||||
|
|
||||||
|
public record BaselineCodeActions(List<BaselineCodeAction> actions) {
|
||||||
|
public BaselineCodeActions {
|
||||||
|
actions = actions == null ? List.of() : List.copyOf(actions);
|
||||||
|
}
|
||||||
|
|
||||||
|
public static BaselineCodeActions empty() {
|
||||||
|
return new BaselineCodeActions(List.of());
|
||||||
|
}
|
||||||
|
}
|
||||||
+15
@@ -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());
|
||||||
|
}
|
||||||
|
}
|
||||||
+28
@@ -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;
|
||||||
|
}
|
||||||
|
}
|
||||||
+3
-1
@@ -9,12 +9,14 @@ public record BaselineDocumentIssue(
|
|||||||
int endCharacter,
|
int endCharacter,
|
||||||
BaselineIssueSeverity severity,
|
BaselineIssueSeverity severity,
|
||||||
String source,
|
String source,
|
||||||
String message) {
|
String message,
|
||||||
|
String code) {
|
||||||
|
|
||||||
public BaselineDocumentIssue {
|
public BaselineDocumentIssue {
|
||||||
severity = Objects.requireNonNull(severity, "severity");
|
severity = Objects.requireNonNull(severity, "severity");
|
||||||
source = requireText(source, "source");
|
source = requireText(source, "source");
|
||||||
message = requireText(message, "message");
|
message = requireText(message, "message");
|
||||||
|
code = code == null ? "" : code.trim();
|
||||||
}
|
}
|
||||||
|
|
||||||
private static String requireText(
|
private static String requireText(
|
||||||
|
|||||||
+41
@@ -0,0 +1,41 @@
|
|||||||
|
package p.studio.lsp.messages;
|
||||||
|
|
||||||
|
import java.util.List;
|
||||||
|
import java.util.Objects;
|
||||||
|
|
||||||
|
public record BaselineDocumentSymbol(
|
||||||
|
String name,
|
||||||
|
BaselineDocumentSymbolKind kind,
|
||||||
|
String detail,
|
||||||
|
int startLine,
|
||||||
|
int startCharacter,
|
||||||
|
int endLine,
|
||||||
|
int endCharacter,
|
||||||
|
int selectionStartLine,
|
||||||
|
int selectionStartCharacter,
|
||||||
|
int selectionEndLine,
|
||||||
|
int selectionEndCharacter,
|
||||||
|
List<BaselineDocumentSymbol> children) {
|
||||||
|
|
||||||
|
public BaselineDocumentSymbol {
|
||||||
|
name = requireText(name, "name");
|
||||||
|
kind = Objects.requireNonNull(kind, "kind");
|
||||||
|
detail = detail == null ? "" : detail;
|
||||||
|
if (startLine < 0 || startCharacter < 0 || endLine < 0 || endCharacter < 0
|
||||||
|
|| selectionStartLine < 0 || selectionStartCharacter < 0
|
||||||
|
|| selectionEndLine < 0 || selectionEndCharacter < 0) {
|
||||||
|
throw new IllegalArgumentException("document symbol range coordinates must not be negative");
|
||||||
|
}
|
||||||
|
children = children == null ? List.of() : List.copyOf(children);
|
||||||
|
}
|
||||||
|
|
||||||
|
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;
|
||||||
|
}
|
||||||
|
}
|
||||||
+21
@@ -0,0 +1,21 @@
|
|||||||
|
package p.studio.lsp.messages;
|
||||||
|
|
||||||
|
public enum BaselineDocumentSymbolKind {
|
||||||
|
KEYWORD,
|
||||||
|
LOCAL,
|
||||||
|
PARAMETER,
|
||||||
|
FIELD,
|
||||||
|
FUNCTION,
|
||||||
|
METHOD,
|
||||||
|
CONSTRUCTOR,
|
||||||
|
STRUCT,
|
||||||
|
BUILTIN_TYPE,
|
||||||
|
SERVICE,
|
||||||
|
HOST,
|
||||||
|
CONTRACT,
|
||||||
|
CALLBACK,
|
||||||
|
ENUM,
|
||||||
|
ERROR,
|
||||||
|
GLOBAL,
|
||||||
|
CONST
|
||||||
|
}
|
||||||
+15
@@ -0,0 +1,15 @@
|
|||||||
|
package p.studio.lsp.messages;
|
||||||
|
|
||||||
|
import java.util.List;
|
||||||
|
|
||||||
|
public record BaselineDocumentSymbols(
|
||||||
|
List<BaselineDocumentSymbol> symbols) {
|
||||||
|
|
||||||
|
public BaselineDocumentSymbols {
|
||||||
|
symbols = symbols == null ? List.of() : List.copyOf(symbols);
|
||||||
|
}
|
||||||
|
|
||||||
|
public static BaselineDocumentSymbols empty() {
|
||||||
|
return new BaselineDocumentSymbols(List.of());
|
||||||
|
}
|
||||||
|
}
|
||||||
+22
@@ -0,0 +1,22 @@
|
|||||||
|
package p.studio.lsp.messages;
|
||||||
|
|
||||||
|
import java.util.Optional;
|
||||||
|
|
||||||
|
public record BaselinePrepareRename(Optional<BaselineDefinitionLocation> placeholder) {
|
||||||
|
|
||||||
|
public BaselinePrepareRename {
|
||||||
|
placeholder = placeholder == null ? Optional.empty() : placeholder;
|
||||||
|
}
|
||||||
|
|
||||||
|
public static BaselinePrepareRename none() {
|
||||||
|
return new BaselinePrepareRename(Optional.empty());
|
||||||
|
}
|
||||||
|
|
||||||
|
public static BaselinePrepareRename of(final BaselineDefinitionLocation location) {
|
||||||
|
return new BaselinePrepareRename(Optional.of(location));
|
||||||
|
}
|
||||||
|
|
||||||
|
public boolean renameable() {
|
||||||
|
return placeholder.isPresent();
|
||||||
|
}
|
||||||
|
}
|
||||||
+16
@@ -0,0 +1,16 @@
|
|||||||
|
package p.studio.lsp.messages;
|
||||||
|
|
||||||
|
import java.util.List;
|
||||||
|
import java.util.Objects;
|
||||||
|
|
||||||
|
public record BaselineReferences(
|
||||||
|
List<BaselineDefinitionLocation> locations) {
|
||||||
|
|
||||||
|
public BaselineReferences {
|
||||||
|
locations = List.copyOf(Objects.requireNonNull(locations, "locations"));
|
||||||
|
}
|
||||||
|
|
||||||
|
public static BaselineReferences empty() {
|
||||||
|
return new BaselineReferences(List.of());
|
||||||
|
}
|
||||||
|
}
|
||||||
@@ -0,0 +1,26 @@
|
|||||||
|
package p.studio.lsp.messages;
|
||||||
|
|
||||||
|
import java.util.List;
|
||||||
|
|
||||||
|
public record BaselineRename(
|
||||||
|
boolean applied,
|
||||||
|
String message,
|
||||||
|
List<BaselineRenameEdit> edits) {
|
||||||
|
|
||||||
|
public BaselineRename {
|
||||||
|
message = message == null ? "" : message;
|
||||||
|
edits = edits == null ? List.of() : List.copyOf(edits);
|
||||||
|
}
|
||||||
|
|
||||||
|
public static BaselineRename unsupported() {
|
||||||
|
return new BaselineRename(false, "unsupported", List.of());
|
||||||
|
}
|
||||||
|
|
||||||
|
public static BaselineRename refused(final String message) {
|
||||||
|
return new BaselineRename(false, message == null || message.isBlank() ? "not renameable" : message, List.of());
|
||||||
|
}
|
||||||
|
|
||||||
|
public static BaselineRename applied(final List<BaselineRenameEdit> edits) {
|
||||||
|
return new BaselineRename(true, "", edits);
|
||||||
|
}
|
||||||
|
}
|
||||||
+30
@@ -0,0 +1,30 @@
|
|||||||
|
package p.studio.lsp.messages;
|
||||||
|
|
||||||
|
import java.util.Objects;
|
||||||
|
|
||||||
|
public record BaselineRenameEdit(
|
||||||
|
String uri,
|
||||||
|
int startLine,
|
||||||
|
int startCharacter,
|
||||||
|
int endLine,
|
||||||
|
int endCharacter,
|
||||||
|
String newText) {
|
||||||
|
|
||||||
|
public BaselineRenameEdit {
|
||||||
|
uri = requireText(uri, "uri");
|
||||||
|
if (startLine < 0 || startCharacter < 0 || endLine < 0 || endCharacter < 0) {
|
||||||
|
throw new IllegalArgumentException("rename range coordinates must not be negative");
|
||||||
|
}
|
||||||
|
newText = Objects.requireNonNull(newText, "newText");
|
||||||
|
}
|
||||||
|
|
||||||
|
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;
|
||||||
|
}
|
||||||
|
}
|
||||||
+6
@@ -10,6 +10,12 @@ public record BaselineServerDescription(
|
|||||||
boolean hoverSupported,
|
boolean hoverSupported,
|
||||||
boolean completionSupported,
|
boolean completionSupported,
|
||||||
boolean signatureHelpSupported,
|
boolean signatureHelpSupported,
|
||||||
|
boolean definitionSupported,
|
||||||
|
boolean referencesSupported,
|
||||||
|
boolean documentSymbolsSupported,
|
||||||
|
boolean workspaceSymbolsSupported,
|
||||||
|
boolean renameSupported,
|
||||||
|
boolean codeActionsSupported,
|
||||||
List<String> semanticTokenTypes,
|
List<String> semanticTokenTypes,
|
||||||
List<BaselineSemanticHostProjection> semanticHostProjections,
|
List<BaselineSemanticHostProjection> semanticHostProjections,
|
||||||
List<BaselineVisualTheme> visualThemes,
|
List<BaselineVisualTheme> visualThemes,
|
||||||
|
|||||||
+36
@@ -0,0 +1,36 @@
|
|||||||
|
package p.studio.lsp.messages;
|
||||||
|
|
||||||
|
import java.util.Objects;
|
||||||
|
|
||||||
|
public record BaselineWorkspaceSymbol(
|
||||||
|
String name,
|
||||||
|
BaselineDocumentSymbolKind kind,
|
||||||
|
String detail,
|
||||||
|
String containerName,
|
||||||
|
String uri,
|
||||||
|
int startLine,
|
||||||
|
int startCharacter,
|
||||||
|
int endLine,
|
||||||
|
int endCharacter) {
|
||||||
|
|
||||||
|
public BaselineWorkspaceSymbol {
|
||||||
|
name = requireText(name, "name");
|
||||||
|
kind = Objects.requireNonNull(kind, "kind");
|
||||||
|
detail = detail == null ? "" : detail;
|
||||||
|
containerName = containerName == null ? "" : containerName;
|
||||||
|
uri = requireText(uri, "uri");
|
||||||
|
if (startLine < 0 || startCharacter < 0 || endLine < 0 || endCharacter < 0) {
|
||||||
|
throw new IllegalArgumentException("workspace symbol 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;
|
||||||
|
}
|
||||||
|
}
|
||||||
+15
@@ -0,0 +1,15 @@
|
|||||||
|
package p.studio.lsp.messages;
|
||||||
|
|
||||||
|
import java.util.List;
|
||||||
|
|
||||||
|
public record BaselineWorkspaceSymbols(
|
||||||
|
List<BaselineWorkspaceSymbol> symbols) {
|
||||||
|
|
||||||
|
public BaselineWorkspaceSymbols {
|
||||||
|
symbols = symbols == null ? List.of() : List.copyOf(symbols);
|
||||||
|
}
|
||||||
|
|
||||||
|
public static BaselineWorkspaceSymbols empty() {
|
||||||
|
return new BaselineWorkspaceSymbols(List.of());
|
||||||
|
}
|
||||||
|
}
|
||||||
+45
@@ -2,12 +2,22 @@ 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.BaselineDocumentSymbols;
|
||||||
|
import p.studio.lsp.messages.BaselineReferences;
|
||||||
|
import p.studio.lsp.messages.BaselineWorkspaceSymbols;
|
||||||
|
import p.studio.lsp.messages.BaselineCodeActionDiagnostic;
|
||||||
|
import p.studio.lsp.messages.BaselineCodeActions;
|
||||||
|
import p.studio.lsp.messages.BaselinePrepareRename;
|
||||||
|
import p.studio.lsp.messages.BaselineRename;
|
||||||
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 p.studio.lsp.messages.LspProjectContext;
|
import p.studio.lsp.messages.LspProjectContext;
|
||||||
|
|
||||||
|
import java.util.List;
|
||||||
|
|
||||||
public interface LanguageServiceBridge {
|
public interface LanguageServiceBridge {
|
||||||
BaselineServerDescription describeServer(LspProjectContext context);
|
BaselineServerDescription describeServer(LspProjectContext context);
|
||||||
|
|
||||||
@@ -17,9 +27,44 @@ 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);
|
||||||
|
|
||||||
|
BaselineReferences references(
|
||||||
|
LspProjectContext context,
|
||||||
|
String documentUri,
|
||||||
|
String text,
|
||||||
|
int line,
|
||||||
|
int character,
|
||||||
|
boolean includeDeclaration);
|
||||||
|
|
||||||
|
BaselineDocumentSymbols documentSymbols(LspProjectContext context, String documentUri, String text);
|
||||||
|
|
||||||
|
BaselineWorkspaceSymbols workspaceSymbols(LspProjectContext context, String query);
|
||||||
|
|
||||||
|
BaselinePrepareRename prepareRename(
|
||||||
|
LspProjectContext context,
|
||||||
|
String documentUri,
|
||||||
|
String text,
|
||||||
|
int line,
|
||||||
|
int character);
|
||||||
|
|
||||||
|
BaselineRename rename(
|
||||||
|
LspProjectContext context,
|
||||||
|
String documentUri,
|
||||||
|
String text,
|
||||||
|
int line,
|
||||||
|
int character,
|
||||||
|
String newName);
|
||||||
|
|
||||||
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);
|
||||||
|
|
||||||
|
BaselineCodeActions codeActions(
|
||||||
|
LspProjectContext context,
|
||||||
|
String documentUri,
|
||||||
|
String text,
|
||||||
|
List<BaselineCodeActionDiagnostic> diagnostics);
|
||||||
|
|
||||||
String onSave(LspProjectContext context, String documentUri);
|
String onSave(LspProjectContext context, String documentUri);
|
||||||
}
|
}
|
||||||
|
|||||||
+463
-17
@@ -4,14 +4,22 @@ import org.apache.commons.lang3.StringUtils;
|
|||||||
import p.studio.compiler.FrontendRegistryService;
|
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.FrontendCodeAction;
|
||||||
import p.studio.compiler.services.FrontendCompletionCandidate;
|
import p.studio.compiler.services.FrontendCompletionCandidate;
|
||||||
|
import p.studio.compiler.services.FrontendLanguageService;
|
||||||
|
import p.studio.compiler.services.FrontendDefinitionLocation;
|
||||||
import p.studio.compiler.services.FrontendDocumentRequest;
|
import p.studio.compiler.services.FrontendDocumentRequest;
|
||||||
|
import p.studio.compiler.services.FrontendDocumentSymbol;
|
||||||
import p.studio.compiler.services.FrontendEditorialContext;
|
import p.studio.compiler.services.FrontendEditorialContext;
|
||||||
import p.studio.compiler.services.FrontendHover;
|
import p.studio.compiler.services.FrontendHover;
|
||||||
import p.studio.compiler.services.FrontendProvider;
|
import p.studio.compiler.services.FrontendProvider;
|
||||||
import p.studio.compiler.services.FrontendSignature;
|
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.FrontendRenameEdit;
|
||||||
|
import p.studio.compiler.services.FrontendRenameResult;
|
||||||
|
import p.studio.compiler.services.FrontendWorkspaceRequest;
|
||||||
|
import p.studio.compiler.services.FrontendWorkspaceSymbol;
|
||||||
import p.studio.compiler.source.identifiers.FileId;
|
import p.studio.compiler.source.identifiers.FileId;
|
||||||
import p.studio.compiler.utilities.SourceProviderFactory;
|
import p.studio.compiler.utilities.SourceProviderFactory;
|
||||||
import p.studio.compiler.workspaces.AssetSurfaceContextLoader;
|
import p.studio.compiler.workspaces.AssetSurfaceContextLoader;
|
||||||
@@ -21,6 +29,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;
|
||||||
@@ -42,6 +52,11 @@ public final class CompilerLanguageServiceBridge implements LanguageServiceBridg
|
|||||||
Objects.requireNonNull(context, "context");
|
Objects.requireNonNull(context, "context");
|
||||||
final var frontend = frontendSpec(context);
|
final var frontend = frontendSpec(context);
|
||||||
final var presentation = frontend.getSemanticPresentation();
|
final var presentation = frontend.getSemanticPresentation();
|
||||||
|
final var languageService = frontendProvider(context).languageService();
|
||||||
|
final boolean languageServicePresent = languageService.isPresent();
|
||||||
|
final boolean codeActionsSupported = languageService
|
||||||
|
.map(FrontendLanguageService::codeActionsSupported)
|
||||||
|
.orElse(false);
|
||||||
return new BaselineServerDescription(
|
return new BaselineServerDescription(
|
||||||
"Prometeu Studio LSP",
|
"Prometeu Studio LSP",
|
||||||
"0.1.0",
|
"0.1.0",
|
||||||
@@ -49,6 +64,12 @@ public final class CompilerLanguageServiceBridge implements LanguageServiceBridg
|
|||||||
true,
|
true,
|
||||||
true,
|
true,
|
||||||
true,
|
true,
|
||||||
|
languageServicePresent,
|
||||||
|
languageServicePresent,
|
||||||
|
languageServicePresent,
|
||||||
|
languageServicePresent,
|
||||||
|
languageServicePresent,
|
||||||
|
codeActionsSupported,
|
||||||
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 +108,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 +139,262 @@ 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
|
||||||
|
public BaselineReferences references(
|
||||||
|
final LspProjectContext context,
|
||||||
|
final String documentUri,
|
||||||
|
final String text,
|
||||||
|
final int line,
|
||||||
|
final int character,
|
||||||
|
final boolean includeDeclaration) {
|
||||||
|
Objects.requireNonNull(context, "context");
|
||||||
|
final var provider = frontendProvider(context);
|
||||||
|
final var languageService = provider.languageService();
|
||||||
|
if (languageService.isEmpty()) {
|
||||||
|
return BaselineReferences.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 LinkedHashMap<String, FrontendDefinitionLocation> merged = new LinkedHashMap<>();
|
||||||
|
for (final FrontendDefinitionLocation location : languageService.orElseThrow().references(
|
||||||
|
request,
|
||||||
|
document.editorialContext(),
|
||||||
|
offset)) {
|
||||||
|
merged.putIfAbsent(frontendLocationKey(location), location);
|
||||||
|
}
|
||||||
|
if (includeDeclaration) {
|
||||||
|
for (final FrontendDefinitionLocation location : languageService.orElseThrow().definition(
|
||||||
|
request,
|
||||||
|
document.editorialContext(),
|
||||||
|
offset)) {
|
||||||
|
merged.putIfAbsent(frontendLocationKey(location), location);
|
||||||
|
}
|
||||||
|
}
|
||||||
|
return new BaselineReferences(mapDefinitionLocations(
|
||||||
|
List.copyOf(merged.values()),
|
||||||
|
request.documentPath(),
|
||||||
|
document.text()));
|
||||||
|
})
|
||||||
|
.orElseGet(BaselineReferences::empty);
|
||||||
|
}
|
||||||
|
|
||||||
|
@Override
|
||||||
|
public BaselineDocumentSymbols documentSymbols(
|
||||||
|
final LspProjectContext context,
|
||||||
|
final String documentUri,
|
||||||
|
final String text) {
|
||||||
|
Objects.requireNonNull(context, "context");
|
||||||
|
final var provider = frontendProvider(context);
|
||||||
|
final var languageService = provider.languageService();
|
||||||
|
if (languageService.isEmpty()) {
|
||||||
|
return BaselineDocumentSymbols.empty();
|
||||||
|
}
|
||||||
|
return editorialDocument(context, documentUri, text)
|
||||||
|
.map(document -> {
|
||||||
|
final FrontendDocumentRequest request = new FrontendDocumentRequest(
|
||||||
|
context.projectRoot(),
|
||||||
|
normalizeDocumentPath(documentUri),
|
||||||
|
document.text());
|
||||||
|
return new BaselineDocumentSymbols(mapDocumentSymbols(
|
||||||
|
languageService.orElseThrow().documentSymbols(request, document.editorialContext()),
|
||||||
|
document.text()));
|
||||||
|
})
|
||||||
|
.orElseGet(BaselineDocumentSymbols::empty);
|
||||||
|
}
|
||||||
|
|
||||||
|
@Override
|
||||||
|
public BaselineWorkspaceSymbols workspaceSymbols(
|
||||||
|
final LspProjectContext context,
|
||||||
|
final String query) {
|
||||||
|
Objects.requireNonNull(context, "context");
|
||||||
|
final var provider = frontendProvider(context);
|
||||||
|
final var languageService = provider.languageService();
|
||||||
|
if (languageService.isEmpty()) {
|
||||||
|
return BaselineWorkspaceSymbols.empty();
|
||||||
|
}
|
||||||
|
final BuilderPipelineContext pipelineContext = BuilderPipelineContext.fromConfig(
|
||||||
|
new BuilderPipelineConfig(
|
||||||
|
false,
|
||||||
|
context.projectRoot().toString(),
|
||||||
|
"core-v1",
|
||||||
|
SourceProviderFactory.overlayUtf8(Map.of())));
|
||||||
|
BuilderPipelineService.INSTANCE.analyze(pipelineContext, LogAggregator.empty());
|
||||||
|
final FrontendPhaseContext frontendPhaseContext = new FrontendPhaseContext(
|
||||||
|
pipelineContext.resolvedWorkspace.graph().projectTable(),
|
||||||
|
pipelineContext.fileTable,
|
||||||
|
pipelineContext.resolvedWorkspace.stack(),
|
||||||
|
pipelineContext.resolvedWorkspace.stdlib(),
|
||||||
|
pipelineContext.resolvedWorkspace.target(),
|
||||||
|
HostAdmissionContext.permissiveDefault(),
|
||||||
|
assetSurfaceContextLoader.load(pipelineContext.resolvedWorkspace.mainProject().getRootPath()));
|
||||||
|
return languageService.orElseThrow()
|
||||||
|
.prepareEditorialContext(frontendPhaseContext)
|
||||||
|
.map(editorialContext -> new BaselineWorkspaceSymbols(mapWorkspaceSymbols(
|
||||||
|
languageService.orElseThrow().workspaceSymbols(
|
||||||
|
new FrontendWorkspaceRequest(context.projectRoot(), query),
|
||||||
|
editorialContext))))
|
||||||
|
.orElseGet(BaselineWorkspaceSymbols::empty);
|
||||||
|
}
|
||||||
|
|
||||||
|
@Override
|
||||||
|
public BaselinePrepareRename prepareRename(
|
||||||
|
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 BaselinePrepareRename.none();
|
||||||
|
}
|
||||||
|
return editorialDocument(context, documentUri, text)
|
||||||
|
.flatMap(document -> {
|
||||||
|
final int offset = new DocumentPositionMapper(document.text()).byteOffsetOf(line, character);
|
||||||
|
final FrontendDocumentRequest request = new FrontendDocumentRequest(
|
||||||
|
context.projectRoot(),
|
||||||
|
normalizeDocumentPath(documentUri),
|
||||||
|
document.text());
|
||||||
|
return languageService.orElseThrow().prepareRename(
|
||||||
|
request,
|
||||||
|
document.editorialContext(),
|
||||||
|
offset);
|
||||||
|
})
|
||||||
|
.map(location -> {
|
||||||
|
final Path documentPath = normalizeDocumentPath(documentUri);
|
||||||
|
final List<BaselineDefinitionLocation> mapped = mapDefinitionLocations(
|
||||||
|
List.of(location),
|
||||||
|
documentPath,
|
||||||
|
text == null ? "" : text);
|
||||||
|
if (mapped.isEmpty()) {
|
||||||
|
return BaselinePrepareRename.none();
|
||||||
|
}
|
||||||
|
return BaselinePrepareRename.of(mapped.getFirst());
|
||||||
|
})
|
||||||
|
.orElseGet(BaselinePrepareRename::none);
|
||||||
|
}
|
||||||
|
|
||||||
|
@Override
|
||||||
|
public BaselineRename rename(
|
||||||
|
final LspProjectContext context,
|
||||||
|
final String documentUri,
|
||||||
|
final String text,
|
||||||
|
final int line,
|
||||||
|
final int character,
|
||||||
|
final String newName) {
|
||||||
|
Objects.requireNonNull(context, "context");
|
||||||
|
final var provider = frontendProvider(context);
|
||||||
|
final var languageService = provider.languageService();
|
||||||
|
if (languageService.isEmpty()) {
|
||||||
|
return BaselineRename.unsupported();
|
||||||
|
}
|
||||||
|
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 FrontendRenameResult result = languageService.orElseThrow().rename(
|
||||||
|
request,
|
||||||
|
document.editorialContext(),
|
||||||
|
offset,
|
||||||
|
newName);
|
||||||
|
if (!result.applied()) {
|
||||||
|
if (result.status() == FrontendRenameResult.Status.UNSUPPORTED) {
|
||||||
|
return BaselineRename.unsupported();
|
||||||
|
}
|
||||||
|
return BaselineRename.refused(result.message());
|
||||||
|
}
|
||||||
|
return BaselineRename.applied(mapRenameEdits(
|
||||||
|
result.edits(),
|
||||||
|
request.documentPath(),
|
||||||
|
document.text()));
|
||||||
|
})
|
||||||
|
.orElseGet(() -> BaselineRename.refused("not renameable"));
|
||||||
|
}
|
||||||
|
|
||||||
|
@Override
|
||||||
|
public BaselineCodeActions codeActions(
|
||||||
|
final LspProjectContext context,
|
||||||
|
final String documentUri,
|
||||||
|
final String text,
|
||||||
|
final List<BaselineCodeActionDiagnostic> diagnostics) {
|
||||||
|
Objects.requireNonNull(context, "context");
|
||||||
|
final var languageService = frontendProvider(context).languageService();
|
||||||
|
if (languageService.isEmpty() || !languageService.orElseThrow().codeActionsSupported()) {
|
||||||
|
return BaselineCodeActions.empty();
|
||||||
|
}
|
||||||
|
if (diagnostics == null || diagnostics.isEmpty()) {
|
||||||
|
return BaselineCodeActions.empty();
|
||||||
|
}
|
||||||
|
return editorialDocument(context, documentUri, text)
|
||||||
|
.map(document -> {
|
||||||
|
final Path documentPath = normalizeDocumentPath(documentUri);
|
||||||
|
final FrontendDocumentRequest request = new FrontendDocumentRequest(
|
||||||
|
context.projectRoot(),
|
||||||
|
documentPath,
|
||||||
|
document.text());
|
||||||
|
final List<FrontendCodeAction> repairs = languageService.orElseThrow().codeActions(
|
||||||
|
request,
|
||||||
|
document.editorialContext());
|
||||||
|
return new BaselineCodeActions(mapCodeActions(
|
||||||
|
repairs,
|
||||||
|
documentUri,
|
||||||
|
documentPath,
|
||||||
|
document.text(),
|
||||||
|
diagnostics));
|
||||||
|
})
|
||||||
|
.orElseGet(BaselineCodeActions::empty);
|
||||||
|
}
|
||||||
|
|
||||||
@Override
|
@Override
|
||||||
public BaselineSignatureHelp signatureHelp(
|
public BaselineSignatureHelp signatureHelp(
|
||||||
final LspProjectContext context,
|
final LspProjectContext context,
|
||||||
@@ -155,13 +415,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)
|
||||||
@@ -312,14 +568,16 @@ public final class CompilerLanguageServiceBridge implements LanguageServiceBridg
|
|||||||
final int endOffset = diagnostic.getEnd() == null ? startOffset : Math.max(startOffset, diagnostic.getEnd());
|
final int endOffset = diagnostic.getEnd() == null ? startOffset : Math.max(startOffset, diagnostic.getEnd());
|
||||||
final DocumentPosition start = positionMapper.positionOf(startOffset);
|
final DocumentPosition start = positionMapper.positionOf(startOffset);
|
||||||
final DocumentPosition end = positionMapper.positionOf(endOffset);
|
final DocumentPosition end = positionMapper.positionOf(endOffset);
|
||||||
|
final String code = diagnostic.getCode() == null ? "" : diagnostic.getCode().trim();
|
||||||
return new BaselineDocumentIssue(
|
return new BaselineDocumentIssue(
|
||||||
start.line(),
|
start.line(),
|
||||||
start.character(),
|
start.character(),
|
||||||
end.line(),
|
end.line(),
|
||||||
end.character(),
|
end.character(),
|
||||||
diagnostic.isError() ? BaselineIssueSeverity.ERROR : BaselineIssueSeverity.WARNING,
|
diagnostic.isError() ? BaselineIssueSeverity.ERROR : BaselineIssueSeverity.WARNING,
|
||||||
diagnostic.getCode() == null || diagnostic.getCode().isBlank() ? "Prometeu Studio" : diagnostic.getCode(),
|
code.isBlank() ? "Prometeu Studio" : code,
|
||||||
diagnostic.getMessage());
|
diagnostic.getMessage(),
|
||||||
|
code);
|
||||||
}
|
}
|
||||||
|
|
||||||
private Path normalizeDocumentPath(final String documentUri) {
|
private Path normalizeDocumentPath(final String documentUri) {
|
||||||
@@ -418,6 +676,194 @@ public final class CompilerLanguageServiceBridge implements LanguageServiceBridg
|
|||||||
};
|
};
|
||||||
}
|
}
|
||||||
|
|
||||||
|
private static String frontendLocationKey(final FrontendDefinitionLocation location) {
|
||||||
|
return location.path() + ":" + location.startOffset() + ":" + location.endOffset();
|
||||||
|
}
|
||||||
|
|
||||||
|
private List<BaselineDocumentSymbol> mapDocumentSymbols(
|
||||||
|
final List<FrontendDocumentSymbol> symbols,
|
||||||
|
final String documentText) {
|
||||||
|
if (symbols == null || symbols.isEmpty()) {
|
||||||
|
return List.of();
|
||||||
|
}
|
||||||
|
final DocumentPositionMapper mapper = new DocumentPositionMapper(documentText == null ? "" : documentText);
|
||||||
|
final ArrayList<BaselineDocumentSymbol> mapped = new ArrayList<>();
|
||||||
|
for (final FrontendDocumentSymbol symbol : symbols) {
|
||||||
|
mapped.add(mapDocumentSymbol(symbol, mapper));
|
||||||
|
}
|
||||||
|
return List.copyOf(mapped);
|
||||||
|
}
|
||||||
|
|
||||||
|
private BaselineDocumentSymbol mapDocumentSymbol(
|
||||||
|
final FrontendDocumentSymbol symbol,
|
||||||
|
final DocumentPositionMapper mapper) {
|
||||||
|
final DocumentPosition rangeStart = mapper.positionOf(symbol.rangeStart());
|
||||||
|
final DocumentPosition rangeEnd = mapper.positionOf(symbol.rangeEnd());
|
||||||
|
final DocumentPosition selectionStart = mapper.positionOf(symbol.selectionStart());
|
||||||
|
final DocumentPosition selectionEnd = mapper.positionOf(symbol.selectionEnd());
|
||||||
|
final ArrayList<BaselineDocumentSymbol> children = new ArrayList<>();
|
||||||
|
for (final FrontendDocumentSymbol child : symbol.children()) {
|
||||||
|
children.add(mapDocumentSymbol(child, mapper));
|
||||||
|
}
|
||||||
|
return new BaselineDocumentSymbol(
|
||||||
|
symbol.name(),
|
||||||
|
BaselineDocumentSymbolKind.valueOf(symbol.kind().name()),
|
||||||
|
symbol.detail(),
|
||||||
|
rangeStart.line(),
|
||||||
|
rangeStart.character(),
|
||||||
|
rangeEnd.line(),
|
||||||
|
rangeEnd.character(),
|
||||||
|
selectionStart.line(),
|
||||||
|
selectionStart.character(),
|
||||||
|
selectionEnd.line(),
|
||||||
|
selectionEnd.character(),
|
||||||
|
children);
|
||||||
|
}
|
||||||
|
|
||||||
|
private List<BaselineWorkspaceSymbol> mapWorkspaceSymbols(final List<FrontendWorkspaceSymbol> symbols) {
|
||||||
|
if (symbols == null || symbols.isEmpty()) {
|
||||||
|
return List.of();
|
||||||
|
}
|
||||||
|
final LinkedHashMap<Path, DocumentPositionMapper> mappers = new LinkedHashMap<>();
|
||||||
|
final ArrayList<BaselineWorkspaceSymbol> mapped = new ArrayList<>();
|
||||||
|
for (final FrontendWorkspaceSymbol symbol : symbols) {
|
||||||
|
final DocumentPositionMapper mapper = mappers.computeIfAbsent(symbol.path(), this::mapperForPath);
|
||||||
|
if (mapper == null) {
|
||||||
|
continue;
|
||||||
|
}
|
||||||
|
final DocumentPosition start = mapper.positionOf(symbol.startOffset());
|
||||||
|
final DocumentPosition end = mapper.positionOf(symbol.endOffset());
|
||||||
|
mapped.add(new BaselineWorkspaceSymbol(
|
||||||
|
symbol.name(),
|
||||||
|
BaselineDocumentSymbolKind.valueOf(symbol.kind().name()),
|
||||||
|
symbol.detail(),
|
||||||
|
symbol.containerName(),
|
||||||
|
symbol.path().toUri().toString(),
|
||||||
|
start.line(),
|
||||||
|
start.character(),
|
||||||
|
end.line(),
|
||||||
|
end.character()));
|
||||||
|
}
|
||||||
|
return List.copyOf(mapped);
|
||||||
|
}
|
||||||
|
|
||||||
|
private DocumentPositionMapper mapperForPath(final Path path) {
|
||||||
|
if (path == null || !Files.isRegularFile(path)) {
|
||||||
|
return null;
|
||||||
|
}
|
||||||
|
try {
|
||||||
|
return new DocumentPositionMapper(Files.readString(path, StandardCharsets.UTF_8));
|
||||||
|
} catch (final Exception ignored) {
|
||||||
|
return null;
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
private List<BaselineCodeAction> mapCodeActions(
|
||||||
|
final List<FrontendCodeAction> repairs,
|
||||||
|
final String documentUri,
|
||||||
|
final Path documentPath,
|
||||||
|
final String documentText,
|
||||||
|
final List<BaselineCodeActionDiagnostic> diagnostics) {
|
||||||
|
if (repairs == null || repairs.isEmpty()) {
|
||||||
|
return List.of();
|
||||||
|
}
|
||||||
|
final DocumentPositionMapper mapper = new DocumentPositionMapper(documentText == null ? "" : documentText);
|
||||||
|
final ArrayList<BaselineCodeAction> mapped = new ArrayList<>();
|
||||||
|
for (final FrontendCodeAction repair : repairs) {
|
||||||
|
if (!repair.path().toAbsolutePath().normalize().equals(documentPath)) {
|
||||||
|
continue;
|
||||||
|
}
|
||||||
|
final DocumentPosition start = mapper.positionOf(repair.startOffset());
|
||||||
|
final DocumentPosition end = mapper.positionOf(repair.endOffset());
|
||||||
|
final boolean matched = diagnostics.stream().anyMatch(diagnostic ->
|
||||||
|
repair.diagnosticCode().equals(diagnostic.code())
|
||||||
|
&& diagnostic.startLine() == start.line()
|
||||||
|
&& diagnostic.startCharacter() == start.character()
|
||||||
|
&& diagnostic.endLine() == end.line()
|
||||||
|
&& diagnostic.endCharacter() == end.character());
|
||||||
|
if (!matched) {
|
||||||
|
continue;
|
||||||
|
}
|
||||||
|
mapped.add(new BaselineCodeAction(
|
||||||
|
repair.title(),
|
||||||
|
repair.diagnosticCode(),
|
||||||
|
documentUri,
|
||||||
|
start.line(),
|
||||||
|
start.character(),
|
||||||
|
end.line(),
|
||||||
|
end.character(),
|
||||||
|
repair.newText()));
|
||||||
|
}
|
||||||
|
return List.copyOf(mapped);
|
||||||
|
}
|
||||||
|
|
||||||
|
private List<BaselineRenameEdit> mapRenameEdits(
|
||||||
|
final List<FrontendRenameEdit> edits,
|
||||||
|
final Path currentDocumentPath,
|
||||||
|
final String currentDocumentText) {
|
||||||
|
if (edits == null || edits.isEmpty()) {
|
||||||
|
return List.of();
|
||||||
|
}
|
||||||
|
final ArrayList<BaselineRenameEdit> mapped = new ArrayList<>();
|
||||||
|
for (final FrontendRenameEdit edit : edits) {
|
||||||
|
final String targetText = textForDefinitionTarget(edit.path(), currentDocumentPath, currentDocumentText);
|
||||||
|
if (targetText == null) {
|
||||||
|
continue;
|
||||||
|
}
|
||||||
|
final DocumentPositionMapper mapper = new DocumentPositionMapper(targetText);
|
||||||
|
final DocumentPosition start = mapper.positionOf(edit.startOffset());
|
||||||
|
final DocumentPosition end = mapper.positionOf(edit.endOffset());
|
||||||
|
mapped.add(new BaselineRenameEdit(
|
||||||
|
edit.path().toUri().toString(),
|
||||||
|
start.line(),
|
||||||
|
start.character(),
|
||||||
|
end.line(),
|
||||||
|
end.character(),
|
||||||
|
edit.newText()));
|
||||||
|
}
|
||||||
|
return List.copyOf(mapped);
|
||||||
|
}
|
||||||
|
|
||||||
|
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();
|
||||||
|
|||||||
+4
-2
@@ -29,7 +29,7 @@ public final class PrometeuLanguageServer implements LanguageServer, LanguageCli
|
|||||||
compilerBridge,
|
compilerBridge,
|
||||||
new Lsp4jProtocolMessageMapper(),
|
new Lsp4jProtocolMessageMapper(),
|
||||||
null,
|
null,
|
||||||
new PrometeuWorkspaceService());
|
null);
|
||||||
}
|
}
|
||||||
|
|
||||||
PrometeuLanguageServer(
|
PrometeuLanguageServer(
|
||||||
@@ -44,7 +44,9 @@ public final class PrometeuLanguageServer implements LanguageServer, LanguageCli
|
|||||||
this.textDocumentService = textDocumentService != null
|
this.textDocumentService = textDocumentService != null
|
||||||
? textDocumentService
|
? textDocumentService
|
||||||
: new PrometeuTextDocumentService(project, languageServiceBridge, protocolMessageMapper);
|
: new PrometeuTextDocumentService(project, languageServiceBridge, protocolMessageMapper);
|
||||||
this.workspaceService = Objects.requireNonNull(workspaceService, "workspaceService");
|
this.workspaceService = workspaceService != null
|
||||||
|
? workspaceService
|
||||||
|
: new PrometeuWorkspaceService(project, languageServiceBridge, protocolMessageMapper);
|
||||||
}
|
}
|
||||||
|
|
||||||
@Override
|
@Override
|
||||||
|
|||||||
+146
@@ -1,13 +1,19 @@
|
|||||||
package p.studio.lsp.services.protocol;
|
package p.studio.lsp.services.protocol;
|
||||||
|
|
||||||
import org.eclipse.lsp4j.*;
|
import org.eclipse.lsp4j.*;
|
||||||
|
import org.eclipse.lsp4j.jsonrpc.ResponseErrorException;
|
||||||
import org.eclipse.lsp4j.jsonrpc.messages.Either;
|
import org.eclipse.lsp4j.jsonrpc.messages.Either;
|
||||||
|
import org.eclipse.lsp4j.jsonrpc.messages.Either3;
|
||||||
|
import org.eclipse.lsp4j.jsonrpc.messages.ResponseError;
|
||||||
|
import org.eclipse.lsp4j.jsonrpc.messages.ResponseErrorCode;
|
||||||
import org.eclipse.lsp4j.services.LanguageClient;
|
import org.eclipse.lsp4j.services.LanguageClient;
|
||||||
import org.eclipse.lsp4j.services.TextDocumentService;
|
import org.eclipse.lsp4j.services.TextDocumentService;
|
||||||
|
import p.studio.lsp.messages.BaselineCodeActionDiagnostic;
|
||||||
import p.studio.lsp.messages.LspProjectContext;
|
import p.studio.lsp.messages.LspProjectContext;
|
||||||
import p.studio.lsp.services.LanguageServiceBridge;
|
import p.studio.lsp.services.LanguageServiceBridge;
|
||||||
import p.studio.lsp.services.protocol.mapping.ProtocolMessageMapper;
|
import p.studio.lsp.services.protocol.mapping.ProtocolMessageMapper;
|
||||||
|
|
||||||
|
import java.util.ArrayList;
|
||||||
import java.util.Objects;
|
import java.util.Objects;
|
||||||
import java.util.concurrent.ConcurrentHashMap;
|
import java.util.concurrent.ConcurrentHashMap;
|
||||||
import java.util.concurrent.CompletableFuture;
|
import java.util.concurrent.CompletableFuture;
|
||||||
@@ -97,6 +103,100 @@ 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
|
||||||
|
public CompletableFuture<List<? extends Location>> references(final ReferenceParams params) {
|
||||||
|
final String uri = params.getTextDocument().getUri();
|
||||||
|
final String text = documentTextByUri.get(uri);
|
||||||
|
final boolean includeDeclaration = params.getContext() != null
|
||||||
|
&& Boolean.TRUE.equals(params.getContext().isIncludeDeclaration());
|
||||||
|
return CompletableFuture.completedFuture(protocolMessageMapper.mapReferences(
|
||||||
|
languageServiceBridge.references(
|
||||||
|
project,
|
||||||
|
uri,
|
||||||
|
text,
|
||||||
|
params.getPosition().getLine(),
|
||||||
|
params.getPosition().getCharacter(),
|
||||||
|
includeDeclaration)));
|
||||||
|
}
|
||||||
|
|
||||||
|
@Override
|
||||||
|
public CompletableFuture<Either3<Range, PrepareRenameResult, PrepareRenameDefaultBehavior>> prepareRename(
|
||||||
|
final PrepareRenameParams params) {
|
||||||
|
final String uri = params.getTextDocument().getUri();
|
||||||
|
final String text = documentTextByUri.get(uri);
|
||||||
|
return CompletableFuture.completedFuture(protocolMessageMapper.mapPrepareRename(
|
||||||
|
languageServiceBridge.prepareRename(
|
||||||
|
project,
|
||||||
|
uri,
|
||||||
|
text,
|
||||||
|
params.getPosition().getLine(),
|
||||||
|
params.getPosition().getCharacter())));
|
||||||
|
}
|
||||||
|
|
||||||
|
@Override
|
||||||
|
public CompletableFuture<WorkspaceEdit> rename(final RenameParams params) {
|
||||||
|
final String uri = params.getTextDocument().getUri();
|
||||||
|
final String text = documentTextByUri.get(uri);
|
||||||
|
final var result = languageServiceBridge.rename(
|
||||||
|
project,
|
||||||
|
uri,
|
||||||
|
text,
|
||||||
|
params.getPosition().getLine(),
|
||||||
|
params.getPosition().getCharacter(),
|
||||||
|
params.getNewName());
|
||||||
|
if (!result.applied()) {
|
||||||
|
final ResponseError error = new ResponseError(
|
||||||
|
ResponseErrorCode.InvalidRequest,
|
||||||
|
result.message() == null || result.message().isBlank() ? "not renameable" : result.message(),
|
||||||
|
null);
|
||||||
|
return CompletableFuture.failedFuture(new ResponseErrorException(error));
|
||||||
|
}
|
||||||
|
return CompletableFuture.completedFuture(protocolMessageMapper.mapRename(result));
|
||||||
|
}
|
||||||
|
|
||||||
|
@Override
|
||||||
|
public CompletableFuture<List<Either<Command, CodeAction>>> codeAction(final CodeActionParams params) {
|
||||||
|
if (!quickFixRequested(params.getContext())) {
|
||||||
|
return CompletableFuture.completedFuture(List.of());
|
||||||
|
}
|
||||||
|
final String uri = params.getTextDocument().getUri();
|
||||||
|
final String text = documentTextByUri.get(uri);
|
||||||
|
final List<Diagnostic> contextDiagnostics = params.getContext() == null
|
||||||
|
|| params.getContext().getDiagnostics() == null
|
||||||
|
? List.of()
|
||||||
|
: params.getContext().getDiagnostics();
|
||||||
|
return CompletableFuture.completedFuture(protocolMessageMapper.mapCodeActions(
|
||||||
|
languageServiceBridge.codeActions(project, uri, text, baselineDiagnostics(contextDiagnostics)),
|
||||||
|
contextDiagnostics));
|
||||||
|
}
|
||||||
|
|
||||||
|
@Override
|
||||||
|
public CompletableFuture<List<Either<SymbolInformation, DocumentSymbol>>> documentSymbol(
|
||||||
|
final DocumentSymbolParams params) {
|
||||||
|
final String uri = params.getTextDocument().getUri();
|
||||||
|
final String text = documentTextByUri.get(uri);
|
||||||
|
final List<Either<SymbolInformation, DocumentSymbol>> symbols = new ArrayList<>();
|
||||||
|
for (final DocumentSymbol symbol : protocolMessageMapper.mapDocumentSymbols(
|
||||||
|
languageServiceBridge.documentSymbols(project, uri, text))) {
|
||||||
|
symbols.add(Either.forRight(symbol));
|
||||||
|
}
|
||||||
|
return CompletableFuture.completedFuture(List.copyOf(symbols));
|
||||||
|
}
|
||||||
|
|
||||||
@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();
|
||||||
@@ -118,6 +218,52 @@ public final class PrometeuTextDocumentService implements TextDocumentService {
|
|||||||
languageServiceBridge.semanticTokens(project, uri, text)));
|
languageServiceBridge.semanticTokens(project, uri, text)));
|
||||||
}
|
}
|
||||||
|
|
||||||
|
private static boolean quickFixRequested(final CodeActionContext context) {
|
||||||
|
if (context == null || context.getOnly() == null || context.getOnly().isEmpty()) {
|
||||||
|
return true;
|
||||||
|
}
|
||||||
|
for (final String kind : context.getOnly()) {
|
||||||
|
if (kind == null || kind.isBlank()) {
|
||||||
|
return true;
|
||||||
|
}
|
||||||
|
if (CodeActionKind.QuickFix.equals(kind) || CodeActionKind.QuickFix.startsWith(kind + ".")) {
|
||||||
|
return true;
|
||||||
|
}
|
||||||
|
}
|
||||||
|
return false;
|
||||||
|
}
|
||||||
|
|
||||||
|
private static List<BaselineCodeActionDiagnostic> baselineDiagnostics(final List<Diagnostic> diagnostics) {
|
||||||
|
final ArrayList<BaselineCodeActionDiagnostic> mapped = new ArrayList<>();
|
||||||
|
for (final Diagnostic diagnostic : diagnostics) {
|
||||||
|
if (diagnostic == null || diagnostic.getRange() == null
|
||||||
|
|| diagnostic.getRange().getStart() == null
|
||||||
|
|| diagnostic.getRange().getEnd() == null) {
|
||||||
|
continue;
|
||||||
|
}
|
||||||
|
mapped.add(new BaselineCodeActionDiagnostic(
|
||||||
|
diagnosticCode(diagnostic),
|
||||||
|
diagnostic.getRange().getStart().getLine(),
|
||||||
|
diagnostic.getRange().getStart().getCharacter(),
|
||||||
|
diagnostic.getRange().getEnd().getLine(),
|
||||||
|
diagnostic.getRange().getEnd().getCharacter()));
|
||||||
|
}
|
||||||
|
return List.copyOf(mapped);
|
||||||
|
}
|
||||||
|
|
||||||
|
private static String diagnosticCode(final Diagnostic diagnostic) {
|
||||||
|
if (diagnostic.getCode() == null) {
|
||||||
|
return "";
|
||||||
|
}
|
||||||
|
if (diagnostic.getCode().isLeft()) {
|
||||||
|
return diagnostic.getCode().getLeft() == null ? "" : diagnostic.getCode().getLeft();
|
||||||
|
}
|
||||||
|
if (diagnostic.getCode().isRight() && diagnostic.getCode().getRight() != null) {
|
||||||
|
return diagnostic.getCode().getRight().toString();
|
||||||
|
}
|
||||||
|
return "";
|
||||||
|
}
|
||||||
|
|
||||||
private void publishAnalysis(
|
private void publishAnalysis(
|
||||||
final String uri,
|
final String uri,
|
||||||
final String text) {
|
final String text) {
|
||||||
|
|||||||
+38
@@ -2,9 +2,36 @@ package p.studio.lsp.services.protocol;
|
|||||||
|
|
||||||
import org.eclipse.lsp4j.DidChangeConfigurationParams;
|
import org.eclipse.lsp4j.DidChangeConfigurationParams;
|
||||||
import org.eclipse.lsp4j.DidChangeWatchedFilesParams;
|
import org.eclipse.lsp4j.DidChangeWatchedFilesParams;
|
||||||
|
import org.eclipse.lsp4j.SymbolInformation;
|
||||||
|
import org.eclipse.lsp4j.WorkspaceSymbol;
|
||||||
|
import org.eclipse.lsp4j.WorkspaceSymbolParams;
|
||||||
|
import org.eclipse.lsp4j.jsonrpc.messages.Either;
|
||||||
import org.eclipse.lsp4j.services.WorkspaceService;
|
import org.eclipse.lsp4j.services.WorkspaceService;
|
||||||
|
import p.studio.lsp.messages.LspProjectContext;
|
||||||
|
import p.studio.lsp.services.LanguageServiceBridge;
|
||||||
|
import p.studio.lsp.services.protocol.mapping.ProtocolMessageMapper;
|
||||||
|
|
||||||
|
import java.util.List;
|
||||||
|
import java.util.concurrent.CompletableFuture;
|
||||||
|
|
||||||
public final class PrometeuWorkspaceService implements WorkspaceService {
|
public final class PrometeuWorkspaceService implements WorkspaceService {
|
||||||
|
private final LspProjectContext project;
|
||||||
|
private final LanguageServiceBridge languageServiceBridge;
|
||||||
|
private final ProtocolMessageMapper protocolMessageMapper;
|
||||||
|
|
||||||
|
public PrometeuWorkspaceService() {
|
||||||
|
this(null, null, null);
|
||||||
|
}
|
||||||
|
|
||||||
|
public PrometeuWorkspaceService(
|
||||||
|
final LspProjectContext project,
|
||||||
|
final LanguageServiceBridge languageServiceBridge,
|
||||||
|
final ProtocolMessageMapper protocolMessageMapper) {
|
||||||
|
this.project = project;
|
||||||
|
this.languageServiceBridge = languageServiceBridge;
|
||||||
|
this.protocolMessageMapper = protocolMessageMapper;
|
||||||
|
}
|
||||||
|
|
||||||
@Override
|
@Override
|
||||||
public void didChangeConfiguration(final DidChangeConfigurationParams params) {
|
public void didChangeConfiguration(final DidChangeConfigurationParams params) {
|
||||||
}
|
}
|
||||||
@@ -12,4 +39,15 @@ public final class PrometeuWorkspaceService implements WorkspaceService {
|
|||||||
@Override
|
@Override
|
||||||
public void didChangeWatchedFiles(final DidChangeWatchedFilesParams params) {
|
public void didChangeWatchedFiles(final DidChangeWatchedFilesParams params) {
|
||||||
}
|
}
|
||||||
|
|
||||||
|
@Override
|
||||||
|
public CompletableFuture<Either<List<? extends SymbolInformation>, List<? extends WorkspaceSymbol>>> symbol(
|
||||||
|
final WorkspaceSymbolParams params) {
|
||||||
|
if (project == null || languageServiceBridge == null || protocolMessageMapper == null) {
|
||||||
|
return CompletableFuture.completedFuture(Either.forLeft(List.of()));
|
||||||
|
}
|
||||||
|
final String query = params == null || params.getQuery() == null ? "" : params.getQuery();
|
||||||
|
return CompletableFuture.completedFuture(Either.forLeft(
|
||||||
|
protocolMessageMapper.mapWorkspaceSymbols(languageServiceBridge.workspaceSymbols(project, query))));
|
||||||
|
}
|
||||||
}
|
}
|
||||||
|
|||||||
+230
@@ -1,6 +1,8 @@
|
|||||||
package p.studio.lsp.services.protocol.mapping;
|
package p.studio.lsp.services.protocol.mapping;
|
||||||
|
|
||||||
import org.eclipse.lsp4j.*;
|
import org.eclipse.lsp4j.*;
|
||||||
|
import org.eclipse.lsp4j.jsonrpc.messages.Either;
|
||||||
|
import org.eclipse.lsp4j.jsonrpc.messages.Either3;
|
||||||
import p.studio.lsp.messages.*;
|
import p.studio.lsp.messages.*;
|
||||||
|
|
||||||
import java.util.ArrayList;
|
import java.util.ArrayList;
|
||||||
@@ -36,6 +38,21 @@ public final class Lsp4jProtocolMessageMapper implements ProtocolMessageMapper {
|
|||||||
signatureHelpOptions.setRetriggerCharacters(List.of(","));
|
signatureHelpOptions.setRetriggerCharacters(List.of(","));
|
||||||
capabilities.setSignatureHelpProvider(signatureHelpOptions);
|
capabilities.setSignatureHelpProvider(signatureHelpOptions);
|
||||||
}
|
}
|
||||||
|
capabilities.setDefinitionProvider(description.definitionSupported());
|
||||||
|
capabilities.setReferencesProvider(description.referencesSupported());
|
||||||
|
capabilities.setDocumentSymbolProvider(description.documentSymbolsSupported());
|
||||||
|
capabilities.setWorkspaceSymbolProvider(description.workspaceSymbolsSupported());
|
||||||
|
if (description.renameSupported()) {
|
||||||
|
final RenameOptions renameOptions = new RenameOptions();
|
||||||
|
renameOptions.setPrepareProvider(true);
|
||||||
|
capabilities.setRenameProvider(renameOptions);
|
||||||
|
}
|
||||||
|
if (description.codeActionsSupported()) {
|
||||||
|
final CodeActionOptions codeActionOptions = new CodeActionOptions();
|
||||||
|
codeActionOptions.setResolveProvider(false);
|
||||||
|
codeActionOptions.setCodeActionKinds(List.of(CodeActionKind.QuickFix));
|
||||||
|
capabilities.setCodeActionProvider(codeActionOptions);
|
||||||
|
}
|
||||||
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 +100,176 @@ 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 mapLocations(definition.locations());
|
||||||
|
}
|
||||||
|
|
||||||
|
@Override
|
||||||
|
public List<Location> mapReferences(final BaselineReferences references) {
|
||||||
|
if (references == null || references.locations().isEmpty()) {
|
||||||
|
return List.of();
|
||||||
|
}
|
||||||
|
return mapLocations(references.locations());
|
||||||
|
}
|
||||||
|
|
||||||
|
@Override
|
||||||
|
public List<DocumentSymbol> mapDocumentSymbols(final BaselineDocumentSymbols symbols) {
|
||||||
|
if (symbols == null || symbols.symbols().isEmpty()) {
|
||||||
|
return List.of();
|
||||||
|
}
|
||||||
|
final ArrayList<DocumentSymbol> mapped = new ArrayList<>();
|
||||||
|
for (final BaselineDocumentSymbol symbol : symbols.symbols()) {
|
||||||
|
mapped.add(mapDocumentSymbol(symbol, null));
|
||||||
|
}
|
||||||
|
return List.copyOf(mapped);
|
||||||
|
}
|
||||||
|
|
||||||
|
@Override
|
||||||
|
public Either3<Range, PrepareRenameResult, PrepareRenameDefaultBehavior> mapPrepareRename(
|
||||||
|
final BaselinePrepareRename prepareRename) {
|
||||||
|
if (prepareRename == null || prepareRename.placeholder().isEmpty()) {
|
||||||
|
return null;
|
||||||
|
}
|
||||||
|
final BaselineDefinitionLocation location = prepareRename.placeholder().orElseThrow();
|
||||||
|
return Either3.forFirst(new Range(
|
||||||
|
new Position(location.startLine(), location.startCharacter()),
|
||||||
|
new Position(location.endLine(), location.endCharacter())));
|
||||||
|
}
|
||||||
|
|
||||||
|
@Override
|
||||||
|
public WorkspaceEdit mapRename(final BaselineRename rename) {
|
||||||
|
final WorkspaceEdit edit = new WorkspaceEdit();
|
||||||
|
if (rename == null || !rename.applied() || rename.edits().isEmpty()) {
|
||||||
|
edit.setChanges(Map.of());
|
||||||
|
return edit;
|
||||||
|
}
|
||||||
|
final LinkedHashMap<String, List<TextEdit>> changes = new LinkedHashMap<>();
|
||||||
|
for (final BaselineRenameEdit renameEdit : rename.edits()) {
|
||||||
|
changes.computeIfAbsent(renameEdit.uri(), ignored -> new ArrayList<>()).add(new TextEdit(
|
||||||
|
new Range(
|
||||||
|
new Position(renameEdit.startLine(), renameEdit.startCharacter()),
|
||||||
|
new Position(renameEdit.endLine(), renameEdit.endCharacter())),
|
||||||
|
renameEdit.newText()));
|
||||||
|
}
|
||||||
|
edit.setChanges(changes);
|
||||||
|
return edit;
|
||||||
|
}
|
||||||
|
|
||||||
|
@Override
|
||||||
|
public List<Either<Command, CodeAction>> mapCodeActions(
|
||||||
|
final BaselineCodeActions actions,
|
||||||
|
final List<Diagnostic> contextDiagnostics) {
|
||||||
|
if (actions == null || actions.actions().isEmpty()) {
|
||||||
|
return List.of();
|
||||||
|
}
|
||||||
|
final ArrayList<Either<Command, CodeAction>> mapped = new ArrayList<>();
|
||||||
|
for (final BaselineCodeAction action : actions.actions()) {
|
||||||
|
final Range range = new Range(
|
||||||
|
new Position(action.startLine(), action.startCharacter()),
|
||||||
|
new Position(action.endLine(), action.endCharacter()));
|
||||||
|
final TextEdit textEdit = new TextEdit(range, action.newText());
|
||||||
|
final WorkspaceEdit edit = new WorkspaceEdit();
|
||||||
|
edit.setChanges(Map.of(action.uri(), List.of(textEdit)));
|
||||||
|
final CodeAction codeAction = new CodeAction();
|
||||||
|
codeAction.setTitle(action.title());
|
||||||
|
codeAction.setKind(CodeActionKind.QuickFix);
|
||||||
|
codeAction.setEdit(edit);
|
||||||
|
codeAction.setDiagnostics(matchingDiagnostics(contextDiagnostics, action.diagnosticCode(), range));
|
||||||
|
mapped.add(Either.forRight(codeAction));
|
||||||
|
}
|
||||||
|
return List.copyOf(mapped);
|
||||||
|
}
|
||||||
|
|
||||||
|
@Override
|
||||||
|
public List<SymbolInformation> mapWorkspaceSymbols(final BaselineWorkspaceSymbols symbols) {
|
||||||
|
if (symbols == null || symbols.symbols().isEmpty()) {
|
||||||
|
return List.of();
|
||||||
|
}
|
||||||
|
final ArrayList<SymbolInformation> mapped = new ArrayList<>();
|
||||||
|
for (final BaselineWorkspaceSymbol symbol : symbols.symbols()) {
|
||||||
|
final SymbolInformation information = new SymbolInformation();
|
||||||
|
information.setName(symbol.name());
|
||||||
|
information.setKind(toLspWorkspaceSymbolKind(symbol.kind(), symbol.containerName()));
|
||||||
|
information.setContainerName(symbol.containerName());
|
||||||
|
information.setLocation(new Location(
|
||||||
|
symbol.uri(),
|
||||||
|
new Range(
|
||||||
|
new Position(symbol.startLine(), symbol.startCharacter()),
|
||||||
|
new Position(symbol.endLine(), symbol.endCharacter()))));
|
||||||
|
mapped.add(information);
|
||||||
|
}
|
||||||
|
return List.copyOf(mapped);
|
||||||
|
}
|
||||||
|
|
||||||
|
private DocumentSymbol mapDocumentSymbol(
|
||||||
|
final BaselineDocumentSymbol symbol,
|
||||||
|
final BaselineDocumentSymbolKind parentKind) {
|
||||||
|
final DocumentSymbol mapped = new DocumentSymbol();
|
||||||
|
mapped.setName(symbol.name());
|
||||||
|
mapped.setDetail(symbol.detail());
|
||||||
|
mapped.setKind(toLspSymbolKind(symbol.kind(), parentKind));
|
||||||
|
mapped.setRange(new Range(
|
||||||
|
new Position(symbol.startLine(), symbol.startCharacter()),
|
||||||
|
new Position(symbol.endLine(), symbol.endCharacter())));
|
||||||
|
mapped.setSelectionRange(new Range(
|
||||||
|
new Position(symbol.selectionStartLine(), symbol.selectionStartCharacter()),
|
||||||
|
new Position(symbol.selectionEndLine(), symbol.selectionEndCharacter())));
|
||||||
|
final ArrayList<DocumentSymbol> children = new ArrayList<>();
|
||||||
|
for (final BaselineDocumentSymbol child : symbol.children()) {
|
||||||
|
children.add(mapDocumentSymbol(child, symbol.kind()));
|
||||||
|
}
|
||||||
|
mapped.setChildren(children);
|
||||||
|
return mapped;
|
||||||
|
}
|
||||||
|
|
||||||
|
private SymbolKind toLspWorkspaceSymbolKind(
|
||||||
|
final BaselineDocumentSymbolKind kind,
|
||||||
|
final String containerName) {
|
||||||
|
if (containerName != null
|
||||||
|
&& !containerName.isBlank()
|
||||||
|
&& (kind == BaselineDocumentSymbolKind.ENUM || kind == BaselineDocumentSymbolKind.ERROR)) {
|
||||||
|
return SymbolKind.EnumMember;
|
||||||
|
}
|
||||||
|
return toLspSymbolKind(kind, null);
|
||||||
|
}
|
||||||
|
|
||||||
|
private SymbolKind toLspSymbolKind(
|
||||||
|
final BaselineDocumentSymbolKind kind,
|
||||||
|
final BaselineDocumentSymbolKind parentKind) {
|
||||||
|
if (parentKind == BaselineDocumentSymbolKind.ENUM || parentKind == BaselineDocumentSymbolKind.ERROR) {
|
||||||
|
if (kind == BaselineDocumentSymbolKind.ENUM || kind == BaselineDocumentSymbolKind.ERROR) {
|
||||||
|
return SymbolKind.EnumMember;
|
||||||
|
}
|
||||||
|
}
|
||||||
|
return switch (kind) {
|
||||||
|
case FUNCTION -> SymbolKind.Function;
|
||||||
|
case METHOD -> SymbolKind.Method;
|
||||||
|
case CONSTRUCTOR -> SymbolKind.Constructor;
|
||||||
|
case FIELD -> SymbolKind.Field;
|
||||||
|
case STRUCT, BUILTIN_TYPE -> SymbolKind.Struct;
|
||||||
|
case SERVICE, HOST -> SymbolKind.Class;
|
||||||
|
case CONTRACT, CALLBACK -> SymbolKind.Interface;
|
||||||
|
case ENUM, ERROR -> SymbolKind.Enum;
|
||||||
|
case GLOBAL, LOCAL, PARAMETER -> SymbolKind.Variable;
|
||||||
|
case CONST -> SymbolKind.Constant;
|
||||||
|
case KEYWORD -> SymbolKind.Key;
|
||||||
|
};
|
||||||
|
}
|
||||||
|
|
||||||
|
private List<Location> mapLocations(final List<BaselineDefinitionLocation> locations) {
|
||||||
|
return 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();
|
||||||
@@ -168,6 +355,9 @@ public final class Lsp4jProtocolMessageMapper implements ProtocolMessageMapper {
|
|||||||
diagnostic.setSeverity(mapSeverity(issue.severity()));
|
diagnostic.setSeverity(mapSeverity(issue.severity()));
|
||||||
diagnostic.setSource(issue.source());
|
diagnostic.setSource(issue.source());
|
||||||
diagnostic.setMessage(issue.message());
|
diagnostic.setMessage(issue.message());
|
||||||
|
if (!issue.code().isBlank()) {
|
||||||
|
diagnostic.setCode(Either.forLeft(issue.code()));
|
||||||
|
}
|
||||||
return diagnostic;
|
return diagnostic;
|
||||||
}
|
}
|
||||||
|
|
||||||
@@ -205,6 +395,46 @@ public final class Lsp4jProtocolMessageMapper implements ProtocolMessageMapper {
|
|||||||
}
|
}
|
||||||
|
|
||||||
|
|
||||||
|
private List<Diagnostic> matchingDiagnostics(
|
||||||
|
final List<Diagnostic> contextDiagnostics,
|
||||||
|
final String diagnosticCode,
|
||||||
|
final Range range) {
|
||||||
|
if (contextDiagnostics == null || contextDiagnostics.isEmpty()) {
|
||||||
|
return List.of();
|
||||||
|
}
|
||||||
|
final ArrayList<Diagnostic> matched = new ArrayList<>();
|
||||||
|
for (final Diagnostic diagnostic : contextDiagnostics) {
|
||||||
|
if (diagnostic == null || diagnostic.getRange() == null) {
|
||||||
|
continue;
|
||||||
|
}
|
||||||
|
if (!diagnosticCode.equals(diagnosticCodeOf(diagnostic)) || !sameRange(diagnostic.getRange(), range)) {
|
||||||
|
continue;
|
||||||
|
}
|
||||||
|
matched.add(diagnostic);
|
||||||
|
}
|
||||||
|
return List.copyOf(matched);
|
||||||
|
}
|
||||||
|
|
||||||
|
private String diagnosticCodeOf(final Diagnostic diagnostic) {
|
||||||
|
if (diagnostic.getCode() == null) {
|
||||||
|
return "";
|
||||||
|
}
|
||||||
|
if (diagnostic.getCode().isLeft()) {
|
||||||
|
return diagnostic.getCode().getLeft() == null ? "" : diagnostic.getCode().getLeft().trim();
|
||||||
|
}
|
||||||
|
if (diagnostic.getCode().isRight() && diagnostic.getCode().getRight() != null) {
|
||||||
|
return diagnostic.getCode().getRight().toString();
|
||||||
|
}
|
||||||
|
return "";
|
||||||
|
}
|
||||||
|
|
||||||
|
private boolean sameRange(final Range left, final Range right) {
|
||||||
|
return left.getStart().getLine() == right.getStart().getLine()
|
||||||
|
&& left.getStart().getCharacter() == right.getStart().getCharacter()
|
||||||
|
&& left.getEnd().getLine() == right.getEnd().getLine()
|
||||||
|
&& left.getEnd().getCharacter() == right.getEnd().getCharacter();
|
||||||
|
}
|
||||||
|
|
||||||
private DiagnosticSeverity mapSeverity(final BaselineIssueSeverity severity) {
|
private DiagnosticSeverity mapSeverity(final BaselineIssueSeverity severity) {
|
||||||
return switch (severity) {
|
return switch (severity) {
|
||||||
case INFORMATION -> DiagnosticSeverity.Information;
|
case INFORMATION -> DiagnosticSeverity.Information;
|
||||||
|
|||||||
+36
@@ -1,19 +1,40 @@
|
|||||||
package p.studio.lsp.services.protocol.mapping;
|
package p.studio.lsp.services.protocol.mapping;
|
||||||
|
|
||||||
|
import org.eclipse.lsp4j.CodeAction;
|
||||||
|
import org.eclipse.lsp4j.Command;
|
||||||
import org.eclipse.lsp4j.Hover;
|
import org.eclipse.lsp4j.Hover;
|
||||||
import org.eclipse.lsp4j.InitializeResult;
|
import org.eclipse.lsp4j.InitializeResult;
|
||||||
import org.eclipse.lsp4j.MessageParams;
|
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.Diagnostic;
|
||||||
|
import org.eclipse.lsp4j.DocumentSymbol;
|
||||||
|
import org.eclipse.lsp4j.Location;
|
||||||
|
import org.eclipse.lsp4j.Range;
|
||||||
|
import org.eclipse.lsp4j.SymbolInformation;
|
||||||
|
import org.eclipse.lsp4j.WorkspaceEdit;
|
||||||
|
import org.eclipse.lsp4j.jsonrpc.messages.Either;
|
||||||
|
import org.eclipse.lsp4j.jsonrpc.messages.Either3;
|
||||||
|
import org.eclipse.lsp4j.PrepareRenameDefaultBehavior;
|
||||||
|
import org.eclipse.lsp4j.PrepareRenameResult;
|
||||||
import p.studio.lsp.messages.BaselineDocumentAnalysis;
|
import p.studio.lsp.messages.BaselineDocumentAnalysis;
|
||||||
|
import p.studio.lsp.messages.BaselineDocumentSymbols;
|
||||||
|
import p.studio.lsp.messages.BaselineWorkspaceSymbols;
|
||||||
|
import p.studio.lsp.messages.BaselineCodeActions;
|
||||||
|
import p.studio.lsp.messages.BaselinePrepareRename;
|
||||||
|
import p.studio.lsp.messages.BaselineRename;
|
||||||
import p.studio.lsp.messages.BaselineCompletion;
|
import p.studio.lsp.messages.BaselineCompletion;
|
||||||
|
import p.studio.lsp.messages.BaselineDefinition;
|
||||||
|
import p.studio.lsp.messages.BaselineReferences;
|
||||||
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 +44,21 @@ public interface ProtocolMessageMapper {
|
|||||||
|
|
||||||
Hover mapHover(BaselineHover hover);
|
Hover mapHover(BaselineHover hover);
|
||||||
|
|
||||||
|
List<Location> mapDefinition(BaselineDefinition definition);
|
||||||
|
|
||||||
|
List<Location> mapReferences(BaselineReferences references);
|
||||||
|
|
||||||
|
List<DocumentSymbol> mapDocumentSymbols(BaselineDocumentSymbols symbols);
|
||||||
|
|
||||||
|
List<SymbolInformation> mapWorkspaceSymbols(BaselineWorkspaceSymbols symbols);
|
||||||
|
|
||||||
|
Either3<Range, PrepareRenameResult, PrepareRenameDefaultBehavior> mapPrepareRename(
|
||||||
|
BaselinePrepareRename prepareRename);
|
||||||
|
|
||||||
|
WorkspaceEdit mapRename(BaselineRename rename);
|
||||||
|
|
||||||
|
List<Either<Command, CodeAction>> mapCodeActions(BaselineCodeActions actions, List<Diagnostic> contextDiagnostics);
|
||||||
|
|
||||||
CompletionList mapCompletion(BaselineCompletion completion);
|
CompletionList mapCompletion(BaselineCompletion completion);
|
||||||
|
|
||||||
SignatureHelp mapSignatureHelp(BaselineSignatureHelp signatureHelp);
|
SignatureHelp mapSignatureHelp(BaselineSignatureHelp signatureHelp);
|
||||||
|
|||||||
+446
@@ -8,15 +8,19 @@ import p.studio.compiler.models.IRBackend;
|
|||||||
import p.studio.compiler.services.FrontendPhaseService;
|
import p.studio.compiler.services.FrontendPhaseService;
|
||||||
import p.studio.compiler.services.FrontendProvider;
|
import p.studio.compiler.services.FrontendProvider;
|
||||||
import p.studio.compiler.source.diagnostics.DiagnosticSink;
|
import p.studio.compiler.source.diagnostics.DiagnosticSink;
|
||||||
|
import p.studio.lsp.messages.BaselineCodeActionDiagnostic;
|
||||||
import p.studio.lsp.messages.BaselineIssueSeverity;
|
import p.studio.lsp.messages.BaselineIssueSeverity;
|
||||||
import p.studio.lsp.messages.LspProjectContext;
|
import p.studio.lsp.messages.LspProjectContext;
|
||||||
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.nio.charset.StandardCharsets;
|
||||||
import java.nio.file.Files;
|
import java.nio.file.Files;
|
||||||
import java.nio.file.Path;
|
import java.nio.file.Path;
|
||||||
|
import java.util.List;
|
||||||
import static org.junit.jupiter.api.Assertions.assertFalse;
|
import static org.junit.jupiter.api.Assertions.assertFalse;
|
||||||
import static org.junit.jupiter.api.Assertions.assertEquals;
|
import static org.junit.jupiter.api.Assertions.assertEquals;
|
||||||
|
import static org.junit.jupiter.api.Assertions.assertNotEquals;
|
||||||
import static org.junit.jupiter.api.Assertions.assertTrue;
|
import static org.junit.jupiter.api.Assertions.assertTrue;
|
||||||
|
|
||||||
class CompilerLanguageServiceBridgeTest {
|
class CompilerLanguageServiceBridgeTest {
|
||||||
@@ -45,9 +49,31 @@ 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 references = bridge.references(context, documentUri, "fn main() {}", 0, 0, true);
|
||||||
|
assertTrue(references.locations().isEmpty());
|
||||||
|
|
||||||
|
final var documentSymbols = bridge.documentSymbols(context, documentUri, "fn main() {}");
|
||||||
|
assertTrue(documentSymbols.symbols().isEmpty());
|
||||||
|
|
||||||
|
final var workspaceSymbols = bridge.workspaceSymbols(context, "frame");
|
||||||
|
assertTrue(workspaceSymbols.symbols().isEmpty());
|
||||||
|
|
||||||
|
final var prepareRename = bridge.prepareRename(context, documentUri, "fn main() {}", 0, 0);
|
||||||
|
assertFalse(prepareRename.renameable());
|
||||||
|
final var rename = bridge.rename(context, documentUri, "fn main() {}", 0, 0, "other");
|
||||||
|
assertFalse(rename.applied());
|
||||||
|
assertTrue(rename.edits().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());
|
||||||
|
|
||||||
|
assertTrue(bridge.codeActions(context, documentUri, "fn main() {}", List.of(
|
||||||
|
new BaselineCodeActionDiagnostic("E_SEM_DUPLICATE_RESERVED_ATTRIBUTE", 0, 0, 0, 1)))
|
||||||
|
.actions().isEmpty());
|
||||||
}
|
}
|
||||||
|
|
||||||
@Test
|
@Test
|
||||||
@@ -309,6 +335,420 @@ 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
|
||||||
|
void referencesUsesDefinitionIdentityOnPhysicalFilesAndHonorsIncludeDeclaration() {
|
||||||
|
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();
|
||||||
|
helper();
|
||||||
|
vec.blend(1, 2);
|
||||||
|
Gfx.clear(5);
|
||||||
|
let n: int = 1;
|
||||||
|
n;
|
||||||
|
// helper
|
||||||
|
let text = "helper";
|
||||||
|
}
|
||||||
|
""";
|
||||||
|
final CompilerLanguageServiceBridge bridge = new CompilerLanguageServiceBridge();
|
||||||
|
final LspProjectContext context = new LspProjectContext("main", "pbs", projectRoot);
|
||||||
|
final DocumentPositionMapper mapper = new DocumentPositionMapper(overlay);
|
||||||
|
final String documentUri = documentPath.toUri().toString();
|
||||||
|
|
||||||
|
final var helperUse = mapper.positionOf(overlay.indexOf("helper();"));
|
||||||
|
final var helperUsages = bridge.references(
|
||||||
|
context,
|
||||||
|
documentUri,
|
||||||
|
overlay,
|
||||||
|
helperUse.line(),
|
||||||
|
helperUse.character(),
|
||||||
|
false);
|
||||||
|
assertEquals(3, helperUsages.locations().size(), helperUsages.locations().toString());
|
||||||
|
assertTrue(helperUsages.locations().stream().allMatch(location -> location.uri().equals(documentUri)));
|
||||||
|
|
||||||
|
final var helperWithDeclaration = bridge.references(
|
||||||
|
context,
|
||||||
|
documentUri,
|
||||||
|
overlay,
|
||||||
|
helperUse.line(),
|
||||||
|
helperUse.character(),
|
||||||
|
true);
|
||||||
|
assertTrue(helperWithDeclaration.locations().size() > helperUsages.locations().size());
|
||||||
|
|
||||||
|
final var clearUse = mapper.positionOf(overlay.indexOf("clear"));
|
||||||
|
final var clearReferences = bridge.references(
|
||||||
|
context,
|
||||||
|
documentUri,
|
||||||
|
overlay,
|
||||||
|
clearUse.line(),
|
||||||
|
clearUse.character(),
|
||||||
|
true);
|
||||||
|
assertTrue(clearReferences.locations().isEmpty());
|
||||||
|
|
||||||
|
final var builtinUse = mapper.positionOf(overlay.indexOf("int = 1"));
|
||||||
|
final var builtinReferences = bridge.references(
|
||||||
|
context,
|
||||||
|
documentUri,
|
||||||
|
overlay,
|
||||||
|
builtinUse.line(),
|
||||||
|
builtinUse.character(),
|
||||||
|
true);
|
||||||
|
assertTrue(builtinReferences.locations().isEmpty());
|
||||||
|
}
|
||||||
|
|
||||||
|
@Test
|
||||||
|
void renameRewritesPhysicalFunctionSitesAndRefusesStdlib() {
|
||||||
|
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;
|
||||||
|
|
||||||
|
fn helper() -> int { return 42; }
|
||||||
|
|
||||||
|
fn frame() -> void {
|
||||||
|
helper();
|
||||||
|
helper();
|
||||||
|
Gfx.clear(5);
|
||||||
|
let n: int = 1;
|
||||||
|
// helper
|
||||||
|
let text = "helper";
|
||||||
|
}
|
||||||
|
""";
|
||||||
|
final CompilerLanguageServiceBridge bridge = new CompilerLanguageServiceBridge();
|
||||||
|
final LspProjectContext context = new LspProjectContext("main", "pbs", projectRoot);
|
||||||
|
final DocumentPositionMapper mapper = new DocumentPositionMapper(overlay);
|
||||||
|
final String documentUri = documentPath.toUri().toString();
|
||||||
|
|
||||||
|
final var helperUse = mapper.positionOf(overlay.indexOf("helper();"));
|
||||||
|
final var prepared = bridge.prepareRename(
|
||||||
|
context,
|
||||||
|
documentUri,
|
||||||
|
overlay,
|
||||||
|
helperUse.line(),
|
||||||
|
helperUse.character());
|
||||||
|
assertTrue(prepared.renameable(), prepared.toString());
|
||||||
|
|
||||||
|
final var renamed = bridge.rename(
|
||||||
|
context,
|
||||||
|
documentUri,
|
||||||
|
overlay,
|
||||||
|
helperUse.line(),
|
||||||
|
helperUse.character(),
|
||||||
|
"aid");
|
||||||
|
assertTrue(renamed.applied(), renamed.message());
|
||||||
|
assertEquals(3, renamed.edits().size(), renamed.edits().toString());
|
||||||
|
assertTrue(renamed.edits().stream().allMatch(edit -> edit.newText().equals("aid")));
|
||||||
|
assertTrue(renamed.edits().stream().allMatch(edit -> edit.uri().equals(documentUri)));
|
||||||
|
|
||||||
|
final var clearUse = mapper.positionOf(overlay.indexOf("clear"));
|
||||||
|
final var stdlibPrepared = bridge.prepareRename(
|
||||||
|
context,
|
||||||
|
documentUri,
|
||||||
|
overlay,
|
||||||
|
clearUse.line(),
|
||||||
|
clearUse.character());
|
||||||
|
assertFalse(stdlibPrepared.renameable());
|
||||||
|
final var stdlibRename = bridge.rename(
|
||||||
|
context,
|
||||||
|
documentUri,
|
||||||
|
overlay,
|
||||||
|
clearUse.line(),
|
||||||
|
clearUse.character(),
|
||||||
|
"wipe");
|
||||||
|
assertFalse(stdlibRename.applied());
|
||||||
|
assertTrue(stdlibRename.edits().isEmpty());
|
||||||
|
}
|
||||||
|
|
||||||
|
@Test
|
||||||
|
void quickFixDeletesTheDuplicateDocDiagnosticAndIgnoresOtherCodes() {
|
||||||
|
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 = """
|
||||||
|
[Doc(markdown = \"""
|
||||||
|
First.
|
||||||
|
\""")]
|
||||||
|
[Doc(markdown = \"""
|
||||||
|
Second.
|
||||||
|
\""")]
|
||||||
|
fn duplicated() -> void { return; }
|
||||||
|
|
||||||
|
fn frame() -> void { return; }
|
||||||
|
""";
|
||||||
|
final CompilerLanguageServiceBridge bridge = new CompilerLanguageServiceBridge();
|
||||||
|
final LspProjectContext context = new LspProjectContext("main", "pbs", projectRoot);
|
||||||
|
final String documentUri = documentPath.toUri().toString();
|
||||||
|
|
||||||
|
final var analysis = bridge.analyzeDocument(context, documentUri, overlay);
|
||||||
|
final var duplicates = analysis.issues().stream()
|
||||||
|
.filter(issue -> issue.code().equals("E_SEM_DUPLICATE_RESERVED_ATTRIBUTE"))
|
||||||
|
.toList();
|
||||||
|
assertEquals(1, duplicates.size(), analysis.issues().toString());
|
||||||
|
final var duplicate = duplicates.getFirst();
|
||||||
|
assertFalse(duplicate.code().isBlank());
|
||||||
|
final var diagnostic = new BaselineCodeActionDiagnostic(
|
||||||
|
duplicate.code(),
|
||||||
|
duplicate.startLine(),
|
||||||
|
duplicate.startCharacter(),
|
||||||
|
duplicate.endLine(),
|
||||||
|
duplicate.endCharacter());
|
||||||
|
|
||||||
|
final var actions = bridge.codeActions(context, documentUri, overlay, List.of(diagnostic));
|
||||||
|
assertEquals(1, actions.actions().size(), actions.toString());
|
||||||
|
final var action = actions.actions().getFirst();
|
||||||
|
assertEquals("Remove duplicate reserved attribute", action.title());
|
||||||
|
assertEquals(documentUri, action.uri());
|
||||||
|
assertEquals("", action.newText());
|
||||||
|
assertEquals(diagnostic.startLine(), action.startLine());
|
||||||
|
assertEquals(diagnostic.startCharacter(), action.startCharacter());
|
||||||
|
assertEquals(diagnostic.endLine(), action.endLine());
|
||||||
|
assertEquals(diagnostic.endCharacter(), action.endCharacter());
|
||||||
|
final String removed = sourceSlice(overlay, action.startLine(), action.startCharacter(), action.endLine(), action.endCharacter());
|
||||||
|
assertTrue(removed.contains("Second."), removed);
|
||||||
|
assertFalse(removed.contains("First."), removed);
|
||||||
|
|
||||||
|
final var wrongCode = new BaselineCodeActionDiagnostic(
|
||||||
|
"E_SEM_MALFORMED_RESERVED_ATTRIBUTE",
|
||||||
|
diagnostic.startLine(),
|
||||||
|
diagnostic.startCharacter(),
|
||||||
|
diagnostic.endLine(),
|
||||||
|
diagnostic.endCharacter());
|
||||||
|
assertTrue(bridge.codeActions(context, documentUri, overlay, List.of(wrongCode)).actions().isEmpty());
|
||||||
|
assertTrue(bridge.codeActions(context, documentUri, overlay, List.of()).actions().isEmpty());
|
||||||
|
|
||||||
|
final String malformed = """
|
||||||
|
[Doc(text = \"""
|
||||||
|
Wrong argument.
|
||||||
|
\""")]
|
||||||
|
fn frame() -> void { return; }
|
||||||
|
""";
|
||||||
|
final var malformedAnalysis = bridge.analyzeDocument(context, documentUri, malformed);
|
||||||
|
final var malformedDiagnostics = malformedAnalysis.issues().stream()
|
||||||
|
.map(issue -> new BaselineCodeActionDiagnostic(
|
||||||
|
issue.code(),
|
||||||
|
issue.startLine(),
|
||||||
|
issue.startCharacter(),
|
||||||
|
issue.endLine(),
|
||||||
|
issue.endCharacter()))
|
||||||
|
.toList();
|
||||||
|
assertTrue(bridge.codeActions(context, documentUri, malformed, malformedDiagnostics).actions().isEmpty());
|
||||||
|
}
|
||||||
|
|
||||||
|
private static String sourceSlice(
|
||||||
|
final String source,
|
||||||
|
final int startLine,
|
||||||
|
final int startCharacter,
|
||||||
|
final int endLine,
|
||||||
|
final int endCharacter) {
|
||||||
|
final DocumentPositionMapper mapper = new DocumentPositionMapper(source);
|
||||||
|
final byte[] bytes = source.getBytes(StandardCharsets.UTF_8);
|
||||||
|
final int start = mapper.byteOffsetOf(startLine, startCharacter);
|
||||||
|
final int end = mapper.byteOffsetOf(endLine, endCharacter);
|
||||||
|
return new String(bytes, start, Math.max(0, end - start), StandardCharsets.UTF_8);
|
||||||
|
}
|
||||||
|
|
||||||
|
@Test
|
||||||
|
void documentSymbolsUseAstHierarchyOfTheOpenPbsFile() {
|
||||||
|
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(x: int) {
|
||||||
|
ctor make(x: int) { return; }
|
||||||
|
fn blend(dx: int, dy: int) -> int { return dx; }
|
||||||
|
}
|
||||||
|
|
||||||
|
fn helper() -> int { return 42; }
|
||||||
|
fn helper(value: int) -> int { return value; }
|
||||||
|
|
||||||
|
fn frame() -> void {
|
||||||
|
let local = 1;
|
||||||
|
helper(local);
|
||||||
|
}
|
||||||
|
""";
|
||||||
|
final CompilerLanguageServiceBridge bridge = new CompilerLanguageServiceBridge();
|
||||||
|
final var symbols = bridge.documentSymbols(
|
||||||
|
new LspProjectContext("main", "pbs", projectRoot),
|
||||||
|
documentPath.toUri().toString(),
|
||||||
|
overlay).symbols();
|
||||||
|
|
||||||
|
assertEquals(List.of("Vec", "helper", "helper", "frame"), symbols.stream().map(symbol -> symbol.name()).toList());
|
||||||
|
assertTrue(symbols.stream().noneMatch(symbol -> symbol.name().equals("Gfx") || symbol.name().equals("local")));
|
||||||
|
final var vec = symbols.getFirst();
|
||||||
|
assertEquals(p.studio.lsp.messages.BaselineDocumentSymbolKind.STRUCT, vec.kind());
|
||||||
|
assertEquals(List.of("x", "make", "blend"), vec.children().stream().map(symbol -> symbol.name()).toList());
|
||||||
|
assertEquals("(dx: int, dy: int) -> int", vec.children().get(2).detail());
|
||||||
|
assertEquals("helper", symbols.get(1).name());
|
||||||
|
assertEquals("helper", symbols.get(2).name());
|
||||||
|
assertNotEquals(symbols.get(1).detail(), symbols.get(2).detail());
|
||||||
|
}
|
||||||
|
|
||||||
|
@Test
|
||||||
|
void workspaceSymbolsSearchPhysicalNamedDeclarationsWithoutAnOpenDocument() {
|
||||||
|
final Path projectRoot = findRepoRoot(Path.of("").toAbsolutePath().normalize())
|
||||||
|
.resolve("test-projects")
|
||||||
|
.resolve("main")
|
||||||
|
.toAbsolutePath()
|
||||||
|
.normalize();
|
||||||
|
final CompilerLanguageServiceBridge bridge = new CompilerLanguageServiceBridge();
|
||||||
|
final var context = new LspProjectContext("main", "pbs", projectRoot);
|
||||||
|
|
||||||
|
final var frameHits = bridge.workspaceSymbols(context, "frame");
|
||||||
|
assertTrue(frameHits.symbols().stream().anyMatch(symbol ->
|
||||||
|
symbol.name().equals("frame") && symbol.containerName().isEmpty()));
|
||||||
|
assertTrue(frameHits.symbols().stream().allMatch(symbol ->
|
||||||
|
symbol.uri().contains("main.pbs")));
|
||||||
|
|
||||||
|
final var caseInsensitive = bridge.workspaceSymbols(context, "BLA");
|
||||||
|
assertTrue(caseInsensitive.symbols().stream().anyMatch(symbol ->
|
||||||
|
symbol.name().equals("Bla") && symbol.containerName().isEmpty()));
|
||||||
|
|
||||||
|
final var all = bridge.workspaceSymbols(context, "");
|
||||||
|
assertTrue(all.symbols().stream().anyMatch(symbol ->
|
||||||
|
symbol.name().equals("a") && symbol.containerName().equals("Bla")));
|
||||||
|
assertTrue(all.symbols().stream().anyMatch(symbol -> symbol.name().equals("init")));
|
||||||
|
assertTrue(all.symbols().stream().noneMatch(symbol ->
|
||||||
|
symbol.name().equals("Gfx")
|
||||||
|
|| symbol.name().equals("Log")
|
||||||
|
|| symbol.name().equals("Composer")));
|
||||||
|
assertTrue(isSortedByNameThenUriThenOffset(all.symbols()));
|
||||||
|
|
||||||
|
final var stdlibMiss = bridge.workspaceSymbols(context, "Gfx");
|
||||||
|
assertTrue(stdlibMiss.symbols().isEmpty());
|
||||||
|
}
|
||||||
|
|
||||||
|
private boolean isSortedByNameThenUriThenOffset(
|
||||||
|
final List<p.studio.lsp.messages.BaselineWorkspaceSymbol> symbols) {
|
||||||
|
for (int index = 1; index < symbols.size(); index += 1) {
|
||||||
|
final var previous = symbols.get(index - 1);
|
||||||
|
final var current = symbols.get(index);
|
||||||
|
final int nameOrder = String.CASE_INSENSITIVE_ORDER.compare(previous.name(), current.name());
|
||||||
|
if (nameOrder > 0) {
|
||||||
|
return false;
|
||||||
|
}
|
||||||
|
if (nameOrder == 0) {
|
||||||
|
final int uriOrder = previous.uri().compareTo(current.uri());
|
||||||
|
if (uriOrder > 0) {
|
||||||
|
return false;
|
||||||
|
}
|
||||||
|
if (uriOrder == 0 && previous.startLine() > current.startLine()) {
|
||||||
|
return false;
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
|
return true;
|
||||||
|
}
|
||||||
|
|
||||||
@Test
|
@Test
|
||||||
void describeServerPublishesFrontendVisualThemes() {
|
void describeServerPublishesFrontendVisualThemes() {
|
||||||
final CompilerLanguageServiceBridge bridge = new CompilerLanguageServiceBridge();
|
final CompilerLanguageServiceBridge bridge = new CompilerLanguageServiceBridge();
|
||||||
@@ -319,6 +759,12 @@ 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());
|
||||||
|
assertTrue(description.referencesSupported());
|
||||||
|
assertTrue(description.documentSymbolsSupported());
|
||||||
|
assertTrue(description.workspaceSymbolsSupported());
|
||||||
|
assertTrue(description.renameSupported());
|
||||||
|
assertTrue(description.codeActionsSupported());
|
||||||
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()
|
||||||
|
|||||||
+117
@@ -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,12 @@ class PrometeuLanguageServerTest {
|
|||||||
true,
|
true,
|
||||||
true,
|
true,
|
||||||
true,
|
true,
|
||||||
|
true,
|
||||||
|
true,
|
||||||
|
true,
|
||||||
|
true,
|
||||||
|
true,
|
||||||
|
false,
|
||||||
List.of(),
|
List.of(),
|
||||||
List.of(new BaselineSemanticHostProjection(
|
List.of(new BaselineSemanticHostProjection(
|
||||||
"vscode",
|
"vscode",
|
||||||
@@ -145,6 +152,63 @@ 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
|
||||||
|
public p.studio.lsp.messages.BaselineReferences references(
|
||||||
|
final LspProjectContext project,
|
||||||
|
final String documentUri,
|
||||||
|
final String text,
|
||||||
|
final int line,
|
||||||
|
final int character,
|
||||||
|
final boolean includeDeclaration) {
|
||||||
|
return p.studio.lsp.messages.BaselineReferences.empty();
|
||||||
|
}
|
||||||
|
|
||||||
|
@Override
|
||||||
|
public p.studio.lsp.messages.BaselineDocumentSymbols documentSymbols(
|
||||||
|
final LspProjectContext project,
|
||||||
|
final String documentUri,
|
||||||
|
final String text) {
|
||||||
|
return p.studio.lsp.messages.BaselineDocumentSymbols.empty();
|
||||||
|
}
|
||||||
|
|
||||||
|
@Override
|
||||||
|
public p.studio.lsp.messages.BaselineWorkspaceSymbols workspaceSymbols(
|
||||||
|
final LspProjectContext project,
|
||||||
|
final String query) {
|
||||||
|
return p.studio.lsp.messages.BaselineWorkspaceSymbols.empty();
|
||||||
|
}
|
||||||
|
|
||||||
|
@Override
|
||||||
|
public p.studio.lsp.messages.BaselinePrepareRename prepareRename(
|
||||||
|
final LspProjectContext project,
|
||||||
|
final String documentUri,
|
||||||
|
final String text,
|
||||||
|
final int line,
|
||||||
|
final int character) {
|
||||||
|
return p.studio.lsp.messages.BaselinePrepareRename.none();
|
||||||
|
}
|
||||||
|
|
||||||
|
@Override
|
||||||
|
public p.studio.lsp.messages.BaselineRename rename(
|
||||||
|
final LspProjectContext project,
|
||||||
|
final String documentUri,
|
||||||
|
final String text,
|
||||||
|
final int line,
|
||||||
|
final int character,
|
||||||
|
final String newName) {
|
||||||
|
return p.studio.lsp.messages.BaselineRename.unsupported();
|
||||||
|
}
|
||||||
|
|
||||||
@Override
|
@Override
|
||||||
public BaselineSignatureHelp signatureHelp(
|
public BaselineSignatureHelp signatureHelp(
|
||||||
final LspProjectContext project,
|
final LspProjectContext project,
|
||||||
@@ -160,6 +224,15 @@ class PrometeuLanguageServerTest {
|
|||||||
return new BaselineSemanticTokens(List.of(), List.of());
|
return new BaselineSemanticTokens(List.of(), List.of());
|
||||||
}
|
}
|
||||||
|
|
||||||
|
@Override
|
||||||
|
public p.studio.lsp.messages.BaselineCodeActions codeActions(
|
||||||
|
final LspProjectContext context,
|
||||||
|
final String documentUri,
|
||||||
|
final String text,
|
||||||
|
final java.util.List<p.studio.lsp.messages.BaselineCodeActionDiagnostic> diagnostics) {
|
||||||
|
return p.studio.lsp.messages.BaselineCodeActions.empty();
|
||||||
|
}
|
||||||
|
|
||||||
@Override
|
@Override
|
||||||
public String onSave(final LspProjectContext project, final String documentUri) {
|
public String onSave(final LspProjectContext project, final String documentUri) {
|
||||||
return "saved";
|
return "saved";
|
||||||
@@ -191,6 +264,50 @@ 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
|
||||||
|
public java.util.List<org.eclipse.lsp4j.Location> mapReferences(
|
||||||
|
final p.studio.lsp.messages.BaselineReferences references) {
|
||||||
|
throw new UnsupportedOperationException();
|
||||||
|
}
|
||||||
|
|
||||||
|
@Override
|
||||||
|
public java.util.List<org.eclipse.lsp4j.DocumentSymbol> mapDocumentSymbols(
|
||||||
|
final p.studio.lsp.messages.BaselineDocumentSymbols symbols) {
|
||||||
|
throw new UnsupportedOperationException();
|
||||||
|
}
|
||||||
|
|
||||||
|
@Override
|
||||||
|
public java.util.List<org.eclipse.lsp4j.SymbolInformation> mapWorkspaceSymbols(
|
||||||
|
final p.studio.lsp.messages.BaselineWorkspaceSymbols symbols) {
|
||||||
|
throw new UnsupportedOperationException();
|
||||||
|
}
|
||||||
|
|
||||||
|
@Override
|
||||||
|
public org.eclipse.lsp4j.jsonrpc.messages.Either3<
|
||||||
|
org.eclipse.lsp4j.Range,
|
||||||
|
org.eclipse.lsp4j.PrepareRenameResult,
|
||||||
|
org.eclipse.lsp4j.PrepareRenameDefaultBehavior> mapPrepareRename(
|
||||||
|
final p.studio.lsp.messages.BaselinePrepareRename prepareRename) {
|
||||||
|
throw new UnsupportedOperationException();
|
||||||
|
}
|
||||||
|
|
||||||
|
@Override
|
||||||
|
public org.eclipse.lsp4j.WorkspaceEdit mapRename(final p.studio.lsp.messages.BaselineRename rename) {
|
||||||
|
throw new UnsupportedOperationException();
|
||||||
|
}
|
||||||
|
|
||||||
|
@Override
|
||||||
|
public java.util.List<org.eclipse.lsp4j.jsonrpc.messages.Either<org.eclipse.lsp4j.Command, org.eclipse.lsp4j.CodeAction>> mapCodeActions(
|
||||||
|
final p.studio.lsp.messages.BaselineCodeActions actions,
|
||||||
|
final java.util.List<org.eclipse.lsp4j.Diagnostic> contextDiagnostics) {
|
||||||
|
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();
|
||||||
|
|||||||
+176
@@ -3,9 +3,15 @@ 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.DocumentSymbol;
|
||||||
|
import org.eclipse.lsp4j.DocumentSymbolParams;
|
||||||
|
import org.eclipse.lsp4j.ReferenceContext;
|
||||||
|
import org.eclipse.lsp4j.ReferenceParams;
|
||||||
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 +22,12 @@ 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.BaselineDocumentSymbol;
|
||||||
|
import p.studio.lsp.messages.BaselineDocumentSymbolKind;
|
||||||
|
import p.studio.lsp.messages.BaselineDocumentSymbols;
|
||||||
|
import p.studio.lsp.messages.BaselineReferences;
|
||||||
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 +89,31 @@ 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);
|
||||||
|
|
||||||
|
final var references = service.references(new ReferenceParams(
|
||||||
|
new TextDocumentIdentifier(uri),
|
||||||
|
new Position(1, 2),
|
||||||
|
new ReferenceContext(true))).join();
|
||||||
|
assertSame(mapper.referenceLocations, references);
|
||||||
|
assertEquals(text, bridge.lastReferencesText);
|
||||||
|
assertEquals(1, bridge.lastReferencesLine);
|
||||||
|
assertEquals(2, bridge.lastReferencesCharacter);
|
||||||
|
assertTrue(bridge.lastIncludeDeclaration);
|
||||||
|
|
||||||
|
final var documentSymbols = service.documentSymbol(new DocumentSymbolParams(
|
||||||
|
new TextDocumentIdentifier(uri))).join();
|
||||||
|
assertEquals(1, documentSymbols.size());
|
||||||
|
assertTrue(documentSymbols.getFirst().isRight());
|
||||||
|
assertSame(mapper.documentSymbols.getFirst(), documentSymbols.getFirst().getRight());
|
||||||
|
assertEquals(text, bridge.lastDocumentSymbolsText);
|
||||||
}
|
}
|
||||||
|
|
||||||
private static final class RecordingBridge implements LanguageServiceBridge {
|
private static final class RecordingBridge implements LanguageServiceBridge {
|
||||||
@@ -84,6 +121,14 @@ 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 lastReferencesText;
|
||||||
|
private int lastReferencesLine;
|
||||||
|
private int lastReferencesCharacter;
|
||||||
|
private boolean lastIncludeDeclaration;
|
||||||
|
private String lastDocumentSymbolsText;
|
||||||
private String lastSignatureHelpText;
|
private String lastSignatureHelpText;
|
||||||
private int lastSignatureHelpLine;
|
private int lastSignatureHelpLine;
|
||||||
private int lastSignatureHelpCharacter;
|
private int lastSignatureHelpCharacter;
|
||||||
@@ -123,6 +168,83 @@ 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
|
||||||
|
public BaselineReferences references(
|
||||||
|
final LspProjectContext context,
|
||||||
|
final String documentUri,
|
||||||
|
final String text,
|
||||||
|
final int line,
|
||||||
|
final int character,
|
||||||
|
final boolean includeDeclaration) {
|
||||||
|
lastReferencesText = text;
|
||||||
|
lastReferencesLine = line;
|
||||||
|
lastReferencesCharacter = character;
|
||||||
|
lastIncludeDeclaration = includeDeclaration;
|
||||||
|
return new BaselineReferences(List.of(new BaselineDefinitionLocation(documentUri, 0, 0, 0, 6)));
|
||||||
|
}
|
||||||
|
|
||||||
|
@Override
|
||||||
|
public BaselineDocumentSymbols documentSymbols(
|
||||||
|
final LspProjectContext context,
|
||||||
|
final String documentUri,
|
||||||
|
final String text) {
|
||||||
|
lastDocumentSymbolsText = text;
|
||||||
|
return new BaselineDocumentSymbols(List.of(new BaselineDocumentSymbol(
|
||||||
|
"frame",
|
||||||
|
BaselineDocumentSymbolKind.FUNCTION,
|
||||||
|
"",
|
||||||
|
0,
|
||||||
|
0,
|
||||||
|
2,
|
||||||
|
1,
|
||||||
|
0,
|
||||||
|
3,
|
||||||
|
0,
|
||||||
|
8,
|
||||||
|
List.of())));
|
||||||
|
}
|
||||||
|
|
||||||
|
@Override
|
||||||
|
public p.studio.lsp.messages.BaselineWorkspaceSymbols workspaceSymbols(
|
||||||
|
final LspProjectContext context,
|
||||||
|
final String query) {
|
||||||
|
return p.studio.lsp.messages.BaselineWorkspaceSymbols.empty();
|
||||||
|
}
|
||||||
|
|
||||||
|
@Override
|
||||||
|
public p.studio.lsp.messages.BaselinePrepareRename prepareRename(
|
||||||
|
final LspProjectContext context,
|
||||||
|
final String documentUri,
|
||||||
|
final String text,
|
||||||
|
final int line,
|
||||||
|
final int character) {
|
||||||
|
return p.studio.lsp.messages.BaselinePrepareRename.none();
|
||||||
|
}
|
||||||
|
|
||||||
|
@Override
|
||||||
|
public p.studio.lsp.messages.BaselineRename rename(
|
||||||
|
final LspProjectContext context,
|
||||||
|
final String documentUri,
|
||||||
|
final String text,
|
||||||
|
final int line,
|
||||||
|
final int character,
|
||||||
|
final String newName) {
|
||||||
|
return p.studio.lsp.messages.BaselineRename.unsupported();
|
||||||
|
}
|
||||||
|
|
||||||
@Override
|
@Override
|
||||||
public BaselineSignatureHelp signatureHelp(
|
public BaselineSignatureHelp signatureHelp(
|
||||||
final LspProjectContext context,
|
final LspProjectContext context,
|
||||||
@@ -142,6 +264,15 @@ final class PrometeuTextDocumentServiceTest {
|
|||||||
return new BaselineSemanticTokens(List.of(), List.of());
|
return new BaselineSemanticTokens(List.of(), List.of());
|
||||||
}
|
}
|
||||||
|
|
||||||
|
@Override
|
||||||
|
public p.studio.lsp.messages.BaselineCodeActions codeActions(
|
||||||
|
final LspProjectContext context,
|
||||||
|
final String documentUri,
|
||||||
|
final String text,
|
||||||
|
final java.util.List<p.studio.lsp.messages.BaselineCodeActionDiagnostic> diagnostics) {
|
||||||
|
return p.studio.lsp.messages.BaselineCodeActions.empty();
|
||||||
|
}
|
||||||
|
|
||||||
@Override
|
@Override
|
||||||
public String onSave(final LspProjectContext context, final String documentUri) {
|
public String onSave(final LspProjectContext context, final String documentUri) {
|
||||||
return "saved";
|
return "saved";
|
||||||
@@ -151,6 +282,9 @@ 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 final List<Location> referenceLocations = List.of();
|
||||||
|
private final List<DocumentSymbol> documentSymbols = List.of(new DocumentSymbol());
|
||||||
private BaselineSignatureHelp mappedSignatureHelp;
|
private BaselineSignatureHelp mappedSignatureHelp;
|
||||||
|
|
||||||
@Override
|
@Override
|
||||||
@@ -178,6 +312,48 @@ final class PrometeuTextDocumentServiceTest {
|
|||||||
return new Hover(content);
|
return new Hover(content);
|
||||||
}
|
}
|
||||||
|
|
||||||
|
@Override
|
||||||
|
public List<Location> mapDefinition(final BaselineDefinition definition) {
|
||||||
|
return definitionLocations;
|
||||||
|
}
|
||||||
|
|
||||||
|
@Override
|
||||||
|
public List<Location> mapReferences(final BaselineReferences references) {
|
||||||
|
return referenceLocations;
|
||||||
|
}
|
||||||
|
|
||||||
|
@Override
|
||||||
|
public List<DocumentSymbol> mapDocumentSymbols(final BaselineDocumentSymbols symbols) {
|
||||||
|
return documentSymbols;
|
||||||
|
}
|
||||||
|
|
||||||
|
@Override
|
||||||
|
public List<org.eclipse.lsp4j.SymbolInformation> mapWorkspaceSymbols(
|
||||||
|
final p.studio.lsp.messages.BaselineWorkspaceSymbols symbols) {
|
||||||
|
return List.of();
|
||||||
|
}
|
||||||
|
|
||||||
|
@Override
|
||||||
|
public org.eclipse.lsp4j.jsonrpc.messages.Either3<
|
||||||
|
org.eclipse.lsp4j.Range,
|
||||||
|
org.eclipse.lsp4j.PrepareRenameResult,
|
||||||
|
org.eclipse.lsp4j.PrepareRenameDefaultBehavior> mapPrepareRename(
|
||||||
|
final p.studio.lsp.messages.BaselinePrepareRename prepareRename) {
|
||||||
|
return null;
|
||||||
|
}
|
||||||
|
|
||||||
|
@Override
|
||||||
|
public org.eclipse.lsp4j.WorkspaceEdit mapRename(final p.studio.lsp.messages.BaselineRename rename) {
|
||||||
|
return new org.eclipse.lsp4j.WorkspaceEdit();
|
||||||
|
}
|
||||||
|
|
||||||
|
@Override
|
||||||
|
public java.util.List<org.eclipse.lsp4j.jsonrpc.messages.Either<org.eclipse.lsp4j.Command, org.eclipse.lsp4j.CodeAction>> mapCodeActions(
|
||||||
|
final p.studio.lsp.messages.BaselineCodeActions actions,
|
||||||
|
final java.util.List<org.eclipse.lsp4j.Diagnostic> contextDiagnostics) {
|
||||||
|
return java.util.List.of();
|
||||||
|
}
|
||||||
|
|
||||||
@Override
|
@Override
|
||||||
public CompletionList mapCompletion(final BaselineCompletion completion) {
|
public CompletionList mapCompletion(final BaselineCompletion completion) {
|
||||||
return completionList;
|
return completionList;
|
||||||
|
|||||||
+280
@@ -0,0 +1,280 @@
|
|||||||
|
package p.studio.lsp.services.protocol;
|
||||||
|
|
||||||
|
import org.eclipse.lsp4j.SymbolInformation;
|
||||||
|
import org.eclipse.lsp4j.WorkspaceSymbolParams;
|
||||||
|
import org.junit.jupiter.api.Test;
|
||||||
|
import p.studio.lsp.messages.BaselineCompletion;
|
||||||
|
import p.studio.lsp.messages.BaselineDefinition;
|
||||||
|
import p.studio.lsp.messages.BaselineDocumentAnalysis;
|
||||||
|
import p.studio.lsp.messages.BaselineDocumentSymbols;
|
||||||
|
import p.studio.lsp.messages.BaselineDocumentSymbolKind;
|
||||||
|
import p.studio.lsp.messages.BaselineHover;
|
||||||
|
import p.studio.lsp.messages.BaselineReferences;
|
||||||
|
import p.studio.lsp.messages.BaselineSemanticTokens;
|
||||||
|
import p.studio.lsp.messages.BaselineServerDescription;
|
||||||
|
import p.studio.lsp.messages.BaselineSignatureHelp;
|
||||||
|
import p.studio.lsp.messages.BaselineWorkspaceSymbol;
|
||||||
|
import p.studio.lsp.messages.BaselineWorkspaceSymbols;
|
||||||
|
import p.studio.lsp.messages.LspProjectContext;
|
||||||
|
import p.studio.lsp.services.LanguageServiceBridge;
|
||||||
|
import p.studio.lsp.services.protocol.mapping.ProtocolMessageMapper;
|
||||||
|
|
||||||
|
import java.nio.file.Path;
|
||||||
|
import java.util.List;
|
||||||
|
|
||||||
|
import static org.junit.jupiter.api.Assertions.assertEquals;
|
||||||
|
import static org.junit.jupiter.api.Assertions.assertSame;
|
||||||
|
import static org.junit.jupiter.api.Assertions.assertTrue;
|
||||||
|
|
||||||
|
final class PrometeuWorkspaceServiceTest {
|
||||||
|
|
||||||
|
@Test
|
||||||
|
void symbolDelegatesQueryWithoutADocumentUri() {
|
||||||
|
final var bridge = new RecordingBridge();
|
||||||
|
final var mapper = new RecordingMapper();
|
||||||
|
final var project = new LspProjectContext("main", "pbs", Path.of("."));
|
||||||
|
final var service = new PrometeuWorkspaceService(project, bridge, mapper);
|
||||||
|
|
||||||
|
final var result = service.symbol(new WorkspaceSymbolParams("blend")).join();
|
||||||
|
|
||||||
|
assertTrue(result.isLeft());
|
||||||
|
assertSame(mapper.workspaceSymbols, result.getLeft());
|
||||||
|
assertEquals("blend", bridge.lastQuery);
|
||||||
|
assertSame(project, bridge.lastContext);
|
||||||
|
}
|
||||||
|
|
||||||
|
private static final class RecordingBridge implements LanguageServiceBridge {
|
||||||
|
private LspProjectContext lastContext;
|
||||||
|
private String lastQuery;
|
||||||
|
|
||||||
|
@Override
|
||||||
|
public BaselineServerDescription describeServer(final LspProjectContext context) {
|
||||||
|
throw new UnsupportedOperationException();
|
||||||
|
}
|
||||||
|
|
||||||
|
@Override
|
||||||
|
public BaselineDocumentAnalysis analyzeDocument(
|
||||||
|
final LspProjectContext context,
|
||||||
|
final String documentUri,
|
||||||
|
final String text) {
|
||||||
|
throw new UnsupportedOperationException();
|
||||||
|
}
|
||||||
|
|
||||||
|
@Override
|
||||||
|
public BaselineCompletion completion(
|
||||||
|
final LspProjectContext context,
|
||||||
|
final String documentUri,
|
||||||
|
final String text,
|
||||||
|
final int line,
|
||||||
|
final int character) {
|
||||||
|
throw new UnsupportedOperationException();
|
||||||
|
}
|
||||||
|
|
||||||
|
@Override
|
||||||
|
public BaselineHover hover(
|
||||||
|
final LspProjectContext context,
|
||||||
|
final String documentUri,
|
||||||
|
final String text,
|
||||||
|
final int line,
|
||||||
|
final int character) {
|
||||||
|
throw new UnsupportedOperationException();
|
||||||
|
}
|
||||||
|
|
||||||
|
@Override
|
||||||
|
public BaselineDefinition definition(
|
||||||
|
final LspProjectContext context,
|
||||||
|
final String documentUri,
|
||||||
|
final String text,
|
||||||
|
final int line,
|
||||||
|
final int character) {
|
||||||
|
throw new UnsupportedOperationException();
|
||||||
|
}
|
||||||
|
|
||||||
|
@Override
|
||||||
|
public BaselineReferences references(
|
||||||
|
final LspProjectContext context,
|
||||||
|
final String documentUri,
|
||||||
|
final String text,
|
||||||
|
final int line,
|
||||||
|
final int character,
|
||||||
|
final boolean includeDeclaration) {
|
||||||
|
throw new UnsupportedOperationException();
|
||||||
|
}
|
||||||
|
|
||||||
|
@Override
|
||||||
|
public BaselineDocumentSymbols documentSymbols(
|
||||||
|
final LspProjectContext context,
|
||||||
|
final String documentUri,
|
||||||
|
final String text) {
|
||||||
|
throw new UnsupportedOperationException();
|
||||||
|
}
|
||||||
|
|
||||||
|
@Override
|
||||||
|
public BaselineWorkspaceSymbols workspaceSymbols(
|
||||||
|
final LspProjectContext context,
|
||||||
|
final String query) {
|
||||||
|
lastContext = context;
|
||||||
|
lastQuery = query;
|
||||||
|
return new BaselineWorkspaceSymbols(List.of(new BaselineWorkspaceSymbol(
|
||||||
|
"blend",
|
||||||
|
BaselineDocumentSymbolKind.METHOD,
|
||||||
|
"",
|
||||||
|
"Vec",
|
||||||
|
"file:///tmp/demo.pbs",
|
||||||
|
0,
|
||||||
|
0,
|
||||||
|
0,
|
||||||
|
5)));
|
||||||
|
}
|
||||||
|
|
||||||
|
@Override
|
||||||
|
public BaselineSignatureHelp signatureHelp(
|
||||||
|
final LspProjectContext context,
|
||||||
|
final String documentUri,
|
||||||
|
final String text,
|
||||||
|
final int line,
|
||||||
|
final int character) {
|
||||||
|
throw new UnsupportedOperationException();
|
||||||
|
}
|
||||||
|
|
||||||
|
@Override
|
||||||
|
public BaselineSemanticTokens semanticTokens(
|
||||||
|
final LspProjectContext context,
|
||||||
|
final String documentUri,
|
||||||
|
final String text) {
|
||||||
|
throw new UnsupportedOperationException();
|
||||||
|
}
|
||||||
|
|
||||||
|
@Override
|
||||||
|
public p.studio.lsp.messages.BaselinePrepareRename prepareRename(
|
||||||
|
final LspProjectContext context,
|
||||||
|
final String documentUri,
|
||||||
|
final String text,
|
||||||
|
final int line,
|
||||||
|
final int character) {
|
||||||
|
throw new UnsupportedOperationException();
|
||||||
|
}
|
||||||
|
|
||||||
|
@Override
|
||||||
|
public p.studio.lsp.messages.BaselineRename rename(
|
||||||
|
final LspProjectContext context,
|
||||||
|
final String documentUri,
|
||||||
|
final String text,
|
||||||
|
final int line,
|
||||||
|
final int character,
|
||||||
|
final String newName) {
|
||||||
|
throw new UnsupportedOperationException();
|
||||||
|
}
|
||||||
|
|
||||||
|
@Override
|
||||||
|
public p.studio.lsp.messages.BaselineCodeActions codeActions(
|
||||||
|
final LspProjectContext context,
|
||||||
|
final String documentUri,
|
||||||
|
final String text,
|
||||||
|
final java.util.List<p.studio.lsp.messages.BaselineCodeActionDiagnostic> diagnostics) {
|
||||||
|
throw new UnsupportedOperationException();
|
||||||
|
}
|
||||||
|
|
||||||
|
@Override
|
||||||
|
public String onSave(final LspProjectContext context, final String documentUri) {
|
||||||
|
throw new UnsupportedOperationException();
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
private static final class RecordingMapper implements ProtocolMessageMapper {
|
||||||
|
private final List<SymbolInformation> workspaceSymbols = List.of(new SymbolInformation());
|
||||||
|
|
||||||
|
@Override
|
||||||
|
public org.eclipse.lsp4j.InitializeResult mapInitializeResult(final BaselineServerDescription description) {
|
||||||
|
throw new UnsupportedOperationException();
|
||||||
|
}
|
||||||
|
|
||||||
|
@Override
|
||||||
|
public org.eclipse.lsp4j.PublishDiagnosticsParams mapDiagnostics(
|
||||||
|
final String uri,
|
||||||
|
final BaselineDocumentAnalysis analysis) {
|
||||||
|
throw new UnsupportedOperationException();
|
||||||
|
}
|
||||||
|
|
||||||
|
@Override
|
||||||
|
public org.eclipse.lsp4j.PublishDiagnosticsParams emptyDiagnostics(final String uri) {
|
||||||
|
throw new UnsupportedOperationException();
|
||||||
|
}
|
||||||
|
|
||||||
|
@Override
|
||||||
|
public org.eclipse.lsp4j.Hover mapHover(final BaselineHover hover) {
|
||||||
|
throw new UnsupportedOperationException();
|
||||||
|
}
|
||||||
|
|
||||||
|
@Override
|
||||||
|
public List<org.eclipse.lsp4j.Location> mapDefinition(final BaselineDefinition definition) {
|
||||||
|
throw new UnsupportedOperationException();
|
||||||
|
}
|
||||||
|
|
||||||
|
@Override
|
||||||
|
public List<org.eclipse.lsp4j.Location> mapReferences(final BaselineReferences references) {
|
||||||
|
throw new UnsupportedOperationException();
|
||||||
|
}
|
||||||
|
|
||||||
|
@Override
|
||||||
|
public List<org.eclipse.lsp4j.DocumentSymbol> mapDocumentSymbols(final BaselineDocumentSymbols symbols) {
|
||||||
|
throw new UnsupportedOperationException();
|
||||||
|
}
|
||||||
|
|
||||||
|
@Override
|
||||||
|
public List<SymbolInformation> mapWorkspaceSymbols(final BaselineWorkspaceSymbols symbols) {
|
||||||
|
return workspaceSymbols;
|
||||||
|
}
|
||||||
|
|
||||||
|
@Override
|
||||||
|
public org.eclipse.lsp4j.jsonrpc.messages.Either3<
|
||||||
|
org.eclipse.lsp4j.Range,
|
||||||
|
org.eclipse.lsp4j.PrepareRenameResult,
|
||||||
|
org.eclipse.lsp4j.PrepareRenameDefaultBehavior> mapPrepareRename(
|
||||||
|
final p.studio.lsp.messages.BaselinePrepareRename prepareRename) {
|
||||||
|
throw new UnsupportedOperationException();
|
||||||
|
}
|
||||||
|
|
||||||
|
@Override
|
||||||
|
public org.eclipse.lsp4j.WorkspaceEdit mapRename(final p.studio.lsp.messages.BaselineRename rename) {
|
||||||
|
throw new UnsupportedOperationException();
|
||||||
|
}
|
||||||
|
|
||||||
|
@Override
|
||||||
|
public java.util.List<org.eclipse.lsp4j.jsonrpc.messages.Either<org.eclipse.lsp4j.Command, org.eclipse.lsp4j.CodeAction>> mapCodeActions(
|
||||||
|
final p.studio.lsp.messages.BaselineCodeActions actions,
|
||||||
|
final java.util.List<org.eclipse.lsp4j.Diagnostic> contextDiagnostics) {
|
||||||
|
throw new UnsupportedOperationException();
|
||||||
|
}
|
||||||
|
|
||||||
|
@Override
|
||||||
|
public org.eclipse.lsp4j.CompletionList mapCompletion(final BaselineCompletion completion) {
|
||||||
|
throw new UnsupportedOperationException();
|
||||||
|
}
|
||||||
|
|
||||||
|
@Override
|
||||||
|
public org.eclipse.lsp4j.SignatureHelp mapSignatureHelp(final BaselineSignatureHelp signatureHelp) {
|
||||||
|
throw new UnsupportedOperationException();
|
||||||
|
}
|
||||||
|
|
||||||
|
@Override
|
||||||
|
public org.eclipse.lsp4j.SemanticTokens mapSemanticTokens(final BaselineSemanticTokens semanticTokens) {
|
||||||
|
throw new UnsupportedOperationException();
|
||||||
|
}
|
||||||
|
|
||||||
|
@Override
|
||||||
|
public org.eclipse.lsp4j.MessageParams mapInfoMessage(final String message) {
|
||||||
|
throw new UnsupportedOperationException();
|
||||||
|
}
|
||||||
|
|
||||||
|
@Override
|
||||||
|
public org.eclipse.lsp4j.MessageParams mapErrorMessage(final String message) {
|
||||||
|
throw new UnsupportedOperationException();
|
||||||
|
}
|
||||||
|
|
||||||
|
@Override
|
||||||
|
public org.eclipse.lsp4j.MessageParams mapWarningMessage(final String message) {
|
||||||
|
throw new UnsupportedOperationException();
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
+192
@@ -1,11 +1,24 @@
|
|||||||
package p.studio.lsp.services.protocol.mapping;
|
package p.studio.lsp.services.protocol.mapping;
|
||||||
|
|
||||||
|
import org.eclipse.lsp4j.CodeActionKind;
|
||||||
import org.eclipse.lsp4j.InitializeResult;
|
import org.eclipse.lsp4j.InitializeResult;
|
||||||
|
import org.eclipse.lsp4j.SymbolKind;
|
||||||
import org.eclipse.lsp4j.jsonrpc.messages.Either;
|
import org.eclipse.lsp4j.jsonrpc.messages.Either;
|
||||||
import org.junit.jupiter.api.Test;
|
import org.junit.jupiter.api.Test;
|
||||||
|
import p.studio.lsp.messages.BaselineCodeAction;
|
||||||
|
import p.studio.lsp.messages.BaselineCodeActions;
|
||||||
import p.studio.lsp.messages.BaselineCompletion;
|
import p.studio.lsp.messages.BaselineCompletion;
|
||||||
|
import p.studio.lsp.messages.BaselineDocumentAnalysis;
|
||||||
|
import p.studio.lsp.messages.BaselineDocumentIssue;
|
||||||
|
import p.studio.lsp.messages.BaselineIssueSeverity;
|
||||||
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.BaselineDocumentSymbol;
|
||||||
|
import p.studio.lsp.messages.BaselineDocumentSymbolKind;
|
||||||
|
import p.studio.lsp.messages.BaselineDocumentSymbols;
|
||||||
|
import p.studio.lsp.messages.BaselineReferences;
|
||||||
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;
|
||||||
@@ -21,6 +34,7 @@ import java.util.Map;
|
|||||||
import static org.junit.jupiter.api.Assertions.assertEquals;
|
import static org.junit.jupiter.api.Assertions.assertEquals;
|
||||||
import static org.junit.jupiter.api.Assertions.assertFalse;
|
import static org.junit.jupiter.api.Assertions.assertFalse;
|
||||||
import static org.junit.jupiter.api.Assertions.assertInstanceOf;
|
import static org.junit.jupiter.api.Assertions.assertInstanceOf;
|
||||||
|
import static org.junit.jupiter.api.Assertions.assertNull;
|
||||||
import static org.junit.jupiter.api.Assertions.assertTrue;
|
import static org.junit.jupiter.api.Assertions.assertTrue;
|
||||||
|
|
||||||
final class Lsp4jProtocolMessageMapperTest {
|
final class Lsp4jProtocolMessageMapperTest {
|
||||||
@@ -35,6 +49,12 @@ final class Lsp4jProtocolMessageMapperTest {
|
|||||||
true,
|
true,
|
||||||
true,
|
true,
|
||||||
true,
|
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 +75,13 @@ 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());
|
||||||
|
assertEquals(Boolean.TRUE, result.getCapabilities().getReferencesProvider().getLeft());
|
||||||
|
assertEquals(Boolean.TRUE, result.getCapabilities().getDocumentSymbolProvider().getLeft());
|
||||||
|
assertEquals(Boolean.TRUE, result.getCapabilities().getWorkspaceSymbolProvider().getLeft());
|
||||||
|
assertEquals(Boolean.TRUE, result.getCapabilities().getRenameProvider().getRight().getPrepareProvider());
|
||||||
|
assertEquals(List.of(CodeActionKind.QuickFix), result.getCapabilities().getCodeActionProvider().getRight().getCodeActionKinds());
|
||||||
|
assertEquals(Boolean.FALSE, result.getCapabilities().getCodeActionProvider().getRight().getResolveProvider());
|
||||||
|
|
||||||
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 +131,169 @@ 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());
|
||||||
|
}
|
||||||
|
|
||||||
|
@Test
|
||||||
|
void referencesMapsPhysicalFileLocations() {
|
||||||
|
final var mapper = new Lsp4jProtocolMessageMapper();
|
||||||
|
final var locations = mapper.mapReferences(new BaselineReferences(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(3, locations.getFirst().getRange().getStart().getCharacter());
|
||||||
|
assertTrue(mapper.mapReferences(BaselineReferences.empty()).isEmpty());
|
||||||
|
}
|
||||||
|
|
||||||
|
@Test
|
||||||
|
void documentSymbolsMapToHierarchicalDocumentSymbolTrees() {
|
||||||
|
final var mapper = new Lsp4jProtocolMessageMapper();
|
||||||
|
final var mapped = mapper.mapDocumentSymbols(new BaselineDocumentSymbols(List.of(
|
||||||
|
new BaselineDocumentSymbol(
|
||||||
|
"Mode",
|
||||||
|
BaselineDocumentSymbolKind.ENUM,
|
||||||
|
"",
|
||||||
|
0,
|
||||||
|
0,
|
||||||
|
0,
|
||||||
|
28,
|
||||||
|
0,
|
||||||
|
14,
|
||||||
|
0,
|
||||||
|
18,
|
||||||
|
List.of(new BaselineDocumentSymbol(
|
||||||
|
"Idle",
|
||||||
|
BaselineDocumentSymbolKind.ENUM,
|
||||||
|
"0",
|
||||||
|
0,
|
||||||
|
19,
|
||||||
|
0,
|
||||||
|
23,
|
||||||
|
0,
|
||||||
|
19,
|
||||||
|
0,
|
||||||
|
23,
|
||||||
|
List.of()))),
|
||||||
|
new BaselineDocumentSymbol(
|
||||||
|
"Point",
|
||||||
|
BaselineDocumentSymbolKind.STRUCT,
|
||||||
|
"",
|
||||||
|
1,
|
||||||
|
0,
|
||||||
|
4,
|
||||||
|
1,
|
||||||
|
1,
|
||||||
|
15,
|
||||||
|
1,
|
||||||
|
20,
|
||||||
|
List.of(new BaselineDocumentSymbol(
|
||||||
|
"x",
|
||||||
|
BaselineDocumentSymbolKind.FIELD,
|
||||||
|
"int",
|
||||||
|
1,
|
||||||
|
21,
|
||||||
|
1,
|
||||||
|
27,
|
||||||
|
1,
|
||||||
|
21,
|
||||||
|
1,
|
||||||
|
22,
|
||||||
|
List.of()))))));
|
||||||
|
|
||||||
|
assertEquals(2, mapped.size());
|
||||||
|
assertEquals("Mode", mapped.getFirst().getName());
|
||||||
|
assertEquals(SymbolKind.Enum, mapped.getFirst().getKind());
|
||||||
|
assertEquals("Idle", mapped.getFirst().getChildren().getFirst().getName());
|
||||||
|
assertEquals(SymbolKind.EnumMember, mapped.getFirst().getChildren().getFirst().getKind());
|
||||||
|
assertEquals("Point", mapped.get(1).getName());
|
||||||
|
assertEquals(SymbolKind.Struct, mapped.get(1).getKind());
|
||||||
|
assertEquals("x", mapped.get(1).getChildren().getFirst().getName());
|
||||||
|
assertEquals(SymbolKind.Field, mapped.get(1).getChildren().getFirst().getKind());
|
||||||
|
assertTrue(mapper.mapDocumentSymbols(BaselineDocumentSymbols.empty()).isEmpty());
|
||||||
|
}
|
||||||
|
|
||||||
|
@Test
|
||||||
|
void workspaceSymbolsMapToFlatSymbolInformation() {
|
||||||
|
final var mapper = new Lsp4jProtocolMessageMapper();
|
||||||
|
final var mapped = mapper.mapWorkspaceSymbols(new p.studio.lsp.messages.BaselineWorkspaceSymbols(List.of(
|
||||||
|
new p.studio.lsp.messages.BaselineWorkspaceSymbol(
|
||||||
|
"blend",
|
||||||
|
BaselineDocumentSymbolKind.METHOD,
|
||||||
|
"(dx: int, dy: int) -> int",
|
||||||
|
"Vec",
|
||||||
|
"file:///tmp/demo.pbs",
|
||||||
|
3,
|
||||||
|
2,
|
||||||
|
3,
|
||||||
|
7),
|
||||||
|
new p.studio.lsp.messages.BaselineWorkspaceSymbol(
|
||||||
|
"Idle",
|
||||||
|
BaselineDocumentSymbolKind.ENUM,
|
||||||
|
"0",
|
||||||
|
"Mode",
|
||||||
|
"file:///tmp/demo.pbs",
|
||||||
|
0,
|
||||||
|
19,
|
||||||
|
0,
|
||||||
|
23))));
|
||||||
|
|
||||||
|
assertEquals(2, mapped.size());
|
||||||
|
assertEquals("blend", mapped.getFirst().getName());
|
||||||
|
assertEquals("Vec", mapped.getFirst().getContainerName());
|
||||||
|
assertEquals(SymbolKind.Method, mapped.getFirst().getKind());
|
||||||
|
assertEquals("file:///tmp/demo.pbs", mapped.getFirst().getLocation().getUri());
|
||||||
|
assertEquals(2, mapped.getFirst().getLocation().getRange().getStart().getCharacter());
|
||||||
|
assertEquals("Idle", mapped.get(1).getName());
|
||||||
|
assertEquals(SymbolKind.EnumMember, mapped.get(1).getKind());
|
||||||
|
assertTrue(mapper.mapWorkspaceSymbols(p.studio.lsp.messages.BaselineWorkspaceSymbols.empty()).isEmpty());
|
||||||
|
}
|
||||||
|
|
||||||
|
@Test
|
||||||
|
void diagnosticsPublishStableCodeAndQuickFixesAreEditsNotCommands() {
|
||||||
|
final var mapper = new Lsp4jProtocolMessageMapper();
|
||||||
|
final var published = mapper.mapDiagnostics("file:///tmp/demo.pbs", new BaselineDocumentAnalysis(List.of(
|
||||||
|
new BaselineDocumentIssue(
|
||||||
|
1,
|
||||||
|
2,
|
||||||
|
1,
|
||||||
|
18,
|
||||||
|
BaselineIssueSeverity.ERROR,
|
||||||
|
"E_SEM_DUPLICATE_RESERVED_ATTRIBUTE",
|
||||||
|
"Duplicate Doc attribute on the same declaration surface",
|
||||||
|
"E_SEM_DUPLICATE_RESERVED_ATTRIBUTE"))));
|
||||||
|
final var diagnostic = published.getDiagnostics().getFirst();
|
||||||
|
assertEquals("E_SEM_DUPLICATE_RESERVED_ATTRIBUTE", diagnostic.getCode().getLeft());
|
||||||
|
assertNull(diagnostic.getData());
|
||||||
|
|
||||||
|
final var mapped = mapper.mapCodeActions(new BaselineCodeActions(List.of(new BaselineCodeAction(
|
||||||
|
"Remove duplicate reserved attribute",
|
||||||
|
"E_SEM_DUPLICATE_RESERVED_ATTRIBUTE",
|
||||||
|
"file:///tmp/demo.pbs",
|
||||||
|
1,
|
||||||
|
2,
|
||||||
|
1,
|
||||||
|
18,
|
||||||
|
""))), List.of(diagnostic));
|
||||||
|
|
||||||
|
assertEquals(1, mapped.size());
|
||||||
|
assertTrue(mapped.getFirst().isRight());
|
||||||
|
assertFalse(mapped.getFirst().isLeft());
|
||||||
|
final var action = mapped.getFirst().getRight();
|
||||||
|
assertEquals(CodeActionKind.QuickFix, action.getKind());
|
||||||
|
assertNull(action.getCommand());
|
||||||
|
assertEquals("", action.getEdit().getChanges().get("file:///tmp/demo.pbs").getFirst().getNewText());
|
||||||
|
assertEquals(1, action.getDiagnostics().size());
|
||||||
|
assertEquals(diagnostic, action.getDiagnostics().getFirst());
|
||||||
|
}
|
||||||
}
|
}
|
||||||
|
|||||||
@@ -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"))
|
||||||
}
|
}
|
||||||
|
|
||||||
|
|||||||
@@ -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")
|
||||||
|
|||||||
Reference in New Issue
Block a user