Compare commits

..

5 Commits

Author SHA1 Message Date
fa21a029ae Merge pull request 'implements PLN-0134' (#28) from dev/pbs-lsp-workspace-symbols into master
All checks were successful
JaCoCo Coverage #### Project Overview No changes detected, that affect the code coverage. * Line Coverage: 63.37% (18783/29640) * Branch Coverage: 53.99% (7369/13648) * Lines of Code: 29640 * Cyclomatic Complexity: 11938 #### Quality Gates Summary Output truncated.
Test / Build skipped: 15, passed: 674
Intrepid/Prometeu/Studio/pipeline/head This commit looks good
Reviewed-on: #28
2026-09-21 16:27:42 +00:00
12e2a4edcc
implements PLN-0134
Some checks are pending
Intrepid/Prometeu/Studio/pipeline/pr-master Build started...
JaCoCo Coverage #### Project Overview No changes detected, that affect the code coverage. * Line Coverage: 63.37% (18783/29640) * Branch Coverage: 53.99% (7369/13648) * Lines of Code: 29640 * Cyclomatic Complexity: 11938 #### Quality Gates Summary Output truncated.
Test / Build skipped: 15, passed: 674
Intrepid/Prometeu/Studio/pipeline/head This commit looks good
Add PBS workspace symbols as a physical flatten of the outline
named-declaration set on FrontendLanguageService. Regular files
only; virtual stdlib, barrels, imports, locals, and compile-only
frontends stay empty. Advertise workspaceSymbolProvider with flat
SymbolInformation. workspace/symbol does not require an open
document.

Housekeep DSC-0042 with LSN-0071.
2026-09-21 17:18:00 +01:00
78d10cf03c Merge pull request 'implements PLN-0133' (#27) from dev/pbs-lsp-document-symbols-and-outline into master
All checks were successful
JaCoCo Coverage #### Project Overview No changes detected, that affect the code coverage. * Line Coverage: 62.84% (18504/29445) * Branch Coverage: 53.33% (7215/13528) * Lines of Code: 29445 * Cyclomatic Complexity: 11850 #### Quality Gates Summary Output truncated.
Test / Build skipped: 15, passed: 669
Intrepid/Prometeu/Studio/pipeline/head This commit looks good
Reviewed-on: #27
2026-09-21 09:23:52 +00:00
5d3d48e802
implements PLN-0133
Some checks are pending
Intrepid/Prometeu/Studio/pipeline/pr-master Build started...
JaCoCo Coverage #### Project Overview No changes detected, that affect the code coverage. * Line Coverage: 62.84% (18504/29445) * Branch Coverage: 53.33% (7215/13528) * Lines of Code: 29445 * Cyclomatic Complexity: 11850 #### Quality Gates Summary Output truncated.
Test / Build skipped: 15, passed: 669
Intrepid/Prometeu/Studio/pipeline/head This commit looks good
Add PBS document symbols as an AST-backed hierarchical outline of
the open .pbs file on FrontendLanguageService. Recovered syntax is
enough; unnamed InvalidDecl is omitted; barrels, imports, locals,
and compile-only frontends stay empty. Advertise documentSymbolProvider
with hierarchical DocumentSymbol.

Housekeep DSC-0041 with LSN-0070.
2026-09-21 10:16:14 +01:00
331ad752d1 Merge pull request 'implements PLN-0132' (#26) from dev/pbs-lsp-find-references into master
All checks were successful
JaCoCo Coverage #### Project Overview No changes detected, that affect the code coverage. * Line Coverage: 62.51% (18192/29102) * Branch Coverage: 53.15% (7093/13345) * Lines of Code: 29102 * Cyclomatic Complexity: 11715 #### Quality Gates Summary Output truncated.
Test / Build skipped: 15, passed: 663
Intrepid/Prometeu/Studio/pipeline/head This commit looks good
Reviewed-on: #26
2026-09-21 08:00:40 +00:00
36 changed files with 2227 additions and 131 deletions

View File

@ -1,4 +1,4 @@
{"type":"meta","next_id":{"DSC":66,"AGD":69,"DEC":54,"PLN":133,"LSN":70,"CLSN":1}}
{"type":"meta","next_id":{"DSC":66,"AGD":69,"DEC":56,"PLN":135,"LSN":72,"CLSN":1}}
{"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":"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"}]}
@ -22,8 +22,8 @@
{"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-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-0042","status":"open","ticket":"pbs-lsp-workspace-symbols","title":"PBS LSP Workspace Symbols","created_at":"2026-07-15","updated_at":"2026-07-15","tags":["studio","lsp","vscode","compiler-pbs","editor","workspace-symbols"],"agendas":[{"id":"AGD-0045","file":"AGD-0045-pbs-lsp-workspace-symbols.md","status":"open","created_at":"2026-07-15","updated_at":"2026-07-15"}],"decisions":[],"plans":[],"lessons":[]}
{"type":"discussion","id":"DSC-0041","status":"open","ticket":"pbs-lsp-document-symbols-outline","title":"PBS LSP Document Symbols and Outline","created_at":"2026-07-15","updated_at":"2026-07-15","tags":["studio","lsp","vscode","compiler-pbs","editor","outline","document-symbols"],"agendas":[{"id":"AGD-0044","file":"AGD-0044-pbs-lsp-document-symbols-and-outline.md","status":"open","created_at":"2026-07-15","updated_at":"2026-07-15"}],"decisions":[],"plans":[],"lessons":[]}
{"type":"discussion","id":"DSC-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":"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":"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":"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"}]}

View File

@ -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

View File

@ -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

View File

@ -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.

View File

@ -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.

View File

@ -276,6 +276,10 @@ When a frontend exposes definition or navigation, each returned location MUST id
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.
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.

View File

@ -6,16 +6,19 @@ import p.studio.compiler.messages.FrontendPhaseContext;
import p.studio.compiler.models.FrontendSemanticToken;
import p.studio.compiler.pbs.ast.PbsAst;
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.PbsEditorialSignatureHelp;
import p.studio.compiler.pbs.semantics.PbsEditorialSymbolKind;
import p.studio.compiler.pbs.semantics.PbsEditorialSupportService;
import p.studio.compiler.pbs.semantics.PbsEditorialSupportService.EditorialDocument;
import p.studio.compiler.pbs.semantics.PbsEditorialWorkspaceSymbol;
import p.studio.compiler.services.PBSFrontendPhaseService.PbsSemanticReadSurface;
import p.studio.compiler.services.FrontendCompletionCandidate;
import p.studio.compiler.services.FrontendDefinitionLocation;
import p.studio.compiler.services.FrontendDocumentRequest;
import p.studio.compiler.services.FrontendDocumentSymbol;
import p.studio.compiler.services.FrontendDocumentation;
import p.studio.compiler.services.FrontendEditorialContext;
import p.studio.compiler.services.FrontendHover;
@ -23,6 +26,8 @@ import p.studio.compiler.services.FrontendLanguageService;
import p.studio.compiler.services.FrontendSignature;
import p.studio.compiler.services.FrontendSignatureHelp;
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.source.Span;
import p.studio.compiler.source.diagnostics.DiagnosticSink;
@ -33,6 +38,7 @@ 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.Objects;
@ -53,6 +59,23 @@ public final class PBSFrontendLanguageService implements FrontendLanguageService
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
public Optional<FrontendEditorialContext> prepareEditorialContext(
final FrontendPhaseContext phaseContext,
@ -267,6 +290,53 @@ public final class PBSFrontendLanguageService implements FrontendLanguageService
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 List<FrontendSemanticToken> semanticTokens(final FrontendDocumentRequest request) {
return semanticTokens(request == null ? "" : request.documentText());
@ -314,6 +384,36 @@ public final class PBSFrontendLanguageService implements FrontendLanguageService
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,
@ -348,6 +448,15 @@ public final class PBSFrontendLanguageService implements FrontendLanguageService
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) {

View File

@ -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";
};
}
}

View File

@ -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));
}
}

View File

@ -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);
}
}

View File

@ -74,6 +74,16 @@ public final class PbsEditorialSupportService {
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,

View File

@ -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");
}
}

View File

@ -434,6 +434,178 @@ final class PbsEditorialSupportServiceTest {
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()));
}
private PbsEditorialResolvedSymbol requireHover(
final String source,
final PbsAst.File ast,
@ -455,6 +627,26 @@ final class PbsEditorialSupportServiceTest {
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) {
return parse(source, new FileId(0), PbsParser.ParseMode.ORDINARY);
}

View File

@ -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;
}
}

View File

@ -11,6 +11,11 @@ import java.util.Optional;
* Optional frontend-owned editor services.
*/
public interface FrontendLanguageService {
default Optional<FrontendEditorialContext> prepareEditorialContext(
final FrontendPhaseContext phaseContext) {
return Optional.empty();
}
default Optional<FrontendEditorialContext> prepareEditorialContext(
final FrontendPhaseContext phaseContext,
final FileId fileId) {
@ -85,4 +90,24 @@ public interface FrontendLanguageService {
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);
}
}

View File

@ -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;
}
}

View File

@ -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;
}
}

View File

@ -24,6 +24,122 @@ class FrontendLanguageServiceTest {
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());
}
@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

View File

@ -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;
}
}

View File

@ -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
}

View File

@ -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());
}
}

View File

@ -12,6 +12,8 @@ public record BaselineServerDescription(
boolean signatureHelpSupported,
boolean definitionSupported,
boolean referencesSupported,
boolean documentSymbolsSupported,
boolean workspaceSymbolsSupported,
List<String> semanticTokenTypes,
List<BaselineSemanticHostProjection> semanticHostProjections,
List<BaselineVisualTheme> visualThemes,

View File

@ -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;
}
}

View File

@ -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());
}
}

View File

@ -4,7 +4,9 @@ import p.studio.lsp.messages.BaselineDocumentAnalysis;
import p.studio.lsp.messages.BaselineCompletion;
import p.studio.lsp.messages.BaselineDefinition;
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.BaselineSemanticTokens;
import p.studio.lsp.messages.BaselineSignatureHelp;
import p.studio.lsp.messages.BaselineServerDescription;
@ -29,6 +31,10 @@ public interface LanguageServiceBridge {
int character,
boolean includeDeclaration);
BaselineDocumentSymbols documentSymbols(LspProjectContext context, String documentUri, String text);
BaselineWorkspaceSymbols workspaceSymbols(LspProjectContext context, String query);
BaselineSignatureHelp signatureHelp(LspProjectContext context, String documentUri, String text, int line, int character);
BaselineSemanticTokens semanticTokens(LspProjectContext context, String documentUri, String text);

View File

@ -7,12 +7,15 @@ import p.studio.compiler.models.*;
import p.studio.compiler.services.FrontendCompletionCandidate;
import p.studio.compiler.services.FrontendDefinitionLocation;
import p.studio.compiler.services.FrontendDocumentRequest;
import p.studio.compiler.services.FrontendDocumentSymbol;
import p.studio.compiler.services.FrontendEditorialContext;
import p.studio.compiler.services.FrontendHover;
import p.studio.compiler.services.FrontendProvider;
import p.studio.compiler.services.FrontendSignature;
import p.studio.compiler.services.FrontendSignatureHelp;
import p.studio.compiler.services.FrontendSymbolKind;
import p.studio.compiler.services.FrontendWorkspaceRequest;
import p.studio.compiler.services.FrontendWorkspaceSymbol;
import p.studio.compiler.source.identifiers.FileId;
import p.studio.compiler.utilities.SourceProviderFactory;
import p.studio.compiler.workspaces.AssetSurfaceContextLoader;
@ -45,6 +48,7 @@ public final class CompilerLanguageServiceBridge implements LanguageServiceBridg
Objects.requireNonNull(context, "context");
final var frontend = frontendSpec(context);
final var presentation = frontend.getSemanticPresentation();
final boolean languageServicePresent = frontendProvider(context).languageService().isPresent();
return new BaselineServerDescription(
"Prometeu Studio LSP",
"0.1.0",
@ -52,8 +56,10 @@ public final class CompilerLanguageServiceBridge implements LanguageServiceBridg
true,
true,
true,
frontendProvider(context).languageService().isPresent(),
frontendProvider(context).languageService().isPresent(),
languageServicePresent,
languageServicePresent,
languageServicePresent,
languageServicePresent,
presentation.semanticKeys(),
presentation.hostProjections().stream().map(this::mapSemanticHostProjection).toList(),
presentation.themes().stream().map(this::mapVisualTheme).toList(),
@ -208,6 +214,64 @@ public final class CompilerLanguageServiceBridge implements LanguageServiceBridg
.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 BaselineSignatureHelp signatureHelp(
final LspProjectContext context,
@ -491,6 +555,84 @@ public final class CompilerLanguageServiceBridge implements LanguageServiceBridg
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<BaselineDefinitionLocation> mapDefinitionLocations(
final List<FrontendDefinitionLocation> locations,
final Path currentDocumentPath,

View File

@ -29,7 +29,7 @@ public final class PrometeuLanguageServer implements LanguageServer, LanguageCli
compilerBridge,
new Lsp4jProtocolMessageMapper(),
null,
new PrometeuWorkspaceService());
null);
}
PrometeuLanguageServer(
@ -44,7 +44,9 @@ public final class PrometeuLanguageServer implements LanguageServer, LanguageCli
this.textDocumentService = textDocumentService != null
? textDocumentService
: new PrometeuTextDocumentService(project, languageServiceBridge, protocolMessageMapper);
this.workspaceService = Objects.requireNonNull(workspaceService, "workspaceService");
this.workspaceService = workspaceService != null
? workspaceService
: new PrometeuWorkspaceService(project, languageServiceBridge, protocolMessageMapper);
}
@Override

View File

@ -8,6 +8,7 @@ import p.studio.lsp.messages.LspProjectContext;
import p.studio.lsp.services.LanguageServiceBridge;
import p.studio.lsp.services.protocol.mapping.ProtocolMessageMapper;
import java.util.ArrayList;
import java.util.Objects;
import java.util.concurrent.ConcurrentHashMap;
import java.util.concurrent.CompletableFuture;
@ -127,6 +128,19 @@ public final class PrometeuTextDocumentService implements TextDocumentService {
includeDeclaration)));
}
@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
public CompletableFuture<SignatureHelp> signatureHelp(final SignatureHelpParams params) {
final String uri = params.getTextDocument().getUri();

View File

@ -2,9 +2,36 @@ package p.studio.lsp.services.protocol;
import org.eclipse.lsp4j.DidChangeConfigurationParams;
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 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 {
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
public void didChangeConfiguration(final DidChangeConfigurationParams params) {
}
@ -12,4 +39,15 @@ public final class PrometeuWorkspaceService implements WorkspaceService {
@Override
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))));
}
}

View File

@ -38,6 +38,8 @@ public final class Lsp4jProtocolMessageMapper implements ProtocolMessageMapper {
}
capabilities.setDefinitionProvider(description.definitionSupported());
capabilities.setReferencesProvider(description.referencesSupported());
capabilities.setDocumentSymbolProvider(description.documentSymbolsSupported());
capabilities.setWorkspaceSymbolProvider(description.workspaceSymbolsSupported());
final SemanticTokensWithRegistrationOptions semanticTokens = new SemanticTokensWithRegistrationOptions();
semanticTokens.setLegend(new SemanticTokensLegend(description.semanticTokenTypes(), List.of()));
semanticTokens.setFull(true);
@ -101,6 +103,94 @@ public final class Lsp4jProtocolMessageMapper implements ProtocolMessageMapper {
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 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(

View File

@ -6,8 +6,12 @@ import org.eclipse.lsp4j.MessageParams;
import org.eclipse.lsp4j.PublishDiagnosticsParams;
import org.eclipse.lsp4j.SignatureHelp;
import org.eclipse.lsp4j.SemanticTokens;
import org.eclipse.lsp4j.DocumentSymbol;
import org.eclipse.lsp4j.Location;
import org.eclipse.lsp4j.SymbolInformation;
import p.studio.lsp.messages.BaselineDocumentAnalysis;
import p.studio.lsp.messages.BaselineDocumentSymbols;
import p.studio.lsp.messages.BaselineWorkspaceSymbols;
import p.studio.lsp.messages.BaselineCompletion;
import p.studio.lsp.messages.BaselineDefinition;
import p.studio.lsp.messages.BaselineReferences;
@ -32,6 +36,10 @@ public interface ProtocolMessageMapper {
List<Location> mapReferences(BaselineReferences references);
List<DocumentSymbol> mapDocumentSymbols(BaselineDocumentSymbols symbols);
List<SymbolInformation> mapWorkspaceSymbols(BaselineWorkspaceSymbols symbols);
CompletionList mapCompletion(BaselineCompletion completion);
SignatureHelp mapSignatureHelp(BaselineSignatureHelp signatureHelp);

View File

@ -15,8 +15,10 @@ import p.studio.utilities.structures.ReadOnlySet;
import java.nio.file.Files;
import java.nio.file.Path;
import java.util.List;
import static org.junit.jupiter.api.Assertions.assertFalse;
import static org.junit.jupiter.api.Assertions.assertEquals;
import static org.junit.jupiter.api.Assertions.assertNotEquals;
import static org.junit.jupiter.api.Assertions.assertTrue;
class CompilerLanguageServiceBridgeTest {
@ -51,6 +53,12 @@ class CompilerLanguageServiceBridgeTest {
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 semanticTokens = bridge.semanticTokens(context, documentUri, "fn main() {}");
assertTrue(semanticTokens.legend().isEmpty());
assertTrue(semanticTokens.tokens().isEmpty());
@ -474,6 +482,103 @@ class CompilerLanguageServiceBridgeTest {
assertTrue(builtinReferences.locations().isEmpty());
}
@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
void describeServerPublishesFrontendVisualThemes() {
final CompilerLanguageServiceBridge bridge = new CompilerLanguageServiceBridge();
@ -486,6 +591,8 @@ class CompilerLanguageServiceBridgeTest {
assertTrue(description.signatureHelpSupported());
assertTrue(description.definitionSupported());
assertTrue(description.referencesSupported());
assertTrue(description.documentSymbolsSupported());
assertTrue(description.workspaceSymbolsSupported());
assertEquals(1, description.semanticHostProjections().size());
assertEquals("vscode", description.semanticHostProjections().getFirst().hostId());
assertTrue(description.semanticHostProjections().getFirst().tokenProjections().stream()

View File

@ -101,6 +101,8 @@ class PrometeuLanguageServerTest {
true,
true,
true,
true,
true,
List.of(),
List.of(new BaselineSemanticHostProjection(
"vscode",
@ -169,6 +171,21 @@ class PrometeuLanguageServerTest {
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 BaselineSignatureHelp signatureHelp(
final LspProjectContext project,
@ -226,6 +243,18 @@ class PrometeuLanguageServerTest {
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.CompletionList mapCompletion(final BaselineCompletion completion) {
throw new UnsupportedOperationException();

View File

@ -4,6 +4,8 @@ import org.eclipse.lsp4j.CompletionItem;
import org.eclipse.lsp4j.CompletionList;
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;
@ -22,6 +24,9 @@ import p.studio.lsp.messages.BaselineCompletionItem;
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.BaselineHover;
@ -102,6 +107,13 @@ final class PrometeuTextDocumentServiceTest {
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 {
@ -116,6 +128,7 @@ final class PrometeuTextDocumentServiceTest {
private int lastReferencesLine;
private int lastReferencesCharacter;
private boolean lastIncludeDeclaration;
private String lastDocumentSymbolsText;
private String lastSignatureHelpText;
private int lastSignatureHelpLine;
private int lastSignatureHelpCharacter;
@ -183,6 +196,34 @@ final class PrometeuTextDocumentServiceTest {
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 BaselineSignatureHelp signatureHelp(
final LspProjectContext context,
@ -213,6 +254,7 @@ final class PrometeuTextDocumentServiceTest {
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;
@Override
@ -250,6 +292,17 @@ final class PrometeuTextDocumentServiceTest {
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 CompletionList mapCompletion(final BaselineCompletion completion) {
return completionList;

View File

@ -0,0 +1,229 @@
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 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.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();
}
}
}

View File

@ -1,6 +1,7 @@
package p.studio.lsp.services.protocol.mapping;
import org.eclipse.lsp4j.InitializeResult;
import org.eclipse.lsp4j.SymbolKind;
import org.eclipse.lsp4j.jsonrpc.messages.Either;
import org.junit.jupiter.api.Test;
import p.studio.lsp.messages.BaselineCompletion;
@ -8,6 +9,9 @@ import p.studio.lsp.messages.BaselineCompletionItem;
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.BaselineSemanticHostProjection;
@ -40,6 +44,8 @@ final class Lsp4jProtocolMessageMapperTest {
true,
true,
true,
true,
true,
List.of("demo-keyword"),
List.of(new BaselineSemanticHostProjection(
"vscode",
@ -62,6 +68,8 @@ final class Lsp4jProtocolMessageMapperTest {
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());
final var experimental = assertInstanceOf(Map.class, result.getCapabilities().getExperimental());
final var semanticPayload = assertInstanceOf(Map.class, experimental.get("prometeuSemanticHostProjections"));
@ -135,4 +143,107 @@ final class Lsp4jProtocolMessageMapperTest {
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());
}
}